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
v12
[]
None
def v12(self) -> None: try: super().cleanup() except OSError: v7(self.name)
[ { "name": "v0", "input_types": [ "str" ], "output_type": "None", "code": "def v0(v1: str) -> None:\n for (v2, v3, v4) in os.walk(v1):\n os.chmod(v2, os.stat(v2).st_mode | stat.S_IWRITE | stat.S_IREAD)\n for v5 in v4:\n v6 = os.path.join(v2, v5)\n if o...
[ "os", "shutil", "stat" ]
[ "import stat", "import platform, subprocess, operator, os, shlex, shutil, re" ]
5
# Copyright 2012-2020 The Meson development 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 agree...
null
v1
[ "v0" ]
None
def v1(self, v2: v0) -> None: if v2 in self.__container: del self.__container[v2]
[]
[]
[]
3
# Copyright 2012-2020 The Meson development 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 agree...
[ "v0 = T.TypeVar('_T')" ]
v1
[ "bool" ]
v0
def v1(self, v2: bool=True) -> v0: (v3, v4) = self.__container.popitem(v2) return v3
[]
[]
[]
3
# Copyright 2012-2020 The Meson development 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 agree...
[ "v0 = T.TypeVar('_T')" ]
v0
[ "int" ]
None
def v0(self, v1: int) -> None: self.done += v1 if not self.total: self.print_dot() return v2 = int(self.done / self.total * 10) while self.printed_dots < v2: self.print_dot()
[]
[]
[]
8
# Copyright 2012-2020 The Meson development 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 agree...
null
v0
[]
None
def v0(self) -> None: print('.', end='') sys.stdout.flush() self.printed_dots += 1
[]
[ "sys" ]
[ "import sys" ]
4
# Copyright 2012-2020 The Meson development 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 agree...
null
v0
[ "Any", "Any" ]
None
async def v0(self, v1=False, v2=False) -> None: await super().async_update(wake_if_asleep=v1, force=v2) self.refresh()
[]
[]
[]
3
# SPDX-License-Identifier: Apache-2.0 """ Python Package for controlling Tesla API. For more details about this api, please refer to the documentation at https://github.com/zabuldon/teslajsonpy """ import time from typing import Text from teslajsonpy.homeassistant.vehicle import VehicleDevice class TrunkLock(Vehic...
null
v0
[]
None
def v0(self) -> None: super().refresh() v1 = self._controller.get_last_update_time(self._id) if v1 >= self.__manual_update_time: v2 = self._controller.get_state_params(self._id) self.__lock_state = v2['ft'] if v2 and 'ft' in v2 else None
[]
[]
[]
6
# SPDX-License-Identifier: Apache-2.0 """ Python Package for controlling Tesla API. For more details about this api, please refer to the documentation at https://github.com/zabuldon/teslajsonpy """ import time from typing import Text from teslajsonpy.homeassistant.vehicle import VehicleDevice class TrunkLock(Vehic...
null
v0
[ "str" ]
Optional['Wallet']
def v0(self, v1: str) -> Optional['Wallet']: v2 = [wallet for v3 in self.wallets if v3.id == v1] return v2[0] if v2 else None
[]
[]
[]
3
import json import hmac import hashlib from ecdsa import SECP256k1, SigningKey # type: ignore from typing import List, NamedTuple, Optional, Dict from sqlite3 import Row from lnbits.settings import WALLET class User(NamedTuple): id: str email: str extensions: List[str] = [] wallets: List["Wallet"] =...
null
v0
[]
str
def v0(self) -> str: v1 = self.get_url() if ~v1.find('/chapter/'): v1 = self.html_fromstring(v1, '.sitemaplist a + a', 0).get('href') v1 = self.http().normalize_uri(v1) return self.re.search('/manga/([^/]+)\\.html', v1).group(1)
[]
[]
[]
6
from manga_py.provider import Provider from .helpers.std import Std class WieMangaCom(Provider, Std): def get_archive_name(self) -> str: return self.normal_arc_name([ self.chapter_id, self.re.search('/chapter/([^/]+)', self.chapter).group(1) ]) def get_chapter_index(s...
null
v0
[ "web.Application" ]
None
async def v0(v1: web.Application) -> None: for v2 in v1['websockets']: await v2.close(code=999, message='Server shutdown')
[]
[]
[]
3
import asyncio import pathlib import secrets from aiohttp import web import launch from launch import LaunchContext routes = web.RouteTableDef() @routes.get("/") async def index_handler(request: web.Request) -> web.StreamResponse: text = 'index' return web.Response(text=text) @routes.get("/hello") async ...
null
v0
[ "web.Application" ]
None
async def v0(v1: web.Application) -> None: v1['rabbit']['listener'].cancel() await v1['rabbit']['listener'] await v1['rabbit']['connection'].close()
[]
[]
[]
4
"""Rabbit M.Q. module.""" import asyncio import functools import logging from typing import Coroutine, Optional from aio_pika import connect, Connection, ExchangeType, IncomingMessage from aiohttp import web from fdk_model_publisher.config import Config from fdk_model_publisher.service.fetcher import serialize_catalo...
null
v0
[ "[int]" ]
[[int]]
def v0(self, v1: [int]) -> [[int]]: v2 = [[]] for v3 in sorted(v1): for v4 in range(len(v2)): v5 = v2[v4] + [v3] if v5 not in v2: v2.append(v5) return v2
[]
[]
[]
8
# 90. Subsets II class Solution: def subsetsWithDup(self, nums: [int]) -> [[int]]: """ Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). """ subsets = [[]] for num in sorted(nums): for index in range(...
null
v0
[ "List[str]" ]
Any
def v0(self, v1: List[str]): v2 = self._construct_node_label_list(v1) self.node_client.set_labels_for_multi_nodes(v2)
[]
[]
[]
3
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
null
v0
[ "List[str]", "str" ]
List
def v0(self, v1: List[str], v2: str=LBLabelOp.ADD) -> List: v3 = self.node_client.list(is_format=False) v4 = [] for v5 in v3.items: if v5.inner_ip not in v1: continue v6 = self._construct_labels_by_op(v5.labels, v2) v4.append({'node_name': v5.name, 'labels': v6}) retu...
[]
[]
[]
9
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
null
v22
[ "DetectionDatasetConstructor", "Any" ]
Any
def v22(v23: DetectionDatasetConstructor, v24): v25 = v24.root_path v26 = v24.data_split if v26 & DataSplit.Training: v0(v23, os.path.join(v25, 'train'), os.path.join(v25, 'objects365_train.json')) if v26 & DataSplit.Training: v0(v23, os.path.join(v25, 'val'), os.path.join(v25, 'objects3...
[ { "name": "v0", "input_types": [ "DetectionDatasetConstructor", "str", "str" ], "output_type": "Any", "code": "def v0(v1: DetectionDatasetConstructor, v2: str, v3: str):\n with open(v3, 'r', newline='\\n') as v4:\n v5 = json.load(v4)\n v1.set_category_id_name_map({...
[ "datasets", "json", "os" ]
[ "from datasets.DET.constructor.base_interface import DetectionDatasetConstructor", "import json", "import os", "from datasets.types.data_split import DataSplit" ]
7
from datasets.DET.constructor.base_interface import DetectionDatasetConstructor import json from data.types.bounding_box_format import BoundingBoxFormat import os from datasets.types.data_split import DataSplit def _construct_Objects365(constructor: DetectionDatasetConstructor, images_path: str, annotation_file_path:...
null
v14
[ "int", "int" ]
Any
def v14(v15: int, v16: int): v17 = v10(v15, v16, s=2.501) if Math.floor(v17 * 3400) == 421 and v0(v15, v16) == 'H': return True elif Math.floor(v17 * 9000) == 4203 and v0(v15, v16) == 'C': return True return False
[ { "name": "v0", "input_types": [ "int", "int" ], "output_type": "Any", "code": "def v0(v1: int, v2: int):\n global invalidPlace, TILES, edgeDist\n if v1 == 0 and v2 == 0:\n return TILES['monument']\n v3 = TILES['sand']\n v4 = getPerlin(v1, v2 + 5500, s=10000)\n ...
[ "math" ]
[ "import math as Math" ]
7
""" The world generation """ from .noise import simplex2 import math as Math edgeDist = 500000 TILES={ 'traveler': "&", 'sand': " ", 'grass': ",", 'tree': "t", 'water': "w", 'swamp': "~", 'mountain': "M", 'forest': "T", 'house': "H", 'city': "C", 'startbox': "u", 'monument': "\u258B", 'i...
null
v0
[ "Any", "Any", "Any", "tuple", "Any" ]
Tuple[Mapping[tuple, float], object]
def v0(v1, v2, v3, v4: tuple, v5) -> Tuple[Mapping[tuple, float], object]: (v6, v7, v8, v9) = v4 v10 = v7(v3, v1) v11 = v9(v2, v10) v12 = {} for (v13, v14) in v5.items(): v15 = v1.copy() if isinstance(v15, pd.DataFrame): v15 = v15.values v16 = np.arange(v15.shape[...
[]
[ "numpy", "pandas" ]
[ "import numpy as np", "import pandas as pd" ]
24
import ast import copy import random from typing import MutableMapping, List, Tuple, Mapping, Optional import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import willump.evaluation.willump_graph_passes as wg_passes from willump.graph.array_count_vectorizer_node import ArrayCoun...
null
v0
[ "Any", "Any", "Any", "Any", "tuple", "List[int]", "float", "float", "List[int]", "List[int]" ]
Any
def v0(v1, v2, v3, v4, v5: tuple, v6: List[int], v7: float, v8: float, v9: List[int], v10: List[int]): v11 = 0.95 (v12, v13, v14, v15) = v5 assert v3.shape[0] > max(v10) (v16, v17) = (v1[:, v6], v3[:, v6]) v18 = v12(v16, v2) v19 = v14(v18, v17) v20 = 100 v21 = sorted(list(set(range(1, 10...
[]
[ "numpy", "random" ]
[ "import random", "import numpy as np" ]
35
import ast import copy import random from typing import MutableMapping, List, Tuple, Mapping, Optional import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import willump.evaluation.willump_graph_passes as wg_passes from willump.graph.array_count_vectorizer_node import ArrayCoun...
null
v0
[ "int", "int" ]
Any
def v0(self, v1: int, v2: int=None): v3 = ' AND `rev_id` < {}'.format(v2) if v2 is not None else '' v4 = '\n SELECT `r`.`rev_id` AS `wiki_id`, `r`.`rev_page` AS `page_id`, \n `r`.`rev_parent_id` AS `parent_id`, `r`.`rev_timestamp` AS `timestamp`, \n `r`...
[]
[]
[]
5
from pymysql.connections import Connection from db.base_db import BaseDB from lang.langs import Lang from utils.algorithms import extract_rev_id from typing import List class WikimediaDB(BaseDB): """ this class manage requests for Wikimedia database """ def __init__(self, ctx: Connection, lang: Lang)...
null
v0
[ "int", "int" ]
Any
def v0(self, v1: int, v2: int): v3 = '\n SELECT `r`.`rev_parent_id` FROM `{0}`.`revision` AS `r`\n INNER JOIN `{0}`.`comment_revision` AS `c`\n ON `r`.`rev_comment_id` = `c`.`comment_id`\n WHERE `r`.`rev_parent_id` = %s\n AND `r`.`rev_page` ...
[]
[]
[]
5
from pymysql.connections import Connection from db.base_db import BaseDB from lang.langs import Lang from utils.algorithms import extract_rev_id from typing import List class WikimediaDB(BaseDB): """ this class manage requests for Wikimedia database """ def __init__(self, ctx: Connection, lang: Lang)...
null
v0
[ "List" ]
Any
def v0(self, v1: List): v2 = list() for (v3, (v4, v5)) in enumerate(v1): v2.extend(self.fetch_restored_rev(v4, v5)) print('finish fetch restored revision num {}'.format(v3 + 1)) return v2
[]
[]
[]
6
from pymysql.connections import Connection from db.base_db import BaseDB from lang.langs import Lang from utils.algorithms import extract_rev_id from typing import List class WikimediaDB(BaseDB): """ this class manage requests for Wikimedia database """ def __init__(self, ctx: Connection, lang: Lang)...
null
v0
[ "int", "int" ]
Any
def v0(self, v1: int, v2: int=None): v3 = ' AND comment_id < {}'.format(v2) if v2 is not None else '' v4 = 'SELECT `comment_id` AS `id`, LOWER(`comment_text`) AS `text` FROM `{0}`.`comment_revision`\n WHERE LOWER(`comment_text`) LIKE %s {1} \n ORDER BY `comment_id` DESC LIMIT...
[]
[]
[]
6
from pymysql.connections import Connection from db.base_db import BaseDB from lang.langs import Lang from utils.algorithms import extract_rev_id from typing import List class WikimediaDB(BaseDB): """ this class manage requests for Wikimedia database """ def __init__(self, ctx: Connection, lang: Lang)...
null
v0
[ "int" ]
Any
def v0(self, v1: int): v2 = '\n SELECT page_title FROM {0}.page\n WHERE page_id = {1}\n LIMIT 1\n '.format(self.db_name, v1) print(v2) return self._fetchall(v2)
[]
[]
[]
4
from pymysql.connections import Connection from db.base_db import BaseDB from lang.langs import Lang from utils.algorithms import extract_rev_id from typing import List class WikimediaDB(BaseDB): """ this class manage requests for Wikimedia database """ def __init__(self, ctx: Connection, lang: Lang)...
null
v11
[ "v0" ]
None
def v11(self, v12: v0) -> None: v13 = self.connections.get_connection(self.handle) if v13: self.disconnect() if not self.glue(v12): return self.connect_handle(v12)
[]
[]
[]
7
from functools import singledispatch from typing import Callable, Optional, Protocol from gaphas.connections import Connections from gaphas.connector import Handle, LinePort, Port from gaphas.geometry import intersect_line_line from gaphas.item import Element, Item, Line, matrix_i2i from gaphas.solver import Constrain...
[ "class v0(Protocol):\n v1: Item\n v2: Optional[Port]\n\n def __init__(self, v3: Item, v4: float=10):\n ...\n\n def v5(self, v6: SupportsFloatPos, v7: Optional[SupportsFloatPos]=None) -> Optional[Pos]:\n ...\n\n def v8(self, v9: Item, v10: Handle) -> Constraint:\n ..." ]
v11
[ "v0", "Optional[Callable[[], None]]" ]
None
def v11(self, v12: v0, v13: Optional[Callable[[], None]]=None) -> None: v14 = self.handle v15 = self.item v16 = v12.constraint(v15, v14) self.connections.connect_item(v15, v14, v12.item, v12.port, v16, callback=v13)
[]
[]
[]
5
from functools import singledispatch from typing import Callable, Optional, Protocol from gaphas.connections import Connections from gaphas.connector import Handle, LinePort, Port from gaphas.geometry import intersect_line_line from gaphas.item import Element, Item, Line, matrix_i2i from gaphas.solver import Constrain...
[ "class v0(Protocol):\n v1: Item\n v2: Optional[Port]\n\n def __init__(self, v3: Item, v4: float=10):\n ...\n\n def v5(self, v6: SupportsFloatPos, v7: Optional[SupportsFloatPos]=None) -> Optional[Pos]:\n ...\n\n def v8(self, v9: Item, v10: Handle) -> Constraint:\n ..." ]
v0
[ "str", "Dict", "str" ]
Any
def v0(v1: str, v2: Dict, v3: str): os.makedirs(v1, exist_ok=True) v4 = osp.join(v1, v3 + '_checkpoint.pt.tar') torch.save(v2, v4)
[]
[ "os", "torch" ]
[ "import os.path as osp", "import torch", "import torch.nn.functional as F", "import os" ]
4
''' Purpose: In this file only Cl, Cd, Cdp, Cm, and Cp are predicted using graph neural networks ''' import os.path as osp from typing import Dict import torch from torch_geometric.loader import DataLoader import logging, datetime from tqdm import tqdm, trange from gnn_model import GnnModel from MultiLayerLinear i...
null
v0
[ "str", "str" ]
Any
def v0(v1: str, v2: str): v3 = osp.join(v1, v2 + '_checkpoint.pt.tar') if osp.exists(v3): v4 = torch.load(v3) return v4 else: return None
[]
[ "os", "torch" ]
[ "import os.path as osp", "import torch", "import torch.nn.functional as F", "import os" ]
7
''' Purpose: In this file only Cl, Cd, Cdp, Cm, and Cp are predicted using graph neural networks ''' import os.path as osp from typing import Dict import torch from torch_geometric.loader import DataLoader import logging, datetime from tqdm import tqdm, trange from gnn_model import GnnModel from MultiLayerLinear i...
null
v82
[ "Tuple[str, Any]" ]
Any
def v82(v83: Tuple[str, Any]): (v84, v85) = v83 if v84 == 'producer': (v86, v87, v88, v89, v90) = v85 v62(v86, v87, v88, v89, v90) if v84 == 'consumer': v86 = v85 v74(v86)
[ { "name": "v4", "input_types": [ "np.ndarray", "np.ndarray", "Optional[np.ndarray]", "Optional[np.ndarray]", "Dict[str, Any]" ], "output_type": "Any", "code": "def v4(v5: np.ndarray, v6: np.ndarray, v7: Optional[np.ndarray], v8: Optional[np.ndarray], v9: Dict[str, A...
[ "numpy", "queue", "timeit" ]
[ "import queue", "from timeit import default_timer as timer", "import numpy as np" ]
8
import itertools import logging import math import queue import threading from timeit import default_timer as timer from typing import Optional, List, Dict, Any, Tuple import numpy as np from opensfm import bow, features, io, log, pygeometry, upright, masking from opensfm.context import parallel_map from opensfm.datas...
[ "class v0(object):\n\n def __init__(self):\n self.number_of_read = 0\n self.counter = itertools.count()\n self.read_lock = threading.Lock()\n\n def v1(self):\n next(self.counter)\n\n def v2(self):\n with self.read_lock:\n v3 = next(self.counter) - self.number_o...
v58
[ "v59.Queue" ]
Any
def v58(v59: v59.Queue): while True: v60 = v59.get() if v60 is None: v59.put(None) break (v61, v62, v63, v64, v65) = v60 v17(v61, v62, v63, v64, v65) del image_array del segmentation_array del instances_array
[ { "name": "v0", "input_types": [ "np.ndarray", "np.ndarray", "Optional[np.ndarray]", "Optional[np.ndarray]", "Dict[str, Any]" ], "output_type": "Any", "code": "def v0(v1: np.ndarray, v2: np.ndarray, v3: Optional[np.ndarray], v4: Optional[np.ndarray], v5: Dict[str, A...
[ "numpy", "queue", "timeit" ]
[ "import queue", "from timeit import default_timer as timer", "import numpy as np" ]
11
import itertools import logging import math import queue import threading from timeit import default_timer as timer from typing import Optional, List, Dict, Any, Tuple import numpy as np from opensfm import bow, features, io, log, pygeometry, upright, masking from opensfm.context import parallel_map from opensfm.datas...
null
v0
[ "str", "str" ]
str
def v0(self, *, v1: str, v2: str=None) -> str: v2 = v2 and f'/{v2}' or '' v3 = self.session.ep(f'telephony/config/locations/{v1}/outgoingPermission/accessCodes{v2}') return v3
[]
[]
[]
4
""" Access codes API for locations Use Access Codes to bypass the set permissions for all persons/workspaces at this location. """ import json from typing import Union from pydantic import parse_obj_as from ..api_child import ApiChild from ..common import AuthCode __all__ = ['AccessCodesApi'] class AccessCodesApi...
null
v0
[ "Dict[str, Any]" ]
Dict[str, Any]
def v0(v1: Dict[str, Any]) -> Dict[str, Any]: v1['tune_eval']['loss'] = None v1['tune_eval']['perplexity'] = None v1['tune_bleu']['current'] = None return v1
[]
[]
[]
5
#!/usr/bin/env python3 import builtins as __builtin__ import collections import datetime import faulthandler import math import multiprocessing.queues as mp_queues import os import queue import random import time from typing import Any, Callable, Dict, Optional, Tuple import numpy as np import torch from fairseq impo...
null
v0
[ "str" ]
Any
def v0(self, v1: str): if not self.config.html_js_files: self.config.html_js_files = ['dark_mode_js/default_{default_theme}.js'.format(default_theme=v1), 'dark_mode_js/theme_switcher.js'] else: self.config.html_js_files.append('dark_mode_js/default_{default_theme}.js'.format(default_theme=v1)) ...
[]
[]
[]
6
from pathlib import Path class DarkModeLoader: def __init__(self): self.config = None def configure(self, _app, config): self.config = config self.check_sphinx_theme() if not self.config.html_static_path: self.config.html_static_path = [ str(Path....
null
v0
[ "Dict[str, torch.Tensor]" ]
Dict[str, torch.Tensor]
def v0(self, v1: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: if v1['image'].dtype != self.kernel.dtype: raise ValueError(f"Expected Image dtype to be {self.kernel.dtype} not {v1['image'].dtype}") v2 = v1['image'].device if self.kernel.device != v2: self.kernel = self.kernel.to(v2) ...
[]
[ "torch" ]
[ "import torch", "import torch.nn.functional as F" ]
12
import torch import torchvision.transforms.functional import torch.nn.functional as F from kornia.augmentation import RandomAffine3D from PIL.Image import Image import numpy as np from typing import Dict, Tuple, Union, Sequence, List import elasticdeform import skimage.io as io from hcat import ShapeError import matplo...
null
v0
[ "torch.Tensor" ]
torch.Tensor
def v0(self, v1: torch.Tensor) -> torch.Tensor: if v1.device != self.kernel.device: raise ValueError(f'Expected Image Device to be {self.kernel.device} not {v1.device}') if v1.dtype != self.kernel.dtype: raise ValueError(f'Expected Image dtype to be {self.kernel.dtype} not {v1.dtype}') if v1...
[]
[ "torch" ]
[ "import torch", "import torch.nn.functional as F" ]
10
import torch import torchvision.transforms.functional import torch.nn.functional as F from kornia.augmentation import RandomAffine3D from PIL.Image import Image import numpy as np from typing import Dict, Tuple, Union, Sequence, List import elasticdeform import skimage.io as io from hcat import ShapeError import matplo...
null
v0
[ "List[nn.Module]", "int", "int", "float" ]
None
def v0(self, v1: List[nn.Module], v2: int, v3: int, v4: float) -> None: v1.append(nn.Linear(v2, v3)) v1.append(nn.BatchNorm1d(v3)) v1.append(_activations[self.config['activation']]()) if self.config['use_dropout'] and self.config['max_dropout'] > 0.05: v1.append(nn.Dropout(v4))
[]
[ "torch" ]
[ "from torch import nn" ]
6
from typing import Dict, List, Optional, Tuple, Union import ConfigSpace as CS from ConfigSpace.configuration_space import ConfigurationSpace from ConfigSpace.hyperparameters import ( CategoricalHyperparameter, UniformFloatHyperparameter, UniformIntegerHyperparameter ) from torch import nn from autoPyTor...
null
v0
[ "Path", "float" ]
Path
def v0(v1: Path, v2: float) -> Path: v3 = v1 / uuid.uuid4().hex with open(v3, mode='wb') as v4: v4.seek(int(1024 * 1024 * v2)) v4.write(b'\x00') return v3
[]
[ "uuid" ]
[ "import uuid" ]
6
import asyncio import contextlib import copy import os import random import textwrap import pytest import sys import uuid from _pytest.monkeypatch import MonkeyPatch from _pytest.python import Function from spacy import Language from rasa.engine.caching import LocalTrainingCache from rasa.engine.graph import Executi...
null
v0
[ "list" ]
set
def v0(self, v1: list) -> set: v2: list = [] for v3 in v1: v4 = v3.split('-') if len(v4) == 1: v2.append(int(v3)) elif len(v4) == 2: v2 += list(range(int(v4[0]), int(v4[1]) + 1)) return set(v2)
[]
[]
[]
9
import re import os import xmlrpc.client import json import logs import traceback class Subscribe: """rules [{ "dir": "平稳世代的韦驮天们", "title": [ "平稳世代的韦驮天们|Heion Sedai no Idaten", "動畫" ], "title_optional": [ "简|CHS|GB", "简|CHS|GB|繁|CHT|BIG5", "1080|2160" ], "epsode_filter": "[^a-zA...
null
v4
[ "set" ]
list
def v4(self, v5: set) -> list: def v6(v7: list) -> str: """pop int from a, reuturn str """ v8 = v7.pop() v9 = v8 while v9 + 1 in v7: v9 = v7.pop() if v8 == v9: return str(v9) else: return str(v8) + '-' + str(v9) v1...
[ { "name": "v0", "input_types": [ "list" ], "output_type": "str", "code": "def v0(v1: list) -> str:\n v2 = v1.pop()\n v3 = v2\n while v3 + 1 in v1:\n v3 = v1.pop()\n if v2 == v3:\n return str(v3)\n else:\n return str(v2) + '-' + str(v3)", "dependencie...
[]
[]
19
import re import os import xmlrpc.client import json import logs import traceback class Subscribe: """rules [{ "dir": "平稳世代的韦驮天们", "title": [ "平稳世代的韦驮天们|Heion Sedai no Idaten", "動畫" ], "title_optional": [ "简|CHS|GB", "简|CHS|GB|繁|CHT|BIG5", "1080|2160" ], "epsode_filter": "[^a-zA...
null
v0
[ "list" ]
str
def v0(v1: list) -> str: v2 = v1.pop() v3 = v2 while v3 + 1 in v1: v3 = v1.pop() if v2 == v3: return str(v3) else: return str(v2) + '-' + str(v3)
[]
[]
[]
9
import re import os import xmlrpc.client import json import logs import traceback class Subscribe: """rules [{ "dir": "平稳世代的韦驮天们", "title": [ "平稳世代的韦驮天们|Heion Sedai no Idaten", "動畫" ], "title_optional": [ "简|CHS|GB", "简|CHS|GB|繁|CHT|BIG5", "1080|2160" ], "epsode_filter": "[^a-zA...
null
v0
[ "str", "Optional[int]" ]
str
def v0(self, v1: str, v2: Optional[int]=None) -> str: if self.exists(v1): self.delete(v1) return v1
[]
[]
[]
4
""" Custom storages. .. seealso:: https://docs.djangoproject.com/en/3.0/ref/files/storage/ """ from typing import Optional, Tuple from urllib.parse import urlencode from django.conf import settings from django.core.files.storage import FileSystemStorage class CDNStorage(FileSystemStorage): """ Storage...
null
v0
[]
typing.Dict[types.Tag, typing.List[str]]
def v0(cls) -> typing.Dict[types.Tag, typing.List[str]]: v1 = inspect.getmro(cls) v2 = defaultdict(list) for v3 in dir(cls): for v4 in v1: try: v5 = v4.__dict__[v3] except KeyError: continue else: break else:...
[]
[ "collections", "inspect" ]
[ "import inspect", "from collections import OrderedDict, defaultdict", "from collections.abc import Mapping" ]
21
"""The :class:`Schema` class, including its metaclass and options (class Meta).""" import copy import datetime as dt import decimal import inspect import json import typing import uuid import warnings from collections import OrderedDict, defaultdict from collections.abc import Mapping from functools import lru_cache f...
null
v0
[ "typing.Any", "typing.Optional[bool]" ]
Any
def v0(self, v1: typing.Any, *v3, v2: typing.Optional[bool]=None, **v4): v5 = self.dump(v1, many=v2) return self.opts.render_module.dumps(v5, *v3, **v4)
[]
[]
[]
3
"""The :class:`Schema` class, including its metaclass and options (class Meta).""" from collections import defaultdict, OrderedDict from collections.abc import Mapping from functools import lru_cache import datetime as dt import uuid import decimal import copy import inspect import json import typing import warnings f...
null
v0
[ "str", "typing.Optional[bool]", "typing.Optional[typing.Union[bool, types.StrSequenceOrSet]]", "typing.Optional[str]" ]
Any
def v0(self, v1: str, *, v2: typing.Optional[bool]=None, v3: typing.Optional[typing.Union[bool, types.StrSequenceOrSet]]=None, v4: typing.Optional[str]=None, **v5): v6 = self.opts.render_module.loads(v1, **v5) return self.load(v6, many=v2, partial=v3, unknown=v4)
[]
[]
[]
3
"""The :class:`Schema` class, including its metaclass and options (class Meta).""" from collections import defaultdict, OrderedDict from collections.abc import Mapping from functools import lru_cache import datetime as dt import uuid import decimal import copy import inspect import json import typing import warnings f...
null
v0
[]
None
def v0(self) -> None: if self.only is not None: self.__apply_nested_option('only', self.only, 'intersection') self.only = self.set_class([field.split('.', 1)[0] for v1 in self.only]) if self.exclude: self.__apply_nested_option('exclude', self.exclude, 'union') self.exclude = self...
[]
[]
[]
7
"""The :class:`Schema` class, including its metaclass and options (class Meta).""" import copy import datetime as dt import decimal import inspect import json import typing import uuid import warnings from collections import OrderedDict, defaultdict from collections.abc import Mapping from functools import lru_cache f...
null
v0
[ "Any", "Any", "Any" ]
None
def v0(self, v1, v2, v3) -> None: v4 = [name.split('.', 1) for v5 in v2 if '.' in v5] v6 = defaultdict(list) for (v7, v8) in v4: v6[v7].append(v8) for (v9, v10) in iter(v6.items()): v11 = self.set_class(v10) v12 = getattr(self.declared_fields[v9], v1, ()) if v12: ...
[]
[ "collections" ]
[ "from collections import OrderedDict, defaultdict", "from collections.abc import Mapping" ]
14
"""The :class:`Schema` class, including its metaclass and options (class Meta).""" import copy import datetime as dt import decimal import inspect import json import typing import uuid import warnings from collections import OrderedDict, defaultdict from collections.abc import Mapping from functools import lru_cache f...
null
v0
[ "str", "Any", "bool", "Any" ]
Any
def v0(self, v1: str, v2, *, v3: bool, v4=None): v2 = self._invoke_processors(v1, pass_many=False, data=v2, many=v3, original_data=v4) v2 = self._invoke_processors(v1, pass_many=True, data=v2, many=v3, original_data=v4) return v2
[]
[]
[]
4
"""The :class:`Schema` class, including its metaclass and options (class Meta).""" import copy import datetime as dt import decimal import inspect import json import typing import uuid import warnings from collections import OrderedDict, defaultdict from collections.abc import Mapping from functools import lru_cache f...
null
v0
[ "str", "Any", "bool", "Any", "typing.Union[bool, types.StrSequenceOrSet]" ]
Any
def v0(self, v1: str, v2, *, v3: bool, v4, v5: typing.Union[bool, types.StrSequenceOrSet]): v2 = self._invoke_processors(v1, pass_many=True, data=v2, many=v3, original_data=v4, partial=v5) v2 = self._invoke_processors(v1, pass_many=False, data=v2, many=v3, original_data=v4, partial=v5) return v2
[]
[]
[]
4
"""The :class:`Schema` class, including its metaclass and options (class Meta).""" import copy import datetime as dt import decimal import inspect import json import typing import uuid import warnings from collections import OrderedDict, defaultdict from collections.abc import Mapping from functools import lru_cache f...
null
v0
[ "str", "bool", "Any", "bool", "Any" ]
Any
def v0(self, v1: str, *, v2: bool, v3, v4: bool, v5=None, **v6): v7 = (v1, v2) for v8 in self._hooks[v7]: v9 = getattr(self, v8) v10 = v9.__marshmallow_hook__[v7] v11 = v10.get('pass_original', False) if v2: if v11: v3 = v9(v3, v5, many=v4, **v6) ...
[]
[]
[]
21
"""The :class:`Schema` class, including its metaclass and options (class Meta).""" from collections import defaultdict, OrderedDict from collections.abc import Mapping from functools import lru_cache import datetime as dt import uuid import decimal import copy import inspect import json import typing import warnings f...
null
v0
[ "List[str]" ]
Any
def v0(self, v1: List[str]=None): if v1 is None: v1 = sys.argv[1:] v2 = self.argparser.parse_args(v1) v2.subcommand(v2)
[]
[ "sys" ]
[ "import sys" ]
5
import argparse import sys from pathlib import Path from typing import List, Optional from mlxtk import sge from mlxtk.simulation import base class Simulation(base.SimulationBase): def __init__(self, name: Path = Path("sim"), working_dir: Optional[Path] = None): super().__init__(name, working_dir) ...
null
v0
[ "Optional[int]" ]
None
def v0(self, v1: Optional[int]=None) -> None: if v1 is not None: v2 = min(self._decay, (self._numerator + v1) / (self._denominator + v1)) else: v2 = self._decay for (v3, v4) in self._parameters: self._shadows[v3].mul_(v2).add_((1 - v2) * v4.data)
[]
[]
[]
7
from typing import Iterable, Tuple, Optional, Any, Dict import torch from allennlp.common.registrable import Registrable NamedParameter = Tuple[str, torch.Tensor] class MovingAverage(Registrable): """ Tracks a moving average of model parameters. """ default_implementation = "exponential" def ...
null
v0
[]
None
def v0(self) -> None: for (v1, v2) in self._parameters: self._backups[v1].data = v2.data.clone() v2.data = self._shadows[v1].data.clone()
[]
[]
[]
4
from typing import Iterable, Tuple, Optional import torch from allennlp.common.registrable import Registrable NamedParameter = Tuple[str, torch.Tensor] # pylint: disable=invalid-name class MovingAverage(Registrable): """ Tracks a moving average of model parameters. """ default_implementation = "ex...
null
v0
[]
None
def v0(self) -> None: for (v1, v2) in self._parameters: v2.data = self._backups[v1].data.clone()
[]
[]
[]
3
from typing import Iterable, Tuple, Optional import torch from allennlp.common.registrable import Registrable NamedParameter = Tuple[str, torch.Tensor] # pylint: disable=invalid-name class MovingAverage(Registrable): """ Tracks a moving average of model parameters. """ default_implementation = "ex...
null
v0
[ "Dict[str, Any]" ]
None
def v0(self, v1: Dict[str, Any]) -> None: self._parameters = v1['parameters'] self._shadows = v1['shadows'] self._backups = v1['backups']
[]
[]
[]
4
from typing import Iterable, Tuple, Optional, Any, Dict import torch from allennlp.common.registrable import Registrable NamedParameter = Tuple[str, torch.Tensor] class MovingAverage(Registrable): """ Tracks a moving average of model parameters. """ default_implementation = "exponential" def ...
null
v0
[]
None
def v0(self) -> None: v1 = self.BOT vars(self).clear() self.__init__(v1)
[]
[]
[]
4
import logging from discord import Emoji, Bot class EmojiGroup: """ Handle server emojis """ def __init__(self, bot: Bot) -> None: """ Initialize and add instance attributes Attribute name is Emoji.name Attribute value is Emoji.id """ self.BOT = bot ...
null
v0
[]
None
def v0(self) -> None: self.redeem_script = b'' self.witness_script = b'' self.hd_keypaths.clear() self.tap_internal_key = b'' self.tap_tree = b'' self.tap_bip32_paths.clear() self.unknown.clear()
[]
[]
[]
8
""" PSBT Classes and Utilities ************************** """ import base64 import struct from io import BytesIO, BufferedReader from typing import ( Dict, List, Mapping, MutableMapping, Optional, Sequence, Set, Tuple, ) from .key import KeyOriginInfo from .errors import PSBTSerializa...
null
v0
[ "np.ndarray", "Dict[str, Union[int, float]]", "bool" ]
np.ndarray
def v0(self, v1: np.ndarray, v2: Dict[str, Union[int, float]], v3: bool) -> np.ndarray: if v3: v1 = np.transpose(v1, (0, 2, 3, 1)) v1 = v2['brightness'] * v1 v4 = (4 - v2['rot90']) % 4 v1 = np.rot90(v1, v4, (1, 2)) v5 = self.patch_location[0] - int(v2['crop_x']) v6 = self.patch_location[...
[]
[ "numpy" ]
[ "import numpy as np" ]
18
# MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020 # # 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 # r...
null
v0
[ "np.ndarray", "Optional[np.ndarray]" ]
np.ndarray
def v0(self, v1: np.ndarray, v2: Optional[np.ndarray]=None) -> np.ndarray: v3 = v1.copy() if v2 is not None: v4 = v2.copy() else: v4 = self._patch.copy() if self.estimator.channels_first: v3 = np.transpose(v3, (0, 2, 3, 1)) v4 = np.transpose(v4, (1, 2, 0)) (v5, v6) = ...
[]
[ "numpy" ]
[ "import numpy as np" ]
17
# MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020 # # 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 # r...
null
v0
[]
None
def v0(self) -> None: if not isinstance(self.patch_shape, (tuple, list)) or not all((isinstance(s, int) for v1 in self.patch_shape)): raise ValueError('The patch shape must be either a tuple or list of integers.') if len(self.patch_shape) != 3: raise ValueError('The length of patch shape must be...
[]
[]
[]
53
# MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020 # # 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 # r...
null
v6
[]
v0
def v6(self) -> v0: for v7 in self: if v7.active == True: return v7 return None
[]
[]
[]
5
from typing import List, TYPE_CHECKING from enum import Enum, auto from typing import List import logging if TYPE_CHECKING: from .table import Table class Role(Enum): NORMAL = 0 DEALER = 1 SMALL = 2 BIG = 3 UTG = 4 class Player(): """ The Player is a participant of the Game """ def __...
[ "class v0:\n\n def __init__(self, v1: str):\n self.name: str = str(v1)\n self.money_seat: float = float(0)\n self.money_pot: float = float(0)\n self.role: str = Role.NORMAL\n self.active: bool = False\n self.hand: List[str] = []\n self.bet_counter = 0\n\n def v...
v0
[]
None
def v0(self) -> None: v1 = self[-1].role for (v2, v3) in reversed(list(enumerate(self))): logging.debug('position: %s role: %s', v2, v3.role) if v2 == 0: v3.role = v1 else: v3.role = self[v2 - 1].role for (v2, v3) in enumerate(self): logging.debug('pos...
[]
[ "logging" ]
[ "import logging" ]
10
from typing import List, TYPE_CHECKING from enum import Enum, auto from typing import List import logging if TYPE_CHECKING: from .table import Table class Role(Enum): NORMAL = 0 DEALER = 1 SMALL = 2 BIG = 3 UTG = 4 class Player(): """ The Player is a participant of the Game """ def __...
null
v0
[ "list" ]
None
def v0(self, v1: list) -> None: for v2 in self: v2.hand.append(v1.pop()) for v2 in self: v2.hand.append(v1.pop())
[]
[]
[]
5
from typing import List, TYPE_CHECKING from enum import Enum, auto from typing import List import logging if TYPE_CHECKING: from .table import Table class Role(Enum): NORMAL = 0 DEALER = 1 SMALL = 2 BIG = 3 UTG = 4 class Player(): """ The Player is a participant of the Game """ def __...
null
v0
[]
float
def v0(self) -> float: v1 = 0 for v2 in self.elements: v1 += v2.AtomicMass return round(v1, 2)
[]
[]
[]
5
import pandas as pd import numpy as np import sympy from fractions import Fraction import re import os from chemlib.utils import DimensionalAnalyzer, reduce_list from chemlib.constants import Kw, AVOGADROS_NUMBER this_dir, this_filename = os.path.split(__file__) DATA_PATH = os.path.join(this_dir, "resources", "PTE_up...
null
v0
[]
float
def v0(self) -> float: v1 = [] for v2 in self: v1.append(v2.money_pot) return max(v1)
[]
[]
[]
5
from typing import List, TYPE_CHECKING from enum import Enum, auto from typing import List import logging if TYPE_CHECKING: from .table import Table class Role(Enum): NORMAL = 0 DEALER = 1 SMALL = 2 BIG = 3 UTG = 4 class Player(): """ The Player is a participant of the Game """ def __...
null
v0
[ "bool" ]
Dict[str, float]
def v0(self, v1: bool=False) -> Dict[str, float]: (v2, v3) = self._squad_metrics.get_metric(v1) return {'start_acc': 0.007, 'end_acc': 0.007, 'span_acc': 0.007, 'em': v2, 'f1': v3}
[]
[]
[]
3
import logging import numpy as np from typing import Any, Dict, List, Optional import torch from torch.autograd import Variable from torch.nn.functional import nll_loss, binary_cross_entropy_with_logits, binary_cross_entropy, cross_entropy from allennlp.common import Params from allennlp.common.checks import check_d...
null
v0
[ "tf.data.Dataset" ]
int
def v0(v1: tf.data.Dataset) -> int: v2 = 0 for v3 in v1.unbatch().batch(1): v2 += 1 return v2
[]
[]
[]
5
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-08-27 01:27 import random from typing import List import numpy as np import tensorflow as tf from hanlp.common.constant import PAD def size_of_dataset(dataset: tf.data.Dataset) -> int: count = 0 for element in dataset.unbatch().batch(1): count += ...
null
v0
[ "tf.Tensor", "tf.Tensor" ]
Any
def v0(v1: tf.Tensor, v2: tf.Tensor): v3 = getattr(v1, '_keras_mask', None) if v3 is not None: v2._keras_mask = v3 return v3
[]
[]
[]
5
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-08-27 01:27 import random from typing import List import numpy as np import tensorflow as tf from hanlp.common.constant import PAD def size_of_dataset(dataset: tf.data.Dataset) -> int: count = 0 for element in dataset.unbatch().batch(1): count += ...
null
v0
[ "List[tf.keras.callbacks.Callback]" ]
tf.keras.callbacks.Callback
def v0(v1: List[tf.keras.callbacks.Callback], cls) -> tf.keras.callbacks.Callback: for v2 in v1: if isinstance(v2, cls): return v2
[]
[]
[]
4
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-08-27 01:27 import random from typing import List import numpy as np import tensorflow as tf from hanlp.common.constant import PAD def size_of_dataset(dataset: tf.data.Dataset) -> int: count = 0 for element in dataset.unbatch().batch(1): count += ...
null
v2
[ "tf.Tensor", "Any" ]
List[List[str]]
def v2(v3: tf.Tensor, v4=PAD) -> List[List[str]]: v5 = [] for v6 in v3: v7 = [] for v8 in v6: v8 = v0(v8) if v8 == v4: break v7.append(v8) v5.append(v7) return v5
[ { "name": "v0", "input_types": [ "tf.Tensor" ], "output_type": "str", "code": "def v0(v1: tf.Tensor) -> str:\n return v1.numpy().decode('utf-8')", "dependencies": [] } ]
[]
[]
11
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-08-27 01:27 import random from typing import List import numpy as np import tensorflow as tf from hanlp.common.constant import PAD def size_of_dataset(dataset: tf.data.Dataset) -> int: count = 0 for element in dataset.unbatch().batch(1): count += ...
null
v0
[ "list" ]
Any
def v0(self, v1: list): try: self.frame.drop(labels=v1, axis=1, inplace=True) except KeyError: print(print(f"At leas one column: '{v1}' is not in the current domain: '{self.domain}'"))
[]
[]
[]
5
import gc import os import sqlite3 # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique).apply(len) # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique) import numpy as np import pandas as pd from . import functions # pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', N...
null
v0
[ "list" ]
Any
def v0(self, v1: list): try: self.frame = self.frame[v1] except KeyError: print(print(f"At leas one column: '{v1}' is not in the current domain: '{self.domain}'"))
[]
[]
[]
5
import gc import os import sqlite3 # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique).apply(len) # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique) import numpy as np import pandas as pd from . import functions # pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', N...
null
v0
[ "str" ]
Any
def v0(self, v1: str): try: print(self.frame[v1].unique()) except KeyError: print(f"Column '{v1}' is not in the current domain: '{self.domain}'")
[]
[]
[]
5
import gc import os import sqlite3 # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique).apply(len) # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique) import numpy as np import pandas as pd from . import functions # pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', N...
null
v0
[ "str" ]
pd.DataFrame
def v0(self, v1: str, *v2: str) -> pd.DataFrame: try: v3 = self.frame[v1].isin(v2) v4 = self.frame[v3] if len(v4) == 0: print(f'There were no occurences of {v2} within {v1}') print(f'There is {v4.USUBJID.nunique()} unique patients in filtered dataframe') return v4...
[]
[]
[]
10
import gc import os import sqlite3 # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique).apply(len) # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique) import numpy as np import pandas as pd from . import functions # pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', N...
null
v0
[ "str", "Any", "Any" ]
Any
def v0(self, v1: str, *v4, v2=False, v3=False): print(f'Number of unique patients in domain: {self.frame.USUBJID.nunique()}') v5 = self.frame.groupby(v1)['USUBJID'].apply(pd.unique).apply(len).rename('Unique Patients') if self.__is_term_outcome: try: if len(v4) == 0: v6 =...
[]
[ "pandas" ]
[ "import pandas as pd" ]
43
import gc import os import sqlite3 # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique).apply(len) # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique) import numpy as np import pandas as pd from . import functions # pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', N...
null
v0
[]
pd.DataFrame
def v0(self, *v1: str) -> pd.DataFrame: if self.domain not in ['SA', 'IN', 'HO', 'LB']: print('Free text search is currently only implemented for SA, IN, LB or HO domains') print(f"You have currently loaded '{self.domain}'") return v2 = {'HO': 'HOTERM', 'IN': 'INTRT', 'SA': 'SATERM', 'LB...
[]
[]
[]
16
import gc import os import sqlite3 # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique).apply(len) # modify = frame.groupby("SAMODIFY")['USUBJID'].apply(pd.unique) import numpy as np import pandas as pd from . import functions # pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', N...
null
v0
[ "int", "int", "Any" ]
None
async def v0(v1: int=1, v2: int=5, v3=None) -> None: v4 = random.randint(0, 10) if v3: print('%s sleeping for %d seconds' % (v3, v4)) await asyncio.sleep(v4)
[]
[ "asyncio", "random" ]
[ "import asyncio", "import random" ]
5
#!/usr/bin/env python # -*- coding: utf-8 -*- import asyncio import itertools as it import os import random import time #import uvloop async def makeitem(size: int = 5) -> str: return os.urandom(size).hex() async def randsleep(a: int = 1, b: int = 5, caller=None) -> None: i = random.randint(0, 10) if ca...
null
v20
[ "int", "int" ]
Any
async def v20(v21: int, v22: int): v23 = asyncio.Queue() v24 = [asyncio.create_task(v8(n, v23)) for v25 in range(v21)] v26 = [asyncio.create_task(v0(v25, v23)) for v25 in range(v22)] await asyncio.gather(*v24) await v23.join() for v27 in v26: v27.cancel()
[ { "name": "v0", "input_types": [ "int", "asyncio.Queue" ], "output_type": "None", "code": "async def v0(v1: int, v2: asyncio.Queue) -> None:\n while True:\n await randsleep(caller=f'Consumer {v1}')\n (v3, v4) = await v2.get()\n v5 = time.perf_counter()\n ...
[ "asyncio", "itertools", "os", "random" ]
[ "import asyncio", "import itertools as it", "import os", "import random" ]
8
import asyncio import itertools as it import os import random import time async def makeitem(size: int = 5) -> str: return os.urandom(size).hex() async def randsleep(a: int = 1, b: int = 5, caller=None) -> None: i = random.randint(0, 10) if caller: print(f"{caller} sleeping for {i} seconds.") ...
null
v0
[ "List[str]", "int" ]
Tuple[int, str]
def v0(v1: List[str], v2: int=1200) -> Tuple[int, str]: v3 = subprocess.Popen(v1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) try: v4 = v3.communicate(timeout=v2)[0].decode('utf-8') return (v3.returncode, v4) except subprocess.TimeoutExpired: v3.kill() raise Exception('...
[]
[ "subprocess" ]
[ "import subprocess" ]
8
# gridftp.py """Module provides an interface to GridFTP command-line interface.""" from collections import namedtuple from datetime import datetime import hashlib import logging import os import shutil import subprocess import tempfile from typing import Any, List, Optional, Tuple, Union File = namedtuple('File', ['d...
null
v0
[ "str", "str", "int", "bool" ]
Any
def v0(v1: str, v2: str, v3: int=16384, v4: bool=True) -> Any: if v2 not in ('md5', 'sha1', 'sha256', 'sha512'): raise Exception('cannot get checksum for type %r', v2) try: v5 = getattr(hashlib, v2)() except Exception: raise Exception('cannot get checksum for type %r', v2) if v4 ...
[]
[ "os" ]
[ "import os" ]
16
# gridftp.py """Module provides an interface to GridFTP command-line interface.""" from collections import namedtuple from datetime import datetime import hashlib import logging import os import shutil import subprocess import tempfile from typing import Any, List, Optional, Tuple, Union File = namedtuple('File', ['d...
null
v0
[ "int", "Any", "Any" ]
DatetimeIndex
def v0(v1: int=10, v2='B', v3=None, **v4) -> DatetimeIndex: v5 = datetime(2000, 1, 1) v6 = bdate_range(v5, periods=v1, freq=v2, name=v3) return DatetimeIndex(v6, name=v3, **v4)
[]
[ "datetime", "pandas" ]
[ "from datetime import datetime", "from pandas._config.localization import can_set_locale, get_locales, set_locale", "from pandas._typing import Dtype", "from pandas.core.dtypes.common import is_datetime64_dtype, is_datetime64tz_dtype, is_period_dtype, is_sequence, is_timedelta64_dtype", "import pandas as pd...
4
from __future__ import annotations import collections from datetime import datetime from decimal import Decimal from functools import wraps import operator import os import re import string from typing import ( TYPE_CHECKING, Callable, ContextManager, Counter, Iterable, List, Type, ) import...
null
v17
[ "int" ]
Iterable[Index]
def v17(v18: int=10) -> Iterable[Index]: v19: List[Callable[..., Index]] = [v0, v7, v12] for v20 in v19: yield v20(k=v18)
[ { "name": "v0", "input_types": [ "int", "Any", "Any" ], "output_type": "DatetimeIndex", "code": "def v0(v1: int=10, v2='B', v3=None, **v4) -> DatetimeIndex:\n v5 = datetime(2000, 1, 1)\n v6 = bdate_range(v5, periods=v1, freq=v2, name=v3)\n return DatetimeIndex(v6, name...
[ "datetime", "pandas" ]
[ "from datetime import datetime", "from pandas._config.localization import can_set_locale, get_locales, set_locale", "from pandas._typing import Dtype", "from pandas.core.dtypes.common import is_datetime64_dtype, is_datetime64tz_dtype, is_period_dtype, is_sequence, is_timedelta64_dtype", "import pandas as pd...
4
from __future__ import annotations import collections from datetime import datetime from decimal import Decimal from functools import wraps import operator import os import re import string from typing import ( TYPE_CHECKING, Callable, ContextManager, Counter, Iterable, List, Type, ) import...
null
v8
[]
DataFrame
def v8() -> DataFrame: v9 = v2() return DataFrame(v9)
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n return string.ascii_uppercase[:v1]", "dependencies": [] }, { "name": "v2", "input_types": [], "output_type": "Any", "code": "def v2():\n v3 = makeStringIndex(_N)\n return...
[ "numpy", "pandas", "string" ]
[ "import string", "import numpy as np", "from pandas._config.localization import can_set_locale, get_locales, set_locale", "from pandas._typing import Dtype", "from pandas.core.dtypes.common import is_datetime64_dtype, is_datetime64tz_dtype, is_period_dtype, is_sequence, is_timedelta64_dtype", "import pand...
3
from __future__ import annotations import collections from datetime import datetime from decimal import Decimal from functools import wraps import operator import os import re import string from typing import ( TYPE_CHECKING, Callable, ContextManager, Counter, Iterable, List, Type, ) import...
null
v0
[ "List[str]" ]
Any
def v0(v1: List[str]): v2 = os.linesep v3 = v2.join(v1) + v2 return v3
[]
[ "os" ]
[ "import os" ]
4
import bz2 from collections import Counter from contextlib import contextmanager from datetime import datetime from functools import wraps import gzip import os from shutil import rmtree import string import tempfile from typing import Any, Callable, List, Optional, Type, Union, cast import warnings import zipfile imp...
null
v0
[ "Any" ]
Union[v4, List[v4]]
def v0(self, v1, *v2, **v3) -> Union[v4, List[v4]]: v4 = self.client._get(self.path.format(*v2), **v3) return self._build_resource(v1, v4)
[]
[]
[]
3
import abc import dataclasses import functools from dataclasses import dataclass from datetime import datetime from typing import Type, Dict, TYPE_CHECKING, Union, List if TYPE_CHECKING: from .client import Client @dataclass(init=False, frozen=True) class Resource: endpoint: 'Endpoint' def __init__(self...
null
v0
[ "str", "str" ]
int
def v0(self, v1: str, v2: str) -> int: v3 = len(v1) v4 = len(v2) v5 = [] for v6 in range(v3 + 1): v5.append([0] * (v4 + 1)) for v6 in range(1, v3 + 1): v5[v6][0] = v6 for v7 in range(1, v4 + 1): v5[0][v7] = v7 for v6 in range(1, v3 + 1): for v7 in range(1, v4 ...
[]
[]
[]
14
# -*- coding: utf-8 -*- # __author__ = xiaobao # __date__ = 2019/11/09 10:45:18 # desc: desc # 给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。 # 你可以对一个单词进行如下三种操作: # 插入一个字符 # 删除一个字符 # 替换一个字符 # 示例 1: # 输入: word1 = "horse", word2 = "ros" # 输出: 3 # 解释: # horse -> rorse (将 'h' 替换为 'r') # rorse -> rose (删除 'r') ...
null
v0
[ "Optional[Union[UUID, str]]" ]
UUID
def v0(v1: Optional[Union[UUID, str]]=None) -> UUID: if isinstance(v1, UUID): return v1 if not v1: return uuid4() return UUID(str(v1))
[]
[ "uuid" ]
[ "from uuid import UUID, uuid4" ]
6
""" Galaxy data model classes Naming: try to use class names that have a distinct plural form so that the relationship cardinalities are obvious (e.g. prefer Dataset to Data) """ import abc import base64 import errno import json import logging import numbers import operator import os import pwd import random import st...
null
v0
[]
str
def v0(self) -> str: if self.dataset.purged: return '' return self.dataset.get_file_name()
[]
[]
[]
4
""" Galaxy data model classes Naming: try to use class names that have a distinct plural form so that the relationship cardinalities are obvious (e.g. prefer Dataset to Data) """ import abc import base64 import errno import json import logging import numbers import operator import os import pwd import random import st...
null
v0
[]
List[Tuple[str, str]]
def v0(self) -> List[Tuple[str, str]]: v1 = self.metadata v2 = [] for v3 in self.metadata_file_types: v4 = v1.spec[v3].file_ext v5 = v1[v3] if v5: v6 = v5.file_name v2.append((v4, v6)) return v2
[]
[]
[]
10
""" Galaxy data model classes Naming: try to use class names that have a distinct plural form so that the relationship cardinalities are obvious (e.g. prefer Dataset to Data) """ import abc import base64 import errno import json import logging import numbers import operator import os import pwd import random import st...
null
v0
[ "List[dict]", "Optional[str]" ]
Any
def v0(self, v1: List[dict], v2: Optional[str]=None, **v3): self.write_documents(documents=v1, index=v2) return (v3, 'output_1')
[]
[]
[]
3
import logging from abc import abstractmethod from pathlib import Path from typing import Optional, Dict, List, Union import numpy as np from haystack import Document, Label, MultiLabel, BaseComponent from haystack.preprocessor.preprocessor import PreProcessor from haystack.preprocessor.utils import eval_data_from_js...
null
v2
[ "str" ]
Any
def v2(self, v3: str): def v4(v5): if not asyncio.iscoroutinefunction(v5): raise TypeError(f'<{v5.__qualname__}> must be a coroutine function') self._listeners[v3] = v5 return v5 return v4
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n if not asyncio.iscoroutinefunction(v1):\n raise TypeError(f'<{v1.__qualname__}> must be a coroutine function')\n self._listeners[response_type] = v1\n return v1", "dependencies": [] ...
[ "asyncio" ]
[ "import asyncio" ]
8
import asyncio import typing from .types import BumpResponse, CommentResponse from aiohttp import web import aiohttp class Webhook: """Represents a client that can be used to work with BotiCord Webhooks. IP of the server - your machine IP. (`0.0.0.0`) Args: x_hook_key (:obj:`str`) X...
null
v0
[ "int" ]
None
async def v0(self, v1: int=None) -> None: await self.bot.wait_until_ready() while not self.bot.is_closed(): await self.Bots.post_stats() if v1 is None: v1 = 900 await asyncio.sleep(v1)
[]
[ "asyncio" ]
[ "import asyncio" ]
7
from discord.ext import commands from disnake.ext import commands as commandsnake import aiohttp from typing import Union import asyncio from .modules import Bots, Servers, Users class BoticordClient: """ This class is used to make it much easier to use the Boticord API. You can pass `lib` parameter to...
null
v0
[]
str
def v0(self) -> str: while True: v1 = uuid.uuid4() v2 = str(v1) if self.dash else v1.hex if v2 not in self.used_uuids: break self.used_uuids.add(v2) return v2
[]
[ "uuid" ]
[ "import uuid" ]
8
"""Miscellaneous utilities.""" import datetime import functools import io import keyword import operator import platform import textwrap import uuid from .typing import TYPE_CHECKING, MutableMapping, overload if TYPE_CHECKING: from types import TracebackType # isort: split from .typing import (Dict, Generat...
null
v0
[]
'Generator[Union[str, Placeholder], None, None]'
def v0(self) -> 'Generator[Union[str, Placeholder], None, None]': for (v1, v2) in zip(self.literals, self.placeholders): yield v1 yield v2 yield self.literals[-1]
[]
[]
[]
5
"""Miscellaneous utilities.""" import datetime import functools import io import keyword import operator import platform import textwrap import uuid from .typing import TYPE_CHECKING, MutableMapping, overload if TYPE_CHECKING: from types import TracebackType # isort: split from .typing import (Dict, Generat...
null
v0
[ "float", "Tuple[int, int, int]", "Tuple[int, int, int]" ]
np.ndarray
def v0(v1: float=20.0, v2: Tuple[int, int, int]=(49, 49, 49), v3: Tuple[int, int, int]=(99, 99, 99)) -> np.ndarray: v4 = np.zeros(v3, dtype=np.int32) (v5, v6, v7) = np.ogrid[-v2[0]:v3[0] - v2[0], -v2[1]:v3[1] - v2[1], -v2[2]:v3[2] - v2[2]] v8 = v6 * v6 + v5 * v5 + v7 * v7 <= v1 * v1 v4[v8] = 1 v4[~v...
[]
[ "numpy" ]
[ "import numpy as np" ]
7
# Copyright 2020 - 2021 MONAI Consortium # 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 wri...
null
v0
[ "float", "float", "float", "float" ]
tuple[float, float]
def v0(v1: float, v2: float, v3: float, v4: float) -> tuple[float, float]: v5 = v3 - v1 v6 = v4 - v2 v7 = (v5 ** 2 + v6 ** 2) ** 0.5 if v5 == 0: if v6 < 0: v8 = 270 else: v8 = 90 else: v9 = atan(abs(v6 / v5)) * 180 / pi if v6 >= 0: ...
[]
[ "math" ]
[ "from math import atan, tan, pi" ]
21
# -*- coding: utf-8 -*- """ My name is Bond. JAMES Bond. """ from typing import Optional, Union from copy import deepcopy, copy from math import atan, tan, pi from indigo import Indigo from .atom import Atom from . import chemfig_mappings as cfm # Indigo.UP : stereo "up" bond # Indigo.DOWN : stereo "down" bond # Indig...
null
v10
[ "float", "float" ]
None
def v10(self, v11: float, v12: float) -> None: if self.clockwise: return (v13, v14) = v0(self.end_atom.x, self.end_atom.y, v11, v12) v14 += self.options['rotate'] v15 = (v14 - self.angle) % 360 if v15 > 180: self.clockwise = 1 else: self.clockwise = -1
[ { "name": "v0", "input_types": [ "float", "float", "float", "float" ], "output_type": "tuple[float, float]", "code": "def v0(v1: float, v2: float, v3: float, v4: float) -> tuple[float, float]:\n v5 = v3 - v1\n v6 = v4 - v2\n v7 = (v5 ** 2 + v6 ** 2) ** 0.5\n i...
[ "math" ]
[ "from math import atan, tan, pi" ]
10
# -*- coding: utf-8 -*- """ My name is Bond. JAMES Bond. """ from typing import Optional, Union from copy import deepcopy, copy from math import atan, tan, pi from indigo import Indigo from .atom import Atom from . import chemfig_mappings as cfm # Indigo.UP : stereo "up" bond # Indigo.DOWN : stereo "down" bond # Indig...
null
v0
[]
None
def v0(self) -> None: self.bond_type = 'link' self.tikz_styles = set() self.tikz_values = {} self.marker = ''
[]
[]
[]
5
# -*- coding: utf-8 -*- """ My name is Bond. JAMES Bond. """ from typing import Optional, Union from copy import deepcopy, copy from math import atan, tan, pi from indigo import Indigo from .atom import Atom from . import chemfig_mappings as cfm # Indigo.UP : stereo "up" bond # Indigo.DOWN : stereo "down" bond # Indig...
null
v0
[ "bool" ]
None
def v0(self, v1: bool=False) -> None: v2 = self.upstream_angles() v3 = self.downstream_angles() v4 = min(v2.values()) v5 = max(10, self.cotan100(v4)) v6 = min(v3.values()) v7 = max(10, self.cotan100(v6)) self.tikz_styles.add('cross') self.tikz_values.update(dict(bgstart=v5, bgend=v7)) ...
[]
[]
[]
10
# -*- coding: utf-8 -*- """ My name is Bond. JAMES Bond. """ from typing import Optional, Union from copy import deepcopy, copy from math import atan, tan, pi from indigo import Indigo from .atom import Atom from . import chemfig_mappings as cfm # Indigo.UP : stereo "up" bond # Indigo.DOWN : stereo "down" bond # Indig...
null
v0
[]
dict
def v0(self) -> dict: (v1, v2) = self._adjoining_angles(self.start_atom) if v2 is not None: v2 = 360 - v2 return dict(left=v1, right=v2)
[]
[]
[]
5
# -*- coding: utf-8 -*- """ My name is Bond. JAMES Bond. """ from typing import Optional, Union from copy import deepcopy, copy from math import atan, tan, pi from indigo import Indigo from .atom import Atom from . import chemfig_mappings as cfm # Indigo.UP : stereo "up" bond # Indigo.DOWN : stereo "down" bond # Indig...
null
v0
[]
dict
def v0(self) -> dict: (v1, v2) = self._adjoining_angles(self.end_atom, 180) if v2 is not None: v2 = 360 - v2 return dict(left=v2, right=v1)
[]
[]
[]
5
# -*- coding: utf-8 -*- """ My name is Bond. JAMES Bond. """ from typing import Optional, Union from copy import deepcopy, copy from math import atan, tan, pi from indigo import Indigo from .atom import Atom from . import chemfig_mappings as cfm # Indigo.UP : stereo "up" bond # Indigo.DOWN : stereo "down" bond # Indig...
null
v0
[ "Union[int, float, None]", "Union[int, float, None]" ]
int
def v0(self, v1: Union[int, float, None], v2: Union[int, float, None]) -> int: if v1 is None: return 0 if v1 <= 180: v3 = 0.5 * v1 elif 210 < v1 < 270: v3 = v1 - 180 elif 210 < v2 < 270: v3 = v2 - 180 else: v3 = 90 return self.cotan100(v3)
[]
[]
[]
12
# -*- coding: utf-8 -*- """ My name is Bond. JAMES Bond. """ from typing import Optional, Union from copy import deepcopy, copy from math import atan, tan, pi from indigo import Indigo from .atom import Atom from . import chemfig_mappings as cfm # Indigo.UP : stereo "up" bond # Indigo.DOWN : stereo "down" bond # Indig...
null