name stringclasses 844
values | input_types listlengths 0 100 | output_type stringlengths 1 419 | code stringlengths 34 233k | dependencies listlengths 0 6 | lib_used listlengths 0 11 | imports listlengths 0 66 | line_count int64 3 199 | full_code stringlengths 39 1.01M | input_type_defs listlengths 1 12 ⌀ |
|---|---|---|---|---|---|---|---|---|---|
v0 | [
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"dict"
] | typing.Tuple[float, float] | def v0(self, v1: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, v4: torch.Tensor, v5: dict) -> typing.Tuple[float, float]:
v6 = self.adaptation(x=v1, y=v2, model=v5)
v7 = self.prediction(x=v3, adapted_hyper_net=v6, model=v5)
v8 = 0
for v9 in v7:
v8 = v8 + self.config['loss_function'](input=v9... | [] | [
"torch"
] | [
"import torch"
] | 13 | import torch
import numpy as np
import higher
import typing
from MLBaseClass import MLBaseClass
from HyperNetClasses import EnsembleNet
from Maml import Maml
class Bmaml(MLBaseClass):
def __init__(self, config: dict) -> None:
super().__init__(config=config)
self.hyper_net_class = Ensemble... | null |
v0 | [
"torch.Tensor"
] | typing.Tuple[torch.Tensor, torch.Tensor, torch.Tensor] | def v0(self, v1: torch.Tensor) -> typing.Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
v2 = self.get_pairwise_distance_matrix(x=v1)
v3 = torch.quantile(input=v2, q=0.5)
v4 = v3 / np.log(self.config['num_models'])
v5 = torch.exp(-v2 / v4)
v6 = torch.sum(input=v5, dim=1, keepdim=True)
v7 = -tor... | [] | [
"numpy",
"torch"
] | [
"import torch",
"import numpy as np"
] | 10 | import torch
import numpy as np
import higher
import typing
from MLBaseClass import MLBaseClass
from HyperNetClasses import EnsembleNet
from Maml import Maml
class Bmaml(MLBaseClass):
def __init__(self, config: dict) -> None:
super().__init__(config=config)
self.hyper_net_class = Ensemble... | null |
v3 | [
"httpx.Client",
"bool",
"bool"
] | dict[str, list[str]] | def v3(v4: httpx.Client, v5: bool=False, v6: bool=False) -> dict[str, list[str]]:
v7 = 'https://script.google.com/macros/s/AKfycbzKbt6JDlvFs0jgR2AqGrjqb6UxnoXjVFmoU4QnEHbCc28Tx7rGMUG-lEm5NklqgBtX/exec'
v8 = {'keepNull': str(v5).lower()}
v9 = v4.get(v7, params=v8, follow_redirects=True).json()
if v6:
... | [
{
"name": "v0",
"input_types": [
"list[T]"
],
"output_type": "list[T]",
"code": "def v0(v1: list[T]) -> list[T]:\n v2 = copy(v1)\n while v2 and (not v2[0]):\n del v2[0]\n while v2 and (not v2[-1]):\n del v2[-1]\n return v2",
"dependencies": []
}
] | [
"copy"
] | [
"from copy import copy"
] | 7 | from __future__ import annotations
import re
from copy import copy
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING, BinaryIO, Optional, Union
from zipfile import ZipFile, is_zipfile
import httpx
import rapidjson
from .classes import Level, SiteMetadata, T
from .excep... | null |
v7 | [
"httpx.Client",
"str"
] | str | def v7(v8: httpx.Client, v9: str) -> str:
with v8.stream('GET', v9, follow_redirects=True) as v10:
v10.raise_for_status()
v11 = v0(v10)
return v11 | [
{
"name": "v0",
"input_types": [
"httpx.Response"
],
"output_type": "str",
"code": "def v0(v1: httpx.Response) -> str:\n v2 = str(v1.url)\n if v2.endswith('.rdzip'):\n v3 = v2.rsplit('/', 1)[-1]\n else:\n v4 = v1.headers.get('Content-Disposition')\n if v4 is N... | [
"re"
] | [
"import re"
] | 5 | from __future__ import annotations
import re
from copy import copy
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING, BinaryIO, Optional, Union
from zipfile import ZipFile, is_zipfile
import httpx
import rapidjson
from .classes import Level, SiteMetadata, T
from .excep... | null |
v0 | [
"Path"
] | Path | def v0(v1: Path) -> Path:
if not v1.exists():
return v1
v2 = 2
while v1.with_stem(v1.stem + f' ({v2})').exists():
v2 += 1
return v1.with_stem(v1.stem + f' ({v2})') | [] | [] | [] | 7 | from __future__ import annotations
import re
from copy import copy
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING, BinaryIO, Optional, Union
from zipfile import ZipFile, is_zipfile
import httpx
import rapidjson
from .classes import Level, SiteMetadata, T
from .excep... | null |
v0 | [
"list",
"Any",
"Any"
] | tuple | def v0(v1: list, v2, v3) -> tuple:
v4 = 0
v5 = 0
v6 = 0
v7 = {}
for v8 in v1:
v9 = v8.problem.id
if v9 not in v7:
v7[v9] = []
v7[v9].append(v8)
for v10 in v7:
v11 = sorted(v7[v10], key=lambda sub: v8.timestamp)
v12 = 0
v13 = False
... | [] | [] | [] | 35 | from code.util.db import Submission, User, Contest, Problem
from code.generator.lib.htmllib import *
from code.generator.lib.page import *
import logging
from code.util import register
import time
from datetime import datetime, timezone
def detailedReport(params, user):
contest = Contest.getCurrent() or Contest.ge... | null |
v0 | [
"Dict"
] | Dict | def v0(v1: Dict) -> Dict:
v2 = dict()
for v3 in v1:
v4 = v1[v3]['mother']
v5 = v1[v3]['father']
if v4 == '0':
v4 = None
if v5 == '0':
v5 = None
if v4 and v5:
v6 = [v4, v5, v3]
v2[v3] = v6
return v2 | [] | [] | [] | 13 | # Copyright (c) 2019. Partners HealthCare, Harvard Medical School’s
# Department of Biomedical Informatics
#
# Developed by Michael Bouzinier, based on contributions by:
# Andrew Bjonnes,
# Ignat Leshchiner, Shamil Sunyaev and other members of Division of Genetics,
# Brigham and Women's Hospital
#
# Licensed und... | null |
v0 | [
"Any",
"Any",
"Union[str, list]"
] | Any | def v0(v1, v2, v3: Union[str, list]='bold'):
if isinstance(v3, str):
v3 = [v3]
v4 = {'black': '\x1b[30m', 'red': '\x1b[31m', 'green': '\x1b[32m', 'yellow': '\x1b[33m', 'blue': '\x1b[34m', 'magenta': '\x1b[35m', 'cyan': '\x1b[36m', 'white': '\x1b[37m', 'bright_black': '\x1b[90m', 'bright_red': '\x1b[91m'... | [] | [] | [] | 5 | from typing import Union
def color_str(text, color, mode: Union[str, list] = 'bold'):
"""
colorful texts!
:param text: input text
:param color: text color
:param mode: defines text's modes. Valid modes: [ underline, bold ]. Pass a list of modes in case more one mode is needed!
:return: colored... | null |
v0 | [
"List",
"Optional[str]",
"Optional[int]",
"Callable"
] | Any | def v0(self, v1: List, v2: Optional[str], v3: Optional[int]=None, v4: Callable=lambda _: _.run_id):
if v2:
try:
v5 = next((i for (v6, v7) in enumerate(v1) if v4(v7) == v2))
except StopIteration:
return []
v8 = v5 + 1
else:
v8 = 0
v9: Optional[int]
... | [] | [] | [] | 15 | from collections import OrderedDict, defaultdict
from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple, Union, cast
import dagster._check as check
from dagster.core.errors import (
DagsterRunAlreadyExists,
DagsterRunNotFoundError,
DagsterSnapshotDoesNotExist,
)
from dagster.core.events im... | null |
v0 | [
"Union[List[int], Tuple[int], None]"
] | None | def v0(self, v1: Union[List[int], Tuple[int], None]) -> None:
self.bands = self._src_data.RasterCount
if v1 is not None:
if len(v1) > self.bands:
raise ValueError('The lenght of band_list must be less than {0}.'.format(str(self.bands)))
if max(v1) > self.bands or min(v1) < 1:
... | [] | [] | [] | 8 | # Copyright (c) 2022 PaddlePaddle 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 b... | null |
v0 | [
"Union[List[int], Tuple[int], None]",
"Union[List[int], Tuple[int]]"
] | np.ndarray | def v0(self, v1: Union[List[int], Tuple[int], None]=None, v2: Union[List[int], Tuple[int]]=[512, 512]) -> np.ndarray:
if v1 is None:
return self.__getAarray()
else:
return self.__getBlock(v1, v2) | [] | [] | [] | 5 | import os.path as osp
import numpy as np
from typing import List, Tuple, Union
from dslpy.utils.raster2uint8 import rasterToUint8
try:
from osgeo import gdal
except:
import gdal
class Raster:
def __init__(self,
path: str,
band_list: Union[List[int], Tuple[... | null |
v0 | [] | None | def v0(self) -> None:
self.bands = self.__src_data.RasterCount
self.width = self.__src_data.RasterXSize
self.height = self.__src_data.RasterYSize | [] | [] | [] | 4 | import os.path as osp
import numpy as np
from typing import List, Tuple, Union
from dslpy.utils.raster2uint8 import rasterToUint8
try:
from osgeo import gdal
except:
import gdal
class Raster:
def __init__(self,
path: str,
band_list: Union[List[int], Tuple[... | null |
v0 | [
"Union[List[int], Tuple[int]]",
"Union[List[int], Tuple[int]]"
] | np.ndarray | def v0(self, v1: Union[List[int], Tuple[int]], v2: Union[List[int], Tuple[int]]=[512, 512]) -> np.ndarray:
if len(v1) != 2 or len(v2) != 2:
raise ValueError('The length start_loc/block_size must be 2.')
(v3, v4) = v1
(v5, v6) = v2
if (v3 < 0 or v3 > self.width) or (v4 < 0 or v4 > self.height):
... | [] | [
"numpy"
] | [
"import numpy as np"
] | 20 | import os.path as osp
import numpy as np
from typing import List, Tuple, Union
from dslpy.utils.raster2uint8 import rasterToUint8
try:
from osgeo import gdal
except:
import gdal
class Raster:
def __init__(self,
path: str,
band_list: Union[List[int], Tuple[... | null |
v0 | [
"List[str]"
] | Any | def v0(self, v1: List[str]):
for v2 in v1:
self.games_queue.append(v2) | [] | [] | [] | 3 | import asyncio
import subprocess
from multiprocessing import Process
import os
import json
from typing import List, Set
from pathlib import Path
from collections import deque
from arenaclient.proxy.frontend import GameRunner
from arenaclient.proxy.server import run_server
class RunLocal:
def __init__(self):
... | null |
v0 | [
"Path",
"Set[str]"
] | Any | def v0(self, v1: Path, v2: Set[str]):
v3: Path
v4: List[str] = []
for v3 in [x for v5 in v1.iterdir() if v5.is_dir()]:
for v6 in [v5 for v5 in v3.iterdir() if v5.is_file()]:
if str(v6).endswith('ladderbots.json'):
with open(str(v6)) as v7:
v8 = json.lo... | [] | [
"json"
] | [
"import json"
] | 17 | import asyncio
import subprocess
from multiprocessing import Process
import os
import json
from typing import List, Set
from pathlib import Path
from collections import deque
from arenaclient.proxy.frontend import GameRunner
from arenaclient.proxy.server import run_server
class RunLocal:
def __init__(self):
... | null |
v0 | [
"List[str]",
"List[str]",
"List[str]"
] | List[str] | def v0(self, v1: List[str], v2: List[str], v3: List[str]) -> List[str]:
v4 = []
for v5 in v1:
for v6 in v2:
for v7 in v3:
v4.append(','.join([v5, v6, v7]))
return v4 | [] | [] | [] | 7 | import asyncio
import subprocess
from multiprocessing import Process
import os
import json
from typing import List, Set
from pathlib import Path
from collections import deque
from arenaclient.proxy.frontend import GameRunner
from arenaclient.proxy.server import run_server
class RunLocal:
def __init__(self):
... | null |
v10 | [] | None | def v10() -> None:
v6(param_name='epochs', param_values=[0, 1, 42, 1000, 1000])
v0(param_name='epochs', param_values=[-2, -1], exp_msg='The value of `epochs` should be > 0 (type=value_error)') | [
{
"name": "v0",
"input_types": [
"str",
"List[Any]",
"str"
],
"output_type": "None",
"code": "def v0(v1: str, v2: List[Any], v3: str) -> None:\n for v4 in v2:\n with pytest.raises(AssertionError) as v5:\n Trainer(**{v1: v4})\n assert v3 in str(v5... | [] | [] | 3 | # Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... | null |
v10 | [] | None | def v10() -> None:
v6(param_name='patience', param_values=[0, 1, 10, 100])
v0(param_name='patience', param_values=[-2, -1], exp_msg='The value of `patience` should be >= 0 (type=value_error)') | [
{
"name": "v0",
"input_types": [
"str",
"List[Any]",
"str"
],
"output_type": "None",
"code": "def v0(v1: str, v2: List[Any], v3: str) -> None:\n for v4 in v2:\n with pytest.raises(AssertionError) as v5:\n Trainer(**{v1: v4})\n assert v3 in str(v5... | [] | [] | 3 | # Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... | null |
v10 | [] | None | def v10() -> None:
v6(param_name='learning_rate', param_values=[0.42, 17.8, 10.0])
v0(param_name='learning_rate', param_values=[-2, -1e-10, 0, float('inf'), float('nan')], exp_msg='The value of `learning_rate` should be > 0 (type=value_error)') | [
{
"name": "v0",
"input_types": [
"str",
"List[Any]",
"str"
],
"output_type": "None",
"code": "def v0(v1: str, v2: List[Any], v3: str) -> None:\n for v4 in v2:\n with pytest.raises(AssertionError) as v5:\n Trainer(**{v1: v4})\n assert v3 in str(v5... | [] | [] | 3 | # Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... | null |
v10 | [] | None | def v10() -> None:
v6(param_name='learning_rate_decay_factor', param_values=[0, 1e-10, 0.5, 1 - 1e-10])
v0(param_name='learning_rate_decay_factor', param_values=[-2, -1e-10, +1, +5, float('inf'), float('nan')], exp_msg='The value of `learning_rate_decay_factor` should be in the [0, 1) range (type=value_error)') | [
{
"name": "v0",
"input_types": [
"str",
"List[Any]",
"str"
],
"output_type": "None",
"code": "def v0(v1: str, v2: List[Any], v3: str) -> None:\n for v4 in v2:\n with pytest.raises(AssertionError) as v5:\n Trainer(**{v1: v4})\n assert v3 in str(v5... | [] | [] | 3 | # Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... | null |
v0 | [
"list",
"Any"
] | Any | def v0(self, v1: list, v2=1):
v3 = super().get_inline_keyboard(v1, v2)
return {'inline_keyboard': v3} | [] | [] | [] | 3 | import json
import threading
from apps.bot.classes.bots.Bot import Bot as CommonBot
from apps.bot.classes.bots.tg.MyTgBotLongPoll import MyTgBotLongPoll
from apps.bot.classes.bots.tg.TgRequests import TgRequests
from apps.bot.classes.consts.ActivitiesEnum import ActivitiesEnum, TG_ACTIVITIES
from apps.bot.classes.cons... | null |
v0 | [
"Union[Path, str]"
] | Any | def v0(v1: Union[Path, str]):
v2 = np.genfromtxt(v1)
return v2 | [] | [
"numpy"
] | [
"import numpy as np"
] | 3 | import os
from pathlib import Path
from typing import Union
import numpy as np
def _load_from_txt(fpath: Union[Path, str]):
data = np.genfromtxt(fpath)
return data
| null |
v0 | [
"str"
] | Any | def v0(v1: str):
v2 = v1.split('.')[-1]
v3 = '.'.join(v1.split('.')[:-1])
if v3 == '':
return getattr(sys.modules[__name__], v2)
v4 = __import__(v3, fromlist=[v2])
return getattr(v4, v2) | [] | [
"sys"
] | [
"import sys"
] | 7 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | null |
v0 | [
"Any"
] | list | def v0(self, v1) -> list:
v2 = []
v3 = open(v1, 'r')
v4 = json.load(v3)
for v5 in v4['data']:
v6 = v5.get('title', '')
for v7 in v5['paragraphs']:
v8 = v7['context']
for v9 in v7['qas']:
v10 = v9['question']
v11 = v9['id']
... | [] | [
"json"
] | [
"import json"
] | 17 | import json
from collections import defaultdict
from datasets.arrow_dataset import Dataset
import torch
from torch.utils.data.sampler import SequentialSampler
from torch.utils.data import DataLoader, dataloader
from transformers import default_data_collator
from transformers import AutoTokenizer, EvalPrediction
from u... | null |
v0 | [
"list"
] | defaultdict(list) | def v0(self, v1: list) -> defaultdict(list):
v2 = {}
v2['id'] = []
v2['context'] = []
v2['title'] = []
v2['question'] = []
for v3 in v1:
v2['id'].append(v3['id'])
v2['title'].append(v3['title'])
v2['context'].append(v3['context'])
v2['question'].append(v3['questio... | [] | [] | [] | 12 | import json
from collections import defaultdict
from datasets.arrow_dataset import Dataset
import torch
from torch.utils.data.sampler import SequentialSampler
from torch.utils.data import DataLoader, dataloader
from transformers import default_data_collator
from transformers import AutoTokenizer, EvalPrediction
from u... | null |
v0 | [
"Any"
] | dict | def v0(self, v1) -> dict:
v1['question'] = [q.lstrip() for v2 in v1['question']]
v3 = True
v4 = 384
v5 = AutoTokenizer.from_pretrained('SQuAD-test/pretrained/deberta-xlarge-tokenizer')
v6 = v5(v1['question' if v3 else 'context'], v1['context' if v3 else 'question'], truncation='only_second' if v3 el... | [] | [
"transformers"
] | [
"from transformers import default_data_collator",
"from transformers import AutoTokenizer, EvalPrediction"
] | 15 | import json
from collections import defaultdict
from datasets.arrow_dataset import Dataset
import torch
from torch.utils.data.sampler import SequentialSampler
from torch.utils.data import DataLoader, dataloader
from transformers import default_data_collator
from transformers import AutoTokenizer, EvalPrediction
from u... | null |
v0 | [] | List | def v0(self) -> List:
v1 = [v for v2 in [self.input_ids, self.position_ids, self.attention_mask, self.incomplete_prediction_mask, self.beam_select_idx, self.input_log_probs, self.input_unfinished_sents, self.prev_step_results, self.prev_step_scores] if v2 is not None]
if self.past:
v1.extend(self.past)
... | [] | [] | [] | 5 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# This s... | null |
v17 | [
"Tree",
"Any"
] | Any | def v17(v18: Tree, v19=None):
v20 = set()
v21 = v0(v18, v20, strtok=v19)[0]
v22 = v11(v21)
return v22 | [
{
"name": "v0",
"input_types": [
"Tree",
"Any",
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1: Tree, v2, v3=False, v4=None):\n if v3 is True:\n assert len(v1) == 0\n if len(v1) == 0:\n if v3 is True:\n if re.match(\"'([^']+)'\", v... | [
"nltk",
"re"
] | [
"import re",
"from nltk import PorterStemmer, Tree"
] | 5 | import math
import os
import random
import re
import sys
from abc import ABC
from functools import partial
from typing import *
import dill as dill
import torch
import numpy as np
import ujson
import qelos as q
from allennlp.modules.seq2seq_encoders import PytorchSeq2SeqWrapper
from nltk import PorterStemmer, Tree
f... | null |
v0 | [
"dict",
"np.ndarray",
"Any",
"dict"
] | Any | def v0(v1: dict, v2: np.ndarray, v3, v4: dict):
if v1.pop('log_hess', False):
v5 = v1['h']
v6 = np.eye(len(v2))
v7 = 4 * np.sin(v5) ** 2
v8 = 4 * v5 ** 2
v9 = v2.copy()
v10 = np.zeros((len(v9), len(v9)))
for v11 in itertools.combinations_with_replacement(range... | [] | [
"itertools",
"numpy"
] | [
"import itertools",
"import numpy as np"
] | 24 | """Performs a single experiment for a given choice of hyper-parameters."""
import time
import itertools
import numpy as np
import pennylane as qml
import yaml
from pennylane.init import *
from pennylane.templates import *
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard... | null |
v0 | [
"dict",
"np.ndarray",
"Any",
"dict"
] | Any | def v0(v1: dict, v2: np.ndarray, v3, v4: dict):
v5 = np.eye(len(v2))
v6 = []
v7 = []
v8 = []
v9 = []
v10 = []
v11 = []
v12 = []
v13 = v1.pop('log_g_fd', False)
v14 = v1.pop('log_g_ps', False)
v15 = v1.pop('log_g_ms', False)
for v16 in v5:
if v13 or v14:
... | [] | [
"numpy"
] | [
"import numpy as np"
] | 48 | """Performs a single experiment for a given choice of hyper-parameters."""
import time
import itertools
import numpy as np
import pennylane as qml
import yaml
from pennylane.init import *
from pennylane.templates import *
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard... | null |
v6 | [
"v0"
] | Generator[None, None, None] | def v6(v7: v0) -> Generator[None, None, None]:
v3(v7)
yield None | [
{
"name": "v3",
"input_types": [
"v0"
],
"output_type": "None",
"code": "def v3(v4: v0) -> None:\n v5 = time.time()\n with v4.acquire():\n while v4.counter < 2:\n if time.time() - v5 > 0.5:\n raise TimeoutError('Tasks did not execute concurrently')\n ... | [] | [] | 3 | import contextvars
import functools
import sys
import threading
import time
from contextlib import contextmanager
from typing import Any, AsyncGenerator, Generator, List
from di import ConcurrentAsyncExecutor, SyncExecutor
if sys.version_info < (3, 8):
from typing_extensions import Literal
else:
from typing i... | [
"class v0:\n\n def __init__(self) -> None:\n self._lock = threading.Lock()\n self._counter = 0\n\n @property\n def v1(self) -> int:\n return self._counter\n\n @contextmanager\n def v2(self) -> Generator[None, None, None]:\n with self._lock:\n self._counter += 1\... |
v6 | [
"v0"
] | AsyncGenerator[None, None] | async def v6(v7: v0) -> AsyncGenerator[None, None]:
await v3(v7)
yield None | [
{
"name": "v3",
"input_types": [
"v0"
],
"output_type": "None",
"code": "async def v3(v4: v0) -> None:\n v5 = time.time()\n with v4.acquire():\n while v4.counter < 2:\n if time.time() - v5 > 0.5:\n raise TimeoutError('Tasks did not execute concurrentl... | [] | [] | 3 | import contextvars
import functools
import sys
import threading
import time
from contextlib import contextmanager
from typing import Any, AsyncGenerator, Generator, List
from di import ConcurrentAsyncExecutor, SyncExecutor
if sys.version_info < (3, 8):
from typing_extensions import Literal
else:
from typing i... | [
"class v0:\n\n def __init__(self) -> None:\n self._lock = threading.Lock()\n self._counter = 0\n\n @property\n def v1(self) -> int:\n return self._counter\n\n @contextmanager\n def v2(self) -> Generator[None, None, None]:\n with self._lock:\n self._counter += 1\... |
v0 | [
"Optional[str]",
"int"
] | None | def v0(self, v1: Optional[str], v2: int) -> None:
self.saved.append((self.filename, self.ocount))
self.filename = v1
self.ocount = v2 | [] | [] | [] | 4 | from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING
# from typing import cast as typecast
import json
import logging
import os
import yaml
from .config import Config
from .acresource import ACResource
from ..utils import parse_yaml, dump_yaml
AnyDict = Dict[str, Any]
HandlerResult = Optional[Tuple[st... | null |
v0 | [
"str",
"str",
"str"
] | bool | def v0(self, v1: str, v2: str, v3: str) -> bool:
v4 = f'{v1}/{v3}.{v2}'
if v4 in self.k8s_parsed:
self.logger.info(f'dropping K8s dup {v4}')
return False
self.k8s_parsed[v4] = True
return True | [] | [] | [] | 7 | from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING
# from typing import cast as typecast
import json
import logging
import os
import yaml
from .config import Config
from .acresource import ACResource
from ..utils import parse_yaml, dump_yaml
AnyDict = Dict[str, Any]
HandlerResult = Optional[Tuple[st... | null |
v0 | [
"Any",
"Any",
"Optional[str]",
"Optional[str]",
"Optional[str]"
] | Any | def v0(self, v1, v2=False, v3: Optional[str]=None, v4: Optional[str]=None, v5: Optional[str]=None):
self.push_location(v4, 1)
for v6 in v1:
if v2:
self.handle_k8s(v6)
else:
self.process_object(v6, rkey=v3, namespace=v5)
self.ocount += 1
self.pop_location() | [] | [] | [] | 9 | from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING
# from typing import cast as typecast
import json
import logging
import os
import yaml
from .config import Config
from .acresource import ACResource
from ..utils import parse_yaml, dump_yaml
AnyDict = Dict[str, Any]
HandlerResult = Optional[Tuple[st... | null |
v0 | [] | str | def v0(self) -> str:
v1: str = ''
if self.hour != 0:
v1 += f"{self.hour} hour{('s ' if self.hour > 1 else ' ')}"
if self.minute != 0:
v1 += f"{self.minute} minute{('s ' if self.minute > 1 else ' ')}"
if self.second != 0:
v1 += f"{self.second:.02f} second{('s ' if self.second > 1 ... | [] | [] | [] | 10 | """This module implements the Metric entities"""
# Copyright (C) 2021-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import abc
import datetime
import logging
import math
from enum import Enum
from typing import Generic, List, Optional, Sequence, TypeVar, Union
import numpy as np
from ote_sdk.utils.... | null |
v0 | [
"dict"
] | Any | def v0(self, v1: dict):
v2: dict = {}
for (v3, v4) in v1.items():
if isinstance(v4, torch.Tensor):
v2[v3] = v4.to(device=self.device)
else:
v2[v3] = v4
return v2 | [] | [
"torch"
] | [
"import torch",
"from torch.utils.data import DataLoader"
] | 8 | import dataclasses
import logging
from pathlib import Path
from typing import Optional
import time
import os
import torch
from abc import ABC
import numpy as np
from omegaconf import OmegaConf
from torch.utils.data import DataLoader
from tqdm import tqdm
import shutil
# Hydra and OmegaConf imports
from hydra.core.co... | null |
v4 | [
"dict",
"str",
"str"
] | list | def v4(self, v5: dict, v6: str, v7: str) -> list:
def v8(v9, v10: str, v11: str) -> Union[dict, str]:
return v9[v10] == v11
return list(filter(partial(v8, target_key=v6, target_value=v7), v5)) | [
{
"name": "v0",
"input_types": [
"Any",
"str",
"str"
],
"output_type": "Union[dict, str]",
"code": "def v0(v1, v2: str, v3: str) -> Union[dict, str]:\n return v1[v2] == v3",
"dependencies": []
}
] | [
"functools"
] | [
"from functools import partial"
] | 5 | # Chartis CWL DAG
# This class allows the creation of a DAG from a CWL input document.
from airflow import DAG
from functools import partial
from datetime import datetime, timedelta, date
import importlib
import json
import logging
from operator import methodcaller
from ruamel.yaml import YAML
from typing import Union
... | null |
v0 | [
"dict"
] | dict | def v0(self, v1: dict) -> dict:
v2 = self._get_nodes(v1['in'], target_key='id', target_value='parents')
if 'source' in v2[0].keys():
v3 = v2[0]['source']
if isinstance(v3, list):
return list(map(methodcaller('pop', 0), map(methodcaller('split', '/'), v3)))
elif isinstance(v3,... | [] | [
"operator"
] | [
"from operator import methodcaller"
] | 12 | # Chartis CWL DAG
# This class allows the creation of a DAG from a CWL input document.
from airflow import DAG
from functools import partial
from datetime import datetime, timedelta, date
import importlib
import json
import logging
from operator import methodcaller
from ruamel.yaml import YAML
from typing import Union
... | null |
v0 | [
"dict",
"dict"
] | dict | def v0(self, v1: dict, v2: dict) -> dict:
for v3 in v1['in']:
if v3['id'] != 'parents' or v3['id'] != 'subdag_kwargs':
v2[v3['id']] = v3['default']
return v2 | [] | [] | [] | 5 | # Chartis CWL DAG
# This class allows the creation of a DAG from a CWL input document.
from airflow import DAG
from functools import partial
from datetime import datetime, timedelta, date
import importlib
import json
import logging
from operator import methodcaller
from ruamel.yaml import YAML
from typing import Union
... | null |
v0 | [] | list | def v0(self) -> list:
for v1 in self.input_dict['steps']:
logging.debug(v1)
logging.debug('Adding task to dag...')
v2 = self._parse_cwl_node(v1)
self.tasks_list.append(v2)
return self.tasks_list | [] | [
"logging"
] | [
"import logging"
] | 7 | # Chartis CWL DAG
# This class allows the creation of a DAG from a CWL input document.
from airflow import DAG
from functools import partial
from datetime import datetime, timedelta, date
import importlib
import json
import logging
from operator import methodcaller
from ruamel.yaml import YAML
from typing import Union
... | null |
v2 | [
"Iterable[v1]",
"Callable[[v1], v0]"
] | Iterable[Tuple[v0, Iterable[v1]]] | def v2(v3: Iterable[v1], v4: Callable[[v1], v0]) -> Iterable[Tuple[v0, Iterable[v1]]]:
v5 = collections.defaultdict(list)
for v6 in v3:
v5[v4(v6)].append(v6)
return v5.items() | [] | [
"collections"
] | [
"import collections"
] | 5 | import collections
from typing import Callable, Iterable, Tuple, TypeVar
T = TypeVar("T")
K = TypeVar("K")
def groupby_unsorted(
iterable: Iterable[T], key: Callable[[T], K]
) -> Iterable[Tuple[K, Iterable[T]]]:
"""The default itertools.groupby() requires that the iterable is already sorted by the key.
T... | [
"v0 = TypeVar('K')",
"v1 = TypeVar('T')"
] |
v32 | [
"str"
] | Any | def v32(v33: str):
v34 = v23(v33)
if 'timeouts' not in v34:
raise ValueError('Only datasets with explicit timeouts are supported.')
v35 = [terminal or timeout for (v36, v37) in zip(v34['terminals'], v34['timeouts'])]
v34['is_first'] = [True] + v35[:-1]
v38 = {}
if 'infos/qpos' in v34.key... | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "Any",
"code": "def v0(v1):\n v2 = []\n\n def v3(v4, v5):\n if isinstance(v5, h5py.Dataset):\n v2.append(v4)\n v1.visititems(v3)\n return v2",
"dependencies": [
"v29"
]
},
{
"name":... | [
"h5py",
"numpy"
] | [
"import h5py",
"import numpy as np"
] | 24 | # coding=utf-8
# Copyright 2021 The TensorFlow Datasets 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 appl... | null |
v0 | [
"Dict[str, Any]"
] | Dict[str, Any] | def v0(v1: Dict[str, Any]) -> Dict[str, Any]:
v2 = {}
for v3 in v1.keys():
if 'metadata/' not in v3:
continue
v4 = v3.split('/')[1:]
v5 = v2
v6 = v1[v3]
for (v7, v8) in enumerate(v4):
if v7 == len(v4) - 1:
v5[v8] = v6
el... | [] | [] | [] | 16 | # coding=utf-8
# Copyright 2021 The TensorFlow Datasets 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 appl... | null |
v0 | [
"Dict[str, Any]",
"Dict[str, Any]",
"int",
"int"
] | Dict[str, Any] | def v0(v1: Dict[str, Any], v2: Dict[str, Any], v3: int, v4: int) -> Dict[str, Any]:
v5 = {}
for v6 in ['is_first', 'is_last', 'observation', 'action', 'reward', 'discount']:
v5[v6] = v1[v6][v3:v4]
v5['is_last'] = [False] * (v4 - v3)
v5['is_terminal'] = [False] * (v4 - v3)
if 'infos' in v1.ke... | [] | [
"numpy"
] | [
"import numpy as np"
] | 28 | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets 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 appl... | null |
v13 | [
"str",
"str",
"str",
"str",
"str",
"str"
] | Tuple | def v13(v14: str, v15: str, v16: str, v17: str=None, v18: str='-v', v19: str=None) -> Tuple:
if not v17:
v17 = v12()
v20 = uuid.uuid4().hex
v21 = f'{v17}{v20}.{v15}'
v22 = f'{v17}{v20}.webp'
v23 = base64.b64decode(v14)
with open(v21, 'wb') as v24:
v24.write(v23)
v25 = v0(inpu... | [
{
"name": "v0",
"input_types": [
"str",
"str",
"str",
"str",
"str"
],
"output_type": "Dict",
"code": "def v0(v1: str, v2: str, v3: str, v4: str='-v', v5: str=None) -> Dict:\n v6 = f'{getcwebp(bin_path=v5)} {v3} {v1} -o {v2} {v4}'\n v7 = subprocess.Popen(v6, sh... | [
"base64",
"os",
"pathlib",
"subprocess",
"uuid"
] | [
"import subprocess",
"from pathlib import Path",
"import os",
"import uuid",
"import base64"
] | 20 | import subprocess
from pathlib import Path
import os
import uuid
import base64
from typing import Tuple
from typing import Dict, List
from .webpbin import getcwebp, getdwebp, getgifwebp, getwebpmux
def grant_permission():
"""
Change permission of webp executables to 755
:return:
"""
files = [getcw... | null |
v0 | [
"torch.Tensor",
"int",
"int"
] | torch.Tensor | def v0(v1: torch.Tensor, v2: int=-1, v3: int=-2) -> torch.Tensor:
assert v1.ndim >= 2, 'The dimension of the tensor must be at least 2.'
assert v1.shape[v2] == v1.shape[v3], 'The size of ``dim1`` and ``dim2`` must be the same.'
v1 = torch.diagonal(v1, 0, dim1=v2, dim2=v3)
return v1.sum(dim=-1) | [] | [
"torch"
] | [
"import torch",
"from torch import Tensor"
] | 5 | # -*- coding: utf-8 -*-
import math
import warnings
from typing import Callable, Optional
import torch
from torch import Tensor
from torchaudio import functional as F
from .functional.functional import (
_get_sinc_resample_kernel,
_apply_sinc_resample_kernel,
)
__all__ = [
'Spectrogram',
'InverseSpe... | null |
v0 | [
"torch.Tensor",
"torch.Tensor",
"Optional[torch.Tensor]"
] | torch.Tensor | def v0(self, v1: torch.Tensor, v2: torch.Tensor, v3: Optional[torch.Tensor]=None) -> torch.Tensor:
if v1.ndim < 3:
raise ValueError(f'Expected at least 3D tensor (..., channel, freq, time). Found: {v1.shape}')
if v1.dtype != torch.cdouble:
raise ValueError(f'The type of ``specgram`` tensor must ... | [] | [
"torch",
"warnings"
] | [
"import warnings",
"import torch",
"from torch import Tensor"
] | 27 | # -*- coding: utf-8 -*-
import math
import warnings
from typing import Callable, Optional
import torch
from torch import Tensor
from torchaudio import functional as F
from .functional.functional import (
_get_sinc_resample_kernel,
_apply_sinc_resample_kernel,
)
__all__ = [
'Spectrogram',
'InverseSpe... | null |
v0 | [
"int"
] | Tensor | def v0(self, v1: int) -> Tensor:
v2 = torch.linspace(0, 1, self.fade_in_len)
v3 = torch.ones(v1 - self.fade_in_len)
if self.fade_shape == 'linear':
v2 = v2
if self.fade_shape == 'exponential':
v2 = torch.pow(2, v2 - 1) * v2
if self.fade_shape == 'logarithmic':
v2 = torch.log1... | [] | [
"math",
"torch"
] | [
"import math",
"import torch",
"from torch import Tensor"
] | 14 | # -*- coding: utf-8 -*-
import math
import warnings
from typing import Callable, Optional
import torch
from torch import Tensor
from torchaudio import functional as F
from .functional.functional import (
_get_sinc_resample_kernel,
_apply_sinc_resample_kernel,
)
__all__ = [
'Spectrogram',
'InverseSpe... | null |
v0 | [
"int"
] | Tensor | def v0(self, v1: int) -> Tensor:
v2 = torch.linspace(0, 1, self.fade_out_len)
v3 = torch.ones(v1 - self.fade_out_len)
if self.fade_shape == 'linear':
v2 = -v2 + 1
if self.fade_shape == 'exponential':
v2 = torch.pow(2, -v2) * (1 - v2)
if self.fade_shape == 'logarithmic':
v2 = ... | [] | [
"math",
"torch"
] | [
"import math",
"import torch",
"from torch import Tensor"
] | 14 | # -*- coding: utf-8 -*-
import math
import warnings
from typing import Callable, Optional
import torch
from torch import Tensor
from torchaudio import functional as F
from .functional.functional import (
_get_sinc_resample_kernel,
_apply_sinc_resample_kernel,
)
__all__ = [
'Spectrogram',
'InverseSpe... | null |
v0 | [
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"str",
"bool",
"float",
"float"
] | torch.Tensor | def v0(self, v1: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, v4: torch.Tensor, v5: torch.Tensor, v6: str='ref_channel', v7: bool=True, v8: float=1e-07, v9: float=1e-08) -> torch.Tensor:
if self.multi_mask:
v3 = v3.mean(dim=-3)
v4 = v4.mean(dim=-3)
if self.psd_s.ndim == 1:
self.psd_... | [] | [] | [] | 18 | # -*- coding: utf-8 -*-
import math
import warnings
from typing import Callable, Optional
import torch
from torch import Tensor
from torchaudio import functional as F
from .functional.functional import (
_get_sinc_resample_kernel,
_apply_sinc_resample_kernel,
)
__all__ = [
'Spectrogram',
'InverseSpe... | null |
v0 | [
"torch.Tensor",
"torch.Tensor"
] | torch.Tensor | def v0(self, v1: torch.Tensor, v2: torch.Tensor) -> torch.Tensor:
v3 = self.mask_sum_s / (self.mask_sum_s + v2.sum(dim=-1))
v4 = 1 / (self.mask_sum_s + v2.sum(dim=-1))
v1 = self.psd_s * v3[..., None, None] + v1 * v4[..., None, None]
return v1 | [] | [] | [] | 5 | # -*- coding: utf-8 -*-
import math
import warnings
from typing import Callable, Optional
import torch
from torch import Tensor
from torchaudio import functional as F
from .functional.functional import (
_get_sinc_resample_kernel,
_apply_sinc_resample_kernel,
)
__all__ = [
'Spectrogram',
'InverseSpe... | null |
v4 | [
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"str",
"bool",
"float",
"float"
] | torch.Tensor | def v4(self, v5: torch.Tensor, v6: torch.Tensor, v7: torch.Tensor, v8: str='ref_channel', v9: bool=True, v10: float=1e-07, v11: float=1e-08) -> torch.Tensor:
if v9:
v6 = self._tik_reg(v6, reg=v10, eps=v11)
if v8 == 'ref_channel':
v12 = torch.linalg.solve(v6, v5)
v13 = v12 / (v0(v12)[...,... | [
{
"name": "v0",
"input_types": [
"torch.Tensor",
"int",
"int"
],
"output_type": "torch.Tensor",
"code": "def v0(v1: torch.Tensor, v2: int=-1, v3: int=-2) -> torch.Tensor:\n assert v1.ndim >= 2, 'The dimension of the tensor must be at least 2.'\n assert v1.shape[v2] == v1.... | [
"torch"
] | [
"import torch",
"from torch import Tensor"
] | 17 | # -*- coding: utf-8 -*-
import math
import warnings
from typing import Callable, Optional
import torch
from torch import Tensor
from torchaudio import functional as F
from .functional.functional import (
_get_sinc_resample_kernel,
_apply_sinc_resample_kernel,
)
__all__ = [
'Spectrogram',
'InverseSpe... | null |
v0 | [
"torch.Tensor"
] | torch.Tensor | def v0(self, v1: torch.Tensor) -> torch.Tensor:
(v2, v3) = torch.linalg.eig(v1)
(v4, v5) = torch.max(v2.abs(), dim=-1, keepdim=True)
v5 = v5.unsqueeze(-1)
v6 = v3.gather(-1, v5.expand(v1.shape[:-1] + (1,)))
return v6 | [] | [
"torch"
] | [
"import torch",
"from torch import Tensor"
] | 6 | # -*- coding: utf-8 -*-
import math
import warnings
from typing import Callable, Optional
import torch
from torch import Tensor
from torchaudio import functional as F
from .functional.functional import (
_get_sinc_resample_kernel,
_apply_sinc_resample_kernel,
)
__all__ = [
'Spectrogram',
'InverseSpe... | null |
v0 | [
"torch.Tensor",
"torch.Tensor",
"torch.Tensor"
] | torch.Tensor | def v0(self, v1: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor) -> torch.Tensor:
v4 = torch.linalg.solve(v2, v1)
v5 = torch.einsum('...fec,...c->...fe', [v4, v3])
v5 = v5.unsqueeze(-1)
for v6 in range(3):
v5 = torch.matmul(v4, v5)
v5 = torch.matmul(v1, v5)
return v5 | [] | [
"torch"
] | [
"import torch"
] | 8 | """Implementation of MVDR Beamforming Module
Based on https://github.com/espnet/espnet/blob/master/espnet2/enh/layers/beamformer.py
We provide three solutions of MVDR beamforming. One is based on reference channel selection:
Souden, Mehrez, Jacob Benesty, and Sofiene Affes.
"On optimal frequency-domain multichannel l... | null |
v0 | [
"torch.Tensor",
"torch.Tensor"
] | torch.Tensor | def v0(self, v1: torch.Tensor, v2: torch.Tensor) -> torch.Tensor:
v3 = torch.einsum('...fc,...cft->...ft', [v2.conj(), v1])
return v3 | [] | [
"torch"
] | [
"import torch",
"from torch import Tensor"
] | 3 | # -*- coding: utf-8 -*-
import math
import warnings
from typing import Callable, Optional
import torch
from torch import Tensor
from torchaudio import functional as F
from .functional.functional import (
_get_sinc_resample_kernel,
_apply_sinc_resample_kernel,
)
__all__ = [
'Spectrogram',
'InverseSpe... | null |
v4 | [
"torch.Tensor",
"float",
"float"
] | torch.Tensor | def v4(self, v5: torch.Tensor, v6: float=1e-07, v7: float=1e-08) -> torch.Tensor:
v8 = v5.size(-1)
v9 = torch.eye(v8, dtype=v5.dtype, device=v5.device)
with torch.no_grad():
v10 = v0(v5).real[..., None, None] * v6
v10 = v10 + v7
v5 = v5 + v10 * v9[..., :, :]
return v5 | [
{
"name": "v0",
"input_types": [
"torch.Tensor",
"int",
"int"
],
"output_type": "torch.Tensor",
"code": "def v0(v1: torch.Tensor, v2: int=-1, v3: int=-2) -> torch.Tensor:\n assert v1.ndim >= 2, 'The dimension of the tensor must be at least 2.'\n assert v1.shape[v2] == v1.... | [
"torch"
] | [
"import torch",
"from torch import Tensor"
] | 8 | # -*- coding: utf-8 -*-
import math
import warnings
from typing import Callable, Optional
import torch
from torch import Tensor
from torchaudio import functional as F
from .functional.functional import (
_get_sinc_resample_kernel,
_apply_sinc_resample_kernel,
)
__all__ = [
'Spectrogram',
'InverseSpe... | null |
v0 | [] | bool | def v0(self) -> bool:
if not self.available:
return False
if not self._roles:
return True
(v1, v2) = (self._roles, self.guild.me._roles)
return any((v2.has(role_id) for v3 in v1)) | [] | [] | [] | 7 | """
The MIT License (MIT)
Copyright (c) 2015-2021 Rapptz 2021-present CuzImSyntax
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to u... | null |
v9 | [] | None | def v9() -> None:
v10 = os.environ.get('PL_GLOBAL_SEED', None)
if v10 is None:
return
v11 = os.environ.get('PL_SEED_WORKERS', '0')
v3(int(v10), workers=bool(int(v11))) | [
{
"name": "v0",
"input_types": [
"int",
"int"
],
"output_type": "int",
"code": "def v0(v1: int=0, v2: int=255) -> int:\n return random.randint(v1, v2)",
"dependencies": []
},
{
"name": "v3",
"input_types": [
"Optional[int]",
"bool"
],
"output_ty... | [
"numpy",
"os",
"random",
"torch"
] | [
"import os",
"import random",
"from random import getstate as python_get_rng_state",
"from random import setstate as python_set_rng_state",
"import numpy as np",
"import torch"
] | 6 | # Copyright The PyTorch 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 i... | null |
v0 | [
"Dict[str, Any]"
] | None | def v0(v1: Dict[str, Any]) -> None:
torch.set_rng_state(v1['torch'])
np.random.set_state(v1['numpy'])
(v2, v3, v4) = v1['python']
python_set_rng_state((v2, tuple(v3), v4)) | [] | [
"numpy",
"random",
"torch"
] | [
"import random",
"from random import getstate as python_get_rng_state",
"from random import setstate as python_set_rng_state",
"import numpy as np",
"import torch"
] | 5 | # Copyright The PyTorch 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 i... | null |
v0 | [
"qg.QWheelEvent"
] | None | def v0(self, v1: qg.QWheelEvent) -> None:
v2 = v1.angleDelta().y() / 120
v3 = math.copysign(1, v2)
v4 = (1 + self._zoom_per_scroll_notch * v3) ** abs(v2)
v5 = self._zoom * v4
if v5 < self._zoom_limits[0]:
v4 = self._zoom_limits[0] / self._zoom
elif v5 > self._zoom_limits[1]:
v4 =... | [] | [
"math"
] | [
"import math"
] | 11 | #!/usr/bin/env python3
# Created: 06.2020
# Copyright (c) 2020, Matthew Broadway
# License: MIT License
import argparse
import math
import signal
import sys
import time
from typing import Iterable, Tuple, List, Dict
from PyQt5 import QtWidgets as qw, QtCore as qc, QtGui as qg
import ezdxf
from ezdxf import recover
fr... | null |
v0 | [
"qg.QMouseEvent"
] | None | def v0(self, v1: qg.QMouseEvent) -> None:
super().mouseMoveEvent(v1)
v2 = self.mapToScene(v1.pos())
self.mouse_moved.emit(v2)
v3 = self.scene().items(v2)
if v3 != self._selected_items:
self._selected_items = v3
self._selected_index = 0 if self._selected_items else None
self._... | [] | [] | [] | 9 | #!/usr/bin/env python3
# Created: 06.2020
# Copyright (c) 2020, Matthew Broadway
# License: MIT License
import argparse
import math
import signal
import sys
import time
from typing import Iterable, Tuple, List, Dict
from PyQt5 import QtWidgets as qw, QtCore as qc, QtGui as qg
import ezdxf
from ezdxf import recover
fr... | null |
v0 | [] | Iterable[Tuple[int, qw.QCheckBox]] | def v0(self) -> Iterable[Tuple[int, qw.QCheckBox]]:
for v1 in range(self.layers.count()):
v2 = self.layers.itemWidget(self.layers.item(v1))
yield (v1, v2) | [] | [] | [] | 4 | #!/usr/bin/env python3
# Created: 06.2020
# Copyright (c) 2020, Matthew Broadway
# License: MIT License
import argparse
import math
import signal
import sys
import time
from typing import Iterable, Tuple, List, Dict
from PyQt5 import QtWidgets as qw, QtCore as qc, QtGui as qg
import ezdxf
from ezdxf import recover
fr... | null |
v0 | [
"int"
] | None | def v0(v1: int) -> None:
v2 = self.map[v1]
v2.prev.next = v2.next
v2.next.prev = v2.prev
v3 = self.tail.prev
v2.next = self.tail
self.tail.prev = v2
v2.prev = v3
v3.next = v2 | [] | [] | [] | 9 | import random
from queue import deque
from typing import (
List,
Dict,
Set,
Tuple
)
random.seed(9000)
"""
Implementation of Union Find / Disjoint Set datastructure
https://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/UnionFind.pdf
"""
class UnionFind(object):
def __init__(self):
sel... | null |
v0 | [
"int"
] | int | def v0(self, v1: int) -> int:
if v1 not in self.map:
return -1
self._move_to_front(v1)
return self.map[v1].val | [] | [] | [] | 5 | import random
from queue import deque
from typing import (
List,
Dict,
Set,
Tuple
)
random.seed(9000)
"""
Implementation of Union Find / Disjoint Set datastructure
https://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/UnionFind.pdf
"""
class UnionFind(object):
def __init__(self):
sel... | null |
v0 | [
"str"
] | bool | def v0(self, v1: str) -> bool:
v2 = self.root
for v3 in v1:
if v3 not in v2.next:
return False
else:
v2 = v2.next[v3]
return v2.is_word | [] | [] | [] | 8 | class Trie:
class Node:
def __init__(self):
self.is_word = False
self.next = dict()
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Trie.Node()
def insert(self, word: str) -> None:
"""
Inserts a wo... | null |
v0 | [
"str"
] | bool | def v0(self, v1: str) -> bool:
v2 = self._find_starting_node(v1)
return len(v2.children.keys()) > 0 | [] | [] | [] | 3 | import random
from queue import deque
from typing import (
List,
Dict,
Set,
Tuple
)
random.seed(9000)
"""
Implementation of Union Find / Disjoint Set datastructure
https://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/UnionFind.pdf
"""
class UnionFind(object):
def __init__(self):
sel... | null |
v5 | [
"str"
] | List[str] | def v5(self, v6: str) -> List[str]:
def v7(v8, v9: List[str], v10: List[str]) -> None:
if v8.is_word:
v9.append(''.join(v10))
else:
for v11 in v8.children.keys():
v10.append(v11)
v7(v8.children[v11], v9, v10)
v10.pop()
v12 ... | [
{
"name": "v0",
"input_types": [
"Any",
"List[str]",
"List[str]"
],
"output_type": "None",
"code": "def v0(v1, v2: List[str], v3: List[str]) -> None:\n if v1.is_word:\n v2.append(''.join(v3))\n else:\n for v4 in v1.children.keys():\n v3.append(v4)... | [] | [] | 15 | import random
from queue import deque
from typing import (
List,
Dict,
Set,
Tuple
)
random.seed(9000)
"""
Implementation of Union Find / Disjoint Set datastructure
https://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/UnionFind.pdf
"""
class UnionFind(object):
def __init__(self):
sel... | null |
v0 | [
"List[str]"
] | str | def v0(self, v1: List[str]) -> str:
for v2 in v1:
self.insert(v2)
v3 = []
v4 = self.root
while len(v4.children.keys()) == 1:
v5 = [k for v6 in v4.children.keys()]
v6 = v5[0]
v3.append(v6)
v4 = v4[v6]
return ''.join(v3) | [] | [] | [] | 11 | import random
from queue import deque
from typing import (
List,
Dict,
Set,
Tuple
)
random.seed(9000)
"""
Implementation of Union Find / Disjoint Set datastructure
https://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/UnionFind.pdf
"""
class UnionFind(object):
def __init__(self):
sel... | null |
v0 | [
"str"
] | None | def v0(self, v1: str) -> None:
(v2, v3, v4) = v1.partition(':')
self._options[v2] = v4 | [] | [] | [] | 3 | from argparse import ArgumentParser
from dataclasses import dataclass
from typing import (
Dict,
List,
)
from begin.constants import DEFAULT_REGISTRY_NAME
class Request:
def __init__(self, target_identifier: str) -> None:
target_name, _, registry_namespace = target_identifier.partition('@')
... | null |
v0 | [
"types.Tensor",
"types.Tensor"
] | types.Tensor | def v0(v1: types.Tensor, v2: types.Tensor) -> types.Tensor:
v3 = tf.shape(v2)[0]
return tf.reduce_sum(tf.reshape(v1, [v3, 1]) * v2, axis=0) | [] | [
"tensorflow"
] | [
"import tensorflow as tf"
] | 3 | # coding=utf-8
# Copyright 2020 The TF-Agents 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | null |
v0 | [
"types.Tensor"
] | types.Tensor | def v0(v1: types.Tensor) -> types.Tensor:
v2 = tf.reduce_sum(v1 * v1, axis=1, keepdims=True)
v3 = v2 - 2 * tf.matmul(v1, v1, transpose_b=True) + tf.transpose(v2)
return tf.cast(v3, dtype=tf.float32) | [] | [
"tensorflow"
] | [
"import tensorflow as tf"
] | 4 | # coding=utf-8
# Copyright 2020 The TF-Agents 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | null |
v46 | [
"v0"
] | None | def v46(self, v47: v0) -> None:
if v47.name in list((c.name for v48 in self.children)):
raise KeyError(f'Node already has a child named {v47.name}')
else:
v47.parent = self | [] | [] | [] | 5 | from __future__ import annotations
from typing import Hashable, Iterable, Sequence, Tuple, Union
import anytree
PathType = Union[Hashable, Sequence[Hashable]]
class TreeNode(anytree.NodeMixin):
"""
Base class representing a node of a tree, with methods for traversing and altering the tree.
Depends on ... | [
"class v0(anytree.NodeMixin):\n v1 = anytree.Resolver('name')\n\n def __init__(self, v2: Hashable, v3: v0=None, v4: Iterable[v0]=None):\n if not isinstance(v2, str) or '/' in v2:\n raise ValueError(f'invalid name {v2}')\n self.name = v2\n self.parent = v3\n if v4:\n ... |
v0 | [
"dict"
] | (dict, dict) | def v0(self, v1: dict) -> (dict, dict):
v2 = {fieldname: v1.get(mapped_name, '') for (v3, v4) in self.field_map.items()}
v5 = {v3: v2.pop(v3) for v3 in self.user_pk_fields}
return (v5, v2) | [] | [] | [] | 4 | import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
import requests
from constance import config as constance
from crashlog.middleware import process_exception
from social_django.models import UserSocialAuth
from unicef_security.... | null |
v0 | [
"int",
"int",
"int",
"bool"
] | bool | def v0(self, v1: int, v2: int, v3: int, v4: bool=False) -> bool:
v5 = 32 if v4 else 512
v6 = v1 // v5
v7 = v3 // v5
return not (v6 != self.x or v7 != self.z or v2 < 0 or (v2 > 255)) | [] | [] | [] | 5 | from typing import Union, List, BinaryIO
from .empty_chunk import EmptyChunk
from .chunk import Chunk
from .empty_section import EmptySection
from .block import Block
from .biome import Biome
from .errors import OutOfBoundsCoordinates
from io import BytesIO
from nbt import nbt
import zlib
import math
def from_inclusiv... | null |
v0 | [] | str | def v0(self) -> str:
assert self.did_info.origin_coin is not None
v1 = self.did_info.origin_coin.puzzle_hash
assert v1 is not None
return v1.hex() | [] | [] | [] | 5 | import logging
import time
import json
from typing import Dict, Optional, List, Any, Set, Tuple, Union
from blspy import AugSchemeMPL, G1Element
from secrets import token_bytes
from plotter.protocols import wallet_protocol
from plotter.protocols.wallet_protocol import RespondAdditions, RejectAdditionsRequest
from plo... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
self.can_use_independent_es_cluster = v1 == 'true'
self.save() | [] | [] | [] | 3 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... | null |
v0 | [
"datetime"
] | int | def v0(self, v1: datetime) -> int:
if not isinstance(v1, datetime):
raise TypeError('a datetime is required')
return int(v1.timestamp()) | [] | [
"datetime"
] | [
"from datetime import datetime, timezone, timedelta"
] | 4 | import jwt, re, uuid, hmac
from jwt.algorithms import requires_cryptography, has_crypto
from datetime import datetime, timezone, timedelta
from typing import Optional, Dict, Union, Sequence
from fastapi import Request, Response, WebSocket
from fastapi_jwt_auth.auth_config import AuthConfig
from fastapi_jwt_auth.excepti... | null |
v0 | [
"str",
"Optional[Union[timedelta, int, bool]]"
] | Union[None, int] | def v0(self, v1: str, v2: Optional[Union[timedelta, int, bool]]=None) -> Union[None, int]:
if v2 and (not isinstance(v2, (timedelta, int, bool))):
raise TypeError('expires_time must be between timedelta, int, bool')
if v2 is not False:
if v1 == 'access':
v2 = v2 or self._access_token... | [] | [
"datetime"
] | [
"from datetime import datetime, timezone, timedelta"
] | 19 | import jwt, re, uuid, hmac
from jwt.algorithms import requires_cryptography, has_crypto
from datetime import datetime, timezone, timedelta
from typing import Optional, Dict, Union, Sequence
from fastapi import Request, Response, WebSocket
from fastapi_jwt_auth.auth_config import AuthConfig
from fastapi_jwt_auth.excepti... | null |
v0 | [
"str",
"Optional[str]"
] | None | def v0(self, v1: str, v2: Optional[str]=None) -> None:
v3 = self._verified_token(v1, v2)
if v3['type'] in self._denylist_token_checks:
self._check_token_is_revoked(v3)
self._verifying_scopes(v3) | [] | [] | [] | 5 | import jwt, re, uuid, hmac
from jwt.algorithms import requires_cryptography, has_crypto
from datetime import datetime, timezone, timedelta
from typing import Optional, Dict, Union, Sequence
from fastapi import Request, Response, WebSocket
from fastapi_jwt_auth.auth_config import AuthConfig
from fastapi_jwt_auth.excepti... | null |
v0 | [
"Optional[str]"
] | Optional[Dict[str, Union[str, int, bool]]] | def v0(self, v1: Optional[str]=None) -> Optional[Dict[str, Union[str, int, bool]]]:
v2 = v1 or self._token
if v2:
return self._verified_token(v2)
return None | [] | [] | [] | 5 | import jwt, re, uuid, hmac
from jwt.algorithms import requires_cryptography, has_crypto
from datetime import datetime, timezone, timedelta
from typing import Optional, Dict, Union, Sequence
from fastapi import Request, Response, WebSocket
from fastapi_jwt_auth.auth_config import AuthConfig
from fastapi_jwt_auth.excepti... | null |
v0 | [] | Optional[Union[str, int]] | def v0(self) -> Optional[Union[str, int]]:
if self._token:
return self._verified_token(self._token)['sub']
return None | [] | [] | [] | 4 | import jwt, re, uuid, hmac
from jwt.algorithms import requires_cryptography, has_crypto
from datetime import datetime, timezone, timedelta
from typing import Optional, Dict, Union, Sequence
from fastapi import Request, Response, WebSocket
from fastapi_jwt_auth.auth_config import AuthConfig
from fastapi_jwt_auth.excepti... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
v2 = ['cbsr', 'ra', 'nuaa']
for v3 in v2:
for (v4, v5) in self._list_variations():
yield [v3, v5, v4] | [] | [] | [] | 5 | import os
from keras.applications import MobileNetV2
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import matplotlib
from keras.utils import np_utils
matplotlib.use('Agg')
import glob
from typing import Tuple, List
import keras
import numpy as np
import ... | null |
v0 | [
"str"
] | Tuple[List[str], List, np.ndarray] | def v0(self, v1: str) -> Tuple[List[str], List, np.ndarray]:
v2 = sorted(os.listdir(os.getcwd()), key=str.lower)
v3 = []
for v4 in range(len(v2)):
os.chdir(join(v2[v4], v1))
v5 = len(self._fetch_all_images('./'))
v3.append(v5)
os.chdir('../..')
v6 = np.sum(v3)
return ... | [] | [
"numpy",
"os"
] | [
"import os",
"import numpy as np",
"from os.path import join"
] | 10 | import os
from keras.applications import MobileNetV2
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import matplotlib
from keras.utils import np_utils
matplotlib.use('Agg')
import glob
from typing import Tuple, List
import keras
import numpy as np
import ... | null |
v0 | [
"Any",
"Any",
"Any"
] | Tuple[np.ndarray, List] | def v0(self, v1, v2, v3) -> Tuple[np.ndarray, List]:
v4 = np.zeros(v3)
v5 = 0
v6 = 0
v7 = []
for v8 in v2:
v7.append(v8)
print('Label:%2d\tFamily: %15s\tNumber of images: %d' % (v6, v1[v6], v8))
for v9 in range(v8):
v4[v5] = v6
v5 += 1
v6 += 1
... | [] | [
"numpy"
] | [
"import numpy as np"
] | 13 | import os
from keras.applications import MobileNetV2
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import matplotlib
from keras.utils import np_utils
matplotlib.use('Agg')
import glob
from typing import Tuple, List
import keras
import numpy as np
import ... | null |
v0 | [
"Any"
] | List[str] | def v0(self, v1) -> List[str]:
v2 = []
for v3 in self.exts:
v2.extend(glob.glob(join(v1, v3)))
return v2 | [] | [
"glob",
"os"
] | [
"import os",
"import glob",
"from os.path import join"
] | 5 | import os
from keras.applications import MobileNetV2
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import matplotlib
from keras.utils import np_utils
matplotlib.use('Agg')
import glob
from typing import Tuple, List
import keras
import numpy as np
import ... | null |
v0 | [
"List[torch.Tensor]"
] | Any | def v0(self, v1: List[torch.Tensor], *v2, **v3):
v4 = v1[-1] / self.loss_config['student_temp']
v4 = v4.chunk(self.loss_config['num_crops'])
v5 = F.softmax((self.teacher_output - self.center) / self.teacher_temp, dim=-1)
v5 = v5.detach().chunk(len(self.loss_config['crops_for_teacher']))
v6 = 0
v... | [] | [
"torch"
] | [
"import torch",
"import torch.distributed as dist",
"import torch.nn.functional as F"
] | 17 | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import pprint
from typing import List
import torch
import torch.distributed as dist
import torch.nn.functional as F
from classy... | null |
v0 | [] | str | def v0() -> str:
global _NEXT_STATE_ID
v1 = 'X%d' % (_NEXT_STATE_ID,)
v2 += 1
return v1 | [] | [] | [] | 5 | # Copyright 2014-2016 OpenMarket Ltd
# Copyright 2018 New Vector 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 ... | null |
v0 | [
"str"
] | Set[str] | async def v0(self, v1: str) -> Set[str]:
v2 = await self.store.get_latest_event_ids_in_room(v1)
return await self.get_hosts_in_room_at_events(v1, v2) | [] | [] | [] | 3 | # Copyright 2014-2016 OpenMarket Ltd
# Copyright 2018 New Vector 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 ... | null |
v0 | [
"str",
"Iterable[str]"
] | Set[str] | async def v0(self, v1: str, v2: Iterable[str]) -> Set[str]:
v3 = await self.resolve_state_groups_for_events(v1, v2)
return await self.store.get_joined_hosts(v1, v3) | [] | [] | [] | 3 | # Copyright 2014-2016 OpenMarket Ltd
# Copyright 2018 New Vector 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 ... | null |
v0 | [
"List[Tensor]"
] | Tensor | def v0(self, v1: List[Tensor]) -> Tensor:
v2 = torch.cat(v1, dim=0)
(v3, v4) = (v2.device, v2.dtype)
v5 = torch.cat([torch.full_like(b[:, :1], i, dtype=v4, layout=torch.strided, device=v3) for (v6, v7) in enumerate(v1)], dim=0)
v8 = torch.cat([v5, v2], dim=1)
return v8 | [] | [
"torch"
] | [
"import torch",
"import torch.nn.functional as F",
"from torch import nn, Tensor",
"from torch.jit.annotations import Optional, List, Dict, Tuple"
] | 6 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from typing import Union
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from torchvision.ops import roi_align
from torchvision.ops.boxes import box_area
from torch.jit.annotations import Optional, List, Dict, Tuple
imp... | null |
v0 | [
"Tensor",
"List[int]"
] | float | def v0(self, v1: Tensor, v2: List[int]) -> float:
v3 = v1.shape[-2:]
v4 = torch.jit.annotate(List[float], [])
for (v5, v6) in zip(v3, v2):
v7 = float(v5) / float(v6)
v8 = 2 ** float(torch.tensor(v7).log2().round())
v4.append(v8)
assert v4[0] == v4[1]
return v4[0] | [] | [
"torch"
] | [
"import torch",
"import torch.nn.functional as F",
"from torch import nn, Tensor",
"from torch.jit.annotations import Optional, List, Dict, Tuple"
] | 9 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from typing import Union
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from torchvision.ops import roi_align
from torchvision.ops.boxes import box_area
from torch.jit.annotations import Optional, List, Dict, Tuple
imp... | null |
v6 | [
"List[Tensor]",
"List[Tuple[int, int]]"
] | None | def v6(self, v7: List[Tensor], v8: List[Tuple[int, int]]) -> None:
assert len(v8) != 0
v9 = 0
v10 = 0
for v11 in v8:
v9 = max(v11[0], v9)
v10 = max(v11[1], v10)
v12 = (v9, v10)
v13 = [self.infer_scale(feat, v12) for v14 in v7]
v15 = -torch.log2(torch.tensor(v13[0], dtype=torc... | [
{
"name": "v0",
"input_types": [
"int",
"int",
"int",
"int",
"float"
],
"output_type": "Any",
"code": "def v0(v1: int, v2: int, v3: int=224, v4: int=4, v5: float=1e-06):\n return LevelMapper(v1, v2, v3, v4, v5)",
"dependencies": []
}
] | [
"torch"
] | [
"import torch",
"from torch import nn, Tensor"
] | 13 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn, Tensor
import torchvision
from torchvision.ops import roi_align
from torchvision.ops.boxes import box_area
from typing import Optional, List, Dict, Tuple, Union
# copying result_idx_in_level to a specific inde... | null |
v0 | [] | None | def v0(self) -> None:
self.mqtt_client.connect(self.auth.hostname, self.auth.port)
self.mqtt_client.loop_start() | [] | [] | [] | 3 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
import logging
from paho.mqtt import client as mqtt
from auth import SymmetricKeyAuth, X509Auth
from mqtt_helpers import IncomingMessageList, IncomingAckList, Conn... | null |
v6 | [
"List[v0]"
] | List[v0] | def v6(v7: List[v0]) -> List[v0]:
v8 = []
for v9 in v7:
v10 = replace(v9, infer_event_timestamp_col=True)
v11 = replace(v9, infer_event_timestamp_col=False)
v8.extend([v10, v11])
return v8 | [] | [
"dataclasses"
] | [
"from dataclasses import dataclass, replace"
] | 7 | import tempfile
import uuid
from contextlib import contextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Optional, Union
import pytest
from feast import FeatureStore, FeatureView, RepoConfig, driver_test_data, importe... | [
"@dataclass(frozen=True, repr=True)\nclass v0:\n v1: str = 'local'\n v2: Union[str, Dict] = 'sqlite'\n v3: str = 'tests.integration.feature_repos.universal.data_sources.file.FileDataSourceCreator'\n v4: bool = True\n v5: bool = True"
] |
v6 | [
"List[v0]"
] | List[v0] | def v6(v7: List[v0]) -> List[v0]:
v8 = []
for v9 in v7:
if 'FileDataSourceCreator' in v9.offline_store_creator:
v8.append(v9)
elif 'RedshiftDataSourceCreator' in v9.offline_store_creator:
for v10 in ['local', 'aws']:
v8.append(replace(v9, provider=v10))
... | [] | [
"dataclasses"
] | [
"from dataclasses import dataclass, replace"
] | 12 | import tempfile
import uuid
from contextlib import contextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Optional, Union
import pytest
from feast import FeatureStore, FeatureView, RepoConfig, driver_test_data, importe... | [
"@dataclass(frozen=True, repr=True)\nclass v0:\n v1: str = 'local'\n v2: Union[str, Dict] = 'sqlite'\n v3: str = 'tests.integration.feature_repos.universal.data_sources.file.FileDataSourceCreator'\n v4: bool = True\n v5: bool = True"
] |
v0 | [] | Optional[str] | def v0(self) -> Optional[str]:
if self._orders_table is None:
v1 = self.data_source_creator.get_prefixed_table_name(self.name, 'orders')
v2 = self.data_source_creator.create_data_source(v1, self.orders_df, event_timestamp_column='event_timestamp', created_timestamp_column='created')
if hasat... | [] | [] | [] | 9 | import tempfile
import uuid
from contextlib import contextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Optional, Union
import pytest
from feast import FeatureStore, FeatureView, RepoConfig, driver_test_data, importe... | null |
v0 | [
"nx.Graph"
] | Any | def v0(v1: nx.Graph):
with open('pid_IPaddr_map.txt', 'w') as v2:
for v3 in v1.nodes:
v4 = []
for (v5, v6) in v1.edges(v3):
if v5 < v6:
v4.append(v1.edges[v5, v6]['addresses'][0])
else:
v4.append(v1.edges[v5, v6]... | [] | [] | [] | 20 | # From https://github.com/mininet/mininet/wiki/Introduction-to-Mininet
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import dumpNodeConnections
from mininet.log import setLogLevel
from mininet.cli import CLI
from mininet.link import TCLink
#from mininet.node import CPULimitedHost
imp... | null |
v0 | [
"dict"
] | dict | def v0(v1: dict) -> dict:
v2 = []
for v3 in v1['shopping_results']:
v2.append({'title': v3['title'], 'price': v3['extracted_price'], 'supplier': v3['source'], 'link': v3['link']})
for v3 in v1['inline_shopping_results']:
v2.append({'title': v3['title'], 'price': v3['extracted_price'], 'suppl... | [] | [] | [] | 7 | from serpapi import GoogleSearch
class SERP:
def __init__(self, serpapi_api_key: str):
self.data = {
"api_key": serpapi_api_key,
"tbm": "shop",
"engine": "google"
}
def get(self, query: str):
self.data.update({"q": query})
res... | null |
v0 | [
"torch.Tensor"
] | Any | def v0(self, v1: torch.Tensor):
if not torch.is_tensor(v1):
v1 = torch.tensor(v1)
self.theta_i = v1
self.update_K_xX_dx() | [] | [
"torch"
] | [
"import torch"
] | 5 | from typing import Tuple
import torch
import gpytorch
import botorch
from src.cholesky import one_step_cholesky
class GradientInformation(botorch.acquisition.AnalyticAcquisitionFunction):
'''Acquisition function to sample points for gradient information.
Attributes:
model: Gaussian process model th... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.