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 |
|---|---|---|---|---|---|
onnxruntime | tools/ci_build/github/apple/build_settings_utils.py | .py | from __future__ import annotations
import json
import pathlib
import typing
_DEFAULT_BUILD_SYSROOT_ARCHS = {
"iphoneos": ["arm64"],
"iphonesimulator": ["arm64", "x86_64"],
}
def parse_build_settings_file(build_settings_file: pathlib.Path) -> dict[str, typing.Any]:
"""
Parses the provided build setti... | 82 | 2,734 |
textual | src/textual/logging.py | .py | """
A Textual Logging handler.
If there is an active Textual app, then log messages will go via the app (and logged via textual console).
If there is *no* active app, then log messages will go to stderr or stdout, depending on configuration.
"""
import sys
from logging import Handler, LogRecord
from textual._contex... | 41 | 1,187 |
mlflow | mlflow/spark/autologging.py | .py | import concurrent.futures
import logging
import sys
import threading
import uuid
from py4j.java_gateway import CallbackServerParameters
from mlflow import MlflowClient
from mlflow.exceptions import MlflowException
from mlflow.spark import FLAVOR_NAME
from mlflow.tracking.context.abstract_context import RunContextProv... | 301 | 11,603 |
saleor | saleor/graphql/order/tests/queries/test_order_by_token.py | .py | import graphene
from .....core.anonymize import obfuscate_email
from .....order.models import Order
from ....tests.utils import assert_no_permission, get_graphql_content
from ..utils import assert_order_and_payment_ids
ORDER_BY_TOKEN_QUERY = """
query OrderByToken($token: UUID!) {
orderByToken(token: $tok... | 688 | 22,053 |
mlflow | mlflow/store/model_registry/base_rest_store.py | .py | from abc import ABCMeta, abstractmethod
from mlflow.store.model_registry.abstract_store import AbstractStore
from mlflow.utils.rest_utils import (
call_endpoint,
call_endpoints,
)
class BaseRestStore(AbstractStore):
"""
Base class client for a remote model registry server accessed via REST API calls
... | 45 | 1,341 |
probability | tensorflow_probability/examples/models/bayesian_resnet.py | .py | # Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 129 | 4,259 |
pyro | pyro/distributions/kl.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import math
from torch.distributions import (
Independent,
MultivariateNormal,
Normal,
kl_divergence,
register_kl,
)
from pyro.distributions.delta import Delta
from pyro.distributions.distribution import Distr... | 57 | 1,661 |
conda | tests/cli/test_main.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from conda.base.context import context
from conda.cli.main import main, main_sourced, main_subshell
from conda.common.compat import on_win
if TYPE_CHECKING:
... | 157 | 4,774 |
kombu | t/unit/test_simple.py | .py | from __future__ import annotations
from unittest.mock import Mock
import pytest
from kombu import Connection, Exchange, Queue
from kombu.exceptions import ContentDisallowed
class SimpleBase:
def Queue(self, name, *args, **kwargs):
q = name
if not isinstance(q, Queue):
q = self.__cl... | 207 | 6,831 |
attrs | src/attr/_funcs.py | .py | # SPDX-License-Identifier: MIT
from ._compat import get_generic_base
from ._make import _OBJ_SETATTR, NOTHING, fields
from .exceptions import AttrsAttributeNotFoundError
_ATOMIC_TYPES = frozenset(
{
type(None),
bool,
int,
float,
str,
complex,
bytes,
... | 496 | 16,346 |
saleor | saleor/webhook/observability/utils.py | .py | import datetime
import functools
import logging
from collections.abc import Callable, Generator
from contextlib import contextmanager
from dataclasses import dataclass
from functools import partial
from time import monotonic
from typing import TYPE_CHECKING
from asgiref.local import Local
from django.conf import setti... | 209 | 6,977 |
httpie | tests/test_downloads.py | .py | import os
import tempfile
import time
import requests
from unittest import mock
from urllib.request import urlopen
import pytest
from requests.structures import CaseInsensitiveDict
from httpie.downloads import (
parse_content_range, filename_from_content_disposition, filename_from_url,
get_unique_filename, Co... | 262 | 9,735 |
readthedocs.org | readthedocs/proxito/exceptions.py | .py | from django.http import Http404
from django.utils.translation import pgettext_lazy
_not_found_subject_translation_context = (
"Names a subject that was not found in a 404 error message. Used like "
"'The {{ not_found_subject }} you are looking for at <code>{{ path_not_found }}</code> "
"was not found.'"
)... | 167 | 5,599 |
saleor | saleor/webhook/circuit_breaker/breaker_board.py | .py | import logging
import time
from typing import TYPE_CHECKING
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.module_loading import import_string
from promise import Promise
from ...core.telemetry import (
MetricType,
Scope,
Unit,
meter,
sal... | 247 | 9,727 |
saleor | saleor/order/webhooks/order_calculate_taxes.py | .py | import json
import logging
from collections.abc import Iterable
from typing import TYPE_CHECKING, Union
import graphene
from django.db.models import QuerySet
from promise import Promise
from ...app.models import App
from ...core.db.connection import allow_writer
from ...core.prices import quantize_price, quantize_pri... | 158 | 5,235 |
sqlmap | tamper/unionalltounion.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.enums import PRIORITY
__priority__ = PRIORITY.HIGHEST
def dependencies():
pass
def tamper(payload, **kwargs):
"""
Replaces instances of UNI... | 34 | 707 |
flit | prepare_license_list.py | .py | # Call with path to SPDX license-list-data repo, cloned from:
# https://github.com/spdx/license-list-data
import json
import pprint
import sys
from pathlib import Path
list_data_repo = Path(sys.argv[1])
with (list_data_repo / 'json' / 'licenses.json').open('rb') as f:
licenses_json = json.load(f)
condensed = {... | 24 | 677 |
probability | tensorflow_probability/python/bijectors/transform_diagonal.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... | 112 | 3,931 |
probability | tensorflow_probability/python/mcmc/replica_exchange_mc.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... | 1,134 | 46,222 |
mlflow | mlflow/tracing/distributed/__init__.py | .py | import logging
from contextlib import contextmanager
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
import mlflow
from mlflow.entities.span import LiveSpan
from mlflow.telemetry.events import TracingContextPropagation
from mlflow.telemetry.track import record_usage_event
from m... | 191 | 7,442 |
beam | sdks/python/apache_beam/yaml/yaml_transform_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,606 | 53,678 |
sphinx | sphinx/util/logging.py | .py | """Logging utility functions for Sphinx."""
from __future__ import annotations
import logging
import logging.handlers
import os.path
from collections import defaultdict
from contextlib import contextmanager, nullcontext
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.utils import get_source... | 647 | 19,746 |
astropy | astropy/table/tests/test_showtable.py | .py | import os
import re
import numpy as np
import pytest
from astropy.table.scripts import showtable
from astropy.units import UnitsWarning
ROOT = os.path.abspath(os.path.dirname(__file__))
ASCII_ROOT = os.path.join(ROOT, "..", "..", "io", "ascii", "tests")
FITS_ROOT = os.path.join(ROOT, "..", "..", "io", "fits", "tests... | 217 | 6,395 |
pymc | pymc/smc/kernels.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... | 736 | 28,068 |
rq | tests/test_utils.py | .py | import datetime
import os
import sys
from unittest.mock import Mock, patch
from redis import Redis
from rq.exceptions import TimeoutFormatError
from rq.job import Job
from rq.queue import Queue
from rq.utils import (
Platform,
as_text,
backend_class,
ceildiv,
decode_redis_hash,
ensure_job_list... | 413 | 17,148 |
saleor | saleor/graphql/account/tests/mutations/staff/test_address_update.py | .py | from unittest.mock import patch
import graphene
from freezegun import freeze_time
from ......webhook.event_types import WebhookEventAsyncType
from .....tests.utils import assert_no_permission, get_graphql_content
from ..utils import generate_address_webhook_call_args
ADDRESS_UPDATE_MUTATION = """
mutation update... | 208 | 6,557 |
mlflow | mlflow/claude_code/__init__.py | .py | """Claude Code integration for MLflow.
This module provides automatic tracing of Claude Code conversations to MLflow.
Usage:
mlflow autolog claude [directory] [options]
After setup, use the regular 'claude' command and traces will be automatically captured.
To enable tracing for the Claude Agent SDK, use `mlflo... | 27 | 644 |
wandb | tests/unit_tests/test_analytics/sentry_relay.py | .py | from __future__ import annotations
import gzip
import socket
import threading
import time
from typing import Any
import flask
import requests
from flask import request
from sentry_sdk.envelope import Envelope
class SentryResponse:
def __init__(
self,
message: str | None,
project_id: str,... | 148 | 4,308 |
probability | tensorflow_probability/python/sts/components/autoregressive_integrated_moving_average.py | .py | # Copyright 2021 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 392 | 18,100 |
mlflow | mlflow/genai/agent_server/__init__.py | .py | from mlflow.genai.agent_server.server import (
AgentServer,
get_invoke_function,
get_stream_function,
invoke,
stream,
)
from mlflow.genai.agent_server.utils import (
get_request_headers,
set_request_headers,
setup_mlflow_git_based_version_tracking,
)
__all__ = [
"set_request_headers... | 24 | 500 |
wandb | tests/system_tests/test_core/test_offline_sync.py | .py | import unittest.mock
import pytest
from wandb.cli import cli
from wandb.sdk.lib.runid import generate_id
@pytest.mark.flaky
def test_sync_with_tensorboard(wandb_backend_spy, runner, copy_asset):
run_id = generate_id()
with unittest.mock.patch.dict("os.environ", {"WANDB_MODE": "offline"}):
tf_event = ... | 22 | 776 |
pyro | tests/distributions/test_one_two_matching.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import logging
import math
import pytest
import torch
import pyro.distributions as dist
from tests.common import assert_close, assert_equal, xfail_if_not_implemented
BP_ITERS = 50
def _hash(value):
return tuple(value.tolist())... | 269 | 9,925 |
toolz | toolz/itertoolz.py | .py | import itertools
import heapq
import collections
import operator
from functools import partial
from itertools import filterfalse, zip_longest
from collections.abc import Sequence
from toolz.utils import no_default
__all__ = ('remove', 'accumulate', 'groupby', 'merge_sorted', 'interleave',
'unique', 'isiter... | 1,058 | 27,697 |
onnxruntime | onnxruntime/test/python/quantization/test_op_flatten.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.
# ---------------------------------------------------------------... | 174 | 6,458 |
mlflow | tests/sentence_transformers/test_sentence_transformers_model_export.py | .py | import json
import os
from unittest import mock
import numpy as np
import pandas as pd
import pytest
import sentence_transformers
import yaml
from packaging.version import Version
from pyspark.sql import SparkSession
from pyspark.sql.types import ArrayType, DoubleType
from sentence_transformers import SentenceTransfor... | 599 | 22,983 |
hydra | tests/test_apps/passes_callable_class_to_hydra_main/my_app.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from omegaconf import DictConfig
import hydra
from hydra.core.hydra_config import HydraConfig
class MyCallable:
def __init__(self, state: int = 123) -> None:
self._state = state
def __call__(self, cfg: DictConfig) -> None:
... | 22 | 488 |
saleor | saleor/thumbnail/tests/test_validators.py | .py | from io import BytesIO
from unittest.mock import Mock
import pytest
from django.core.exceptions import ValidationError
from PIL import Image, UnidentifiedImageError
from .. import MIN_ICON_SIZE
from ..validators import (
validate_icon_image,
validate_image_exif,
validate_image_format,
validate_image_s... | 80 | 2,370 |
bazel | tools/ctexplain/util.py | .py | # Copyright 2020 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... | 53 | 1,642 |
wagtail | wagtail/admin/widgets/switch.py | .py | from django.forms import widgets
class SwitchInput(widgets.CheckboxInput):
template_name = "wagtailadmin/widgets/switch.html"
| 6 | 132 |
luigi | luigi/contrib/external_program.py | .py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2016 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... | 295 | 11,159 |
black | tests/data/cases/remove_with_brackets.py | .py | with (open("bla.txt")):
pass
with (open("bla.txt")), (open("bla.txt")):
pass
with (open("bla.txt") as f):
pass
# Remove brackets within alias expression
with (open("bla.txt")) as f:
pass
# Remove brackets around one-line context managers
with (open("bla.txt") as f, (open("x"))):
pass
with ((ope... | 146 | 2,869 |
coremltools | coremltools/test/sklearn_tests/test_composite_pipelines.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
import unittest
import pandas as pd
from packaging.version import Version
from ..utils import load_bos... | 86 | 3,033 |
mlflow | mlflow/genai/utils/prompts/available_tools_extraction.py | .py | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from mlflow.types.llm import ChatMessage
AVAILABLE_TOOLS_EXTRACTION_SYSTEM_PROMPT = """You are an expert in analyzing agent execution traces.
Your task is to examine an MLflow trace and identify all tools or functions that were
available to the LLM, not which too... | 105 | 3,960 |
cvxpy | cvxpy/tests/test_nlp_namespace.py | .py | """Tests for cp.nlp namespace."""
import cvxpy as cp
from cvxpy.atoms.elementwise.hyperbolic import tanh
from cvxpy.atoms.elementwise.normcdf import normcdf
from cvxpy.atoms.elementwise.trig import cos, sin
class TestNLPNamespace:
def test_nlp_namespace_accessible(self):
"""Test that cp.nlp submodule is a... | 44 | 1,532 |
readthedocs.org | readthedocs/wsgi.py | .py | """WSGI application helper."""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "readthedocs.settings.docker_compose")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.co... | 14 | 402 |
wandb | wandb/sdk/launch/runner/abstract.py | .py | """Implementation of the abstract runner class.
This class defines the interface that the W&B launch runner uses to manage the lifecycle
of runs launched in different environments (e.g. runs launched locally or in a cluster).
"""
from __future__ import annotations
import logging
import os
import shutil
import sys
fr... | 166 | 4,820 |
sphinx | sphinx/ext/autodoc/_event_listeners.py | .py | """Some useful event listener factories for autodoc-process-docstring."""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Sequence
from typing import Any, Protocol
from sphinx.application import Sphinx
from sphinx.ext.autodo... | 170 | 5,009 |
saleor | saleor/graphql/tax/filters.py | .py | from django.db.models import Exists, OuterRef
from ...tax import models
from ..account.enums import CountryCodeEnum
from ..core.doc_category import DOC_CATEGORY_TAXES
from ..core.filters import (
FilterInputObjectType,
GlobalIDMultipleChoiceFilter,
ListObjectTypeFilter,
MetadataFilterBase,
)
from ..uti... | 54 | 1,491 |
saleor | saleor/tests/e2e/promotions/test_staff_can_create_promotion_for_collections.py | .py | import pytest
from ....product.tasks import recalculate_discounted_price_for_products_task
from ..product.utils import (
create_category,
create_collection,
create_collection_channel_listing,
create_product,
create_product_channel_listing,
create_product_type,
create_product_variant,
cr... | 139 | 4,279 |
django-cms | menus/utils.py | .py | from django.conf import settings
from django.urls import NoReverseMatch, Resolver404, resolve, reverse
from cms.toolbar.utils import get_object_edit_url, get_object_for_language, get_object_preview_url
from cms.utils import get_language_from_request
from cms.utils.i18n import (
force_language,
get_default_lang... | 322 | 11,075 |
flit | flit_core/flit_core/versionno.py | .py | """Normalise version number according to PEP 440"""
import logging
import os
import re
log = logging.getLogger(__name__)
# Regex below from packaging, via PEP 440. BSD License:
# Copyright (c) Donald Stufft and individual contributors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with... | 126 | 4,711 |
hatch | src/hatch/publish/plugin/interface.py | .py | from __future__ import annotations
from abc import ABC, abstractmethod
class PublisherInterface(ABC):
"""
Example usage:
```python tab="plugin.py"
from hatch.publish.plugin.interface import PublisherInterface
class SpecialPublisher(PublisherInterface):
PLUGIN_NAME = 'specia... | 116 | 3,353 |
luigi | test/contrib/external_daily_snapshot_test.py | .py | # Copyright (c) 2013 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 or agreed to in writing, s... | 51 | 2,059 |
saleor | saleor/graphql/invoice/dataloaders.py | .py | from collections import defaultdict
from ...invoice.models import Invoice
from ..core.dataloaders import DataLoader
class InvoicesByOrderIdLoader(DataLoader[int, list[Invoice]]):
context_key = "invoices_by_order_id"
def batch_load(self, keys):
invoices = (
Invoice.objects.using(self.data... | 20 | 648 |
openvino | src/bindings/python/tests/test_graph/test_inverse.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import openvino.opset14 as ops
from openvino import PartialShape, Type
@pytest.mark.parametrize(
("input_shape", "adjoint", "expected_output_shape"),
[
([4, 4], ... | 68 | 2,305 |
beam | sdks/python/apache_beam/io/avroio.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... | 796 | 28,982 |
astropy | astropy/modeling/statistic.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Statistic functions used in `~astropy.modeling.fitting`.
"""
# pylint: disable=invalid-name
import numpy as np
__all__ = ["leastsquare", "leastsquare_1d", "leastsquare_2d", "leastsquare_3d"]
def leastsquare(measured_vals, updated_model, weights, *... | 174 | 5,416 |
readthedocs.org | readthedocs/domains/apps.py | .py | """Custom domains application."""
from django.apps import AppConfig
class DomainsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "readthedocs.domains"
def ready(self):
import readthedocs.domains.tasks # noqa
| 12 | 264 |
jupytext | tests/functional/simple_notebooks/test_read_simple_scheme.py | .py | import jupytext
from jupytext.compare import compare
def test_read_simple_file(
script=""";; ---
;; title: Simple file
;; ---
;; Here we have some text
;; And below we have some code
(define a 35)
""",
):
for file_extension in ("ss", "scm"):
nb = jupytext.reads(script, file_extension)
assert... | 28 | 784 |
coremltools | coremltools/optimize/torch/layerwise_compression/layerwise_compressor.py | .py | # Copyright (c) 2024, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
# Original implementation from https://github.com/IST-DASLab/sparsegpt
# Copyright 2023 IST Austria D... | 430 | 18,146 |
openvino | src/bindings/python/tests/test_transformations/test_matcher_pass.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino import opset8
from openvino.passes import Manager, Matcher, MatcherPass, WrapType
from openvino.utils import replace_node
from tests.test_transformations.utils.utils import count_ops, get_relu_model,... | 58 | 1,841 |
voila | voila/request_info_handler.py | .py | import logging
from typing import Dict
from tornado.websocket import WebSocketHandler
class RequestInfoSocketHandler(WebSocketHandler):
"""A websocket handler used to provide the request info
associated with kernel ids in preheat kernel mode.
Class variables
---------------
- _waiters : A dictio... | 64 | 2,215 |
beam | sdks/python/apache_beam/internal/http_client.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 | 2,451 |
scikit-bio | skbio/io/format/tests/test_genbank.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.
# --------------------------------------------... | 408 | 15,587 |
rq | tests/test_cron.py | .py | import json
import os
import signal
import socket
import tempfile
import time
from datetime import datetime, timedelta, timezone
from multiprocessing import Process
from typing import cast
from unittest.mock import patch
from redis import Redis
from rq import Queue, cron, utils
from rq.connections import get_connecti... | 943 | 42,191 |
qutip | doc/guide/scripts/correlation_ex1.py | .py | import numpy as np
import matplotlib.pyplot as plt
import qutip
times = np.linspace(0, 10, 200)
a = qutip.destroy(10)
x = a.dag() + a
H = a.dag() * a
corr1 = qutip.correlation_2op_1t(H, None, times, [np.sqrt(0.5) * a], x, x)
corr2 = qutip.correlation_2op_1t(H, None, times, [np.sqrt(1.0) * a], x, x)
corr3 = qutip.corr... | 18 | 542 |
wagtail | wagtail/admin/datetimepicker.py | .py | # Adapted from https://djangosnippets.org/snippets/10563/
# original author bernd-wechner
def to_datetimepicker_format(python_format_string):
"""
Given a python datetime format string, attempts to convert it to
the nearest PHP datetime format string possible.
"""
python2PHP = {
"%a": "D",
... | 39 | 880 |
rq | rq/intermediate_queue.py | .py | from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING
from redis import Redis
from rq.utils import now
if TYPE_CHECKING:
from .queue import Queue
from .worker import BaseWorker
class IntermediateQueue:
def __init__(self, queue_key: str, ... | 120 | 3,845 |
beam | sdks/python/apache_beam/testing/benchmarks/inference/pytorch_image_object_detection_benchmarks.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... | 43 | 1,616 |
beam | sdks/python/apache_beam/io/gcp/tests/pubsub_matcher_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... | 195 | 7,870 |
hydra | tests/test_hydra_cli_errors.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from pathlib import Path
from typing import Any, List
from pytest import mark, param
from hydra.test_utils.test_utils import (
chdir_hydra_root,
normalize_newlines,
run_with_error,
)
chdir_hydra_root()
@mark.parametrize(
"overri... | 113 | 3,703 |
coremltools | coremltools/converters/mil/mil/ops/tests/iOS15/__init__.py | .py | # Copyright (c) 2023, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import coremltools as ct
from coremltools.converters.mil.testing_reqs import backends_internal, clean... | 10 | 399 |
onnx | onnx/reference/ops/op_celu.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import numpy as np
from onnx.reference.op_run import OpRun
def _vcelu1(x: np.ndarray, alpha: float = 1.0) -> np.ndarray:
positive_input = np.maximum(0, x)
negative_input = np.minimum(0, alpha ... | 20 | 498 |
biopython | Bio/SeqIO/SffIO.py | .py | # Copyright 2009-2020 by Peter Cock. All rights reserved.
# Based on code contributed and copyright 2009 by Jose Blanca (COMAV-UPV).
#
# 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.
"""Bio.SeqIO sup... | 1,480 | 55,441 |
wagtail | wagtail/permission_policies/sites.py | .py | from django.contrib.auth import get_user_model
from django.db.models import Q
from wagtail.models import GroupSitePermission, Site
from .base import BaseDjangoAuthPermissionPolicy
class SitePermissionPolicy(BaseDjangoAuthPermissionPolicy):
"""
A permission policy for objects that are associated with site re... | 198 | 7,730 |
mlflow | mlflow/genai/utils/message_utils.py | .py | from __future__ import annotations
from typing import Any
from pydantic import BaseModel
_JSON_SCHEMA_MAP_KEYWORDS = {
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
"patternProperties",
"properties",
}
def serialize_messages_to_prompts(
messages: list[Any],
) -> tuple[str,... | 133 | 4,266 |
wandb | wandb/integration/xgboost/__init__.py | .py | """W&B callback for xgboost.
Simple callback to get logging for each tree
Use the `wandb_callback` to add `wandb` logging to any `XGboost` model. However, it will
be deprecated in favor of WandbCallback. Use it instead for more features.
"""
from .xgboost import WandbCallback, wandb_callback
__all__ = ["wandb_callb... | 12 | 343 |
python-prompt-toolkit | src/prompt_toolkit/contrib/regular_languages/completion.py | .py | """
Completer for a regular grammar.
"""
from __future__ import annotations
from collections.abc import Iterable
from prompt_toolkit.completion import CompleteEvent, Completer, Completion
from prompt_toolkit.document import Document
from .compiler import Match, _CompiledGrammar
__all__ = [
"GrammarCompleter",
... | 101 | 3,477 |
textual | docs/examples/app/simple02.py | .py | from textual.app import App
class MyApp(App):
pass
if __name__ == "__main__":
app = MyApp()
app.run()
| 11 | 118 |
onnx | tests/python/numpy_helper_test.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import numpy as np
import pytest
import onnx
import onnx.reference
from onnx import helper, numpy_helper
class TestNumpyHelper:
def _test_numpy_helper_float_type(self, dtype: np.number) -> None:
... | 325 | 12,886 |
pyomo | pyomo/common/flags.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... | 144 | 4,571 |
metrics | tests/unittests/retrieval/test_hit_rate.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... | 192 | 7,121 |
textual | docs/examples/styles/hatch.py | .py | from textual.app import App, ComposeResult
from textual.containers import Horizontal, Vertical
from textual.widgets import Static
HATCHES = ("cross", "horizontal", "custom", "left", "right")
class HatchApp(App):
CSS_PATH = "hatch.tcss"
def compose(self) -> ComposeResult:
with Horizontal():
... | 23 | 577 |
onnxruntime | onnxruntime/core/flatbuffers/ort_flatbuffers_py/fbs/Model.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 Model(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffer... | 224 | 7,440 |
beam | sdks/python/apache_beam/examples/snippets/transforms/other/window.py | .py | # coding=utf-8
#
# 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");... | 84 | 2,556 |
gunicorn | tests/requests/valid/rfc9112_target_authority_connect_01.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
# RFC 9112 section 3.2.3: authority-form, only valid with CONNECT.
request = {
"method": "CONNECT",
"uri": uri("example.com:443"),
"version": (1, 1),
"headers": [
("HOST", "example.com:443")... | 15 | 348 |
openvino | tests/layer_tests/pytorch_tests/test_adaptive_avg_pool.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
from pytorch_layer_test_class import PytorchLayerTest
@pytest.mark.parametrize('input_tensor', [[1, 2, 8, 9, 10], [2, 8, 9, 10]])
@pytest.mark.parametrize('output_size', [[5, 7, 9], 7])
class TestAdaptiveAvg... | 97 | 3,528 |
saleor | saleor/graphql/csv/mutations/export_gift_cards.py | .py | import graphene
from ....csv import models as csv_models
from ....csv.events import export_started_event
from ....csv.tasks import export_gift_cards_task
from ....permission.enums import GiftcardPermissions
from ....webhook.event_types import WebhookEventAsyncType
from ...app.dataloaders import get_app_promise
from ..... | 76 | 2,689 |
onnxruntime | onnxruntime/test/testdata/input_propagated_to_output.py | .py | """
Run this script to recreate the original onnx model.
Example usage:
python input_propagated_to_output.py input_propagated_to_output.onnx
"""
import sys
import numpy as np
import onnx
def order_repeated_field(repeated_proto, key_name, order):
order = list(order)
repeated_proto.sort(key=lambda x: order.in... | 114 | 4,166 |
mlflow | tests/ag2/test_ag2_autolog.py | .py | import contextlib
import time
from unittest.mock import patch
import pytest
from autogen import ConversableAgent, GroupChat, GroupChatManager, UserProxyAgent, io
from openai import APIConnectionError
from openai.types.chat import ChatCompletion
from openai.types.chat.chat_completion import ChatCompletionMessage, Choic... | 405 | 14,047 |
textual | src/textual/widgets/_collapsible.py | .py | from __future__ import annotations
from textual import events
from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Container
from textual.content import Content, ContentText
from textual.css.query import NoMatches
from textual.message import Message
from textual.reac... | 251 | 7,775 |
onnxruntime | onnxruntime/python/tools/transformers/__init__.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import os
import sys
sys.path.append(os.path.dirname(__file__))
| 9 | 313 |
beam | sdks/python/apache_beam/examples/snippets/transforms/elementwise/mltransform_test.py | .py | # coding=utf-8
#
# 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");... | 92 | 3,417 |
coremltools | deps/pybind11/pybind11/setup_helpers.py | .py | """
This module provides helpers for C++11+ projects using pybind11.
LICENSE:
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>, All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions... | 501 | 17,490 |
saleor | saleor/product/tests/test_product_minimal_variant_price.py | .py | import datetime
from decimal import Decimal
from unittest.mock import patch
import graphene
import pytest
from django.core.management import call_command
from prices import Money
from ...discount import RewardValueType
from ...discount.models import Promotion, PromotionRule
from ...product.interface import VariantDis... | 807 | 29,713 |
onnxruntime | onnxruntime/test/python/transformers/test_moe_cuda.py | .py | # --------------------------------------------------------------------------
# Copyright 2020 The HuggingFace Inc. 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/l... | 1,910 | 69,624 |
wagtail | wagtail/contrib/routable_page/models.py | .py | import logging
from functools import partial
from django.core.checks import Warning
from django.http import Http404
from django.template.response import TemplateResponse
from django.urls import URLResolver
from django.urls import path as path_func
from django.urls import re_path as re_path_func
from django.urls.resolv... | 229 | 7,605 |
pyro | tests/infer/test_sampling.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
from unittest import TestCase
import pytest
import torch
import pyro
import pyro.infer
from pyro.distributions import Bernoulli, Normal
from pyro.infer import EmpiricalMarginal
from tests.common import assert_equal
class HMMSam... | 104 | 3,216 |
onnxruntime | onnxruntime/python/tools/transformers/fusion_shape.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
from logging import getLogger
from fusion_base import Fusion
from fusi... | 110 | 3,654 |
beam | sdks/python/apache_beam/yaml/yaml_testing_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... | 402 | 11,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.