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 |
|---|---|---|---|---|---|
clearml | examples/scheduler/trigger_example.py | .py | from clearml import Task, Dataset, Model
from clearml.automation import TriggerScheduler
def trigger_model_func(model_id):
model = Model(model_id=model_id)
print(f'model id {model.id} modified')
def trigger_dataset_func(dataset_id):
dataset = Dataset.get(dataset_id=dataset_id)
print(f'dataset id {da... | 66 | 2,190 |
metrics | src/torchmetrics/functional/audio/sdr.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... | 304 | 11,910 |
jupyterlab | jupyterlab/pytest_plugin.py | .py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import urllib.parse
from collections.abc import Awaitable, Mapping
from pathlib import Path
from typing import Any, Protocol
import pytest
from jupyter_server.serverapp import ServerApp
from jupyter_server.utils impor... | 153 | 4,579 |
hydra | tools/landscape/build_landscape_review.py | .py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""Build a resumable, evidence-backed Hydra Landscape review queue."""
from __future__ import annotations
import argparse
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any,... | 514 | 19,221 |
saleor | saleor/graphql/account/utils.py | .py | from typing import TYPE_CHECKING, Optional, Union
from django.conf import settings
from django.contrib.postgres.aggregates import ArrayAgg
from django.db.models import Q, Value
from django.db.models.functions import Concat
from graphene.utils.str_converters import to_camel_case
from ...account.models import Group, Us... | 403 | 14,831 |
textual | docs/examples/guide/layout/grid_layout4_row_col_adjust.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Static
class GridLayoutExample(App):
CSS_PATH = "grid_layout4_row_col_adjust.tcss"
def compose(self) -> ComposeResult:
yield Static("One", classes="box")
yield Static("Two", classes="box")
yield Static("Three", cla... | 20 | 536 |
wandb | wandb/integration/sklearn/calculate/feature_importances.py | .py | from warnings import simplefilter
import numpy as np
import wandb
# ignore all future warnings
simplefilter(action="ignore", category=FutureWarning)
def feature_importances(model, feature_names):
attributes_to_check = ["feature_importances_", "feature_log_prob_", "coef_"]
found_attribute = check_for_attrib... | 68 | 2,261 |
jupytext | src/jupytext/doxygen.py | .py | """Convert Markdown equations to doxygen equations and back
See https://github.com/mwouts/jupytext/issues/517"""
import re
def markdown_to_doxygen(string):
"""Markdown to Doxygen equations"""
long_equations = re.sub(r"(?<!\\)\$\$(.*?)(?<!\\)\$\$", r"\\f[\g<1>\\f]", string, flags=re.DOTALL)
inline_equatio... | 19 | 661 |
coveragepy | tests/moremodules/namespace_420/sub2/__init__.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
sub2 = "namespace_420 sub2"
| 5 | 186 |
wandb | tests/unit_tests/test_wandb_settings.py | .py | import copy
import json
import os
import pathlib
import platform
import re
import subprocess
import sys
import tempfile
from unittest import mock
import pytest
import wandb
from wandb import Settings
from wandb.errors import UsageError
from wandb.sdk.lib.run_moment import RunMoment
from tests.fixtures.mock_wandb_log ... | 740 | 20,101 |
wagtail | wagtail/admin/staticfiles.py | .py | import hashlib
import os
from django.conf import STATICFILES_STORAGE_ALIAS, settings
from django.contrib.staticfiles.storage import HashedFilesMixin
from django.core.files.storage import storages
from django.templatetags.static import static
from wagtail import __version__
# Check whether we should add cache-busting... | 70 | 2,829 |
hatch | tests/helpers/templates/new/feature_ci.py | .py | from hatch.template import File
from hatch.utils.fs import Path
from .default import get_files as get_template_files
def get_files(**kwargs):
files = [File(Path(f.path), f.contents) for f in get_template_files(**kwargs)]
files.append(
File(
Path(".github", "workflows", "test.yml"),
... | 60 | 1,450 |
sphinx | sphinx/builders/latex/nodes.py | .py | """Additional nodes for LaTeX writer."""
from __future__ import annotations
from docutils import nodes
class captioned_literal_block(nodes.container):
"""A node for a container of literal_block having a caption."""
pass
class footnotemark(nodes.Inline, nodes.Referential, nodes.TextElement):
r"""A nod... | 45 | 895 |
coremltools | coremltools/converters/mil/frontend/torch/ssa_passes/__init__.py | .py | # Copyright (c) 2021, 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 . import torch_tensor_assign_to_core, torch_upsample_to_core_upsample
| 7 | 294 |
hatch | backend/src/hatchling/__main__.py | .py | import sys
if __name__ == "__main__":
from hatchling.cli import hatchling
sys.exit(hatchling())
| 7 | 106 |
wandb | tests/unit_tests/test_sandbox/test_sandbox_auth.py | .py | from __future__ import annotations
from unittest.mock import Mock
import pytest
import wandb.sandbox._auth as sandbox_auth
_VALID_API_KEY = "x" * 40
_SETTINGS_API_KEY = "y" * 40
def _singleton(
*,
entity: str | None = "default-entity",
project: str | None = "default-project",
api_key: str | None = ... | 199 | 6,338 |
jupytext | tests/data/notebooks/inputs/python/python_notebook_sample.py | .py | # # Specifications for Jupyter notebooks as python scripts
# ## Markdown cells
# Markdown cells are escaped with a single quote. Two consecutive
# cells are separated with a blank line.
# ## Code cells
# Python code and adjacent comments are mapped to cell codes.
# For instance, this is a code cell that starts wit... | 61 | 1,188 |
mkdocs-material | material/plugins/info/plugin.py | .py | # Copyright (c) 2016-2025 Martin Donath <martin.donath@squidfunk.com>
# 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, c... | 564 | 23,793 |
deap | doc/code/examples/nsga3_ref_points_combined.py | .py | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy
from deap import tools
NOBJ = 3
P = [2, 1]
SCALES = [1, 0.5]
fig = plt.figure(figsize=(7, 7))
ax = fig.add_subplot(111, projection="3d")
# the coordinate origin
ax.scatter(0, 0, 0, c="k", marker="+", s=100)
# reference points
# Pa... | 43 | 1,080 |
gunicorn | tests/requests/valid/027.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
request = {
"method": "GET",
"uri": uri("/\xc3\xa0%20k"),
"version": (1, 0),
"headers": [
],
"body": ''
}
| 13 | 236 |
hatch | tests/backend/version/source/test_regex.py | .py | from itertools import product
import pytest
from hatchling.version.source.regex import RegexSource
DEFAULT_PATTERN_PRODUCTS = list(product(("__version__", "VERSION", "version"), ('"', "'"), ("", "v")))
def test_no_path(isolation):
source = RegexSource(str(isolation), {})
with pytest.raises(ValueError, mat... | 120 | 3,603 |
beam | learning/katas/python/Core Transforms/Side Input/Side Input/tests/test_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"); you may not... | 42 | 1,480 |
saleor | saleor/graphql/tax/dataloaders.py | .py | from collections import defaultdict
from decimal import Decimal
from django.db.models import Exists, OuterRef
from promise import Promise
from ...tax.models import (
TaxClass,
TaxClassCountryRate,
TaxConfiguration,
TaxConfigurationPerCountry,
)
from ..core.dataloaders import DataLoader
from ..product.... | 164 | 5,773 |
wagtail | wagtail/contrib/forms/tests/test_forms.py | .py | import itertools
from django import forms
from django.test import TestCase
from wagtail.contrib.forms.forms import FormBuilder
from wagtail.contrib.forms.utils import get_field_clean_name
from wagtail.test.testapp.models import (
ExtendedFormField,
FormBuilderWithCustomWidget,
FormField,
FormPage,
... | 418 | 15,427 |
biopython | Tests/test_Consensus.py | .py | # Copyright (C) 2013 by Yanbo Ye (yeyanbo289@gmail.com)
# 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.
"""Unit tests for the Bio.Phylo.Consensus module."""
import os
import tempfile
import unittest
... | 182 | 7,916 |
onnxruntime | onnxruntime/python/tools/quantization/fusions/replace_upsample_with_resize.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from __fut... | 97 | 3,331 |
gunicorn | examples/http2_gevent/test_http2_gevent.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
#!/usr/bin/env python
"""
Tests for HTTP/2 with gevent example.
Run with:
# Start the server first
docker compose up -d
# Run tests
python test_http2_gevent.py
# Or with pytest
pytest tes... | 306 | 10,300 |
readthedocs.org | readthedocs/projects/tests/test_signals.py | .py | from django.contrib.auth.models import User
from django.test import TestCase
from django_dynamic_fixture import get
from readthedocs.integrations.models import Integration
from readthedocs.oauth.constants import GITHUB, GITHUB_APP
from readthedocs.oauth.models import GitHubAppInstallation, RemoteRepository
from readthe... | 48 | 1,848 |
wagtail | wagtail/images/tests/test_jinja2_svg.py | .py | from django.test import TestCase
from wagtail.images.exceptions import InvalidFilterSpecError
from wagtail.images.models import Image
from wagtail.images.tests.utils import (
get_test_image_file,
get_test_image_file_svg,
get_test_image_filename,
)
from wagtail.test.utils import WagtailTestUtils
class Tes... | 242 | 8,977 |
probability | tensorflow_probability/python/experimental/bijectors/distribution_bijectors_test.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... | 234 | 10,206 |
pyomo | examples/pyomobook/dae-ch/run_path_constraint.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 24 | 949 |
sqlmap | tests/test_common_helpers.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
Assorted request-shaping helpers in lib/core/common.py:
chunkSplitPostData (HTTP chunked-transfer evasion), randomizeParameterValue
(tamper/cache-buster), getHostHeader (Host header d... | 76 | 2,690 |
cvxpy | cvxpy/reductions/solvers/conic_solvers/scip_conif.py | .py | """
Copyright, 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, software
... | 511 | 16,809 |
kafka | tests/kafkatest/services/trogdor/process_stop_fault_spec.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 ... | 39 | 1,899 |
saleor | saleor/graphql/app/mutations/app_token_create.py | .py | import graphene
from django.core.exceptions import ValidationError
from oauthlib.common import generate_token
from ....app import models
from ....app.error_codes import AppErrorCode
from ....permission.enums import AppPermission
from ...account.utils import can_manage_app
from ...core import ResolveInfo
from ...core.d... | 70 | 2,686 |
openvino | tests/layer_tests/tensorflow_tests/test_tf_ClipByValue.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import tensorflow as tf
from common.tf_layer_test_class import CommonTFLayerTest
class TestClipByValue(CommonTFLayerTest):
def _prepare_input(self, inputs_info):
assert 't:0' in inputs_info,... | 50 | 2,018 |
jupytext | tests/integration/contents_manager/test_load_multiple.py | .py | import pytest
from jupyter_server.utils import ensure_async
from nbformat.v4.nbbase import new_notebook
from tornado.web import HTTPError
import jupytext
@pytest.mark.asyncio
async def test_combine_same_version_ok(tmpdir, cm):
tmp_ipynb = "notebook.ipynb"
tmp_nbpy = "notebook.py"
with open(str(tmpdir.jo... | 64 | 1,471 |
returns | returns/context/__init__.py | .py | """This module was quite a big one, so we have split it."""
from returns.context.requires_context import NoDeps as NoDeps
from returns.context.requires_context import Reader as Reader
from returns.context.requires_context import RequiresContext as RequiresContext
from returns.context.requires_context_future_result imp... | 40 | 1,556 |
pyomo | examples/pyomobook/abstract-ch/AbstractHLinear.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... | 48 | 1,294 |
readthedocs.org | readthedocs/notifications/email.py | .py | """Email notifications."""
import structlog
from django.conf import settings
from django.db import models
from django.template import Context
from django.template import Template
from django.template.loader import render_to_string
from readthedocs.core.context_processors import readthedocs_processor
from readthedocs.... | 98 | 3,077 |
sphinx | tests/roots/test-inheritance/dummy/test_nested.py | .py | """Test with nested classes."""
class A:
class B: # NoQA: D106
pass
class C(A.B):
pass
| 11 | 108 |
openvino | tests/samples_tests/smoke_tests/test_benchmark_app.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""
Copyright (C) 2018-2026 Intel Corporation
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.a... | 521 | 22,784 |
openvino | src/frontends/tensorflow/tests/test_models/gen_scripts/generate_nms_named_outputs.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import sys
import tensorflow.compat.v1 as tf
def main():
tf.compat.v1.reset_default_graph()
@tf.function
def second_func(boxes, scores):
# the second function is used to obtain the body graph with NonMax... | 46 | 2,044 |
hatch | src/hatch/template/plugin/hooks.py | .py | from hatch.template.default import DefaultTemplate
from hatchling.plugin import hookimpl
@hookimpl
def hatch_register_template():
return DefaultTemplate
| 8 | 159 |
eve | examples/notifications_settings.py | .py | # -*- coding: utf-8 -*-
SETTINGS = {"DEBUG": True, "DOMAIN": {"test": {}}}
| 3 | 75 |
pynacl | docs/conf.py | .py | #
# This file is execfile()d with the current directory set to its containing dir
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
try:
import sphinx_rtd_theme
except... | 189 | 6,148 |
wandb | wandb/integration/metaflow/__init__.py | .py | """W&B Integration for Metaflow.
Defines a custom step and flow decorator `wandb_log` that automatically logs
flow parameters and artifacts to W&B.
"""
from .metaflow import wandb_log, wandb_track, wandb_use
__all__ = ["wandb_log", "wandb_track", "wandb_use"]
| 10 | 263 |
wandb | wandb/sdk/lib/ratelimit.py | .py | """A small asyncio rate limiter."""
import asyncio
from wandb.sdk.lib import asyncio_compat
class Cooldown:
"""A very simple rate limiter for asyncio loops.
Implemented by sleeping until the next unblock time.
Use the `looptime` package to test code that uses this.
"""
def __init__(self, cool... | 50 | 1,464 |
confluent-kafka-python | tests/ducktape/test_producer.py | .py | """
Ducktape test for Confluent Kafka Python Producer
Assumes Kafka is already running on localhost:9092
"""
import time
from ducktape.mark import matrix
from ducktape.tests.test import Test
from tests.ducktape.producer_benchmark_metrics import (
MetricsBounds,
MetricsCollector,
print_metrics_report,
... | 523 | 21,894 |
wagtail | wagtail/admin/views/pages/preview.py | .py | import uuid
import swapper
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.functional import cached_property
from django.utils.translation import gettext
from ... | 123 | 4,519 |
black | tests/data/cases/fmtonoff6.py | .py | # Regression test for https://github.com/psf/black/issues/2478.
def foo():
arr = (
(3833567325051000, 5, 1, 2, 4229.25, 6, 0),
# fmt: off
)
# Regression test for https://github.com/psf/black/issues/3458.
dependencies = {
a: b,
# fmt: off
}
# Regression test for https://github.com/psf... | 90 | 1,245 |
onnxruntime | onnxruntime/python/tools/transformers/models/phi2/convert_to_onnx.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
from __future__ import annotations
import argparse
import logging
import... | 591 | 20,408 |
pyomo | examples/pyomobook/blocks-ch/lotsizing_uncertain.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... | 35 | 1,252 |
sphinx | tests/roots/test-latex-figure-in-admonition/conf.py | .py | extensions = ['sphinx.ext.todo']
todo_include_todos = True
exclude_patterns = ['_build']
| 4 | 89 |
mlflow | mlflow/data/spark_dataset_source.py | .py | from typing import Any
from mlflow.data.dataset_source import DatasetSource
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
class SparkDatasetSource(DatasetSource):
"""
Represents the source of a dataset stored in a spark table.
"""
def ... | 75 | 2,110 |
python-prompt-toolkit | src/prompt_toolkit/completion/fuzzy_completer.py | .py | from __future__ import annotations
import re
from collections.abc import Callable, Iterable, Mapping, Sequence
from typing import NamedTuple
from prompt_toolkit.document import Document
from prompt_toolkit.filters import FilterOrBool, to_filter
from prompt_toolkit.formatted_text import AnyFormattedText, StyleAndTextT... | 215 | 7,790 |
saleor | saleor/graphql/app/tests/mutations/test_reenable_sync_webhooks.py | .py | from unittest.mock import patch
import graphene
from .....app.error_codes import AppErrorCode
from ....tests.utils import get_graphql_content
REENABLE_BREAKER_MUTATION = """
mutation AppReenableSyncWebhooks($appId: ID!) {
appReenableSyncWebhooks(appId: $appId) {
app {
name
... | 102 | 3,068 |
pyro | tests/infer/test_inspect.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
import pyro
import pyro.distributions as dist
from pyro.distributions.testing.fakes import NonreparameterizedNormal
from pyro.infer.inspect import _deep_merge, get_dependencies, get_model_relations
@pytest... | 559 | 16,351 |
mlflow | mlflow/entities/issue.py | .py | from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from functools import cached_property
from typing import Any
from mlflow.entities._mlflow_object import _MlflowObject
from mlflow.protos.issues_pb2 import Issue as ProtoIssue
class IssueStatus(str, Enum):
"""Enum for stat... | 188 | 6,308 |
readthedocs.org | readthedocs/payments/utils.py | .py | """
Payment utility functions.
These are mostly one-off functions. Define the bulk of Stripe operations on
:py:class:`readthedocs.payments.forms.StripeResourceMixin`.
"""
import stripe
import structlog
from django.conf import settings
from djstripe.models import Account
log = structlog.get_logger(__name__)
def ge... | 59 | 1,764 |
sqlmap | plugins/generic/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 readInput
from lib.core.data import logger
from lib.core.enums import OS
from lib.core.exception import SqlmapUndef... | 59 | 1,722 |
saleor | saleor/core/management/commands/clearorders.py | .py | """Clear the transactions data preserving shop's catalog and configuration.
This command clears the database from data such as orders, checkouts, payments and
optionally customer accounts. It doesn't remove shop's catalog (products, variants) nor
configuration, such as: warehouses, shipping zones, staff accounts, plug... | 208 | 7,355 |
gunicorn | tests/test_sock.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from unittest import mock
from gunicorn import sock
@mock.patch('os.stat')
def test_create_sockets_unix_bytes(stat):
conf = mock.Mock(address=[b'127.0.0.1:8000'])
log = mock.Mock()
with mock.patch.ob... | 57 | 1,853 |
readthedocs.org | readthedocs/search/parsers.py | .py | """JSON/HTML parsers for search indexing."""
import hashlib
import itertools
import re
import structlog
from selectolax.parser import HTMLParser
from readthedocs.projects.constants import MEDIA_TYPE_HTML
from readthedocs.storage import build_media_storage
log = structlog.get_logger(__name__)
class GenericParser:... | 497 | 17,061 |
wandb | tests/unit_tests/test_artifacts/test_artifact_manifest_entry.py | .py | from __future__ import annotations
from pathlib import Path, PurePath
from typing import Any
from pytest import mark, param, raises
from pytest_mock import MockerFixture
from wandb.sdk.artifacts._validators import validate_fspath
from wandb.sdk.artifacts.artifact import Artifact
from wandb.sdk.artifacts.artifact_mani... | 106 | 3,595 |
saleor | saleor/graphql/invoice/tests/test_invoice_request.py | .py | from unittest.mock import patch
import graphene
import pytest
from ....core import JobStatus
from ....graphql.tests.utils import assert_no_permission, get_graphql_content
from ....invoice.error_codes import InvoiceErrorCode
from ....invoice.models import Invoice, InvoiceEvent, InvoiceEvents
from ....order import Orde... | 294 | 9,084 |
probability | spinoffs/autobnn/setup.py | .py | # Copyright 2024 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... | 76 | 2,680 |
kombu | t/unit/asynchronous/http/test_http.py | .py | from __future__ import annotations
from io import BytesIO
from unittest.mock import Mock
import pytest
from vine import promise
import t.skip
from kombu.asynchronous import http
from kombu.asynchronous.http.base import BaseClient, normalize_header
from kombu.exceptions import HttpError
from t.mocks import PromiseMoc... | 156 | 4,221 |
wandb | wandb/integration/sacred/__init__.py | .py | import warnings
import numpy
from sacred.dependencies import get_digest
from sacred.observers import RunObserver
import wandb
class WandbObserver(RunObserver):
"""Log sacred experiment data to W&B.
Args:
Accepts all the arguments accepted by wandb.init().
name — A display name for this run... | 120 | 5,780 |
bazel | src/test/py/bazel/genrule_test.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... | 204 | 6,503 |
onnxruntime | onnxruntime/core/providers/vsinpu/patches/test_scripts/compare_cosine_sim.py | .py | import sys
import numpy as np
from numpy.linalg import norm
def read_values(filename):
with open(filename) as file:
values = np.array([float(line.strip()) for line in file])
return values
def cosine_similarity(vec1, vec2):
return np.dot(vec1, vec2) / (norm(vec1) * norm(vec2))
if __name__ == "... | 30 | 650 |
eve | tests/__init__.py | .py | # -*- coding: utf-8 -*-
import os
import random
import string
import unittest
from datetime import datetime, timedelta, timezone
import simplejson as json
from bson import ObjectId
from pymongo import MongoClient
import eve
from eve import ETAG, ISSUES
from eve.methods.common import field_definition
from .test_setti... | 647 | 22,402 |
cvxpy | cvxpy/tests/nlp_tests/test_problem.py | .py | """
Copyright, 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, software
... | 74 | 2,694 |
deap | deap/tools/emo.py | .py | import bisect
from collections import defaultdict, namedtuple
from itertools import chain
import math
from operator import attrgetter, itemgetter
import random
import numpy
######################################
# Non-Dominated Sorting (NSGA-II) #
######################################
def selNSGA2(individuals, ... | 863 | 33,160 |
pyro | tests/perf/test_benchmark.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import argparse
import cProfile
import os
import re
from collections import namedtuple
import pytest
import torch
import pyro
import pyro.contrib.gp as gp
import pyro.distributions as dist
import pyro.optim as optim
from pyro.dis... | 209 | 6,793 |
wandb | wandb/apis/_generated/delete_api_key.py | .py | # Generated by ariadne-codegen
# Source: tools/graphql_codegen/api/
from __future__ import annotations
from wandb._pydantic import GQLResult
class DeleteApiKey(GQLResult):
result: DeleteApiKeyResult | None
class DeleteApiKeyResult(GQLResult):
success: bool | None
DeleteApiKey.model_rebuild()
| 18 | 309 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_partial_sum.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# partial_sum paddle model generator
#
import numpy as np
import os
from save_model import saveModel
import paddle
import sys
def _get_framework_pb2():
try:
from paddle.fluid.proto import framework_pb2
return fram... | 113 | 3,419 |
cvxpy | cvxpy/reductions/complex2real/canonicalizers/constant_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... | 28 | 912 |
pyomo | examples/dae/simulator_dae_multindex_example.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 124 | 3,632 |
openvino | tools/commit_slider/utils/subscription.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from utils.map_builder import buildMap
from utils.e2e_preparator import buildWheelMap
class SubscriptionManager():
def __init__(self, cfg) -> None:
self.cfg = cfg
def apply(self):
for sub in self.cfg["subscript... | 41 | 1,366 |
beam | sdks/python/apache_beam/utils/byte_limited_queue.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... | 205 | 6,630 |
jupyterlab | jupyterlab/tests/mock_packages/service-manager-extension/mock_service_manager_package.py | .py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import os.path as osp
HERE = osp.abspath(osp.dirname(__file__))
with open(osp.join(HERE, "package.json")) as fid:
data = json.load(fid)
def _jupyter_labextension_paths():
return [{"src": data["j... | 15 | 383 |
saleor | saleor/graphql/shipping/tests/mutations/test_shipping_price_update.py | .py | import json
from unittest import mock
import graphene
import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from .....core.utils.json_serializer import CustomJsonEncoder
from .....shipping.error_codes import ShippingErrorCode
from .....tests.utils import dummy_editorjs
f... | 502 | 17,197 |
gunicorn | examples/slowclient.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
import time
def app(environ, start_response):
"""Application which cooperatively pauses 10 seconds before responding"""
data = b'Hello, World!\n'
status = '200 OK'
response_headers = [
... | 22 | 582 |
beam | sdks/python/apache_beam/yaml/test_utils/__init__.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... | 19 | 836 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_squeeze.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# squeeze paddle model generator
#
import numpy as np
from save_model import saveModel
import paddle
import sys
data_type = 'float32'
def squeeze(name : str, x, axes : list):
paddle.enable_static()
with paddle.static.program... | 44 | 1,299 |
django-cms | cms/forms/widgets.py | .py | from django.contrib.auth import get_permission_codename
from django.contrib.sites.models import Site
from django.forms.widgets import MultiWidget, Select, TextInput
from django.templatetags.static import static
from django.urls import NoReverseMatch, reverse_lazy
from django.utils.encoding import force_str
from django.... | 250 | 9,512 |
readthedocs.org | readthedocs/subscriptions/constants.py | .py | """Constants for subscriptions."""
from django.utils.translation import gettext_lazy as _
# Days after the subscription has ended to disable the organization
DISABLE_AFTER_DAYS = 30
TYPE_CNAME = "cname"
TYPE_CDN = "cdn"
TYPE_SSL = "ssl"
TYPE_SUPPORT = "support"
TYPE_PRIVATE_DOCS = "private_docs"
TYPE_EMBED_API = "... | 43 | 1,418 |
saleor | saleor/order/delivery_context.py | .py | import logging
from collections.abc import Iterable
from typing import TYPE_CHECKING, Union
from django.conf import settings
from promise import Promise
from ..shipping.interface import ExcludedShippingMethod, ShippingMethodData
from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
from ..shippin... | 136 | 4,456 |
coremltools | coremltools/converters/mil/frontend/tensorflow/converter.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 import _logger as logger
from coremltools.converters._profile_utils import _profile
... | 526 | 23,778 |
astropy | astropy/coordinates/sites.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Currently the only site accessible without internet access is the Royal
Greenwich Observatory, as an example (and for testing purposes). In future
releases, a canonical set of sites may be bundled into astropy for when the
online registry is unavailab... | 126 | 4,514 |
beam | sdks/python/apache_beam/examples/cookbook/bigquery_schema.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... | 134 | 4,478 |
beam | sdks/python/apache_beam/internal/test_data/module_with_default_argument.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... | 25 | 964 |
astropy | astropy/modeling/tests/test_spline.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Tests for spline models and fitters"""
import unittest.mock as mk
import numpy as np
import pytest
from numpy.testing import assert_allclose
from astropy.modeling.core import FittableModel, ModelDefinitionError
from astropy.modeling.fitting import (... | 1,556 | 53,658 |
wagtail | wagtail/models/reference_index.py | .py | import uuid
from itertools import groupby
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRel
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import FieldDoesNotExist
from django.db import connection, models
from django.db.models import CharField, Count, ... | 908 | 36,336 |
mlflow | mlflow/gemini/genai_semconv_converter.py | .py | import json
from typing import Any
from mlflow.tracing.constant import GenAiSemconvKey
from mlflow.tracing.export.genai_semconv.converter import GenAiSemconvConverter
class GeminiConverter(GenAiSemconvConverter):
def convert_inputs(self, inputs: dict[str, Any]) -> list[dict[str, Any]] | None:
contents = ... | 127 | 4,972 |
flit | tests/test_wheel.py | .py | import configparser
import csv
import io
import os
import stat
from pathlib import Path
import tempfile
from unittest import skipIf
import zipfile
import pytest
from testpath import assert_isfile, assert_isdir, assert_not_path_exists
from flit.wheel import WheelBuilder, make_wheel_in
from flit.config import ConfigErr... | 255 | 9,669 |
pyomo | pyomo/core/tests/unit/test_lp_dual.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... | 443 | 16,064 |
saleor | saleor/tests/e2e/checkout/test_unlogged_customer_should_not_be_able_to_order_product_quantity_greater_than_stock.py | .py | import pytest
from ..product.utils import (
create_category,
create_product,
create_product_channel_listing,
create_product_type,
create_product_variant_channel_listing,
raw_create_product_variant,
)
from ..shop.utils.preparing_shop import prepare_default_shop
from ..utils import assign_permiss... | 122 | 3,076 |
omegaconf | tests/interpolation/built_in_resolvers/test_oc_env.py | .py | import re
from typing import Any, Optional
from pytest import mark, param, raises
from omegaconf import OmegaConf
from omegaconf._utils import _ensure_container
from omegaconf.errors import InterpolationResolutionError
class TestEnvInterpolation:
@mark.parametrize(
("cfg", "env_name", "env_val", "key", ... | 115 | 3,033 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.