id int64 0 6k | code stringlengths 4k 8k | code_compressed listlengths 0 44 |
|---|---|---|
5,900 | # Copyright 2023 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " \"\"\"weight initial for conv layer\"\"\"\n weight = weight_variable()\n return nn.Conv2d(in_channels, out_channels,\n kernel_size=kernel_size, stride=stride, padding=padding,\n weight_init=weight, has_bias=False, pad_mode=\"valid\")",
"name": "co... |
5,901 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
impo... | [
{
"body": " test_slot = mock.Mock()\n register_func(test_slot)\n assert signal_func.call_count == 1",
"name": "check_second_func_called(self,PeriodicTablePresenterTest(unittest.TestCase):"
},
{
"body": " self.check_second_func_called(self.presenter.unregister_table_lclick... |
5,902 | # Copyright (c) 2022 Tulir Asokan
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from typing import Optional
import asyncio
import olm
from mautrix.errors import De... | [
{
"body": " if not isinstance(evt.content, EncryptedOlmEventContent):\n raise DecryptionError(\"unsupported event content class\")\n elif evt.content.algorithm != EncryptionAlgorithm.OLM_V1:\n raise DecryptionError(\"unsupported event encryption algorithm\")\n try:\n ... |
5,903 | # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | [
{
"body": " in_planes,\n out_planes,\n kernel_size=1,\n stride=1,\n padding=0):\n super(Conv_BN_ReLU, self).__init__()\n self.conv = nn.Conv2D(\n in_planes,\n out_planes,\n kernel_size=... |
5,904 | # SPDX-FileCopyrightText: 2023 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
from queue import Queue
import time
import speech_recognition as sr
class Listener:
def __init__(
self, api_key, energy_threshold=300, phrase_timeout=3.0, record_timeout=30
):
sel... | [
{
"body": " print(\"Start listening...\")\n self.phrase_complete = False\n start = time.monotonic()\n self._start_listening()\n if ready_callback:\n ready_callback()\n while (\n self.listener_handle and not self.speech_waiting()\n ) or not s... |
5,905 | import gzip
from datetime import timedelta
from typing import Any
import pytest
from django.utils import timezone
from freezegun.api import FrozenDateTimeFactory
from storages.backends.s3boto3 import S3Boto3Storage
from thunderstore.cache.storage import get_cache_storage
from thunderstore.community.factories import C... | [
{
"body": " community: Community,",
"name": "test_api_v1_package_cache_get_latest_for_community_without_community("
},
{
"body": " settings.DISABLE_TRANSACTION_CHECKS = True\n community_a = CommunityFactory()\n community_b = CommunityFactory()\n assert (\n APIV1PackageCache.get... |
5,906 | import numpy as np
import cantera as ct
from . import utilities
import math
import pytest
class TestFunc1(utilities.CanteraTest):
def test_function(self):
f = ct.Func1(np.sin)
self.assertNear(f(0), np.sin(0))
self.assertNear(f(0.1), np.sin(0.1))
self.assertNear(f(0.7), np.sin(0.7))... | [
{
"body": " self.factor = factor",
"name": "__init__(self,Multiplier:"
},
{
"body": " return self.factor * t",
"name": "__call__(self,Multiplier:"
},
{
"body": " raise ValueError('bad')",
"name": "METHOD_NAME(t):Multiplier:"
},
{
"body... |
5,907 | import os
import unittest
import dcs
from dcs.drawing.drawing import LineStyle, Rgba
from dcs.drawing.drawings import StandardLayer
from dcs.drawing.icon import StandardIcon
from dcs.drawing.polygon import Circle
from dcs.mapping import Point
from dcs.mission import Mission
class DrawingTests(unittest.TestCase):
... | [
{
"body": " m: Mission = dcs.mission.Mission()\n layer = m.drawings.get_layer(StandardLayer.Common)\n self.assertEqual(0, len(layer.objects))\n oblong = layer.add_oblong(\n Point(1000, 1000, m.terrain),\n Point(4000, 1000, m.terrain),\n 1000,\n ... |
5,908 | # Copyright 2019 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " check_filename(map_file)\n self.map_file = map_file\n check_filename(image_dir)\n self.image_dir = image_dir\n check_filename(destination)\n self.destination = destination\n if partition_number is not None:\n if not isinstance(partition_num... |
5,909 | ##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2023, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
import json
impor... | [
{
"body": " super().setUp()\n self.db_name = parent_node_dict[\"database\"][-1][\"db_name\"]\n schema_info = parent_node_dict[\"schema\"][-1]\n self.schema_id = schema_info[\"schema_id\"]\n self.schema_name = schema_info[\"schema_name\"]\n self.server_id = schema_info[\... |
5,910 | # """
# This file demonstrates writing tests using the unittest module. These will pass
# when you run "manage.py test".
# Replace this with more appropriate tests for your application.
# """
from django.test import TestCase
from django.contrib.gis.measure import D
# from nose.tools import istest
from nose.tools impo... | [
{
"body": " url = utils.build_relative_url('http://ex.co/', 'https://google.com/')\n assert_equal(url, 'https://google.com/')",
"name": "METHOD_NAME(self):TestBuildRelativeURL"
}
] |
5,911 | #!/usr/bin/env python
from collections import OrderedDict
from decimal import Decimal
from agate import Table, TableSet
from agate.aggregations import Count, MaxLength, Mean, Min, Sum
from agate.data_types import Number, Text
from agate.exceptions import DataTypeError
from agate.testcase import AgateTestCase
class ... | [
{
"body": " self.table1 = (\n ('a', 1),\n ('a', 3),\n ('b', 2)\n )\n self.table2 = (\n ('b', 0),\n ('a', 2),\n ('c', 5)\n )\n self.table3 = (\n ('a', 1),\n ('a', 2),\n ('c', 3)\n... |
5,912 | __author__ = "Nitin Kumar, Rick Sherman"
__credits__ = "Jeremy Schulman"
try:
import unittest2 as unittest
except ImportError:
import unittest
from nose.plugins.attrib import attr
from mock import patch, MagicMock
import os
from jnpr.junos import Device
from jnpr.junos.ofacts.swver import facts_software_versi... | [
{
"body": " if args[0] == \"show version all-members\":\n raise RpcError()",
"name": "raise_ex(*args):TestSwver(unittest.TestCase):"
},
{
"body": " if kwargs:\n device_params = kwargs[\"device_params\"]\n device_handler = make_device_handler(dev... |
5,913 | # SPDX-FileCopyrightText: 2020 Jeff Epler for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import random
import time
import board
import displayio
import framebufferio
import rgbmatrix
displayio.release_displays()
matrix = rgbmatrix.RGBMatrix(
width=64, height=32, bit_depth=3,
rgb_pins=[board.D6, bo... | [
{
"body": " return sorted(seq, key=lambda _: random.random())",
"name": "METHOD_NAME(seq):"
},
{
"body": " # Update each wheel for one time step\n if self.state == RUNNING:\n # Slowly lose speed when running, but go at least speed 64\n self.vel = max(self.vel *... |
5,914 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
from... | [
{
"body": " checkable.blockSignals(True)\n checkable.setChecked(should_be_checked)\n checkable.blockSignals(False)",
"name": "set_checked_without_signal(checkable,SummationSettingsWidget(QtWidgets.QWidget,"
},
{
"body": " super(SummationSettingsWidget, self).__init__(parent)\n ... |
5,915 | from math import isclose
import pytest
from ufo2ft.filters.transformations import TransformationsFilter
@pytest.fixture(
params=[
{
"capHeight": 700,
"xHeight": 500,
"glyphs": [
{"name": "space", "width": 500},
{
"na... | [
{
"body": " return request.param",
"name": "origin(request):TransformationsFilterTest:"
},
{
"body": " with pytest.raises(ValueError) as excinfo:\n TransformationsFilter(Origin=5)\n excinfo.match(r\"is not a valid (TransformationsFilter\\.)?Origin\")",
"name": "test_i... |
5,916 | """
Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any la... | [
{
"body": " BaseConsole.__init__(self)\n self.greeting = greeting + \" Shares\"\n self.prompt = self.greeting + \"> \"\n self.url = \"%sshares\" % BaseConsole.url",
"name": "__init__(self,SharesConsole(BaseConsole):"
},
{
"body": " snps = \"Display details of share... |
5,917 | ##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2023, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
import json
impor... | [
{
"body": " super().setUp()\n self.schema_data = parent_node_dict['schema'][-1]\n self.server_id = self.schema_data['server_id']\n self.db_id = self.schema_data['db_id']\n self.schema_name = self.schema_data['schema_name']\n self.schema_id = self.schema_data['schema_id'... |
5,918 | ##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2023, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
import re
import ... | [
{
"body": " self.client = client",
"name": "__init__(self,TestClient(testing.FlaskClient):"
},
{
"body": " \"Set the cookie on the Flask test client.\"\n server_name = current_app.config[\"SERVER_NAME\"] or \"localhost\"\n return self.client.set_cookie(\n serve... |
5,919 | import hail as hl
from .hgvs import hgvsp_from_consequence_amino_acids
from .vep import consequence_term_rank
OMIT_CONSEQUENCE_TERMS = hl.set(["upstream_gene_variant", "downstream_gene_variant"])
def METHOD_NAME(variants_path, transcripts_path, mane_transcripts_path=None):
ds = hl.read_table(variants_path)
... | [
{
"body": " ds = hl.read_table(variants_path)\n most_severe_consequence = ds.vep.most_severe_consequence\n transcript_consequences = ds.vep.transcript_consequences\n # Drop irrelevant consequences\n transcript_consequences = transcript_consequences.map(\n lambda c: c.annotate(\n ... |
5,920 | # -*- coding: utf-8 -*-
###
# (C) Copyright [2019] Hewlett Packard Enterprise Development LP
#
# 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
#... | [
{
"body": " super(SasLogicalInterconnects, self).__init__(connection, data)",
"name": "__init__(self,SasLogicalInterconnects(Resource):"
},
{
"body": " \"\"\"\n Gets a list of SAS Logical Interconnects based on optional sorting and filtering and constrained by start and\n ... |
5,921 | #!/usr/bin/env python
"""Random sequences and random evolution of sequences in a tree"""
import bisect
import numpy
def argpicks(freqs, random_series):
partition = numpy.add.accumulate(freqs)
assert abs(partition[-1] - 1.0) < 1e-6, (freqs, partition)
while True:
x = random_series.uniform(0.0, 1.... | [
{
"body": " random_series, motifs, parent_seq, site_cats, psubs, preserved_sites=()",
"name": "METHOD_NAME("
},
{
"body": " getRootRandomMotif = _randomMotifGenerator(random_series, motif_probs).__next__\n return [getRootRandomMotif() for i in range(sequence_length)]",
"name": "random_s... |
5,922 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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
#
# httpwww.apache.orglicensesLICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | [
{
"body": " with open(file_path, 'a+', encoding='utf-8') as file_out:\n file_out.write(out_str + '\\n')",
"name": "METHOD_NAME(file_path,"
},
{
"body": " super(LossCallBack, self).__init__()\n if not isinstance(per_print_times, int) or per_print_times < 0:\n raise ... |
5,923 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " predict = self.merge_op(vectors, segment_ids, self.num_segments)\n return predict",
"name": "construct(self,NetWithLoss(nn.Cell):"
},
{
"body": " context.set_auto_parallel_context(device_num=4, global_rank=0)\n x = Tensor(np.ones((4, 8)), ms.float32)\n y = Tensor(n... |
5,924 | import pytest
from pybind11_tests import ConstructorStats
def test_regressions():
from pybind11_tests.issues import print_cchar, print_char
# #137: const char* isn't handled properly
assert print_cchar("const char *") == "const char *"
# #150: char bindings broken
assert print_char("c") == "c"
... | [
{
"body": " \"\"\"#159: virtual function dispatch has problems with similar-named functions\"\"\"\n from pybind11_tests.issues import DispatchIssue, dispatch_issue_go\n class PyClass1(DispatchIssue):\n def dispatch(self):\n return \"Yay..\"\n class PyClass2(DispatchIssue):\n ... |
5,925 | import struct
from ..base import TestBase
from ...messaging.serialization import DefaultStruct, PackError, Serializable, Serializer
class Short(Serializable):
format_list = ["H"]
def __init__(self, number):
self.number = number
def to_pack_list(self):
return [("H", self.number)]
@c... | [
{
"body": " self.number = number",
"name": "__init__(self,TestSerializer(TestBase):"
},
{
"body": " return Short(*args)",
"name": "from_unpack_list(cls,TestSerializer(TestBase):"
},
{
"body": " self.byte = byte",
"name": "__init__(self,TestSerializer(TestBase):"
... |
5,926 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
impo... | [
{
"body": " return _gen_required_files()",
"name": "requiredFiles(self):CreateVanadiumTest(systemtesting.MantidSystemTest):"
},
{
"body": " setup_mantid_paths()\n self.calibration_results = run_vanadium_calibration()",
"name": "runTest(self):CreateVanadiumTest(systemtesting.... |
5,927 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " super(Dataset, self).__init__(size=length)\n self.predict = predict\n self.label = label\n self.index = 0\n self.length = length",
"name": "__init__(self,SoftmaxCrossEntropyWithLogits(LossBase):"
},
{
"body": " return self",
"name": "__iter__... |
5,928 | #!/usr/bin/env python3
#
#===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License.
#
# ==========================================================... | [
{
"body": " parser = argparse.ArgumentParser(description=\n 'Reformat changed lines in diff. Without -i '\n 'option just output the diff that would be '\n 'introduced.')\n parser.add_argument('-i', action='st... |
5,929 | from collections import ChainMap
from typing import Any
from graphql.error import GraphQLError
from graphql.execution import ExecutionResult, execute_sync
from graphql.language import SourceLocation, parse
from graphql.type import (
GraphQLArgument,
GraphQLField,
GraphQLInputField,
GraphQLInputObjectTy... | [
{
"body": " def _test_schema(test_field: GraphQLField) -> GraphQLSchema:\n return GraphQLSchema(GraphQLObjectType(\"Query\", {\"test\": test_field}))\n def default_function_accesses_attributes():\n class RootValue:\n test = \"testValue\"\n assert execute_sync(\n ... |
5,930 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2019 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
# T... | [
{
"body": " def function_reference(func):\n def function_parameters(self):\n if not make_them_errors:\n # plot this line with specNum\n self.ax.plot(self.ws2d_histo, specNum=1)\n # and another one with wkspIndex\n self.ax.plot(self... |
5,931 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2021 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
from... | [
{
"body": " \"\"\"Initializes the ModelFittingView, and adds the ModelFittingDataSelectorView widget.\"\"\"\n super(ModelFittingView, self).__init__(parent)\n self.model_fitting_data_selector = ModelFittingDataSelectorView(self)\n self.general_fitting_options_layout.addWidget(self.mo... |
5,932 | import unittest
from util import *
import json
class BIP39Tests(unittest.TestCase):
cases = None
langs = { 'en': 'english',
'es': 'spanish',
'fr': 'french',
'it': 'italian',
'jp': 'japanese',
'zhs': 'chinese_simplified',
'zht... | [
{
"body": " for lang, wl in self.wordlists.items():\n self.assertIsNotNone(wl)\n def_wl = self.get_wordlist(None)\n en_wl = self.wordlists['en']\n self.assertEqual(def_wl.value, en_wl.value)",
"name": "METHOD_NAME(self):BIP39Tests(unittest.TestCase):"
},
{
"bod... |
5,933 | ##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2023, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
import json
impor... | [
{
"body": " super().setUp()\n self.data = self.test_data\n self.db_name = parent_node_dict[\"database\"][-1][\"db_name\"]\n schema_info = parent_node_dict[\"schema\"][-1]\n self.server_id = schema_info[\"server_id\"]\n self.db_id = schema_info[\"db_id\"]\n # Chec... |
5,934 | # Copyright 2021-2022 Huawei Technologies Co., Ltd
#
# 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 agre... | [
{
"body": " # Only generate floating points that are fractions like n / 256, since they\n # are RGB pixels. Some low-precision floating point types in this test can't\n # handle arbitrary precision floating points well.\n return np.random.randint(0, 256, shape) / 255.",
"name": "METHOD_NAME(shap... |
5,935 | # Copyright 2022 Google LLC. 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 law or a... | [
{
"body": " beam_pipeline: annotations.BeamComponentParameter[beam.Pipeline] = None):\n with beam_pipeline as p:\n direct_num_workers = p.options.view_as(\n pipeline_options.DirectOptions).direct_num_workers\n direct_running_mode = p.options.view_as(\n pipeline_options.DirectOptions).dir... |
5,936 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " \"\"\"\n Feature: celu cpu kernel.\n Description: test celu vmap feature.\n Expectation: Success.\n \"\"\"\n error = 1e-3\n def cal_celu(x):\n return P.CeLU(1.0)(x)\n x = Tensor(np.array([[-2.0, -1.0, 1.0, 2.0], [-2.0, -1.0, 1.0, 2.0], [-2.0, -1.0, 1.0, 2.0],\n ... |
5,937 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
impo... | [
{
"body": " \"\"\"\n :param view: A reference to the view managed by this presenter\n :param exit_code: A string containing the exit_code of the failing application\n :param application: A string containing the failing application name\n :param traceback: An optional string co... |
5,938 | import os
from testtools import TestCase
from mock import (
patch,
MagicMock,
)
from charmhelpers.payload import archive
from tempfile import mkdtemp
from shutil import rmtree
import subprocess
class ArchiveTestCase(TestCase):
def create_archive(self, format):
workdir = mkdtemp()
if forma... | [
{
"body": " workdir = mkdtemp()\n if format == \"tar\":\n workfile = \"{}/foo.tar.gz\".format(workdir)\n cmd = \"tar czf {} hosts\".format(workfile)\n elif format == \"zip\":\n workfile = \"{}/foo.zip\".format(workdir)\n cmd = \"zip {} hosts\".for... |
5,939 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " with pytest.raises(ValueError) as raise_info:\n context = mslite.Context()\n context.parallel.workers_num = -4\n assert \"workers_num must be a non-negative int\" in str(raise_info.value)",
"name": "test_context_parallel_workers_num_negative_error():"
},
{
"body": " ... |
5,940 | """Store object for a list of games"""
# pylint: disable=not-an-iterable
import time
from gi.repository import GLib, GObject, Gtk
from lutris import settings
from lutris.database import sql
from lutris.database.games import get_games
from lutris.gui.views.store_item import StoreItem
from lutris.util.strings import gt... | [
{
"body": " try:\n out = value.lower()\n except AttributeError:\n out = value\n return out",
"name": "METHOD_NAME(value):"
},
{
"body": " super().__init__()\n self.service = service\n self.service_media = service_media\n self._installed_games = []\n... |
5,941 | """
Briefing generation logic
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from typing import Dict, List, TYPE_CHECKING
from dcs.mission import Mission
from jinja2 import Environment, FileSystemLoader, select_autoescape
from game.ato.flightwaypoint import FlightWaypoint
from gam... | [
{
"body": " \"\"\"Adds communications info to the mission.\n Args:\n name: Name of the radio channel.\n freq: Frequency of the radio channel.\n \"\"\"\n self.comms.append(CommInfo(name, freq))",
"name": "add_comm(self,MissionInfoGenerator:"
},
{
"bod... |
5,942 | import os
import random
import pytest
from solana.rpc.api import Client
from solana.publickey import PublicKey
from solana.rpc.commitment import Confirmed
from .solana_utils import neon_cli, create_treasury_pool_address, get_neon_balance, get_transaction_count
from .solana_utils import solana_client, wait_confirm_tra... | [
{
"body": " result = neon_cli().call(\n f\"get-ether-account-data --evm_loader {evm_loader.loader_id} {user_account.eth_address.hex()}\")\n assert f\"0x{user_account.eth_address.hex()}\" == result[\"address\"]\n assert str(user_account.solana_account_address) == result[\"solana_address\"]\n a... |
5,943 | # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... | [
{
"body": " \"\"\"Ensure that DNS errors in host selection are caught.\"\"\"\n def _select_workflow_host(cached=False):\n # fake a \"get address info\" error\n # this error can occur due to an unknown host resulting from broken\n # DNS or an invalid host name in the global config\n ... |
5,944 | import operator as op
from functools import reduce
import numpy as np
def combination_Cnr(n, r):
r = min(r, n - r)
numer = reduce(op.mul, range(n, n - r, -1), 1)
denom = reduce(op.mul, range(1, r + 1), 1)
return numer / denom
def fisher_test_pValue_by_formula(ts_len, g_f):
a = int((ts_len - 1) /... | [
{
"body": " # based on paper \"Statistical power of Fisher test for the detection\n # of short periodic gene expression profiles\"\n # formula 1-4. tested, the following\n # periodogram_values, ts_len = fft_periodogram(input_data)\n # period_candi, pValue, observed_g =\n # fisher_g_test(perio... |
5,945 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " \"\"\"\n Feature: test Lerp grad dynamic rank on Ascend.\n Description: input is dynamic rank.\n Expectation: the result match with static shape\n \"\"\"\n context.set_context(mode=context.PYNATIVE_MODE, device_target=\"Ascend\")\n grad_dyn_case(False)\n grad_partial_dyn_case... |
5,946 | # Copyright 2020-2022 Huawei Technologies Co., Ltd
#
# 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 agre... | [
{
"body": " \"\"\"\n Determine if a number not in tuple.\n Args:\n x (Number): x\n y (tuple): y\n Returns:\n bool, if x not in y return true, x in y return false.\n \"\"\"\n if F.is_sequence_shape_unknown(y) or not F.isconstant(x):\n return not InSequence()(x, y)\n r... |
5,947 | import os
from pkg_resources import parse_version
import shutil
import subprocess
import tempfile
from testtools import TestCase
from mock import (
MagicMock,
patch,
)
from charmhelpers.core.host import chdir
from urllib.parse import urlparse
try:
from charmhelpers.fetch import (
giturl,
... | [
{
"body": " if self._git_version_2_28_plus is None:\n try:\n cmd = \"git --version\"\n version = subprocess.check_output(cmd.split()).decode()\n if version:\n version = version.split()[-1]\n if parse_version(ver... |
5,948 | from __future__ import annotations
import heapq
import math
from collections import defaultdict
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Dict, Iterator, List, Optional, Set, Tuple
from .conflicttheater import ConflictTheater
from .controlpoint import ControlPoint
class... | [
{
"body": " super().__init__(f\"Could not reconstruct path to {destination} from {origin}\")",
"name": "__init__(self,TransitNetwork:"
},
{
"body": " try:\n return heapq.heappop(self.nodes)\n except IndexError:\n return None",
"name": "pop(self)TransitN... |
5,949 | #!/usr/bin/env python3
#Copyright (C) 2011 by Glenn Hickey
#
#Released under the MIT license, see LICENSE.txt
"""
"""
import unittest
import os
import sys
from sonLib.bioio import TestStatus
from sonLib.bioio import getTempDirectory
from sonLib.bioio import logger
from sonLib.bioio import system
from cactus.progres... | [
{
"body": " parser = NXNewick()\n mcTree1 = MultiCactusTree(parser.parseString(self.tree1, addImpliedRoots = False))\n tree1String = NXNewick().writeString(mcTree1)\n self.assertEqual(tree1String, self.tree1)\n mcTree2 = MultiCactusTree(parser.parseString(self.tree2, addImplie... |
5,950 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2019 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
from... | [
{
"body": " return AnalysisDataService.doesExist(workspace_name)",
"name": "exists_in_ads(workspace_name):IndirectQuickRunTest(unittest.TestCase):"
},
{
"body": " return AnalysisDataService.retrieve(workspace_name) if exists_in_ads(workspace_name) else None",
"name": "get_ads_workspace(wor... |
5,951 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
impo... | [
{
"body": " # Need to set the random seed because the scipy kmeans algorithm\n # randomly initilizes the starting centroids. This can lead to a\n # different but equivilent indexing.\n np.random.seed(10)",
"name": "setUp(self):FractionIndexingTests(unittest.TestCase):"
},
{
... |
5,952 | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... | [
{
"body": " unittest.TestResult.__init__(self)\n self.parent_result = parent_result",
"name": "__init__(self,ReferenceLeakCheckerTestCase(unittest.TestCase):"
},
{
"body": " self.parent_result.addError(test, error)",
"name": "addError(self,ReferenceLeakCheckerTestCase(unittest.TestCase)... |
5,953 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " self._input_path = input_path\n self._output_filename = output_filename\n self._source_flie_name = self._get_source_file()\n self._dynamic_status = dynamic_status",
"name": "__init__(self,HWTSLogParser:"
},
{
"body": " \"\"\"\n Execute the parser... |
5,954 | """Specialized text support classes for segment displays."""
import abc
from collections import namedtuple
from typing import Optional, List, Union
from mpf.core.rgb_color import RGBColor
DisplayCharacter = namedtuple("DisplayCharacter", ["char_code", "dot", "comma", "color"])
DOT_CODE = ord(".")
COMMA_CODE = ord(",... | [
{
"body": " \"\"\"Initialize segment display text.\"\"\"\n self.embed_dots = embed_dots\n self.embed_commas = embed_commas\n self.use_dots_for_commas = use_dots_for_commas\n self._text = char_list",
"name": "__init__(self,SegmentDisplayText(metaclass=abc.ABCMeta):"
},
... |
5,955 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
fr... | [
{
"body": " if fqdn and not isinstance(fqdn, str):\n raise TypeError(\"Expected argument 'fqdn' to be a str\")\n pulumi.set(__self__, \"fqdn\", fqdn)\n if id and not isinstance(id, str):\n raise TypeError(\"Expected argument 'id' to be a str\")\n pulumi.set(__se... |
5,956 | #!/usr/bin/env python3
from __future__ import annotations
import json
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
headers = {"UserAgent": UserAgent().random}
def extract_user_profile(script) -> dict:
"""
May raise json.decoder.JSONDecodeError
"""
data = script... | [
{
"body": " \"\"\"\n Return a dict of user information\n \"\"\"\n html = requests.get(self.url, headers=headers).text\n scripts = BeautifulSoup(html, \"html.parser\").find_all(\"script\")\n try:\n return extract_user_profile(scripts[4])\n except (json.... |
5,957 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2021 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
impo... | [
{
"body": " self.view = GeneralFittingView()",
"name": "setUp(self):GeneralFittingViewTest(unittest.TestCase):"
},
{
"body": " self.assertTrue(self.view.close())",
"name": "tearDown(self):GeneralFittingViewTest(unittest.TestCase):"
},
{
"body": " selected_dataset = \... |
5,958 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2019 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
impo... | [
{
"body": " # Store an empty widget to parent all the views, and ensure they are deleted correctly\n self.obj = QWidget()\n setup_context_for_tests(self)\n self.model = GroupingTabModel(context=self.context)\n self.view = PairingTableView(parent=self.obj)\n self.present... |
5,959 | import os
import sys
# Add parent path to use local src as package for tests
root_dir = os.path.abspath(
os.path.join(
os.path.dirname(__file__), os.path.pardir, os.path.pardir, os.path.pardir
)
)
sys.path.append(root_dir)
import asyncio
from multiprocessing import Process
import pytest
import uvicor... | [
{
"body": " return {DATA_KEY: DATA_SECRET_VALUE}",
"name": "METHOD_NAME(token=Depends(check_token_header)):"
},
{
"body": " # Run the server as a separate process\n proc = Process(target=setup_server, args=(), daemon=True)\n proc.start()\n yield proc\n proc.kill() # Cleanup af... |
5,960 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
# py... | [
{
"body": " super(PdAndScConversionWidget, self).__init__(parent, state, settings, data_type=data_type)\n class PdAndScConversionFrame(QtGui.QFrame, ui.inelastic.ui_dgs_pd_sc_conversion.Ui_PdScConversionFrame):\n def __init__(self, parent=None):\n QtGui.QFrame.__init__(se... |
5,961 | import os
import mock
import pytest
import libensemble.tests.unit_tests.setup as setup
from libensemble.alloc_funcs.give_sim_work_first import give_sim_work_first
from libensemble.comms.logs import LogConfig
from libensemble.libE import libE
from libensemble.manager import LoggedException
from libensemble.resources.r... | [
{
"body": " try:\n print(f\"teardown_module module:{module.__name__}\")\n except AttributeError:\n print(f\"teardown_module (direct run) module:{module}\")\n if Resources.resources is not None:\n del Resources.resources\n Resources.resources = None",
"name": "METHOD_NAME... |
5,962 | #!/usr/bin/env python
"""
[{"service": "foo", "level": "2345", "state": "on"},
{"service": "foo", "level": "016", "state": "off"},
{"service": "bar", "state": "on"},
...]
"""
import os
import sys
import json
import pwd
import re
from subprocess import *
sys.path.append(os.path.dirname(__file__))
from comp import... | [
{
"body": " self.prefix = prefix.upper()\n self.sysname, self.nodename, x, x, self.machine = os.uname()\n self.services = []\n for k in [key for key in os.environ if key.startswith(self.prefix)]:\n try:\n l = json.loads(os.environ[k])\n for i,... |
5,963 | import unittest
import os
import numpy as np
import skrf as rf
class CitiTestCase(unittest.TestCase):
"""
Test the IO of CITI files.
"""
def METHOD_NAME(self):
"""
Sets up the test directory
"""
self.test_dir = os.path.dirname(os.path.abspath(__file__))+'/MDIF_CITI_MDL/'... | [
{
"body": " \"\"\"\n Sets up the test directory\n \"\"\"\n self.test_dir = os.path.dirname(os.path.abspath(__file__))+'/MDIF_CITI_MDL/'\n # constructor from filename\n self.oneport_example1 = rf.Citi(self.test_dir + 'test_1p_citi.cti')\n self.oneport_example2 = r... |
5,964 | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " np.random.seed(42)\n prediction = np.random.rand(20).astype(np.float32)\n target = np.random.rand(20).astype(np.float32)\n sens = np.random.rand(20).astype(np.float32)\n weight = np.random.rand(20).astype(np.float32)\n reduction = \"none\"\n grad = Grad(Net(reduction))\n dx =... |
5,965 | import pytest
from kopf._cogs.structs.references import EVERYTHING, Resource, Selector
@pytest.fixture()
def resource():
return Resource(
group='group1', version='version1', preferred=True,
plural='plural1', singular='singular1', kind='kind1',
shortcuts=['shortcut1', 'shortcut2'],
... | [
{
"body": " return Resource(\n group='group1', version='version1', preferred=True,\n plural='plural1', singular='singular1', kind='kind1',\n shortcuts=['shortcut1', 'shortcut2'],\n categories=['category1', 'category2'],\n )",
"name": "resource():"
},
{
"body": " ... |
5,966 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2022 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
fr... | [
{
"body": " # run information table\n run_info = self.make_runinfo_table()\n self._log_workspaces = GroupWorkspaces([run_info], OutputWorkspace=\"logs\" + self._suffix)\n # a table per logs\n logs = get_setting(output_settings.INTERFACES_SETTINGS_GROUP, output_settings.ENGINEE... |
5,967 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2014 Uwe Hermann <uwe@hermann-uwe.de>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the Li... | [
{
"body": " if key == srd.SRD_CONF_SAMPLERATE:\n self.samplerate = value\n # One bit: 1.78ms (one half low, one half high).\n self.halfbit = int((self.samplerate * 0.00178) / 2.0)",
"name": "METHOD_NAME(self,Decoder(srd.Decoder):"
},
{
"body": " # Categ... |
5,968 | #!/usr/bin/env python
## Copyright (c) 2019, Alliance for Open Media. All rights reserved
##
## This source code is subject to the terms of the BSD 2 Clause License and
## the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
## was not distributed with this source code in the LICENSE file, you ca... | [
{
"body": " filename = recfile + '-libvmaf.xml'\n file = os.path.join(path, filename)\n return file",
"name": "METHOD_NAME(recfile,"
}
] |
5,969 | # Copyright 2014-2021 Canonical Limited.
#
# 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 ... | [
{
"body": " stop_service('myservice')",
"name": "post_mount_hook():VolumeConfigurationError(Exception):"
},
{
"body": " start_service('myservice')",
"name": "post_mount_hook():VolumeConfigurationError(Exception):"
},
{
"body": " '''Gather and sanity-check volume configur... |
5,970 | """
Module to run tests on SpecObj
"""
import numpy as np
import sys
import os
from copy import deepcopy
import pytest
from IPython import embed
from astropy.table import Table
from astropy.io import fits
from pypeit import spec2dobj
from pypeit.spectrographs.util import load_spectrograph
from pypeit.tests import ts... | [
{
"body": " allspec2D = spec2dobj.AllSpec2DObj()\n allspec2D['meta']['bkg_redux'] = False\n allspec2D['meta']['find_negative'] = False\n for i in range(2):\n d = load_spectrograph('keck_deimos').get_detector_par(i+1)\n allspec2D[d.name] = spec2dobj.Spec2DObj(detector=d, **init_dict)\n ... |
5,971 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
# py... | [
{
"body": " return \"Calculates the resolution function for VESUVIO\"",
"name": "summary(self):VesuvioResolution(VesuvioBase):"
},
{
"body": " self.declareProperty(\n MatrixWorkspaceProperty(name=\"Workspace\", defaultValue=\"\", direction=Direction.Input), doc=\"Sample matr... |
5,972 | from collections import namedtuple
_ColumnMetadata = namedtuple(
"ColumnMetadata", ["name", "datatype", "foreignkeys", "default",
"has_default"]
)
def ColumnMetadata(name, datatype, foreignkeys=None, default=None,
has_default=False):
return _ColumnMetadata(name, data... | [
{
"body": " has_default=False):\n return _ColumnMetadata(name, datatype, foreignkeys or [], default,\n has_default)",
"name": "ColumnMetadata(name,FunctionMetadata:"
},
{
"body": " \"\"\"Yields default values for a function, given the string provided... |
5,973 | # Min heap data structure
# with decrease key functionality - in O(log(n)) time
class Node:
def __init__(self, name, val):
self.name = name
self.val = val
def __str__(self):
return f"{self.__class__.__name__}({self.name}, {self.val})"
def __lt__(self, other):
return self.... | [
{
"body": " while True:\n l = self.get_left_child_idx(idx) # noqa: E741\n r = self.get_right_child_idx(idx)\n smallest = idx\n if l < len(array) and array[l] < array[idx]:\n smallest = l\n if r < len(array) and array[r] < array[smalle... |
5,974 | """
guiscrcpy
Licensed under GNU Public License
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in... | [
{
"body": " \"\"\"\n Manages guiscrcpy's configuration files\n \"\"\"\n self.os = platform.System()\n self.cfgpath = self.os.cfgpath()\n self.paths = self.os.paths()\n self.config = {\n \"version\": 1,\n \"paths\": self.paths,\n \... |
5,975 | import ctypes
import io
import struct
import pytest
import env
from pybind11_tests import ConstructorStats
from pybind11_tests import buffers as m
np = pytest.importorskip("numpy")
def test_from_python():
with pytest.raises(RuntimeError) as excinfo:
m.Matrix(np.array([1, 2, 3])) # trying to assign a 1... | [
{
"body": " \"\"\"SquareMatrix is derived from Matrix and inherits the buffer protocol\"\"\"\n matrix = m.SquareMatrix(5)\n assert memoryview(matrix).shape == (5, 5)\n assert np.asarray(matrix).shape == (5, 5)",
"name": "test_inherited_protocol():"
},
{
"body": " buf = m.BufferReadOnl... |
5,976 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " \"\"\"_BatchNormFold2Grad TBE register\"\"\"\n return",
"name": "METHOD_NAME():"
}
] |
5,977 | from __future__ import annotations
from collections import Counter
import click
import mock
import pytest
from requests import HTTPError, Response
from requests.adapters import BaseAdapter
from meltano.cli import cli
from meltano.cli.hub import hub
from meltano.core.hub.client import HubConnectionError, HubPluginVar... | [
{
"body": " self,\n project: Project,\n hub_request_counter: Counter,",
"name": "test_find_definition_specified_variant(_Adapter(BaseAdapter):"
},
{
"body": " self,\n project: Project,\n hub_request_counter: Counter,",
"name": "test_find_definition_defau... |
5,978 | # Copyright 2019-2021 Huawei Technologies Co., Ltd
#
# 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 agre... | [
{
"body": " converted_to_dynamic = self.gpu_convert_to_dynamic_shape(x)\n return self.zeros_like(converted_to_dynamic)",
"name": "construct(self,ZerosLikeDynamicNet(nn.Cell):"
},
{
"body": " x = Tensor(np.arange(30).reshape(3, 2, 5).astype(np.uint8))\n output = zeros_like_dynamic... |
5,979 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
fr... | [
{
"body": " if account_name and not isinstance(account_name, str):\n raise TypeError(\"Expected argument 'account_name' to be a str\")\n pulumi.set(__self__, \"account_name\", account_name)\n if format and not isinstance(format, str):\n raise TypeError(\"Expected argum... |
5,980 | from sha3 import keccak_256
import json
from web3.auto import w3
from eth_keys import keys
import struct
def unpack(data):
ch = data[0]
if ch <= 0x7F:
return ch, data[1:]
elif ch == 0x80:
return None, data[1:]
elif ch <= 0xB7:
l = ch - 0x80
return data[1:1 + l].tobytes(... | [
{
"body": " self.nonce = None\n self.gasPrice = None\n self.gasLimit = None\n self.toAddress = None\n self.value = None\n self.callData = None\n self.v = None\n self.r = None\n self.s = None",
"name": "__init__(self):Trx:"
},
{
"body": "... |
5,981 | """
django-helpdesk - A Django powered ticket tracker for small enterprise.
(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.
lib.py - Common functions (eg multipart e-mail)
"""
from datetime import date, datetime, time
from django.conf import settings
from django.core.exceptions import Valida... | [
{
"body": " context = {}\n for field in ('title', 'created', 'modified', 'submitter_email',\n 'status', 'get_status_display', 'on_hold', 'description',\n 'resolution', 'priority', 'get_priority_display',\n 'last_escalation', 'ticket', 'ticket_for_url', 'm... |
5,982 | import json
import uuid
from pilot.common.schema import DBType
from pilot.configs.config import Config
from pilot.configs.model_config import (
KNOWLEDGE_UPLOAD_ROOT_PATH,
EMBEDDING_MODEL_CONFIG,
LOGDIR,
)
from pilot.scene.base import ChatScene
from pilot.scene.base_chat import BaseChat
from pilot.scene.ch... | [
{
"body": " pass",
"name": "__init__(self):DBSummaryClient:"
},
{
"body": " \"\"\"put db profile and table profile summary into vector store\"\"\"\n from langchain.embeddings import HuggingFaceEmbeddings\n from pilot.embedding_engine.string_embedding import StringEmbeddin... |
5,983 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2020 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
# std imports
import numpy as np
import unitt... | [
{
"body": " mock_get_peaks_workspace.return_value = MagicMock(spec=PeaksWorkspace)\n first_model = create_peaksviewermodel(\"test\", \"red\", \"gray\")\n second_model = create_peaksviewermodel(\"test\", \"blue\", \"white\")\n self.assertEqual(\"red\", first_model.fg_color)\n s... |
5,984 | # Copyright 2020 Google LLC
#
# 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, ... | [
{
"body": " \"\"\"Returns benchmark variables from benchmark.yaml files.\"\"\"\n variables = ''\n for benchmark in benchmarks:\n benchmark_vars = yaml_utils.read(\n os.path.join(BENCHMARK_DIR, benchmark, 'benchmark.yaml'))\n variables += (benchmark + '-fuzz-target=' +\n ... |
5,985 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... | [
{
"body": " \"\"\"\n Feature: test NLLLossGrad vmap interface.\n Description: test the rightness of NLLLossGrad kernel.\n Expectation: the result match with numpy result\n \"\"\"\n context.set_context(mode=context.PYNATIVE_MODE)\n reduction = \"none\"\n def cal_nll_loss_grad(x, dout_x, t... |
5,986 | # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... | [
{
"body": " \"\"\"Suppress at's routine output to stderr.\n Otherwise we get warning messages that suggest something is wrong.\n 1) move the standard job ID message from stderr to stdout\n 2) suppress the message warning that commands will be executed with\n /bin/sh (this refe... |
5,987 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2019 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
# T... | [
{
"body": " self.pr = ProjectRecovery(multifileinterpreter=None)\n # Make absolutely sure that the workbench-recovery directory is cleared.\n if os.path.exists(self.pr.recovery_directory):\n shutil.rmtree(self.pr.recovery_directory)\n # Set up some checkpoints\n sel... |
5,988 | import queue
import string
from functools import partial, reduce
from echo.callback_container import CallbackContainer
__all__ = ['DeferredMethod', 'nonpartial', 'lookup_class', 'as_variable_name',
'as_list', 'file_format', 'CallbackMixin', 'PropertySetMixin',
'Pointer', 'common_prefix', 'queue... | [
{
"body": " self.method = method\n self.calls = [] # avoid hashability issues with dict/set",
"name": "__init__(self,class"
},
{
"body": " return self.method",
"name": "original_method(self):class"
},
{
"body": " if instance is None:\n return self\... |
5,989 | # Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
{
"body": " backends = ['cpu', 'wasm']\n for backend in backends:\n binary_path = os.path.join('../binaries', 'tfjs-inference-linux')\n model_path = os.path.join('../test_data', 'model_structured_outputs.json')\n test_data_dir = os.path.join('../test_data')\n tmp_dir = tempfile.mkdtemp... |
5,990 | import logging
import click
from tqdm import tqdm
from pymobiledevice3.cli.cli_common import Command
from pymobiledevice3.lockdown import LockdownClient
from pymobiledevice3.services.mobilebackup2 import Mobilebackup2Service
source_option = click.option('--source', default='', help='The UDID of the source device.')
... | [
{
"body": " \"\"\"\n Backup device.\n All backup data will be written to BACKUP_DIRECTORY, under a directory named with the device's udid.\n \"\"\"\n backup_client = Mobilebackup2Service(service_provider)\n with tqdm(total=100, dynamic_ncols=True) as pbar:\n def update_bar(percentage):\... |
5,991 | from typing import Dict, Iterator, List, Optional, Tuple, Union, cast
import torch
from torch.distributions import Categorical
from kornia.augmentation.auto.base import SUBPLOLICY_CONFIG, PolicyAugmentBase
from kornia.augmentation.auto.operations import OperationBase
from kornia.augmentation.auto.operations.policy im... | [
{
"body": " self,\n n: int,\n m: int,\n policy: Optional[List[SUBPLOLICY_CONFIG]] = None,\n transformation_matrix_mode: str = \"silent\",",
"name": "__init__(RandAugment(PolicyAugmentBase):"
},
{
"body": " if len(subpolicy) != 1:\n raise RuntimeEr... |
5,992 | from lxml import etree
from bbot.modules.base import BaseModule
class nmap(BaseModule):
watched_events = ["IP_ADDRESS", "DNS_NAME"]
produced_events = ["OPEN_TCP_PORT"]
flags = ["active", "portscan", "aggressive", "web-thorough"]
meta = {"description": "Execute port scans with nmap"}
options = {
... | [
{
"body": " self.helpers.depsinstaller.ensure_root(message=\"Nmap requires root privileges\")\n self.ports = self.config.get(\"ports\", \"\")\n self.timing = self.config.get(\"timing\", \"T4\")\n self.top_ports = self.config.get(\"top_ports\", 100)\n self.skip_host_discovery =... |
5,993 | # Copyright 2019 Google LLC. 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 law or a... | [
{
"body": " \"\"\"Check whether the model artifact is generated by old TFX version.\"\"\"\n if model_artifact.type != standard_artifacts.Model:\n absl.logging.warning(f'Artifact type is not Model: {model_artifact.type}.')\n return artifact_utils.is_artifact_version_older_than(\n model_artifact, artif... |
5,994 | import binascii
import pytest
from paradox import event
from paradox.hardware.evo.event import event_map
from paradox.hardware.evo.parsers import LiveEvent, RequestedEvent
def label_provider(type, id):
if type == "user":
assert id == 1
return "Test"
elif type == "partition":
assert i... | [
{
"body": " if type == \"user\":\n assert id == 1\n return \"Test\"\n elif type == \"partition\":\n assert id == 5\n return \"First floor\"\n elif type == \"door\":\n assert id == 5\n return \"Door 1\"\n else:\n raise AssertionError()",
"name": "l... |
5,995 | import importlib
from importlib import abc
from importlib import util
import sys
import types
import unittest
from test.test_importlib import util as test_util
class CollectInit:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def exec_module(self, module):
... | [
{
"body": " return self",
"name": "exec_module(self,LazyLoaderTests(unittest.TestCase):"
},
{
"body": " factory = util.LazyLoader.factory(CollectInit)\n # E.g. what importlib.machinery.FileFinder instantiates loaders with\n # plus keyword arguments.\n lazy_loader =... |
5,996 | import siliconcompiler
import re
from siliconcompiler import SiliconCompilerError
from siliconcompiler.flows._common import setup_frontend
from siliconcompiler.tools.yosys import syn_fpga as yosys_syn
from siliconcompiler.tools.vpr import place as vpr_place
from siliconcompiler.tools.vpr import route as vpr_route
fro... | [
{
"body": " '''\n A configurable FPGA compilation flow.\n The 'fpgaflow' module is a configurable FPGA flow with support for\n open source and commercial tool flows.\n The following step convention is recommended for VPR.\n * **import**: Sources are collected and packaged for compilation\n ... |
5,997 | # Copyright 2020-2023 Huawei Technologies Co., Ltd
#
# 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 agre... | [
{
"body": " class NetMissReturn(nn.Cell):\n def construct(self, x, y, z):\n if x == 1:\n return 10\n elif x == 20:\n if y == 1:\n return 3\n elif y == 2:\n for i in range(z):\n ... |
5,998 | from collections import ChainMap
from typing import (
TYPE_CHECKING,
Any,
Dict,
ItemsView,
Iterable,
MutableMapping,
NamedTuple,
Optional,
Type,
TypeVar,
Union,
ValuesView,
)
from docarray.array.list_advance_indexing import ListAdvancedIndexing
from docarray.typing impor... | [
{
"body": " self,\n tensor_columns: Dict[str, Optional[AbstractTensor]],\n doc_columns: Dict[str, Optional['DocVec']],\n docs_vec_columns: Dict[str, Optional[ListAdvancedIndexing['DocVec']]],\n any_columns: Dict[str, ListAdvancedIndexing],\n tensor_type: Type[AbstractTe... |
5,999 | from sympy.concrete.summations import Sum
from sympy.core.expr import Expr
from sympy.core.function import (Derivative, Function, diff, Subs)
from sympy.core.numbers import (I, Rational, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions... | [
{
"body": " assert Rational(1, 3).diff(x) is S.Zero\n assert I.diff(x) is S.Zero\n assert pi.diff(x) is S.Zero\n assert x.diff(x, 0) == x\n assert (x**2).diff(x, 2, x) == 0\n assert (x**2).diff((x, 2), x) == 0\n assert (x**2).diff((x, 1), x) == 2\n assert (x**2).diff((x, 1), (x, 1)) == 2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.