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 | [
"list"
] | pd.DataFrame | def v0(v1: list) -> pd.DataFrame:
v2 = ['date', 'time', 'network', 'station', 'channel', 'duration', 'cc', 'noise']
assert len(v1[0]) == len(v2), '(ValueError) Data length must match column length'
v3 = pd.DataFrame(v1, columns=v2)
return v3 | [] | [
"pandas"
] | [
"import pandas as pd"
] | 5 | """
duration.py
measure the duration using the coda envelope
"""
import obspy
import types
import warnings
import numpy as np
import pandas as pd
import madpy.noise as n
from typing import Tuple
import madpy.checks as ch
import madpy.config as config
import matplotlib.pyplot as plt
from scipy.signal import hilbert
im... | null |
v0 | [
"List[int]",
"int"
] | List[int] | def v0(self, v1: List[int], v2: int) -> List[int]:
v3 = {}
v4 = []
for v5 in range(0, len(v1)):
v6 = v2 - v1[v5]
v7 = v3.get(v6, None)
if v7 is None:
v3[v1[v5]] = v5
else:
v4.append(v5)
v4.append(v7)
return v4
return v4 | [] | [] | [] | 13 | #!/bin/env python3
#-*- coding: utf8 -*-
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
numMap = {}
result = []
for i in range(0, len(nums)):
needNum = target - nums[i]
index = numMap.get(needNum, None)
... | null |
v0 | [
"BaseEstimator",
"str"
] | None | def v0(v1: BaseEstimator, v2: str) -> None:
with bz2.open(v2, 'wb') as v3:
pickle.dump(v1, v3) | [] | [
"bz2",
"pickle"
] | [
"import bz2",
"import pickle"
] | 3 | """This module cointains the implementation of the scorer based on naive bayes."""
import bz2
import math
import pickle
from datetime import datetime
from typing import Sequence, Union
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import... | null |
v0 | [
"Union[Path, str]"
] | Any | def v0(v1: Union[Path, str]) -> Any:
with open(v1, 'rb') as v2:
v3 = pickle.load(v2)
return v3 | [] | [
"pickle"
] | [
"import pickle"
] | 4 | import configparser
import os.path
import pickle
from pathlib import Path
from typing import Any, Union
def write_pickle(obj: Any, filepath: str):
with open(filepath, "wb") as save_file:
pickle.dump(obj, save_file)
def read_pickle(filepath: Union[Path, str]) -> Any:
with open(filepath, "rb") as f:
... | null |
v0 | [
"Optional[bytes]",
"Optional[bytes]"
] | Tuple[Optional[bytes], Optional[bytes]] | def v0(v1: Optional[bytes], v2: Optional[bytes]) -> Tuple[Optional[bytes], Optional[bytes]]:
if v1:
if v2:
v1 = b''.join([v2, v1])
v2 = None
if b'\n' not in v1:
v2 = v1
v1 = None
elif not v1.endswith(b'\n'):
v3 = v1.rindex(b'\n') + ... | [] | [] | [] | 13 | """This module defines the `IoManager` class
which manages I/O for file objects connected to an existing gdb process
or pty.
"""
import io
import select
import time
from pprint import pformat
from typing import Union, List, Optional, Dict, Any, Tuple
from pygdbmi import gdbmiparser
import os
import logging
from pygdbmi... | null |
v0 | [
"Union[np.ndarray, float]",
"Union[np.ndarray, float]",
"Union[np.ndarray, float]",
"Any"
] | None | def v0(self, v1: Union[np.ndarray, float]=0, v2: Union[np.ndarray, float]=0, v3: Union[np.ndarray, float]=0, v4='earth') -> None:
(v5, v6, v7) = self.convert_axes(x_from=v1, y_from=v2, z_from=v3, from_axes=v4, to_axes='earth')
self.Fx_e = self.Fx_e + v5
self.Fy_e = self.Fy_e + v6
self.Fz_e = self.Fz_e +... | [] | [] | [] | 5 | from aerosandbox.dynamics.point_mass.common_point_mass import _DynamicsPointMassBaseClass
from aerosandbox.weights.mass_properties import MassProperties
import aerosandbox.numpy as np
from typing import Union, Dict, Tuple
class DynamicsPointMass3DCartesian(_DynamicsPointMassBaseClass):
"""
Dynamics instance:
... | null |
v2 | [
"Any"
] | Dict[int, str] | def v2(v3: Any) -> Dict[int, str]:
v4 = {}
v5 = 0
v6 = v0(v3)
for v7 in v6:
v8 = v3.index(v7)
v9 = v5 + v8
v4[v9] = v7
v10 = len(v7)
v5 = v9 + v10
v3 = v3[v8 + v10:]
return v4 | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "List[str]",
"code": "def v0(v1: Any) -> List[str]:\n return codegrabpat.findall(str(v1))",
"dependencies": []
}
] | [] | [] | 12 | #!/usr/bin/env python3
""" FormatBlock - Escape Codes
Functions to test against/strip terminal escape codes from strings.
-Christopher Welborn 2-17-18
"""
import re
from typing import (
Any,
Dict,
List,
)
_codepats = (
# Colors.
r'(([\d;]+)?m{1})',
# Cursor show/hide.
r'(\?25l)',
... | null |
v11 | [
"Any"
] | Dict[int, str] | def v11(v12: Any) -> Dict[int, str]:
v13 = v0(v12)
if not v13:
return {i: c for (v14, v15) in enumerate(v12)}
v16 = {}
for v17 in sorted(v13):
v18 = v13[v17]
if v17 == 0:
v16[v17] = v18
continue
v19 = max(v16 or {0: ''}, key=int)
v20 = v16.... | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "Dict[int, str]",
"code": "def v0(v1: Any) -> Dict[int, str]:\n v2 = {}\n v3 = 0\n v4 = get_codes(v1)\n for v5 in v4:\n v6 = v1.index(v5)\n v7 = v3 + v6\n v2[v7] = v5\n v8 = len(v5)\n v3... | [] | [] | 24 | #!/usr/bin/env python3
""" FormatBlock - Escape Codes
Functions to test against/strip terminal escape codes from strings.
-Christopher Welborn 2-17-18
"""
import re
from typing import (
Any,
Dict,
List,
)
_codepats = (
# Colors.
r'(([\d;]+)?m{1})',
# Cursor show/hide.
r'(\?25l)',
... | null |
v25 | [
"Any"
] | List[str] | def v25(v26: Any) -> List[str]:
v27 = v11(v26)
return [v27[i] for v28 in sorted(v27, key=int)] | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "Dict[int, str]",
"code": "def v0(v1: Any) -> Dict[int, str]:\n v2 = {}\n v3 = 0\n v4 = get_codes(v1)\n for v5 in v4:\n v6 = v1.index(v5)\n v7 = v3 + v6\n v2[v7] = v5\n v8 = len(v5)\n v3... | [] | [] | 3 | #!/usr/bin/env python3
""" FormatBlock - Escape Codes
Functions to test against/strip terminal escape codes from strings.
-Christopher Welborn 2-17-18
"""
import re
from typing import (
Any,
Dict,
List,
)
_codepats = (
# Colors.
r'(([\d;]+)?m{1})',
# Cursor show/hide.
r'(\?25l)',
... | null |
v0 | [
"Union[Tensor, List[Tensor]]"
] | Tensor | def v0(v1: Union[Tensor, List[Tensor]]) -> Tensor:
v1 = v1 if isinstance(v1, (list, tuple)) else [v1]
v1 = [y.unsqueeze(0) if y.numel() == 1 and y.ndim == 0 else y for v2 in v1]
if not v1:
raise ValueError('No samples to concatenate')
return torch.cat(v1, dim=0) | [] | [
"torch"
] | [
"import torch",
"from torch import Tensor, tensor"
] | 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 | [
"torch.Tensor",
"Optional[int]"
] | torch.Tensor | def v0(v1: torch.Tensor, v2: Optional[int]=None) -> torch.Tensor:
if v2 is None:
v2 = int(v1.max().detach().item() + 1)
v3 = torch.zeros(v1.shape[0], v2, *v1.shape[1:], dtype=v1.dtype, device=v1.device)
v4 = v1.long().unsqueeze(1).expand_as(v3)
return v3.scatter_(1, v4, 1.0) | [] | [
"torch"
] | [
"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 | [
"Tensor",
"int",
"int"
] | Tensor | def v0(v1: Tensor, v2: int=1, v3: int=1) -> Tensor:
v4 = torch.zeros_like(v1)
if v2 == 1:
v5 = v4.scatter(v3, v1.argmax(dim=v3, keepdim=True), 1.0)
else:
v5 = v4.scatter(v3, v1.topk(k=v2, dim=v3).indices, 1.0)
return v5.int() | [] | [
"torch"
] | [
"import torch",
"from torch import Tensor, tensor"
] | 7 | # 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 | [
"Tensor"
] | List[Tensor] | def v0(v1: Tensor) -> List[Tensor]:
v2: dict = {}
for (v3, v4) in enumerate(v1):
v4 = v4.item()
if v4 in v2:
v2[v4] += [v3]
else:
v2[v4] = [v3]
return [tensor(x, dtype=torch.long) for v5 in v2.values()] | [] | [
"torch"
] | [
"import torch",
"from torch import Tensor, tensor"
] | 9 | # 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 | [
"int",
"Any"
] | List[str] | def v0(self, v1: int, v2) -> List[str]:
v3 = ['--node-vm-size', v2.machine_type, '--node-count', str(v1)] + self.resource_group.args
if self.vm_config.os_disk and self.vm_config.os_disk.disk_size:
v3 += ['--node-osdisk-size', str(self.vm_config.os_disk.disk_size)]
if self.cluster_version:
v3... | [] | [] | [] | 7 | # Copyright 2017 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | null |
v2 | [
"torch.Tensor"
] | Any | def v2(self, v3: torch.Tensor):
v4 = v3.shape[0]
(v5, v6) = self.rnn(self.input_dropout(v3))
def v7(v8):
v8 = v8.view(self.num_layers, 2, v4, self.hidden_size).permute(0, 2, 1, 3).reshape(self.num_layers, v4, self.num_direction * self.hidden_size)
return v8
if self.bidirectional and sel... | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "Any",
"code": "def v0(v1):\n v1 = v1.view(self.num_layers, 2, batch_size, self.hidden_size).permute(0, 2, 1, 3).reshape(self.num_layers, batch_size, self.num_direction * self.hidden_size)\n return v1",
"dependencies": []
... | [] | [] | 13 | # encoding: utf-8
"""
@author : zhirui zhou
@contact: evilpsycho42@gmail.com
@time : 2020/9/27 14:51
"""
import torch
import torch.nn as nn
class RNNEncoder(nn.Module):
def __init__(self, input_size, rnn_type, hidden_size, bidirectional, num_layers, dropout):
super().__init__()
self.input_size ... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
v2 = self.get_topics(v1)
v3 = self.get_countries(v1)
v4 = self.get_stats()
v4 = v4['stats']
v5 = self.get_sources()
v6 = {country['country']: i for (v7, v8) in enumerate(v3)}
for v9 in v4:
v3[v6[v9]]['stats'] = v4[v9]
v3[v6[v9]]['sources'] = v5[v9]
... | [] | [] | [] | 11 | import json
import os
from typing import List
from util import COUNTRIES, TOPICS
class MetaDataHandler:
def __init__(self):
self.meta_data_dir = os.path.join(os.path.dirname(__file__), "data")
self.stats_path = os.path.join(self.meta_data_dir, "stats.json")
self.sources_path = os.path.joi... | null |
v28 | [
"List[str]"
] | Tuple[List[str], List[str], List[str]] | def v28(v29: List[str]) -> Tuple[List[str], List[str], List[str]]:
v30 = []
v31 = []
v32 = []
for v33 in v29:
v33 = ' '.join(v33.split())
v34 = v10(v33)
v35 = v33 != v34
v36 = v14(v34)
if not v36:
v30.append(v33)
elif v36 and v35:
v... | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "List[str]",
"code": "def v0(v1: str) -> List[str]:\n v2 = v1.lower()\n v3 = []\n for (v4, v5) in BANNED_WORDS.items():\n if v4 in v2:\n if 'realm_name' in v2:\n continue\n v6 = di... | [] | [] | 15 | import re
from typing import List, Match, Tuple
from bs4 import BeautifulSoup
# The phrases in this list will be ignored. The longest phrase is
# tried first; this removes the chance of smaller phrases changing
# the text before longer phrases are tried.
# The errors shown by `tools/check-capitalization` can be added... | null |
v0 | [
"str",
"str",
"int"
] | bool | def v0(v1: str, v2: str, v3: int) -> bool:
if len(v1) > v3:
return False
if re.search(v2, v1):
return True
return False | [] | [
"re"
] | [
"import re"
] | 6 | # Copyright 2020 The Merlin Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | null |
v0 | [] | None | def v0(self) -> None:
v1 = 0
v2 = self.len_ce * math.sqrt(3) / 2
for v3 in range(self.nr):
for v4 in range(self.nc):
v5 = v2 + v3 * v2 + 2 * v4 * v2
v6 = 1.5 * v3 * self.len_ce
v7 = ((v5, v6), (v5 + v2, v6 + self.len_ce * 0.5), (v5 + v2, v6 + self.len_ce * 1.5), (... | [] | [
"math"
] | [
"import math"
] | 12 | """Strategy generator app with Tkinter GUI."""
import math
import os
import tkinter as tk
import typing
from collections import Counter
from copy import deepcopy
from tkinter import Grid, filedialog, font, messagebox
from darkhex.utils.cell_state import cellState
from darkhex.utils.isomorphic import isomorphic_single
... | null |
v0 | [
"str"
] | None | def v0(self, v1: str) -> None:
self.canvas.delete('all')
for v2 in range(self.nr * self.nc):
self._draw_cell(v1[v2], v2) | [] | [] | [] | 4 | """Strategy generator app with Tkinter GUI."""
import math
import os
import tkinter as tk
import typing
from collections import Counter
from copy import deepcopy
from tkinter import Grid, filedialog, font, messagebox
from darkhex.utils.cell_state import cellState
from darkhex.utils.isomorphic import isomorphic_single
... | null |
v23 | [
"v0"
] | Any | def v23(self, v24: v0):
self.num_cols = v24.game_info['num_cols']
self.num_rows = v24.game_info['num_rows']
self.p = v24.game_info['player']
self.o = 1 - self.p
self.history_buffer = v24
self.history_buffer.stratgen_class = self
self.board = v24.board[-1]
self.move_stack = v24.move_stack... | [] | [] | [] | 11 | """Strategy generator app with Tkinter GUI."""
import math
import os
import tkinter as tk
import typing
from collections import Counter
from copy import deepcopy
from tkinter import Grid, filedialog, font, messagebox
from darkhex.utils.cell_state import cellState
from darkhex.utils.isomorphic import isomorphic_single
... | [
"class v0:\n\n def __init__(self, v1: str, v2: int, v3: int, v4: int, v5: bool, v6) -> None:\n self.game_info = {'num_rows': v2, 'num_cols': v3, 'player': v4, 'isomorphic': v5, 'initial_board': v1}\n self.info_states = []\n self.moves_and_boards = []\n self.board = []\n self.mo... |
v0 | [
"typing.List[int]",
"typing.List[float]"
] | typing.List[typing.Tuple[int, float]] | def v0(self, v1: typing.List[int], v2: typing.List[float]=None) -> typing.List[typing.Tuple[int, float]]:
if v2 is None:
v2 = [1 / len(v1)] * len(v1)
else:
assert len(v1) == len(v2)
return list(zip(v1, v2)) | [] | [] | [] | 6 | """Strategy generator app with Tkinter GUI."""
import math
import os
import tkinter as tk
import typing
from collections import Counter
from copy import deepcopy
from tkinter import Grid, filedialog, font, messagebox
from darkhex.utils.cell_state import cellState
from darkhex.utils.isomorphic import isomorphic_single
... | null |
v0 | [
"DataFrame",
"dict"
] | DataFrame | def v0(self, v1: DataFrame, v2: dict) -> DataFrame:
v1.loc[(v1['close'] > v1['bb_upperband']) & (v1['rsi'] > 74), 'sell'] = 1
return v1 | [] | [] | [] | 3 |
# --- Do not remove these libs ---
from freqtrade.strategy.interface import IStrategy
from typing import Dict, List
from functools import reduce
from pandas import DataFrame
# --------------------------------
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib
class BB_RSI(IStrategy):
... | null |
v0 | [
"Dataset"
] | Tuple[torch.Tensor, torch.Tensor] | def v0(v1: Dataset) -> Tuple[torch.Tensor, torch.Tensor]:
v2 = torch.zeros((3,), dtype=torch.float)
v3 = torch.zeros((3,), dtype=torch.float)
for v4 in range(len(v1)):
(v5, v6) = torch.var_mean(v1[v4][0])
v2 += v6
v3 += v5
v2 /= len(v1)
v3 /= len(v3)
v7 = torch.sqrt(v3)
... | [] | [
"torch"
] | [
"import torch",
"from torch.utils.data import Dataset, TensorDataset"
] | 11 | from typing import Any, Dict, List, Optional, Tuple, Union
from PIL import Image
import numpy as np
import torch
from torch.utils.data import Dataset, TensorDataset
import torchvision.transforms
from torchvision.transforms import functional as TF
from autoPyTorch.constants import (
CLASSIFICATION_OUTPUTS,
... | null |
v1 | [
"v0",
"Optional[v0]"
] | None | def v1(v2: v0, v3: Optional[v0]=None) -> None:
if not isinstance(v2, Dataset):
if len(v2[0]) != len(v2[1]):
raise ValueError(f'expected train inputs to have the same length, but got lengths {len(v2[0])} and {len(v2[1])}')
if v3 is not None:
if len(v3[0]) != len(v3[1]):
... | [] | [
"torch"
] | [
"import torch",
"from torch.utils.data import Dataset, TensorDataset"
] | 7 | from typing import Any, Dict, List, Optional, Tuple, Union
from PIL import Image
import numpy as np
import torch
from torch.utils.data import Dataset, TensorDataset
import torchvision.transforms
from torchvision.transforms import functional as TF
from autoPyTorch.constants import (
CLASSIFICATION_OUTPUTS,
... | [
"v0 = Union[Dataset, Tuple[Union[np.ndarray, List[str]], np.ndarray]]"
] |
v0 | [
"List"
] | None | def v0(self, v1: List) -> None:
if len(v1) != 2:
return
if not v1[0].startswith('c.') and (not v1[0].startswith('g.')):
return
v2 = v1[0][:1]
v1[0] = v1[0][2:]
v3 = self.tokenize_base.get_positions_deleted(v1)
if not v3:
return
v4 = v3[0]
v5 = v3[1]
v6 = self.... | [] | [] | [] | 20 | """A module for DelIns Tokenization Base Class."""
from abc import abstractmethod
from typing import Optional, Dict, List
from variation.schemas.token_response_schema import DelIns, TokenMatchType, Token
from .tokenizer import Tokenizer
from .caches import AminoAcidCache, NucleotideCache
from .tokenize_base import Tok... | null |
v0 | [
"str"
] | Any | def v0(v1: str):
global _PREFERRED_DB
v2 = v1 | [] | [] | [] | 3 | from pathlib import PurePath
from typing import List, Tuple
import numpy as np
from labml.internal.analytics.indicators import IndicatorClass, Indicator, Run, IndicatorCollection, \
StepSelect
from labml.internal.analytics.sqlite import SQLiteAnalytics
from labml.internal.analytics.tensorboard import TensorBoardA... | null |
v0 | [
"str"
] | Any | def v0(v1: str):
global _data_extra_dir
v2 = os.path.abspath(v1) | [] | [
"os"
] | [
"import os"
] | 3 | import sys
import os
import re
import time
import math
import struct
import platform
import hashlib
import zipfile
from typing import Tuple, List
from . import png
def _timestr():
return time.strftime("%Y%m%d_%H_%M_%S", time.gmtime()) + "_" + str(round(time.time() % 1000))
# Thanks to https://stackoverflow.com/... | null |
v0 | [
"str"
] | Any | def v0(v1: str):
global _artifact_dir
v2 = os.path.abspath(v1) | [] | [
"os"
] | [
"import os"
] | 3 | import sys
import os
import re
import time
import math
import struct
import platform
import hashlib
import zipfile
from typing import Tuple, List
from . import png
def _timestr():
return time.strftime("%Y%m%d_%H_%M_%S", time.gmtime()) + "_" + str(round(time.time() % 1000))
# Thanks to https://stackoverflow.com/... | null |
v0 | [
"str"
] | Any | def v0(v1: str):
global _test_name
v2 = v1 | [] | [] | [] | 3 | import sys
import os
import re
import time
import math
import struct
import platform
import hashlib
import zipfile
from typing import Tuple, List
from . import png
def _timestr():
return time.strftime("%Y%m%d_%H_%M_%S", time.gmtime()) + "_" + str(round(time.time() % 1000))
# Thanks to https://stackoverflow.com/... | null |
v0 | [
"str",
"str"
] | Any | def v0(v1: str, v2: str):
v3 = zipfile.ZipFile(v1)
v4 = zipfile.ZipFile(v2)
v5 = []
for v6 in v3.infolist():
v7 = hashlib.md5()
with v3.open(v6.filename) as v8:
for v9 in iter(lambda : v8.read(4096), b''):
v7.update(v9)
v5.append((v6.filename, v6.file_... | [] | [
"hashlib",
"zipfile"
] | [
"import hashlib",
"import zipfile"
] | 20 | import sys
import os
import re
import time
import math
import struct
import platform
import hashlib
import zipfile
from typing import Tuple, List
from . import png
def _timestr():
return time.strftime("%Y%m%d_%H_%M_%S", time.gmtime()) + "_" + str(round(time.time() % 1000))
# Thanks to https://stackoverflow.com/... | null |
v0 | [] | None | def v0(self) -> None:
super().setUp()
self.sender = self.example_user('hamlet')
self.recipient = self.example_user('cordelia') | [] | [] | [] | 4 | from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Tuple
from unittest import mock
from django.conf import settings
from django.utils.timezone import now as timezone_now
from zerver.lib.actions import internal_send_private_message, do_add_submessage, do_delete_messages
from zerver.... | null |
v0 | [] | None | def v0(self) -> None:
v1 = self.example_user('hamlet')
for v2 in range(3):
v3 = 'mentioning... @**' + v1.full_name + '** hello ' + str(v2)
self.verify_action(lambda : self.send_stream_message(self.example_user('cordelia'), 'Verona', v3)) | [] | [] | [] | 5 | # See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for
# high-level documentation on how this system works.
#
# This module is closely integrated with zerver/lib/event_schema.py
# and zerver/lib/data_types.py systems for validating the schemas of
# events; it also uses the OpenAPI tools to valid... | null |
v0 | [] | None | def v0(self) -> None:
for v1 in range(3):
v2 = 'mentioning... @**all** hello ' + str(v1)
self.verify_action(lambda : self.send_stream_message(self.example_user('cordelia'), 'Verona', v2)) | [] | [] | [] | 4 | # See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for
# high-level documentation on how this system works.
#
# This module is closely integrated with zerver/lib/event_schema.py
# and zerver/lib/data_types.py systems for validating the schemas of
# events; it also uses the OpenAPI tools to valid... | null |
v0 | [] | None | def v0(self) -> None:
v1 = [self.example_user('hamlet'), self.example_user('othello')]
self.verify_action(lambda : self.send_huddle_message(self.example_user('cordelia'), v1, 'hola')) | [] | [] | [] | 3 | # See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for
# high-level documentation on how this system works.
#
# This module is closely integrated with zerver/lib/event_schema.py
# and zerver/lib/data_types.py systems for validating the schemas of
# events; it also uses the OpenAPI tools to valid... | null |
v0 | [] | None | def v0(self) -> None:
v1 = self.example_user('cordelia')
self.send_stream_message(v1, 'Verona', 'hello 1')
self.verify_action(lambda : self.send_stream_message(v1, 'Verona', 'hello 2'), state_change_expected=True) | [] | [] | [] | 4 | # See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for
# high-level documentation on how this system works.
#
# This module is closely integrated with zerver/lib/event_schema.py
# and zerver/lib/data_types.py systems for validating the schemas of
# events; it also uses the OpenAPI tools to valid... | null |
v0 | [
"Dict[str, Any]"
] | None | def v0(v1: Dict[str, Any]) -> None:
for v2 in v1['never_subscribed']:
if 'subscribers' in v2:
v2['subscribers'].sort()
for v2 in v1['subscriptions']:
if 'subscribers' in v2:
v2['subscribers'].sort()
v1['subscriptions'] = {v2['name']: v2 for v2 in v1['subscriptions']}
... | [] | [] | [] | 12 | # See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for
# high-level documentation on how this system works.
#
# This module is closely integrated with zerver/lib/event_schema.py
# and zerver/lib/data_types.py systems for validating the schemas of
# events; it also uses the OpenAPI tools to valid... | null |
v0 | [] | Any | def v0() -> Any:
v1 = ('zproject.backends.DevAuthBackend', 'zproject.backends.EmailAuthBackend', 'zproject.backends.GitHubAuthBackend', 'zproject.backends.GoogleMobileOauth2Backend', 'zproject.backends.ZulipLDAPAuthBackend')
return self.settings(AUTHENTICATION_BACKENDS=v1) | [] | [] | [] | 3 | # -*- coding: utf-8 -*-
# See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for
# high-level documentation on how this system works.
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
import os
import shutil
import sys
from django.conf import settings
from django.http impo... | null |
v0 | [
"str",
"list",
"dict"
] | Any | def v0(self, v1: str, v2: list, v3: dict):
v4 = self._get_selector(v3)
v5 = self.base_request(v1, 'POST', data=v4, find=True)
if v5 and v5.status_code == requests.codes.ok and ('docs' in v5.json()):
return v5.json()['docs']
return [] | [] | [
"requests"
] | [
"import requests"
] | 6 | import requests
from ..utils.logs import Log
from urllib.parse import quote
class Client:
valid_operators = ['eq', 'gt', 'gte', 'lt', 'lte', 'in']
_instances = {}
__conn = None
def __init__(self, server_conf):
for _server_key in server_conf.keys():
_conf = server_conf[_server_ke... | null |
v0 | [
"str",
"str"
] | Any | def v0(self, v1: str, v2: str):
v3 = quote(v1, safe='')
v4 = self.base_request(v2, 'GET', find=False, uri=v3)
if v4 and v4.status_code == requests.codes.ok:
return v4.json()
return {} | [] | [
"requests",
"urllib"
] | [
"import requests",
"from urllib.parse import quote"
] | 6 | import requests
from ..utils.logs import Log
from urllib.parse import quote
class Client:
valid_operators = ['eq', 'gt', 'gte', 'lt', 'lte', 'in']
_instances = {}
__conn = None
def __init__(self, server_conf):
for _server_key in server_conf.keys():
_conf = server_conf[_server_ke... | null |
v0 | [
"str",
"dict"
] | Any | def v0(self, v1: str, v2: dict):
v3 = self.base_request(v1, 'POST', data=v2)
if v3 and v3.status_code == requests.codes.created and ('docs' in v3.json()):
return v3.json()['docs']
return v3.json() | [] | [
"requests"
] | [
"import requests"
] | 5 | import requests
from ..utils.logs import Log
from urllib.parse import quote
class Client:
valid_operators = ['eq', 'gt', 'gte', 'lt', 'lte', 'in']
_instances = {}
__conn = None
def __init__(self, server_conf):
for _server_key in server_conf.keys():
_conf = server_conf[_server_ke... | null |
v0 | [
"torch.nn.Module",
"DataLoader",
"torch.optim.Optimizer"
] | Any | def v0(self, v1: torch.nn.Module, v2: DataLoader, v3: torch.optim.Optimizer=None):
if v3 is None:
v3 = torch.optim.SGD(self.parameters(), lr=0.001, momentum=0.9, nesterov=True)
v4 = {'train_loss': [], 'train_acc': []}
self.train()
for (v5, v6) in v2:
v7 = self.forward(v5)
v8 = v1... | [] | [
"torch"
] | [
"import torch",
"import torch.nn as nn",
"from torch.utils.data import Dataset, DataLoader"
] | 19 | """
implementation of LassoNet where the hierarchical penalty is applied to the convolutional filters.
some snippets from: https://medium.com/dataseries/visualizing-the-feature-maps-and-filters-by-convolutional-neural-networks-e1462340518e
"""
import numpy as np
import torch
import torch.nn as nn
from torch.utils.d... | null |
v0 | [
"List[List[Any]]",
"Any"
] | List[List[Any]] | def v0(v1: List[List[Any]], v2) -> List[List[Any]]:
v3 = []
if not isinstance(v1, list):
raise ValueError("Can't sort it")
for v4 in v1:
if not isinstance(v4, list):
raise ValueError("Can't sort it")
v5 = []
for v6 in v4:
if v5 and type(v6) not in v5:
... | [] | [] | [] | 14 | from typing import List, Any
def execute(lists: List[List[Any]], proc) -> List[List[Any]]:
out = []
if not isinstance(lists, list):
raise ValueError("Can't sort it")
for list_ in lists:
if not isinstance(list_, list):
raise ValueError("Can't sort it")
types = []
... | null |
v0 | [
"List"
] | Any | def v0(v1: List):
if not v1:
return None
return max(v1) | [] | [] | [] | 4 | from typing import List, Any
def execute(lists: List[List[Any]], proc) -> List[List[Any]]:
out = []
if not isinstance(lists, list):
raise ValueError("Can't sort it")
for list_ in lists:
if not isinstance(list_, list):
raise ValueError("Can't sort it")
types = []
... | null |
v0 | [
"str",
"int"
] | str | def v0(v1: str, v2: int) -> str:
(v3, v4) = os.path.splitext(v1)
return ''.join((str(v2), v4)) | [] | [
"os"
] | [
"import os"
] | 3 | import os
import re
import ujson
from django.utils.translation import ugettext as _
from typing import Optional, Tuple
from zerver.lib.request import JsonableError
from zerver.lib.storage import static_path
from zerver.lib.upload import upload_backend
from zerver.lib.exceptions import OrganizationAdministratorRequire... | null |
v0 | [
"str"
] | Tuple[List[str], List[str]] | def v0(self, v1: str) -> Tuple[List[str], List[str]]:
v2 = v1.replace('<>', '').split('\n')
v3 = re.split('\\n|<>', v1)
return (v2, v3) | [] | [
"re"
] | [
"import re"
] | 4 | from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_add_alert_words,
do_set_realm_property,
)
from zerver.lib.alert_words import get_alert_word_automat... | null |
v0 | [] | None | def v0(self) -> None:
(v1, v2) = self.load_bugdown_tests()
for (v3, v4) in v1.items():
v5 = 'Test "%s" shouldn\'t be ignored.' % (v3,)
v6 = v4.get('ignore', False)
self.assertFalse(v6, v5) | [] | [] | [] | 6 | from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_add_alert_words,
do_set_realm_property,
)
from zerver.lib.alert_words import get_alert_word_automat... | null |
v3 | [] | None | def v3(self) -> None:
v4 = 'To bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa or not to bitcoin'
v5 = v0(v4)
self.assertEqual(v5, '<p>To <a href="bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa" target="_blank" title="bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa">bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa</a> or not t... | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n v2 = cast(Message, FakeMessage())\n v2.content = v1\n v2.id = 999\n return bugdown.convert(content=v1, message_realm=get_realm('zulip'), message=v2)",
"dependencies": []
}
] | [
"typing"
] | [
"from typing import cast, Any, Dict, List, Optional, Set, Tuple"
] | 4 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_set_alert_words,
)
from zerver.lib.alert_words import get_alert_word_automaton
... | null |
v3 | [] | None | def v3(self) -> None:
v4 = 'Check out the debate: http://www.youtube.com/watch?v=hx1mjT73xYE'
v5 = v0(v4)
self.assertEqual(v5, '<p>Check out the debate: <a href="http://www.youtube.com/watch?v=hx1mjT73xYE" target="_blank" title="http://www.youtube.com/watch?v=hx1mjT73xYE">http://www.youtube.com/watch?v=hx1m... | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n v2 = cast(Message, FakeMessage())\n v2.content = v1\n v2.id = 999\n return bugdown.convert(content=v1, message_realm=get_realm('zulip'), message=v2)",
"dependencies": []
}
] | [
"typing"
] | [
"from typing import cast, Any, Dict, List, Optional, Set, Tuple"
] | 19 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_set_alert_words,
)
from zerver.lib.alert_words import get_alert_word_automaton
... | null |
v3 | [] | None | def v3(self) -> None:
v4 = 'Test: https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png'
v5 = v0(v4)
self.assertEqual(v5, '<p>Test: <a href="https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png" target="_blank" title="https://github.com/zulip/zu... | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n v2 = cast(Message, FakeMessage())\n v2.content = v1\n v2.id = 999\n return bugdown.convert(content=v1, message_realm=get_realm('zulip'), message=v2)",
"dependencies": []
}
] | [
"typing"
] | [
"from typing import cast, Any, Dict, List, Optional, Set, Tuple"
] | 7 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_set_alert_words,
)
from zerver.lib.alert_words import get_alert_word_automaton
... | null |
v9 | [] | None | def v9(self) -> None:
def v10(v11: str) -> str:
return '<a href="%s" target="_blank" title="%s">%s</a>' % (v11, v11, v11)
v12 = '<a href="https://twitter.com/Twitter" target="_blank" title="https://twitter.com/Twitter">@Twitter</a> meets @seepicturely at #tcdisrupt cc.<a href="https://twitter.com/bosco... | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n v2 = cast(Message, FakeMessage())\n v2.content = v1\n v2.id = 999\n return bugdown.convert(content=v1, message_realm=get_realm('zulip'), message=v2)",
"dependencies": []
},
... | [
"typing"
] | [
"from typing import cast, Any, Dict, List, Optional, Set, Tuple"
] | 50 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_set_alert_words,
)
from zerver.lib.alert_words import get_alert_word_automaton
... | null |
v3 | [] | None | def v3(self) -> None:
v4 = u'☕'
v5 = v0(v4)
self.assertEqual(v5, u'<p><span aria-label="coffee" class="emoji emoji-2615" role="img" title="coffee">:coffee:</span></p>')
v4 = u'☕☕'
v5 = v0(v4)
self.assertEqual(v5, u'<p><span aria-label="coffee" class="emoji emoji-2615" role="img" title="coffee">:... | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n v2 = cast(Message, FakeMessage())\n v2.content = v1\n v2.id = 999\n return bugdown.convert(content=v1, message_realm=get_realm('zulip'), message=v2)",
"dependencies": []
}
] | [
"typing"
] | [
"from typing import cast, Any, Dict, List, Optional, Set, Tuple"
] | 7 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_set_alert_words,
)
from zerver.lib.alert_words import get_alert_word_automaton
... | null |
v3 | [] | None | def v3(self) -> None:
v4 = u'☕'
v5 = v0(v4)
v4 = u':coffee:'
v6 = v0(v4)
self.assertEqual(v6, v5) | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n v2 = cast(Message, FakeMessage())\n v2.content = v1\n v2.id = 999\n return bugdown.convert(content=v1, message_realm=get_realm('zulip'), message=v2)",
"dependencies": []
}
] | [
"typing"
] | [
"from typing import cast, Any, Dict, List, Optional, Set, Tuple"
] | 6 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_set_alert_words,
)
from zerver.lib.alert_words import get_alert_word_automaton
... | null |
v0 | [
"int",
"int"
] | List[str] | def v0(self, v1: int, v2: int) -> List[str]:
v3 = ['x' * v2] * v1
return v3 | [] | [] | [] | 3 | from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_add_alert_words,
do_set_realm_property,
)
from zerver.lib.alert_words import get_alert_word_automat... | null |
v3 | [] | None | def v3(self) -> None:
v4 = '[My favorite image](https://example.com/testimage.png)'
v5 = v0(v4)
self.assertEqual(v5, '<p><a href="https://example.com/testimage.png" target="_blank" title="https://example.com/testimage.png">My favorite image</a></p>\n<div class="message_inline_image"><a href="https://example... | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n v2 = cast(Message, FakeMessage())\n v2.content = v1\n v2.id = 999\n return bugdown.convert(content=v1, message_realm=get_realm('zulip'), message=v2)",
"dependencies": []
}
] | [
"typing"
] | [
"from typing import cast, Any, Dict, List, Optional, Set, Tuple"
] | 4 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_set_alert_words,
)
from zerver.lib.alert_words import get_alert_word_automaton
... | null |
v0 | [] | None | def v0(self) -> None:
v1 = 'That is a **bold** statement'
v2 = self.client_post('/api/v1/messages/render', dict(content=v1), **self.api_auth(self.example_email('othello')))
self.assert_json_success(v2)
self.assertEqual(v2.json()['rendered'], u'<p>That is a <strong>bold</strong> statement</p>') | [] | [] | [] | 5 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_remove_realm_emoji,
do_set_alert_words,
get_realm,
)
from zerver.lib.alert_words import alert_words_in_realm
from zerver.lib.camo i... | null |
v0 | [
"str",
"str",
"str"
] | str | def v0(v1: str, v2: str, v3: str='') -> str:
if v2[:4] == 'http':
v4 = v2
elif '@' in v2:
v4 = 'mailto:' + v2
else:
v4 = 'http://' + v2
return v1 % ('<a href="%s" title="%s">%s</a>' % (v4, v4, v2),) | [] | [] | [] | 8 | from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown
from zerver.lib.actions import (
do_set_user_display_setting,
do_remove_realm_emoji,
do_add_alert_words,
do_set_realm_property,
)
from zerver.lib.alert_words import get_alert_word_automat... | null |
v0 | [
"str"
] | NoReturn | def v0(v1: str) -> NoReturn:
logging.fatal(v1)
exit(1) | [] | [
"logging"
] | [
"import logging"
] | 3 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v0 | [
"int"
] | bool | def v0(v1: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as v2:
v2.settimeout(0.1)
return v2.connect_ex(('127.0.0.1', v1)) == 0 | [] | [
"socket"
] | [
"import socket"
] | 4 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v0 | [] | builtins.str | def v0(self) -> builtins.str:
(v1, self._cur_number) = (self._cur_number, self._cur_number + 1)
return self.words[v1] | [] | [] | [] | 3 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v0 | [
"Callable[[builtins.str], Any]",
"builtins.str"
] | Any | def v0(self, v1: Callable[[builtins.str], Any], v2: builtins.str) -> Any:
v3 = self.str()
try:
return v1(v3)
except Exception:
logging.error(f'Expected {v2!r}, got {v3!r}')
raise | [] | [
"logging"
] | [
"import logging"
] | 7 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v0 | [] | None | def v0(self) -> None:
if self._proto is not None:
self.cmd('Stop')
self.cmd(f'SR,V,{self._init_Volts}')
self.cmd(f'SR,A,{self._init_Amps}')
logging.info(f'Set initial values for Amps {self._init_Amps} and Volts {self._init_Volts}')
self._proto = None
if self._socket is no... | [] | [
"logging",
"subprocess"
] | [
"import logging",
"import subprocess"
] | 22 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v0 | [] | None | def v0(self) -> None:
if self._process is not None:
logging.info('Force stopping ptd...')
self._process.kill()
self._process.wait()
self._process = None
if self._tee is not None:
self._tee.done()
self._tee = None | [] | [
"logging"
] | [
"import logging"
] | 9 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v2 | [
"str"
] | Optional[str] | def v2(self, v3: str) -> Optional[str]:
if self._proto is None:
return None
if self._process is None or self._process.poll() is not None:
v0('PTDaemon unexpectedly terminated')
logging.info(f'Sending to ptd: {v3!r}')
self._proto.send(v3)
v4 = self._proto.recv()
if v4 is None:
... | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "NoReturn",
"code": "def v0(v1: str) -> NoReturn:\n logging.fatal(v1)\n exit(1)",
"dependencies": []
}
] | [
"logging"
] | [
"import logging"
] | 13 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v3 | [] | None | def v3(self) -> None:
v4 = self.cmd('RR')
if v4 is None or v4 == '':
logging.error('Can not get initial range')
exit(1)
v5 = v4.split(',')
def v6(v7: int, v8: str) -> str:
try:
if v5[v7] == '0' and float(v5[v7 + 1]) > 0:
return v5[v7 + 1]
exce... | [
{
"name": "v0",
"input_types": [
"int",
"str"
],
"output_type": "str",
"code": "def v0(v1: int, v2: str) -> str:\n try:\n if response_list[v1] == '0' and float(response_list[v1 + 1]) > 0:\n return response_list[v1 + 1]\n except (ValueError, IndexError):\n ... | [
"logging"
] | [
"import logging"
] | 18 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v0 | [] | None | def v0(self) -> None:
if not self._closed:
os.close(self.w)
self._closed = True
self._thread.join() | [] | [
"os"
] | [
"import os"
] | 5 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v0 | [] | None | def v0(self) -> None:
try:
while True:
v1 = os.read(self._r, 1024)
if len(v1) == 0:
break
v2 = v1.decode(errors='ignore')
sys.stderr.write(v2)
sys.stderr.flush()
self._f.write(v1)
finally:
self._f.close()
... | [] | [
"os",
"sys"
] | [
"import os",
"import sys"
] | 13 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v0 | [
"str",
"str"
] | bool | def v0(self, v1: str, v2: str) -> bool:
try:
with zipfile.ZipFile(v1, 'r') as v3:
v3.extractall(v2)
logging.info(f'Extracted {v1!r} into {v2!r}')
return True
except Exception:
logging.exception(f'Got an exception while extracting {v1!r} into {v2!r}')
return False | [] | [
"logging",
"zipfile"
] | [
"import logging",
"import zipfile"
] | 9 | # Copyright 2018 The MLPerf Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | null |
v10 | [
"Mapping[Any, Any]",
"Mapping[Any, Any]",
"float"
] | Tuple[bool, str] | def v10(v11: Mapping[Any, Any], v12: Mapping[Any, Any], v13: float) -> Tuple[bool, str]:
def v14(v15: Any, v16: Any, v17: str) -> Tuple[bool, str]:
if type(v15) != type(v16):
return (False, f"Key '{v17}' type mismatch. Expected: '{type(v15)}', but found: '{type(v16)}'")
elif type(v15) =... | [
{
"name": "v0",
"input_types": [
"Any",
"Any",
"str"
],
"output_type": "Tuple[bool, str]",
"code": "def v0(v1: Any, v2: Any, v3: str) -> Tuple[bool, str]:\n if type(v1) != type(v2):\n return (False, f\"Key '{v3}' type mismatch. Expected: '{type(v1)}', but found: '{typ... | [] | [] | 33 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v0 | [
"str",
"str",
"float"
] | bool | def v0(v1: str, v2: str, v3: float) -> bool:
v4 = float(v1)
v5 = float(v2)
if math.isinf(v4) and math.isinf(v5):
return True
if math.isnan(v4) and math.isnan(v5):
return True
v6 = abs(v4 - v5)
if v6 < v3:
return True
if abs(v5) <= 1.0:
return False
v7 = ab... | [] | [
"math"
] | [
"import math"
] | 14 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v0 | [
"List[Path]",
"Callable[[Path], bool]"
] | Optional[Path] | def v0(v1: List[Path], v2: Callable[[Path], bool]) -> Optional[Path]:
for v3 in v1:
if v3.is_dir():
for v4 in v3.iterdir():
if v2(v4):
return v4
elif v3.is_file():
if v2(v3):
return v3
else:
continue
... | [] | [] | [] | 12 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v0 | [
"str",
"str",
"str",
"str"
] | List[str] | def v0(v1: str, v2: str, v3: str, v4: str) -> List[str]:
v5 = [line.strip() for v6 in v1.strip().splitlines()]
v7 = [v6.strip() for v6 in v3.strip().splitlines()]
v8 = difflib.unified_diff(v7, v5, fromfile=v4, tofile=v2, lineterm='')
return list([v6 for v6 in v8]) | [] | [
"difflib"
] | [
"import difflib"
] | 5 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v10 | [
"str",
"str",
"float"
] | Tuple[bool, str, bool] | def v10(v11: str, v12: str, v13: float) -> Tuple[bool, str, bool]:
v14 = re.split('[ \t:,@]+', v11)
v15 = re.split('[ \t:,@]+', v12)
if v15[0] == '[critical]' and v14[0] == '[critical]':
if v15[2][0] == '(' and v15[3][-1] == ')':
if v15[3][:-1].isnumeric():
v15.pop(3)
... | [
{
"name": "v0",
"input_types": [
"str",
"str",
"float"
],
"output_type": "bool",
"code": "def v0(v1: str, v2: str, v3: float) -> bool:\n v4 = float(v1)\n v5 = float(v2)\n if math.isinf(v4) and math.isinf(v5):\n return True\n if math.isnan(v4) and math.isnan(v... | [
"math",
"re"
] | [
"import re",
"import math"
] | 30 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v24 | [
"List[str]",
"List[str]",
"float",
"Any"
] | Tuple[bool, str] | def v24(v25: List[str], v26: List[str], v27: float, v28=False) -> Tuple[bool, str]:
if len(v25) != len(v26):
return (True, 'Diff mismatch')
v29 = False
for (v30, v31) in zip(v25, v26):
if v28:
v30 = v30.replace('...', '')
v31 = v31.replace('...', '')
(v32,... | [
{
"name": "v0",
"input_types": [
"str",
"str",
"float"
],
"output_type": "bool",
"code": "def v0(v1: str, v2: str, v3: float) -> bool:\n v4 = float(v1)\n v5 = float(v2)\n if math.isinf(v4) and math.isinf(v5):\n return True\n if math.isnan(v4) and math.isnan(v... | [
"math",
"re"
] | [
"import re",
"import math"
] | 15 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v35 | [
"str",
"str",
"float",
"Any"
] | Tuple[bool, str] | def v35(v36: str, v37: str, v38: float, v39=False) -> Tuple[bool, str]:
v40 = [line.strip() for v41 in v36.strip().splitlines()]
v42 = [v41.strip() for v41 in v37.strip().splitlines()]
(v43, v44) = v0(v40, v42, v38, fuzzy_compare=v39)
return (v43, v44) | [
{
"name": "v0",
"input_types": [
"List[str]",
"List[str]",
"float",
"Any"
],
"output_type": "Tuple[bool, str]",
"code": "def v0(v1: List[str], v2: List[str], v3: float, v4=False) -> Tuple[bool, str]:\n if len(v1) != len(v2):\n return (True, 'Diff mismatch')\n ... | [
"math",
"re"
] | [
"import re",
"import math"
] | 5 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v12 | [
"Any",
"Type[Union[v0, v6]]"
] | Any | def v12(v13, v14: Type[Union[v0, v6]]):
for v15 in v13:
if v15.startswith('+'):
print(v14.LIGHT_GREEN + v15 + v14.ENDC)
elif v15.startswith('-'):
print(v14.LIGHT_RED + v15 + v14.ENDC)
elif v15.startswith('^'):
print(v15)
else:
print(v15... | [] | [] | [] | 10 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | [
"class v0:\n v1 = '\\x1b[96m'\n v2 = '\\x1b[92m'\n v3 = '\\x1b[95m'\n v4 = '\\x1b[91m'\n v5 = '\\x1b[0m'",
"class v6:\n v7 = ''\n v8 = ''\n v9 = ''\n v10 = ''\n v11 = ''"
] |
v0 | [
"int",
"List[str]",
"Path",
"Path",
"List[int]"
] | Path | def v0(v1: int, v2: List[str], v3: Path, v4: Path, v5: List[int]=[]) -> Path:
v6 = v3.joinpath(f'test_{v1}')
v6.mkdir(parents=True, exist_ok=True)
(v6 / 'models').mkdir(parents=True, exist_ok=True)
for v7 in v2:
v8 = None
v9 = [v4 / v7]
if len(v5) > 0:
v9.extend([v3 /... | [] | [
"os",
"shutil"
] | [
"import shutil",
"import os"
] | 26 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v14 | [
"Path",
"Optional[str]"
] | Optional[Union[str, Path]] | def v14(v15: Path, v16: Optional[str]) -> Optional[Union[str, Path]]:
def v17(v18: Optional[str]) -> bool:
if not v18:
return False
elif v18.startswith('python') and v18.endswith('-m vowpalwabbit'):
return True
else:
return False
if v17(v16):
... | [
{
"name": "v0",
"input_types": [
"List[Path]",
"Callable[[Path], bool]"
],
"output_type": "Optional[Path]",
"code": "def v0(v1: List[Path], v2: Callable[[Path], bool]) -> Optional[Path]:\n for v3 in v1:\n if v3.is_dir():\n for v4 in v3.iterdir():\n ... | [
"pathlib"
] | [
"from pathlib import Path"
] | 17 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v12 | [
"Path",
"Optional[str]"
] | Optional[Path] | def v12(v13: Path, v14: Optional[str]) -> Optional[Path]:
v15 = [v13 / '..' / 'build' / 'vowpalwabbit' / 'spanning_tree_bin']
def v16(v17: Path) -> bool:
return v17.name == 'spanning_tree'
v14 = Path(v14) if v14 is not None else None
return v5(test_base_ref_dir=v13, user_supplied_bin_path=v14, ... | [
{
"name": "v0",
"input_types": [
"List[Path]",
"Callable[[Path], bool]"
],
"output_type": "Optional[Path]",
"code": "def v0(v1: List[Path], v2: Callable[[Path], bool]) -> Optional[Path]:\n for v3 in v1:\n if v3.is_dir():\n for v4 in v3.iterdir():\n ... | [
"pathlib"
] | [
"from pathlib import Path"
] | 7 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v5 | [
"Path",
"Optional[Path]",
"List[Path]",
"Callable[[Path], bool]"
] | Optional[Path] | def v5(v6: Path, v7: Optional[Path], v8: List[Path], v9: Callable[[Path], bool]) -> Optional[Path]:
if v7 is None:
return v0(v8, v9)
if not v7.is_file():
return None
return v7 | [
{
"name": "v0",
"input_types": [
"List[Path]",
"Callable[[Path], bool]"
],
"output_type": "Optional[Path]",
"code": "def v0(v1: List[Path], v2: Callable[[Path], bool]) -> Optional[Path]:\n for v3 in v1:\n if v3.is_dir():\n for v4 in v3.iterdir():\n ... | [] | [] | 6 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v2 | [
"Path"
] | None | def v2(v3: Path) -> None:
v4 = subprocess.run('git clean --dry-run -d -x -e __pycache__'.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=v3, timeout=10)
v5 = v4.returncode
if v5 != 0:
print("Failed to run 'git clean --dry-run -d -x -e __pycache__'")
v6 = v0(v4.stdout)
if len(v6)... | [
{
"name": "v0",
"input_types": [
"Optional[bytes]"
],
"output_type": "str",
"code": "def v0(v1: Optional[bytes]) -> str:\n return v1.decode('utf-8', 'ignore') if v1 is not None else ''",
"dependencies": []
}
] | [
"subprocess",
"sys"
] | [
"import subprocess",
"import sys"
] | 11 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v0 | [
"Path"
] | None | def v0(v1: Path) -> None:
v2 = 'git clean --force -d -x --exclude __pycache__'
v3 = subprocess.run(v2.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=v1, timeout=10)
if v3.returncode != 0:
print(f'Failed to run {v2}') | [] | [
"subprocess"
] | [
"import subprocess"
] | 5 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v0 | [
"List[Any]"
] | None | def v0(v1: List[Any]) -> None:
v2: Set[int] = set()
for v3 in v1:
if 'id' not in v3:
raise ValueError(f'id field missing in test: {v3}')
if v3['id'] in v2:
raise ValueError(f"Duplicate found for id: {v3['id']}")
v2.add(v3['id'])
v4 = min(v2)
if v4 != 1:
... | [] | [] | [] | 18 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v0 | [
"str",
"int"
] | List[int] | def v0(v1: str, *, v2: int) -> List[int]:
v3 = re.compile('^\\d+$')
v4 = re.compile('^(\\d+)?\\.\\.(\\d+)?$')
if v3.match(v1):
return [int(v1)]
elif v4.match(v1):
(v5, v6) = v4.match(v1).groups()
v5 = int(v5) if v5 else 1
v6 = int(v6) if v6 else v2
if v5 > v6:
... | [] | [
"re"
] | [
"import re"
] | 14 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v0 | [
"int",
"bool"
] | None | def v0(self, v1: int, v2: bool) -> None:
self.lock.acquire()
self.completed[v1] = v2
self.condition.notify_all()
self.lock.release() | [] | [] | [] | 5 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v1 | [
"int"
] | bool | def v1(self, v2: int) -> bool:
def v3() -> bool:
return v2 in self.completed
self.lock.acquire()
if not v3():
self.condition.wait_for(v3)
v4 = self.completed[v2]
self.lock.release()
return v4 | [
{
"name": "v0",
"input_types": [],
"output_type": "bool",
"code": "def v0() -> bool:\n return id in self.completed",
"dependencies": []
}
] | [] | [] | 10 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v0 | [
"Optional[str]"
] | bool | def v0(v1: Optional[str]) -> bool:
if not v1:
return False
elif v1.startswith('python') and v1.endswith('-m vowpalwabbit'):
return True
else:
return False | [] | [] | [] | 7 | import shutil
import threading
import argparse
import difflib
from pathlib import Path
import re
import os
import subprocess
import sys
import traceback
import shlex
import math
import json
from concurrent.futures import ThreadPoolExecutor, Future
from enum import Enum
import socket
from typing import (
Any,
Ca... | null |
v0 | [
"'TimestampCache'"
] | Any | async def v0(self, v1: 'TimestampCache'):
if self.target:
v2 = Path(self.target)
if v2.exists():
if v2.is_dir():
shutil.rmtree(v2, True)
else:
v2.unlink()
else:
v1.pop(self, None) | [] | [
"pathlib",
"shutil"
] | [
"from pathlib import Path",
"import shutil"
] | 10 | from typing import Iterable, List, Union, Optional, TypeVar, TYPE_CHECKING
from pathlib import Path
from abc import ABC, abstractmethod
from copy import copy
import shutil
import inspect
import os
import re
from ..logger import BLUE, RESET
if TYPE_CHECKING:
from ..cache import TimestampCache
Dependencies = List[U... | null |
v0 | [] | float | async def v0(self) -> float:
if self.target is None:
return float('inf')
assert not self.has_wildcard()
v1 = Path(self.target)
try:
return v1.stat().st_mtime
except FileNotFoundError:
return float('inf') | [] | [
"pathlib"
] | [
"from pathlib import Path"
] | 9 | from typing import Iterable, List, Union, Optional, TypeVar, TYPE_CHECKING
from pathlib import Path
from abc import ABC, abstractmethod
from copy import copy
import shutil
import inspect
import os
import re
from ..logger import BLUE, RESET
if TYPE_CHECKING:
from ..cache import TimestampCache
Dependencies = List[U... | null |
v0 | [
"'re.Pattern[str]'"
] | Optional[str] | def v0(self, v1: 're.Pattern[str]') -> Optional[str]:
if self.target:
v2 = re.match(v1, str(self.cwd / self.target))
if v2:
return v2.string | [] | [
"re"
] | [
"import re"
] | 5 | from typing import Iterable, List, Union, Optional, TypeVar, TYPE_CHECKING
from pathlib import Path
from abc import ABC, abstractmethod
from copy import copy
import shutil
import inspect
import os
import re
from ..logger import BLUE, RESET
if TYPE_CHECKING:
from ..cache import TimestampCache
Dependencies = List[U... | null |
v0 | [
"Optional[str]",
"Optional[str]",
"Dict"
] | bool | def v0(self, v1: Optional[str], v2: Optional[str], v3: Dict, **v4) -> bool:
if self.optimizer:
return False
v5 = self.convert_search_space(v3)
self._space = v5
if v1:
self._metric = v1
if v2:
self._mode = v2
if self._mode == 'max':
self._metric_op = 1.0
elif s... | [] | [] | [] | 15 | from collections import defaultdict
import logging
import pickle
import json
from typing import Dict, List, Optional, Tuple, Any
from ray.tune import ExperimentAnalysis
from ray.tune.result import DEFAULT_METRIC
from ray.tune.sample import Domain, Float, Quantized
from ray.tune.suggest.suggestion import (
UNRESOLV... | null |
v0 | [
"object"
] | Dict | def v0(v1: object) -> Dict:
try:
v2 = {x: v for (v3, v4) in v1.__dict__.items() if not v3.startswith('_')}
except AttributeError:
return {}
return {**get_type_hints(v1.__class__), **v2} | [] | [
"typing"
] | [
"from typing import Any, Dict, List, Union, get_type_hints"
] | 6 | import json
from enum import Enum
from datetime import date, datetime, time
from typing import Any, Dict, List, Union, get_type_hints
class Definition:
__fields: dict
def __init__(self, **kwargs):
self.__fields = self.guard(kwargs)
@property
def fields(self):
return self.__fields
... | null |
v0 | [] | None | def v0(self, *v1: List[Object]) -> None:
self.objects.extend(v1)
for v2 in v1:
v2.canvas = self | [] | [] | [] | 4 | import os
import subprocess
import time
from typing import List, Optional
from physim.models.objects import Object
from pynput.keyboard import Key, KeyCode
BLOCK_EMPTY = " "
class Canvas:
def __init__(
self,
width: int,
height: int,
objects: Optional[List[Object]] = None,
... | null |
v0 | [] | None | async def v0(self) -> None:
if self._bpf is not None:
for v1 in self._handlers:
v1.handle(self._bpf) | [] | [] | [] | 4 | """
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... | null |
v1 | [
"List[List[str]]"
] | str | def v1(self, v2: List[List[str]]=None) -> str:
v2 = v2 or self.render_list()
v0()
print('\n'.join([''.join(row) for v3 in v2])) | [
{
"name": "v0",
"input_types": [],
"output_type": "None",
"code": "def v0() -> None:\n subprocess.call('cls' if os.name == 'nt' else 'clear')",
"dependencies": []
}
] | [
"os",
"subprocess"
] | [
"import os",
"import subprocess"
] | 4 | import os
import subprocess
import time
from typing import List, Optional
from physim.models.objects import Object
from pynput.keyboard import Key, KeyCode
BLOCK_EMPTY = " "
class Canvas:
def __init__(
self,
width: int,
height: int,
objects: Optional[List[Object]] = None,
... | null |
v0 | [
"tf.TensorShape"
] | Any | def v0(self, v1: tf.TensorShape):
v2 = self.patch_embeddings.num_patches
self.cls_token = self.add_weight(shape=(1, 1, self.config.hidden_size), initializer='zeros', trainable=True, name='cls_token')
self.position_embeddings = self.add_weight(shape=(1, v2 + 1, self.config.hidden_size), initializer='zeros', ... | [] | [] | [] | 5 | # coding=utf-8
# Copyright 2021 Google AI, Ross Wightman, The HuggingFace Inc. team. 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/license... | null |
v0 | [
"tf.Tensor",
"int"
] | tf.Tensor | def v0(self, v1: tf.Tensor, v2: int) -> tf.Tensor:
v1 = tf.reshape(tensor=v1, shape=(v2, -1, self.num_attention_heads, self.attention_head_size))
return tf.transpose(v1, perm=[0, 2, 1, 3]) | [] | [
"tensorflow"
] | [
"import tensorflow as tf"
] | 3 | # coding=utf-8
# Copyright 2021 Google AI, Ross Wightman, The HuggingFace Inc. team. 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/license... | null |
v0 | [] | Optional[str] | def v0(self) -> Optional[str]:
v1 = []
v2 = super().xml_serialization_ctxt()
if v2:
v1.append(v2)
if self.xml_metadata.get('wrapped', False):
v1.append("'wrapped': True")
v3 = self.element_type.xml_metadata
if v3.get('name'):
v1.append(f"'itemsName': '{v3['name']}'")
... | [] | [] | [] | 15 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from typin... | null |
v0 | [] | str | def v0() -> str:
v1 = 'jeffstar'
v2 = {'ali': 'UCoOae5nYA7VqaXzerajD0lg', 'jeffstar': 'UCkvK_5omS-42Ovgah8KRKtg', 'shiv': 'UCrbYXWUmeCy4GqArthu4hCw', 'dbourke': 'UCr8O8l5cCX85Oem1d18EezQ'}
v3 = v2[v1]
return v3 | [] | [] | [] | 5 | #!usr/bin/env python3
# test/test_setting.py - contains settings such as test channel cases
#
# by Shivan Sivakumaran
def set_channel_ID_test_case() -> str:
"""
Sets channel test ID
:params: None
:return: channel ID
:rtype: str
"""
# set this to desired channel
CHANNEL = 'jeffstar'
... | null |
v4 | [
"Any"
] | v0 | def v4(self, v5) -> v0:
v6 = getattr(v5, v5.type.lower())
v7: v0 = {}
v8 = {'Pods': self.parse_pod_metric, 'External': self.parse_external_metric, 'Resource': self.parse_resource_metric, 'Object': self.parse_object_metric}
v8[v5.type](v6, v7)
v7['target_value'] = str(v7['target_value']) if v7['targe... | [] | [] | [] | 7 | from typing import Optional
from kubernetes.client.models.v2beta2_object_metric_status import (
V2beta2ObjectMetricStatus,
)
from mypy_extensions import TypedDict
class HPAMetricsDict(TypedDict, total=False):
name: str
target_value: str
current_value: str
class HPAMetricsParser:
def __init__(se... | [
"class v0(TypedDict, total=False):\n v1: str\n v2: str\n v3: str"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.