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 | [
"str",
"Any"
] | Any | def v0(self, v1: str, v2: Any):
if self._dictionary is None:
self._dictionary = {}
self._dictionary[v1] = v2 | [] | [] | [] | 4 | import pprint
from typing import Dict, Any, Callable, List, Optional
class ValueKeyNotFound(Exception):
def __init__(self, key, dictonary):
self.key = key
self.dictionary = dictonary
class DynamicObject(object):
_slots = "_dictionary", "_list", "_value"
def __init__(self):
sel... | null |
v8 | [
"v0"
] | Any | def v8(self, v9: v0):
assert self.indices_ref is not None
return v9.get(self.indices_ref) | [] | [] | [] | 3 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"class v0:\n v1: List[Array]\n\n def __init__(self, v2=()):\n self._buffers = list(v2)\n\n def v3(self, v4: Array) -> int:\n self._buffers.append(jnp.asarray(v4))\n return len(self._buffers) - 1\n\n def v5(self, v6: int) -> Array:\n return self._buffers[v6]\n\n def v7(self... |
v7 | [
"str"
] | Any | def v7(v8: str):
v9 = pathlib.Path(v8)
print('Downloading...')
for v10 in range(2002, 2018):
print('Downloading work ad data set for year: {0}'.format(v10))
v0(v10, v9.joinpath('work_ad_dataset-{0}.csv'.format(v10)).absolute())
print('Completed download successfully') | [
{
"name": "v0",
"input_types": [
"int",
"str"
],
"output_type": "str",
"code": "def v0(v1: int, v2: str) -> str:\n v3 = pathlib.Path(v2).absolute()\n v4 = requests.api.get(API_URL_BASE + str(v1))\n if v4.status_code == 200:\n with open(v3, 'wb') as v5:\n fo... | [
"pathlib",
"requests"
] | [
"import requests",
"import pathlib"
] | 7 | import requests
import pathlib
API_URL_BASE = "https://hotell.difi.no/download/nav/ledige-stillinger/"
def make_data_set_for_year(year: int, file_path: str) -> str:
"""Attempts to download a NAV work ad data set for a given year"""
path = pathlib.Path(file_path).absolute()
result = requests.api.get(API... | null |
v0 | [
"torch.Tensor",
"torch.Tensor"
] | torch.Tensor | def v0(v1: torch.Tensor, v2: torch.Tensor) -> torch.Tensor:
v3 = v2.size()
v4 = v1.size()[1:]
v5 = v3 + v4
v6 = v1.index_select(dim=0, index=v2.view(-1))
v6 = v6.view(v5)
v6[v2 == 0] = 0
return v6 | [] | [] | [] | 8 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 19:56:35 2019
@author: SY
"""
import torch
def index_select_ND(source: torch.Tensor, index: torch.Tensor) -> torch.Tensor:
index_size = index.size() # (num_atoms/num_bonds, max_num_bonds)
suffix_dim = source.size()[1:] # (hidden_size,)
final_size = index... | null |
v0 | [
"str"
] | str | def v0(self, v1: str) -> str:
v2 = ''
v3 = self._img_ref_pattern.split(v1)
for v4 in v3:
v5 = self._img_ref_pattern.fullmatch(v4)
if v5:
self.logger.debug(f'Image reference found: {v5.group(0)}')
v6 = self._fmt_specified_img_ref_pattern.fullmatch(v4)
if v6... | [] | [] | [] | 25 | '''
Preprocessor for Foliant documentation authoring tool.
Converts images from different formats to PNG.
'''
import re
from pathlib import Path
from hashlib import md5
from subprocess import run, PIPE, STDOUT, CalledProcessError
from foliant.preprocessors.base import BasePreprocessor
class Preprocessor(BasePrepro... | null |
v0 | [
"str",
"str"
] | Any | def v0(self, v1: str=None, v2: str=None):
if v1 is None:
raise Exception('specify either country (and region)')
if v1 is not None:
v3 = self.data.loc[self.data['Country/Region'] == v1]
if v2 is not None:
v4 = v3.loc[self.data['Province/State'] == v2]
else:
... | [] | [] | [] | 14 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
class CovidReader:
def __init__(self, filename):
self.filename = filename
self.data = pd.read_csv(self.filename)
def fetch_time_series(self, country: str = None, state: str = None):
if country is None:
... | null |
v0 | [
"List[List]"
] | Dict | def v0(v1: List[List]) -> Dict:
if len(v1) < 2:
raise ValueError('invalid input format')
return {'fields': v1[0], 'rows': [[str(item) for v2 in row] for v3 in v1[1:]]} | [] | [] | [] | 4 | # Copyright 2021 H2O.ai, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | null |
v0 | [
"IO"
] | Dict | def v0(v1: IO) -> Dict:
v2 = csv.reader(v1)
return {'fields': next(v2), 'rows': [row for v3 in v2]} | [] | [
"csv"
] | [
"import csv"
] | 3 | # Copyright 2021 H2O.ai, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | null |
v2 | [
"Any"
] | List[Tuple] | def v2(v3) -> List[Tuple]:
v4 = [v0(name) for v5 in v3['fields']]
v6 = []
for v7 in v3['score']:
v8 = [float(item) for v9 in v7]
v10 = v8.index(max(v8))
v6.append(tuple([v4[v10], *v8]))
return v6 | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n return v1.split('.')[-1]",
"dependencies": []
}
] | [] | [] | 8 | # Copyright 2021 H2O.ai, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | null |
v0 | [
"'Callable[..., None]'"
] | Any | def v0(self, v1: 'Callable[..., None]', *v2: Any, **v3: Any):
assert self.exception_callbacks is not None
self.exception_callbacks.append((v1, v2, v3)) | [] | [] | [] | 3 | # -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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 Licens... | null |
v0 | [
"str",
"float"
] | None | def v0(self, v1: str, v2: float) -> None:
(v3, v4) = self.current_counters.get(v1, (0, 0.0))
v3 += 1
v4 += v2
self.current_counters[v1] = (v3, v4) | [] | [] | [] | 5 | # Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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.... | null |
v0 | [
"float",
"int"
] | str | def v0(self, v1: float, v2: int=3) -> str:
v3 = []
for (v4, (v5, v6)) in self.current_counters.items():
(v7, v8) = self.previous_counters.get(v4, (0, 0))
v3.append(((v6 - v8) / v1, v5 - v7, v4))
self.previous_counters = dict(self.current_counters)
v3.sort(reverse=True)
v9 = ', '.join... | [] | [] | [] | 9 | # -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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 Licens... | null |
v0 | [
"str",
"Dict[str, Any]",
"bool",
"str"
] | bool | async def v0(self, v1: str, v2: Dict[str, Any], v3: bool=False, v4: str='simple_insert') -> bool:
try:
await self.runInteraction(v4, self.simple_insert_txn, v1, v2)
except self.engine.module.IntegrityError:
if not v3:
raise
return False
return True | [] | [] | [] | 8 | # -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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 Licens... | null |
v49 | [
"v0",
"str",
"Dict[str, Any]",
"Dict[str, Any]",
"Optional[Dict[str, Any]]",
"bool"
] | Optional[bool] | def v49(self, v50: v0, v51: str, v52: Dict[str, Any], v53: Dict[str, Any], v54: Optional[Dict[str, Any]]=None, v55: bool=True) -> Optional[bool]:
v54 = v54 or {}
if self.engine.can_native_upsert and v51 not in self._unsafe_to_upsert_tables:
self.simple_upsert_txn_native_upsert(v50, v51, v52, v53, insert... | [] | [] | [] | 7 | # -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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 Licens... | [
"class v0:\n v1 = ['txn', 'name', 'database_engine', 'after_callbacks', 'exception_callbacks']\n\n def __init__(self, v2: Cursor, v3: str, v4: BaseDatabaseEngine, v5: Optional[List[_CallbackListEntry]]=None, v6: Optional[List[_CallbackListEntry]]=None):\n self.txn = v2\n self.name = v3\n ... |
v51 | [
"v0",
"str",
"Dict[str, Any]",
"Dict[str, Any]",
"Optional[Dict[str, Any]]",
"bool"
] | bool | def v51(self, v52: v0, v53: str, v54: Dict[str, Any], v55: Dict[str, Any], v56: Optional[Dict[str, Any]]=None, v57: bool=True) -> bool:
v56 = v56 or {}
if v57:
self.engine.lock_table(v52, v53)
def v58(v59):
if v54[v59] is None:
return '%s IS ?' % (v59,)
else:
... | [
{
"name": "v49",
"input_types": [
"Any"
],
"output_type": "Any",
"code": "def v49(v50):\n if keyvalues[v50] is None:\n return '%s IS ?' % (v50,)\n else:\n return '%s = ?' % (v50,)",
"dependencies": []
}
] | [] | [] | 29 | # Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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.... | [
"class v0:\n v1 = ['txn', 'name', 'database_engine', 'after_callbacks', 'exception_callbacks']\n\n def __init__(self, v2: Cursor, v3: str, v4: BaseDatabaseEngine, v5: Optional[List[_CallbackListEntry]]=None, v6: Optional[List[_CallbackListEntry]]=None):\n self.txn = v2\n self.name = v3\n ... |
v49 | [
"v0",
"str",
"Dict[str, Any]",
"Dict[str, Any]",
"Optional[Dict[str, Any]]"
] | bool | def v49(self, v50: v0, v51: str, v52: Dict[str, Any], v53: Dict[str, Any], v54: Optional[Dict[str, Any]]=None) -> bool:
v55: Dict[str, Any] = {}
v55.update(v52)
v55.update(v54 or {})
if not v53:
v56 = 'NOTHING'
else:
v55.update(v53)
v56 = 'UPDATE SET ' + ', '.join((k + '=EXCL... | [] | [] | [] | 12 | # Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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.... | [
"class v0:\n v1 = ['txn', 'name', 'database_engine', 'after_callbacks', 'exception_callbacks']\n\n def __init__(self, v2: Cursor, v3: str, v4: BaseDatabaseEngine, v5: Optional[List[_CallbackListEntry]]=None, v6: Optional[List[_CallbackListEntry]]=None):\n self.txn = v2\n self.name = v3\n ... |
v0 | [
"str",
"str",
"Iterable[Any]",
"Iterable[str]",
"Optional[Dict[str, Any]]",
"str",
"int"
] | List[Any] | async def v0(self, v1: str, v2: str, v3: Iterable[Any], v4: Iterable[str], v5: Optional[Dict[str, Any]]=None, v6: str='simple_select_many_batch', v7: int=100) -> List[Any]:
v5 = v5 or {}
v8: List[Dict[str, Any]] = []
if not v3:
return v8
v9 = list(v3)
v10 = [v9[i:i + v7] for v11 in range(0, ... | [] | [] | [] | 11 | # Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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.... | null |
v18 | [
"v0",
"str",
"str",
"str",
"int",
"int"
] | Tuple[Dict[Any, int], int] | def v18(self, v19: v0, v20: str, v21: str, v22: str, v23: int, v24: int=100000) -> Tuple[Dict[Any, int], int]:
v25 = 'SELECT %(entity)s, MAX(%(stream)s) FROM %(table)s WHERE %(stream)s > ? - %(limit)s GROUP BY %(entity)s' % {'table': v20, 'entity': v21, 'stream': v22, 'limit': v24}
v26 = v19.cursor(txn_name='ge... | [] | [] | [] | 11 | # -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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 Licens... | [
"@attr.s(slots=True)\nclass v0:\n v1 = attr.ib(type=Connection)\n v2 = attr.ib(type=BaseDatabaseEngine)\n v3 = attr.ib(type=str)\n\n def v4(self, *, v5=None, v6=None, v7=None) -> 'LoggingTransaction':\n if not v5:\n v5 = self.default_txn_name\n return LoggingTransaction(self.con... |
v0 | [
"torch.Tensor",
"torch.Tensor",
"Dict[str, Any]",
"Any"
] | Any | def v0(self, v1: torch.Tensor, v2: torch.Tensor, v3: Dict[str, Any], v4=True):
v5 = -1 * self.crf(v1, v2, reduce=False)
return v5.mean() if v4 else v5 | [] | [] | [] | 3 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Any, Dict, List, Optional, Tuple
import torch
import torch.nn.functional as F
from caffe2.python import core
from pytext.config.component import create_loss
from pytext.config.serialize import MissingValue... | null |
v0 | [
"Any",
"Any",
"Any",
"Any"
] | None | def v0(v1, v2, v3, v4) -> None:
v5 = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36'
v6 = webdriver.ChromeOptions()
v6.headless = True
v6.add_argument(f'user-agent={v5}')
v6.add_argument('--window-size=1920,1080')
v6.add_argument('--igno... | [] | [
"selenium"
] | [
"from selenium import webdriver",
"from selenium.webdriver.chrome.service import Service",
"from selenium.webdriver.common.by import By",
"from selenium.webdriver.chrome.options import Options"
] | 37 | from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from time import sleep
def take_screenshot(machine, chromedrivers_path, timetable_name, credentials) -> None:
"""This function l... | null |
v0 | [
"Tuple[List[str], List[List[float]]]",
"bool"
] | Tuple[np.float, np.float] | def v0(v1: Tuple[List[str], List[List[float]]], v2: bool=False) -> Tuple[np.float, np.float]:
v3 = spearmanr(np.array(v1[1][0 + (not v2)]), np.array(v1[1][1 + (not v2)]), nan_policy='raise')
return (v3.correlation, v3.pvalue) | [] | [
"numpy",
"scipy"
] | [
"import scipy.stats",
"import numpy as np",
"from numpy import array, nan",
"from scipy.stats import spearmanr"
] | 3 | import asyncio
import itertools
import math
import os
import shutil
import sys
import traceback
from collections import namedtuple
import os.path as osp
from glob import glob
from typing import Union, List, Optional, Tuple, Dict, Iterable
import scipy.stats
from amas import AMAS
from ete3 import PhyloTree
import netwo... | null |
v14 | [
"str",
"str",
"str",
"str",
"int"
] | Any | async def v14(v15: str, v16: str, v17: str, v18: str=None, v19: int=5):
try:
if not v17 or not osp.exists(v17):
await v0(v15, v16, model='LG+F+G+I', output=v17, ancestral_states=True, partitions_file=v18, cpus=v19)
except Exception as e:
print(f'WARNING: Could not generate tree for {... | [
{
"name": "v0",
"input_types": [
"str",
"str",
"str",
"str",
"int",
"int",
"bool",
"str",
"bool",
"bool",
"bool"
],
"output_type": "Any",
"code": "async def v0(v1: str, v2: str=None, v3: str='AUTO', v4: str=None, v5: int=1000, v6:... | [
"os",
"shutil",
"traceback"
] | [
"import os",
"import shutil",
"import traceback",
"import os.path as osp"
] | 7 | import asyncio
import itertools
import math
import os
import shutil
import sys
import traceback
from collections import namedtuple
import os.path as osp
from glob import glob
from typing import Union, List, Optional, Tuple, Dict, Iterable
import scipy.stats
from amas import AMAS
from ete3 import PhyloTree
import netwo... | null |
v0 | [
"str",
"str"
] | Any | def v0(self, v1: str, v2: str=None):
assert osp.exists(v1)
if not v2:
self.aligns.append(v1)
else:
assert osp.exists(v2)
self.paired_aligns.append((v1, v2)) | [] | [
"os"
] | [
"import os",
"import os.path as osp"
] | 7 | import asyncio
import itertools
import math
import os
import shutil
import sys
import traceback
from collections import namedtuple
import os.path as osp
from glob import glob
from typing import Union, List, Optional, Tuple, Dict, Iterable
import scipy.stats
from amas import AMAS
from ete3 import PhyloTree
import netwo... | null |
v0 | [
"List[str]",
"str",
"List[str]",
"str"
] | Any | def v0(self, v1: List[str], v2: str, v3: List[str]=None, v4: str=None):
if '.' not in v2:
v2 += '.fa'
if v4 and '.' not in v4:
v4 += '.fa'
v2 = osp.basename(v2)
self.concatenated[v2] = (v1, osp.join(self.directory, 'concat', v2 + '.part'))
if not v3:
self.aligns.append(v2)
... | [] | [
"os"
] | [
"import os",
"import os.path as osp"
] | 13 | import asyncio
import itertools
import math
import os
import shutil
import sys
import traceback
from collections import namedtuple
import os.path as osp
from glob import glob
from typing import Union, List, Optional, Tuple, Dict, Iterable
import scipy.stats
from amas import AMAS
from ete3 import PhyloTree
import netwo... | null |
v0 | [
"Any"
] | bool | def v0(v1: Any) -> bool:
if not isinstance(v1, str):
return False
try:
uuid.UUID(v1)
return True
except ValueError:
return False | [] | [
"uuid"
] | [
"import uuid"
] | 8 | import re
import uuid
from collections.abc import Iterable, Mapping
import unicodedata
from typing import Sequence, Union, Callable, Any, Optional
from django.utils.translation import gettext as _
def form_bool_choices():
"""Return tuple with yes/no choices in format for django forms.
Returns:
tuple... | null |
v0 | [
"int",
"int"
] | int | def v0(self, v1: int, v2: int) -> int:
v3 = [[0 for v4 in range(v2 + 1)] for v4 in range(v1 + 1)]
for v5 in range(v1):
v3[v5][0] = 1
for v6 in range(v2):
v3[0][v6] = 1
for v5 in range(1, v1):
for v6 in range(1, v2):
v3[v5][v6] = v3[v5 - 1][v6] + v3[v5][v6 - 1]
ret... | [] | [] | [] | 10 | '''
62. Unique Paths(Medium)
i/p := m = 3, n = 2
o/p := 3
Explaination := From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
i.e count steps required to reach from 0,0 to given point
'''
c... | null |
v0 | [
"Any",
"Any",
"str"
] | Any | def v0(self, v1=None, v2=None, v3: str=None):
try:
self.db.hset(v1, v2, v3)
finally:
self.kill() | [] | [] | [] | 5 | __all__ = ['RedisClient', 'RedisDataDisasterTolerance']
from typing import List, Tuple
import redis
from src.BusinessCentralLayer.setting import REDIS_MASTER, REDIS_SECRET_KEY, TIME_ZONE_CN, CRAWLER_SEQUENCE, logger
REDIS_CLIENT_VERSION = redis.__version__
IS_REDIS_VERSION_2 = REDIS_CLIENT_VERSION.startswith('2.')
... | null |
v0 | [] | str | def v0(self) -> str:
if self.db.ping():
return '欢迎使用v2ray云彩姬' | [] | [] | [] | 3 | __all__ = ['RedisClient', 'RedisDataDisasterTolerance']
from typing import List, Tuple
import redis
from src.BusinessCentralLayer.setting import REDIS_MASTER, REDIS_SECRET_KEY, TIME_ZONE_CN, CRAWLER_SEQUENCE, logger
REDIS_CLIENT_VERSION = redis.__version__
IS_REDIS_VERSION_2 = REDIS_CLIENT_VERSION.startswith('2.')
... | null |
v0 | [
"Any",
"Any",
"network.Network",
"int",
"float"
] | List[float] | def v0(v1: Any, v2: Any, v3: network.Network, v4: int, v5: float) -> List[float]:
v6 = 0
for v7 in v3.named_children():
if isinstance(v7[1], nn.Conv2d) or isinstance(v7[1], nn.Linear):
v6 += 1
v8 = [0.0] * v6
for v9 in range(v6):
for (v10, (v11, v12)) in enumerate(v1):
... | [] | [
"torch"
] | [
"import torch",
"import torch.nn as nn"
] | 30 | from typing import Any, List
import torch
import torch.nn as nn
import n3ml.network as network
def spikenorm(train_loader: Any,
encoder: Any,
model: network.Network,
num_steps: int,
scaling_factor: float) -> List[float]:
"""
This function implements Sp... | null |
v0 | [] | str | def v0() -> str:
v1 = os.getenv('BUILD_WORKSPACE_DIRECTORY')
if v1:
return v1
v2 = pathlib.Path('x')
for v3 in v2.parents:
if (v3 / 'WORKSPACE').exists():
return str(v2)
raise RuntimeError('Could not find WORKSPACE root') | [] | [
"os",
"pathlib"
] | [
"import os",
"import pathlib"
] | 9 | # Copyright 2020 The TensorStore 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... | null |
v0 | [] | str | def v0(self) -> str:
if self.guilds is None:
return 'Bot not initialized.'
v1 = [i.name for v2 in self.guilds]
return f'[------------------------STATUS------------------------]\nSource: https://github.com/CodeBizarre/discord-bot\nTime: {datetime.now()}\nVersion: {self.version}\nLogged in as {self.us... | [] | [
"datetime"
] | [
"from datetime import datetime"
] | 5 | import sys
import os
import logging
import shutil
import json
from datetime import datetime
from sqlitedict import SqliteDict
from discord.ext import commands
from discordbot.core.time_tools import pretty_datetime
VERSION = "3.3.0b2"
def get_logger(file_name) -> logging.Logger:
"""Get an instance of Logger and... | null |
v0 | [
"np.array",
"np.array"
] | Any | def v0(self, v1: np.array, v2: np.array):
v3 = np.power(v2 + self.epsilon, self.alpha)
v4 = np.array(self.probs)
v4[v1] = np.squeeze(v3, axis=-1)
self.probs = deque(v4, maxlen=self.size)
self._max_prob = max(self._max_prob, np.max(v3).item()) | [] | [
"collections",
"numpy"
] | [
"from collections import deque",
"import numpy as np"
] | 6 | import torch
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
from collections import deque
import random
import numpy as np
from schedule import LinearSchedule
class RolloutStorage(object):
def __init__(self, num_steps, num_processes, obs_shape, action_space,
state_size, nu... | null |
v0 | [
"str"
] | List[re.Match] | def v0(self, v1: str) -> List[re.Match]:
v1 = self.clean_input(v1)
v2 = []
v3 = self._get_filterlist_items('filter_token', allowed=False)
for v4 in v3:
if (v5 := re.search(v4, v1, flags=re.IGNORECASE)):
v2.append(v5)
return v2 | [] | [
"re"
] | [
"import re"
] | 8 | import asyncio
import logging
import re
from datetime import datetime, timedelta
from typing import Any, Dict, List, Mapping, NamedTuple, Optional, Tuple, Union
import dateutil
import discord.errors
import regex
from async_rediscache import RedisCache
from dateutil.relativedelta import relativedelta
from discord impor... | null |
v0 | [
"List[str]"
] | Dict[str, int] | def v0(v1: List[str]) -> Dict[str, int]:
v2 = collections.defaultdict(int)
for v3 in v1:
for v4 in open(v3, 'rt'):
for v5 in v4.lower():
v2[v5] += 1
return dict(v2) | [] | [
"collections"
] | [
"import collections"
] | 7 | # Copyright 2021-2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | null |
v5 | [
"Dict[str, int]",
"str"
] | None | def v5(v6: Dict[str, int], v7: str) -> None:
if v7 == 'all':
v7 = set(v6.keys())
else:
v7 = v0(v7)
v8 = sorted(sorted(v7), key=lambda char: -v6.get(char, 0))
v9 = sum(v6.values())
print('Rank char count %')
for (v10, v11) in enumerate(v8):
v12 = v6.get(v11, 0)
... | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "Set[str]",
"code": "def v0(v1: str) -> Set[str]:\n v2 = {'symbols': '!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~', 'digits': '0123456789', 'letters': 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'}\n v3 = ''\n for v4 in ... | [
"sys"
] | [
"import sys"
] | 14 | # Copyright 2021-2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | null |
v0 | [
"str"
] | Set[str] | def v0(v1: str) -> Set[str]:
v2 = {'symbols': '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', 'digits': '0123456789', 'letters': 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'}
v3 = ''
for v4 in v1.split('+'):
try:
v3 += v2[v4.lower()]
except KeyError:
print(f'Invalid c... | [] | [
"sys"
] | [
"import sys"
] | 10 | # Copyright 2021-2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | null |
v0 | [] | None | def v0(self) -> None:
self.assert_bootstrap_options(pantsrc=True)
v1 = partial(self.assert_bootstrap_options, pantsrc=False)
v1(args=['--no-pantsrc'])
v1(config={'pantsrc': 'false'})
v1(env={'PANTS_PANTSRC': 'False'}) | [] | [
"functools"
] | [
"from functools import partial"
] | 6 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import unittest
from functools import partial
from textwrap import dedent
from typing import Dict, List, Optional
from pants.base.build_environment import get_buildroot
from pan... | null |
v6 | [
"Any"
] | str | def v6(v7) -> str:
if not v7:
return ''
v7 = v0(v7)
v8 = ['#: {}'.format(l) for v9 in v7.split('\n')]
return '\n'.join(v8) | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n\n def v2(v3):\n if v3.group(2) == 's':\n return f\"``{v3.group(1)}``'s\"\n elif v3.group(2):\n return f'``{v3.group(1)}`` {v3.group(2)}'\n else:\... | [] | [] | 6 | import builtins
from dataclasses import dataclass
from enum import Enum
import itertools
import json
import logging
import operator
import os
from pathlib import Path
import re
from textwrap import dedent, indent as tw_indent
import typing
import inflection # type: ignore
log_level = getattr(logging, os.environ.get(... | null |
v6 | [
"typing.Optional[str]"
] | str | def v6(v7: typing.Optional[str]) -> str:
if not v7:
return ''
v7 = v0(v7)
return dedent("r'''\n{}\n'''").format(v7) | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n\n def v2(v3):\n if v3.group(2) == 's':\n return f\"``{v3.group(1)}``'s\"\n elif v3.group(2):\n return f'``{v3.group(1)}`` {v3.group(2)}'\n else:\... | [
"textwrap"
] | [
"from textwrap import dedent, indent as tw_indent"
] | 5 | import builtins
from dataclasses import dataclass
from enum import Enum
import itertools
import json
import logging
import operator
import os
from pathlib import Path
import re
from textwrap import dedent, indent as tw_indent
import typing
import inflection # type: ignore
log_level = getattr(logging, os.environ.get(... | null |
v4 | [
"str"
] | str | def v4(v5: str) -> str:
if '.' in v5:
(v6, v7) = v5.split('.')
v5 = '{}.{}'.format(v2(v6), v7)
return f'{v5}' | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "bool",
"code": "def v0(v1: str) -> bool:\n try:\n getattr(builtins, v1)\n return True\n except AttributeError:\n return False",
"dependencies": []
},
{
"name": "v2",
"input_types": [
... | [] | [] | 5 | import builtins
from dataclasses import dataclass
from enum import Enum
import itertools
import json
import logging
import operator
import os
from pathlib import Path
import re
from textwrap import dedent, indent as tw_indent
import typing
import inflection # type: ignore
log_level = getattr(logging, os.environ.get(... | null |
v10 | [] | str | def v10(self) -> str:
if self.description:
v11 = v4(self.description)
v11 += '\n'
else:
v11 = ''
v11 += f'{self.py_name}: {self.py_annotation}'
return v11 | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "str",
"code": "def v0(v1: str) -> str:\n\n def v2(v3):\n if v3.group(2) == 's':\n return f\"``{v3.group(1)}``'s\"\n elif v3.group(2):\n return f'``{v3.group(1)}`` {v3.group(2)}'\n else:\... | [] | [] | 8 | import builtins
from dataclasses import dataclass
from enum import Enum
import itertools
import json
import logging
import operator
import os
from pathlib import Path
import re
from textwrap import dedent, indent as tw_indent
import typing
import inflection # type: ignore
log_level = getattr(logging, os.environ.get(... | null |
v0 | [
"str",
"bool"
] | str | def v0(self, v1: str, v2: bool=True) -> str:
v3 = 'self.' if v2 else ''
v4 = f"{v1}['{self.name}'] = "
if self.items:
if self.items.ref:
v4 += f'[i.to_json() for i in {v3}{self.py_name}]'
else:
v4 += f'[i for i in {v3}{self.py_name}]'
elif self.ref:
v4 += ... | [] | [
"textwrap"
] | [
"from textwrap import dedent, indent as tw_indent"
] | 17 | import builtins
from dataclasses import dataclass
from enum import Enum
import itertools
import json
import logging
import operator
import os
from pathlib import Path
import re
from textwrap import dedent, indent as tw_indent
import typing
import inflection # type: ignore
log_level = getattr(logging, os.environ.get(... | null |
v0 | [
"Any"
] | str | def v0(self, v1) -> str:
v2 = super().generate_from_json(v1)
return f'{self.py_name}={v2}' | [] | [] | [] | 3 | import builtins
from dataclasses import dataclass
from enum import Enum
import itertools
import json
import logging
import operator
import os
from pathlib import Path
import re
from textwrap import dedent, indent as tw_indent
import typing
import inflection # type: ignore
log_level = getattr(logging, os.environ.get(... | null |
v15 | [] | str | def v15(self) -> str:
v16 = dedent(' def to_json(self) -> str:\n return self.value')
v17 = dedent(f' @classmethod\n def from_json(cls, json: str) -> {self.id}:\n return cls(json)')
v18 = f'class {self.id}(enum.Enum):\n'
v19 = v0(self.descrip... | [
{
"name": "v0",
"input_types": [
"typing.Optional[str]"
],
"output_type": "str",
"code": "def v0(v1: typing.Optional[str]) -> str:\n if not v1:\n return ''\n v1 = escape_backticks(v1)\n return dedent(\"'''\\n{}\\n'''\").format(v1)",
"dependencies": [
"v2",
"... | [
"textwrap"
] | [
"from textwrap import dedent, indent as tw_indent"
] | 14 | import builtins
from dataclasses import dataclass
from enum import Enum
import itertools
import json
import logging
import operator
import os
from pathlib import Path
import re
from textwrap import dedent, indent as tw_indent
import typing
import inflection # type: ignore
log_level = getattr(logging, os.environ.get(... | null |
v11 | [] | str | def v11(self) -> str:
v12 = dedent(f' @dataclass\n class {self.id}:\n')
v13 = v0(self.description)
if v13:
v12 += v6(v13, 4) + '\n'
v14 = list(self.properties)
v14.sort(key=operator.attrgetter('optional'))
v12 += '\n\n'.join((v6(p.generate_decl(), 4) for v15 in v14)... | [
{
"name": "v0",
"input_types": [
"typing.Optional[str]"
],
"output_type": "str",
"code": "def v0(v1: typing.Optional[str]) -> str:\n if not v1:\n return ''\n v1 = escape_backticks(v1)\n return dedent(\"'''\\n{}\\n'''\").format(v1)",
"dependencies": [
"v2",
"... | [
"operator",
"textwrap"
] | [
"import operator",
"from textwrap import dedent, indent as tw_indent"
] | 25 | import builtins
from dataclasses import dataclass
from enum import Enum
import itertools
import json
import logging
import operator
import os
from pathlib import Path
import re
from textwrap import dedent, indent as tw_indent
import typing
import inflection # type: ignore
log_level = getattr(logging, os.environ.get(... | null |
v0 | [] | str | def v0(self) -> str:
v1 = self.domain + '\n'
v1 += '=' * len(self.domain) + '\n\n'
if self.description:
v1 += f'{self.description}\n\n'
if self.experimental:
v1 += '*This CDP domain is experimental.*\n\n'
v1 += f'.. module:: cdp.{self.module}\n\n'
v1 += '* Types_\n* Commands_\n* ... | [] | [
"operator",
"textwrap"
] | [
"import operator",
"from textwrap import dedent, indent as tw_indent"
] | 37 | import builtins
from dataclasses import dataclass
from enum import Enum
import itertools
import json
import logging
import operator
import os
from pathlib import Path
import re
from textwrap import dedent, indent as tw_indent
import typing
import inflection # type: ignore
log_level = getattr(logging, os.environ.get(... | null |
v0 | [
"str"
] | Any | def v0(v1: str):
v2 = open(v1).read().split('\n')[:-1]
v3 = [[item.strip() for v4 in line.split(',')] for v5 in v2]
return v3 | [] | [] | [] | 4 | #! /usr/bin/env python3
def read_paths(filename: str):
lines = open(filename).read().split("\n")[:-1]
paths = [[item.strip() for item in line.split(",")] for line in lines]
return paths
DIR = {
"L": (-1, 0),
"R": (1, 0),
"U": (0, 1),
"D": (0, -1)
}
def get_points(path: list):
points = []
x, y = 0, 0
fo... | null |
v3 | [
"Any",
"Any"
] | int | def v3(v4, v5) -> int:
v6 = 'https://github.com/mindblockchain/mindblockchain'
if v5.remove_dir:
if Path(v4).is_dir():
shutil.rmtree(v4)
if not Path(v4).is_dir():
subprocess.run(['git', 'fetch', v6, '--tags'])
v7 = subprocess.check_output(['git', 'tag', '-l', v4])
... | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "None",
"code": "@contextlib.contextmanager\ndef v0(v1) -> None:\n v2 = os.getcwd()\n os.chdir(v1)\n try:\n yield\n finally:\n os.chdir(v2)",
"dependencies": []
}
] | [
"os",
"pathlib",
"shutil",
"subprocess"
] | [
"import os",
"from pathlib import Path",
"import shutil",
"import subprocess"
] | 36 | #!/usr/bin/env python3
#
# Copyright (c) 2018-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Download or build previous releases.
# Needs curl and tar to download a release, or the build depend... | null |
v0 | [
"Any"
] | int | def v0(v1) -> int:
v1.host = os.environ.get('HOST', subprocess.check_output('./depends/config.guess').decode())
if v1.download_binary:
v2 = {'aarch64-*-linux*': 'aarch64-linux-gnu', 'x86_64-*-linux*': 'x86_64-linux-gnu', 'x86_64-apple-darwin*': 'x86_64-apple-darwin', 'aarch64-apple-darwin*': 'aarch64-ap... | [] | [
"fnmatch",
"os",
"subprocess"
] | [
"from fnmatch import fnmatch",
"import os",
"import subprocess"
] | 12 | #!/usr/bin/env python3
#
# Copyright (c) 2018-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Download or build previous releases.
# Needs curl and tar to download a release, or the build depend... | null |
v35 | [
"Any"
] | int | def v35(v36) -> int:
Path(v36.target_dir).mkdir(exist_ok=True, parents=True)
print('Releases directory: {}'.format(v36.target_dir))
v0(v36.tags[0], v36)
return
v37 = v12(v36)
if v37:
return v37
if v36.download_binary:
with v32(v36.target_dir):
for v38 in v36.tags:... | [
{
"name": "v0",
"input_types": [
"Any",
"Any"
],
"output_type": "int",
"code": "def v0(v1, v2) -> int:\n v3 = 'https://github.com/bitcoin/bitcoin'\n if v2.remove_dir:\n if Path(v1).is_dir():\n shutil.rmtree(v1)\n if not Path(v1).is_dir():\n subproces... | [
"fnmatch",
"hashlib",
"os",
"pathlib",
"re",
"shutil",
"subprocess"
] | [
"from fnmatch import fnmatch",
"import os",
"from pathlib import Path",
"import re",
"import shutil",
"import subprocess",
"import hashlib"
] | 23 | #!/usr/bin/env python3
#
# Copyright (c) 2018-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Download or build previous releases.
# Needs curl and tar to download a release, or the build depend... | null |
v0 | [] | Optional[pd.DataFrame] | def v0(self) -> Optional[pd.DataFrame]:
if self.only_load_factor:
return self.factor_df
return self.data_df | [] | [] | [] | 4 | # -*- coding: utf-8 -*-
import enum
import json
import logging
import time
from typing import List, Union, Optional, Type
import pandas as pd
from sqlalchemy import Column, String, Text
from sqlalchemy.orm import declarative_base
from zvt.contract import IntervalLevel, TradableEntity
from zvt.contract import Mixin
fr... | null |
v0 | [
"torch.Tensor",
"torch.Tensor"
] | torch.Tensor | def v0(self, v1: torch.Tensor, v2: torch.Tensor) -> torch.Tensor:
v3 = v1.size()
v4 = v2.size()
assert v3[:-1] == v4[:-1], 'batch size of left and right inputs mis-match: (%s, %s)' % (v3[:-1], v4[:-1])
v5 = int(np.prod(v3[:-1]))
v1 = v1.contiguous().view(v5, self.left_features)
v2 = v2.contiguou... | [] | [
"numpy",
"torch"
] | [
"import numpy as np",
"import torch",
"import torch.nn as nn",
"import torch.nn.functional as F",
"from torch.nn.parameter import Parameter",
"from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence"
] | 10 | import argparse
import logging
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from overrides import overrides
from torch.nn.parameter import Parameter
from torch.nn.utils.rnn impor... | null |
v3 | [
"List[v0]",
"List[v0]"
] | None | def v3(self, v4: List[v0], v5: List[v0]) -> None:
(v6, v7, v8, v9) = self._flatten_prediction_and_labels(v4, v5)
v10 = self.output_dir.joinpath('transformers/pred')
if not os.path.exists(v10):
os.makedirs(v10, exist_ok=True)
with open(os.path.join(v10, f'pred-{self.step_count}.json'), 'w', encod... | [] | [
"os"
] | [
"import os"
] | 8 | import argparse
import logging
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from overrides import overrides
from torch.nn.parameter import Parameter
from torch.nn.utils.rnn impor... | [
"class v0:\n\n def __init__(self, v1: torch.Tensor, v2: torch.Tensor) -> None:\n self.heads = v1\n self.types = v2"
] |
v3 | [
"List[v0]",
"List[v0]"
] | Tuple[List, List, List, List] | def v3(self, v4: List[v0], v5: List[v0]) -> Tuple[List, List, List, List]:
v6 = list()
v7 = list()
v8 = list()
v9 = list()
for (v10, v11) in zip(v4, v5):
v6 += v10.heads.cpu().flatten().tolist()
v7 += v11.heads.cpu().flatten().tolist()
v8 += v10.types.cpu().flatten().tolist()... | [] | [
"numpy"
] | [
"import numpy as np"
] | 21 | import argparse
import logging
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from overrides import overrides
from torch.nn.parameter import Parameter
from torch.nn.utils.rnn impor... | [
"class v0:\n\n def __init__(self, v1: torch.Tensor, v2: torch.Tensor) -> None:\n self.heads = v1\n self.types = v2"
] |
v0 | [
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"int"
] | Tuple[torch.Tensor, List] | def v0(self, v1: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, v4: int) -> Tuple[torch.Tensor, List]:
(v5, v6, v7) = v1.size()
v8 = torch.zeros(v5, v4 + 1, v7 * 2).to(v1.device)
v9 = list()
for v10 in range(v5):
v11 = [i for (v12, v13) in enumerate(v2[v10]) if v13 == 1]
v14 = [v12 fo... | [] | [
"torch"
] | [
"import torch",
"import torch.nn as nn",
"import torch.nn.functional as F",
"from torch.nn.parameter import Parameter",
"from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence"
] | 13 | import argparse
import logging
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from overrides import overrides
from torch.nn.parameter import Parameter
from torch.nn.utils.rnn impor... | null |
v0 | [
"torch.Tensor"
] | torch.Tensor | def v0(self, v1: torch.Tensor) -> torch.Tensor:
(v1, v2) = v1
v2 = v2[-2:]
(v3, v4, v5) = v2.size()
v2 = v2.transpose(0, 1).contiguous()
v2 = v2.view(v4, 1, 2 * v5).transpose(0, 1)
v2 = self.hx_dense(v2)
if self.decoder.num_layers > 1:
v2 = torch.cat([v2, torch.autograd.Variable(v2.d... | [] | [
"torch"
] | [
"import torch",
"import torch.nn as nn",
"import torch.nn.functional as F",
"from torch.nn.parameter import Parameter",
"from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence"
] | 12 | import argparse
import logging
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from overrides import overrides
from torch.nn.parameter import Parameter
from torch.nn.utils.rnn impor... | null |
v0 | [] | None | def v0(self) -> None:
nn.init.xavier_uniform_(self.W_l)
nn.init.xavier_uniform_(self.W_r)
nn.init.constant_(self.bias, 0.0)
nn.init.xavier_uniform_(self.U) | [] | [
"torch"
] | [
"import torch",
"import torch.nn as nn",
"import torch.nn.functional as F",
"from torch.nn.parameter import Parameter",
"from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence"
] | 5 | import argparse
import logging
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from overrides import overrides
from torch.nn.parameter import Parameter
from torch.nn.utils.rnn impor... | null |
v0 | [
"'Net'"
] | Any | def v0(self, v1: 'Net'):
if v1.mask_size <= self.mask_size:
return 0
return self.net == v1.net & self.mask | [] | [] | [] | 4 |
BIG_MASK = (1 << 32) - 1
def getMaskByMaskSize(mask_size):
return BIG_MASK ^ ((1 << (32 - mask_size)) - 1)
def getIpVolumeByMaskSize(mask_size):
return 1 << (32 - mask_size)
class Net:
__slots__ = ['mask_size', 'net', 'mask', 'ip_volume']
def __init__(self, net: int, mask_size: int):
self.m... | null |
v0 | [
"list"
] | Any | def v0(self, v1: list):
self.updated = True
v1.reverse()
for v2 in v1:
self.table.insert_new_row(v2) | [] | [] | [] | 5 | import csv
import subprocess
from datetime import datetime, timedelta
from copy import copy
import numpy as np
import pyqtgraph as pg
from vnpy.trader.constant import Interval, Direction, Exchange
from vnpy.trader.engine import MainEngine
from vnpy.trader.ui import QtCore, QtWidgets, QtGui
from vnpy.trader.ui.widget ... | null |
v0 | [
"list"
] | Any | def v0(self, v1: list):
self.updated = True
self.chart.update_history(v1)
for (v2, v3) in enumerate(v1):
self.ix_bar_map[v2] = v3
self.dt_ix_map[v3.datetime] = v2
if not self.high_price:
self.high_price = v3.high_price
self.low_price = v3.low_price
els... | [] | [] | [] | 13 | import csv
import subprocess
from datetime import datetime, timedelta
from copy import copy
import numpy as np
import pyqtgraph as pg
from vnpy.trader.constant import Interval, Direction, Exchange
from vnpy.trader.engine import MainEngine
from vnpy.trader.ui import QtCore, QtWidgets, QtGui
from vnpy.trader.ui.widget ... | null |
v0 | [] | str or None | def v0(self) -> str or None:
v1 = self.view.selectedIndexes()
if len(v1) > 0:
return self.view.selectedIndexes()[1].data()
else:
return None | [] | [] | [] | 6 | from PySide2 import QtCore, QtWidgets
from PySide2.QtGui import QStandardItemModel, QStandardItem
from conanguide.api.conan_api import ConanApi
class ConanRecipeController:
"""
Controller class to control view and model of the conan package
"""
def __init__(self, view: QtWidgets.QTreeView, conan_api... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
self.conan_api.remove(v1, force=True)
self.filter('')
self.model.removeRow(self.view.currentIndex().row()) | [] | [] | [] | 4 | from PySide2 import QtCore, QtWidgets
from PySide2.QtGui import QStandardItemModel, QStandardItem
from conanguide.api.conan_api import ConanApi
class ConanRecipeController:
"""
Controller class to control view and model of the conan package
"""
def __init__(self, view: QtWidgets.QTreeView, conan_api... | null |
v0 | [] | Optional[str] | def v0(self) -> Optional[str]:
v1 = self._j_rocks_db_state_backend.getRocksDBOptions()
if v1 is not None:
return v1.getClass().getName()
else:
return None | [] | [] | [] | 6 | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... | null |
v9 | [
"Dict[str, str]"
] | Dict | def v9(v10: Dict[str, str]) -> Dict:
v11 = {}
v0(v10)
if 'fill-opacity' in v10:
v11['fill_opacity'] = float(v10['fill-opacity'])
if 'stroke-opacity' in v10:
v11['stroke_opacity'] = float(v10['stroke-opacity'])
if 'fill' in v10:
if v10['fill'] == 'none':
v11['fill_... | [
{
"name": "v0",
"input_types": [
"Dict"
],
"output_type": "None",
"code": "def v0(v1: Dict) -> None:\n for v2 in SVG_DEFAULT_ATTRIBUTES:\n if v2 not in v1:\n v1[v2] = SVG_DEFAULT_ATTRIBUTES[v2]",
"dependencies": []
},
{
"name": "v3",
"input_types": [
... | [] | [] | 20 | """Utility functions for parsing SVG styles."""
__all__ = ["cascade_element_style", "parse_style", "parse_color_string"]
from typing import Dict, List
from xml.dom.minidom import Element as MinidomElement
from colour import web2hex
from ...utils.color import rgb_to_hex
CASCADING_STYLING_ATTRIBUTES: List[str] = [
... | null |
v4 | [
"'DirectedGraph[Optional[str]]'",
"int"
] | Dict[Optional[str], int] | def v4(v5: 'DirectedGraph[Optional[str]]', v6: int) -> Dict[Optional[str], int]:
v7: Set[Optional[str]] = set()
v8: Dict[Optional[str], int] = {}
def v9(v10: Optional[str]) -> None:
if v10 in v7:
return
v7.add(v10)
for v11 in v5.iter_children(v10):
v9(v11)
... | [
{
"name": "v0",
"input_types": [
"Optional[str]"
],
"output_type": "None",
"code": "def v0(v1: Optional[str]) -> None:\n if v1 in path:\n return\n path.add(v1)\n for v2 in graph.iter_children(v1):\n v0(v2)\n path.remove(v1)\n v3 = weights.get(v1, 0)\n weight... | [] | [] | 17 | import functools
import logging
import os
from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, cast
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.packaging.version import parse as parse_version
from pip._vendor.resolvelib import BaseReporter, ResolutionImpossible
from pip._v... | null |
v0 | [] | dict | def v0(self) -> dict:
v1 = self.saved_layers
self.saved_layers = None
v2 = self.weights
if self.weights is not None:
v3 = []
for v4 in self.weights:
v3.append(v4.tolist())
self.weights = v3
v5 = self._serialize()
self.saved_layers = v1
self.weights = v2
... | [] | [] | [] | 13 | """Base class for genome nodes"""
import copy
import itertools
from abc import ABC, abstractmethod
from keras.engine.keras_tensor import KerasTensor
from networkx import MultiDiGraph
class TensorNode(ABC):
"""''Base class for nodes in a tensor network"""
id_iter = itertools.count()
def __init__(self):
... | null |
v0 | [
"bool"
] | Any | def v0(self, v1: bool):
self.has_variable_length_input = v1
if v1:
self.variable_output_size = True
else:
self.variable_output_size = False | [] | [] | [] | 6 | """Base class for genome nodes"""
import copy
import itertools
from abc import ABC, abstractmethod
from keras.engine.keras_tensor import KerasTensor
from networkx import MultiDiGraph
class TensorNode(ABC):
"""''Base class for nodes in a tensor network"""
id_iter = itertools.count()
def __init__(self):
... | null |
v0 | [] | str | def v0(self) -> str:
v1 = str(type(self)).split('.')[-1]
v1 = v1.split("'")[0]
return v1 | [] | [] | [] | 4 | """Base class for genome nodes"""
import copy
import itertools
from abc import ABC, abstractmethod
from keras.engine.keras_tensor import KerasTensor
from networkx import MultiDiGraph
class TensorNode(ABC):
"""''Base class for nodes in a tensor network"""
id_iter = itertools.count()
def __init__(self):
... | null |
v0 | [
"Any"
] | int | def v0(v1) -> int:
if not isinstance(v1, str):
try:
v1 = json.dumps(v1)
except json.JSONDecodeError:
v1 = str(v1)
return len(v1.encode('utf-8')) | [] | [
"json"
] | [
"import json"
] | 7 | # Copyright (C) 2020 by eHealth Africa : http://www.eHealthAfrica.org
#
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with
# the License. Y... | null |
v0 | [
"Any",
"Any"
] | List[Tuple[str, Any]] | def v0(self, v1, v2) -> List[Tuple[str, Any]]:
v3 = self._filter_good_objects(v1, v2)
for (v4, v5) in v2:
self._mark_copied(v1, v4)
return v3 | [] | [] | [] | 5 | # Copyright (C) 2020 by eHealth Africa : http://www.eHealthAfrica.org
#
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with
# the License. Y... | null |
v0 | [] | dict | def v0(self) -> dict:
v1 = {'in': []}
for v2 in self.usertags or []:
v1['in'].append(v2)
return v1 | [] | [] | [] | 5 | from . import common as cmmn
import uuid
import random
import time
# pyre-ignore[21]
import imagesize
import logging
import pprint
from pathlib import Path
from dataclasses import dataclass, field
from typing import Optional, List, Union, Tuple
from ..helpers import HelperMixin
from instauto.api.structs import PostLo... | null |
v23 | [
"DataLoader",
"List[Dict[str, Any]]"
] | DataLoader | def v23(v24: DataLoader, v25: List[Dict[str, Any]]) -> DataLoader:
v26 = v21(v24)
if isinstance(v26, Sampler):
v25 = {k: v for (v27, v28) in v25.items() if v27 not in ('num_workers', 'previous_worker')}
v26.load_state_dict(v25)
return v24 | [
{
"name": "v21",
"input_types": [
"DataLoader"
],
"output_type": "Optional[v0]",
"code": "def v21(v22: DataLoader) -> Optional[v0]:\n if isinstance(v22.sampler, v0):\n return v22.sampler\n if isinstance(v22.batch_sampler, v0):\n return v22.batch_sampler",
"dependenc... | [
"torch"
] | [
"from torch.utils.data import Dataset, get_worker_info, Sampler",
"from torch.utils.data.dataloader import _MultiProcessingDataLoaderIter, DataLoader, IterableDataset"
] | 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... | [
"class v0(Sampler):\n\n def __init__(self, v1: Union[Sampler, Generator], v2: Optional[str]=None) -> None:\n super().__init__(data_source=None)\n self._sampler = v1\n self.restarting: bool = False\n self._current_iteration = 0\n self._dataloader_batch_size: Optional[int] = None... |
v0 | [
"Iterator"
] | Dict[str, Optional[int]] | def v0(v1: Iterator) -> Dict[str, Optional[int]]:
v2 = getattr(v1, '_num_workers', 0)
if isinstance(v1, _MultiProcessingDataLoaderIter):
v3 = next(v1._worker_queue_idx_cycle) % v2
v4 = (v3 - 1) % v2
while next(v1._worker_queue_idx_cycle) != v4:
pass
else:
v4 = Non... | [] | [
"torch"
] | [
"from torch.utils.data import Dataset, get_worker_info, Sampler",
"from torch.utils.data.dataloader import _MultiProcessingDataLoaderIter, DataLoader, IterableDataset"
] | 10 | # 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 | [
"Optional[int]"
] | int | def v0(self, v1: Optional[int]=None) -> int:
if v1 is not None:
v2 = v1
else:
v2 = self._current_iteration
if self._dataloader_batch_size and v1 is not None:
v2 *= self._dataloader_batch_size
return v2 | [] | [] | [] | 8 | # 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 |
v10 | [
"Any",
"Path",
"int",
"int",
"int",
"bool"
] | bytes | def v10(v11, *, v12: Path=CACHE_DIR, v13: int=None, v14: int=None, v15: int=None, v16: bool=False, **v17) -> bytes:
if not v12.exists():
Path.mkdir(v12)
v18 = dict(cache_dir=v12, height=v13, width=v14, zoom=v15, disable_javascript=v16)
v18.update(v17)
v19 = v0(**v18)
v20 = v6(*v19, input=v11... | [
{
"name": "v0",
"input_types": [],
"output_type": "Any",
"code": "def v0(**v1):\n v2 = []\n for (v3, v4) in v1.items():\n if v4 in {None, False}:\n continue\n v5 = '--' + v3.replace('_', '-')\n if v4 is True:\n v2.append(v5)\n else:\n ... | [
"pathlib",
"subprocess"
] | [
"import subprocess",
"from pathlib import Path"
] | 11 | import os
import subprocess
import tempfile
from pathlib import Path
from utils.log import log
WK_PATH = os.environ.get('WKHTMLTOIMAGE', str(
Path(__file__).parent.resolve() / 'bin' / 'wkhtmltoimage'))
CACHE_DIR = Path(tempfile.gettempdir()) / 'saiki_cache'
def _execute_wk(*args, input=None):
"""
Generat... | null |
v0 | [
"str"
] | Any | def v0(v1: str):
if not v1:
v1 = '0 0'
(v2, v3) = v1.split()
return (int(v2, 0), int(v3, 0)) | [] | [] | [] | 5 | import ast
import re
import struct
import warnings
from .lint import lint
from .parse import parse_file
class Device(dict):
def __init__(self, cfg: dict, env: dict = None):
self.cfg = cfg
self.env = env if env is not None else {}
if (
"NODEID" not in self.env
and ... | null |
v0 | [
"dict"
] | Any | def v0(self, v1: dict={}):
v2 = self.data_type.parse_value(self.value)
if self.data_type.is_basic():
v3 = 0
if self.variable is not None:
if self.variable.upper() in v1:
v3 = v1[self.variable.upper()]
else:
raise KeyError('$' + self.variabl... | [] | [] | [] | 11 | import ast
import re
import struct
import warnings
from .lint import lint
from .parse import parse_file
class Device(dict):
def __init__(self, cfg: dict, env: dict = None):
self.cfg = cfg
self.env = env if env is not None else {}
if (
"NODEID" not in self.env
and ... | null |
v0 | [
"int"
] | int | def v0(self, v1: int) -> int:
v2 = [1] * v1
for v3 in range(2, v1 + 1):
for v4 in range(1, v3 // 2 + 1):
v2[v3 - 1] = max(v2[v3 - 1], max(v2[v4 - 1], v4) * max(v2[v3 - v4 - 1], v3 - v4))
return v2[-1] | [] | [] | [] | 6 | class Solution:
def integerBreak(self, n: int) -> int:
dp = [1] * n
for total in range(2, n + 1):
for i in range(1, total//2 + 1):
dp[total - 1] = max(dp[total - 1], max(dp[i - 1], i) * max(dp[total - i - 1], total - i))
return dp[-1]
'''
class Solution {
pri... | null |
v0 | [
"np.ndarray",
"np.ndarray",
"np.ndarray",
"np.ndarray"
] | list | def v0(v1: np.ndarray, v2: np.ndarray, v3: np.ndarray, v4: np.ndarray) -> list:
v5 = v1
v6 = [v2[0]]
v7 = [v3[0] / v6[0]]
for v8 in range(1, len(v2) - 1):
v6.append(v2[v8] - v5[v8 - 1] * v7[v8 - 1])
v7.append(v3[v8] / v6[v8])
v6.append(v2[-1] - v5[-1] * v7[-2])
v9 = [v4[0] / v6[0... | [] | [] | [] | 16 | from ._tools import *
class ElementaryTransformation:
"""
In order to use conveniently, I putted three basic elementary transformations in this class and make them
as static method, that represent I can use them without instantiation.
"""
@staticmethod
def multiple(num: int, array_: np.ndarra... | null |
v3 | [
"Any",
"bool"
] | Any | def v3(v4, v5: bool=False):
v6 = v4('./NWPU VHR-10 dataset', v0(train=False))
v7 = v4('./NWPU VHR-10 dataset', v0(train=False))
v8 = v4('./NWPU VHR-10 dataset', v0(train=False))
torch.manual_seed(1)
v9 = torch.randperm(len(v6)).tolist()
v10 = 0.2
v11 = 0.2
v12 = int(len(v6) * v10)
v1... | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "Any",
"code": "def v0(v1):\n v2 = []\n v2.append(T.ToTensor())\n if v1:\n v2.append(T.RandomHorizontalFlip(0.5))\n return T.Compose(v2)",
"dependencies": []
}
] | [
"torch"
] | [
"import torch"
] | 17 | import os
import numpy as np
import torch
from PIL import Image
import torch_utils.transforms as T
def train_test_split(dataset_class, validation_flag: bool = False):
dataset = dataset_class('./NWPU VHR-10 dataset', get_transform(train=False))
dataset_test = dataset_class('./NWPU VHR-10 dataset', get_transfor... | null |
v0 | [
"str"
] | Any | async def v0(self, v1: str):
v2 = await self.bot.get_cog('Core')._invite_url()
return v1.replace('{invite}', f'{v2}') | [] | [] | [] | 3 | """
MIT License
Copyright (c) 2021 Obi-Wan3
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, dist... | null |
v0 | [
"int",
"bool"
] | Any | async def v0(self, v1: int, v2: bool=True):
v3 = await self.config.auto_leave()
if not v3['toggle']:
return
v4 = (datetime.now() + timedelta(hours=v3['delay'])).timestamp()
await self.config.user_from_id(v1).end_timestamp.set(v4)
if v2:
await self._expire_timer(v1, v4) | [] | [
"datetime"
] | [
"from datetime import datetime, timedelta"
] | 8 | """
MIT License
Copyright (c) 2021 Obi-Wan3
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, dist... | null |
v0 | [
"int",
"float"
] | Any | async def v0(self, v1: int, v2: float):
v3 = (datetime.fromtimestamp(v2) - datetime.now()).total_seconds()
if v3 > 0:
await asyncio.sleep(v3)
await self._expire_leave(v1) | [] | [
"asyncio",
"datetime"
] | [
"import asyncio",
"from datetime import datetime, timedelta"
] | 5 | """
MIT License
Copyright (c) 2021 Obi-Wan3
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, dist... | null |
v0 | [
"int"
] | Any | async def v0(self, v1: int):
v2 = await self.config.user_from_id(v1).all()
v3 = await self.config.main_servers()
v4 = await self.config.allowed()
if v2['end_timestamp'] and (not v2['supporting_in']):
if datetime.fromtimestamp(v2['end_timestamp']) <= datetime.now():
for v5 in v2['serv... | [] | [
"datetime"
] | [
"from datetime import datetime, timedelta"
] | 13 | """
MIT License
Copyright (c) 2021 Obi-Wan3
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, dist... | null |
v0 | [
"float"
] | Any | def v0(self, v1: float):
self.large_scheduled_vehicle_repository.set_transportation_buffer(v1)
self.logger.info(f'Use transportation buffer of {v1} for reporting statistics.') | [] | [] | [] | 3 | import logging
import statistics
from typing import List
from conflowgen.domain_models.data_types.mode_of_transport import ModeOfTransport
from conflowgen.domain_models.repositories.large_scheduled_vehicle_repository import LargeScheduledVehicleRepository
from conflowgen.domain_models.vehicle import AbstractLargeSched... | null |
v0 | [
"str"
] | int | def v0(self, v1: str) -> int:
if len(v1) <= 1:
return 0
v2 = len(v1)
v3 = 0
v4 = [0] * v2
for v5 in range(v2 - 2, -1, -1):
if v1[v5] == '(':
v6 = v5 + v4[v5 + 1] + 1
if v6 < v2 and v1[v6] == ')':
v4[v5] = v4[v5 + 1] + 2
if v6 + ... | [] | [] | [] | 14 | # https://leetcode.com/problems/longest-valid-parentheses/
# Given a string containing just the characters '(' and ')', find the length of
# the longest valid (well-formed) parentheses substring.
################################################################################
# dp[i] = longest valid of s[i:n] starti... | null |
v29 | [
"'CamerasBase'",
"'CamerasBase'",
"bool",
"str",
"float"
] | 'CamerasBase' | def v29(v30: 'CamerasBase', v31: 'CamerasBase', v32: bool=True, v33: str='extrinsics', v34: float=1e-09) -> 'CamerasBase':
if v30.R.shape[0] != v31.R.shape[0]:
raise ValueError('cameras_src and cameras_tgt have to contain the same number of cameras!')
if v33 == 'centers':
v35 = v0
elif v33 =... | [
{
"name": "v0",
"input_types": [
"'CamerasBase'",
"'CamerasBase'",
"bool",
"float"
],
"output_type": "Any",
"code": "def v0(v1: 'CamerasBase', v2: 'CamerasBase', v3: bool=True, v4: float=1e-09):\n v5 = v1.get_camera_center()\n v6 = v2.get_camera_center()\n v7 = o... | [
"torch"
] | [
"import torch"
] | 14 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
from typing import TYPE_CHECKING
import torch
from .. import ops
if TYPE_CHECKING:
from pytorch3d.renderer.cameras import CamerasBase
def corresponding_cameras_alignment(
cameras_src: "CamerasBase",
cameras_tgt: "CamerasBase",
... | null |
v0 | [
"'CamerasBase'",
"'CamerasBase'",
"bool",
"float"
] | Any | def v0(v1: 'CamerasBase', v2: 'CamerasBase', v3: bool=True, v4: float=1e-09):
v5 = torch.bmm(v1.R, v2.R.transpose(2, 1)).mean(0)
(v6, v7, v8) = torch.svd(v5)
v9 = v8 @ v6.t()
"\n The translation + scale `T_A` and `s_A` is computed by finding\n a translation and scaling that aligns two tensors `A, ... | [] | [
"torch"
] | [
"import torch"
] | 17 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
from typing import TYPE_CHECKING
import torch
from .. import ops
if TYPE_CHECKING:
from pytorch3d.renderer.cameras import CamerasBase
def corresponding_cameras_alignment(
cameras_src: "CamerasBase",
cameras_tgt: "CamerasBase",
... | null |
v0 | [] | str | def v0(self) -> str:
v1 = self.connections.get_if_exists()
if v1 is None or v1.name is None:
return '<None>'
return v1.name | [] | [] | [] | 5 | import abc
from concurrent.futures import as_completed, Future
from contextlib import contextmanager
from datetime import datetime
from itertools import chain
from typing import (
Optional, Tuple, Callable, Iterable, Type, Dict, Any, List, Mapping,
Iterator, Union, Set
)
import agate
import pytz
from dbt.exce... | null |
v0 | [
"str",
"str",
"str",
"Optional[str]"
] | str | def v0(self, v1: str, v2: str, v3: str, v4: Optional[str]=None) -> str:
v3 = f'alter table {v1} update {v2} = {v3}'
if v4 is not None:
v3 += f' where {v4}'
return v3 | [] | [] | [] | 5 | from typing import Optional, List, Union, Set, Callable
import io
import csv
import agate
import dbt.exceptions
from dataclasses import dataclass
from concurrent.futures import Future
from dbt.contracts.relation import RelationType
from dbt.contracts.graph.manifest import Manifest
from dbt.clients.agate_helper import... | null |
v0 | [
"dict",
"dict"
] | dict | def v0(v1: dict, v2: dict) -> dict:
v3: dict = v1.copy()
v3.update(v2)
return v3 | [] | [] | [] | 4 | """
Utils class with useful helper functions
utils: https://www.quora.com/What-do-utils-files-tend-to-be-in-computer-programming-documentation
"""
import json
import subprocess
import time
import math
from datetime import datetime
from pprint import pprint
import dill
import networkx as nx
import numpy as np
import ... | null |
v0 | [
"int",
"int"
] | str | def v0(self, v1: int, v2: int) -> str:
v3 = min(v1, v2)
v4 = max(v1, v2)
return self.format_mu.format(v3, v4) | [] | [] | [] | 4 | # Copyright 2019 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | null |
v0 | [
"Any"
] | None | def v0(self, v1) -> None:
self.result.msg = f'number of sampling points changed to {v1}'
self.result.value = v1 | [] | [] | [] | 3 | from dataclasses import dataclass
from osa import factory
from handlers.file import get_valid_setting, set_setting
from handlers.result import BaseResult
@dataclass
class ChangeSamplingPoints:
"""
Change the Sampling Points in the settings.json file {51|101|251|501|1001|2001|5001|10001|20001|50001}
"""
... | null |
v0 | [
"Any"
] | None | def v0(self, v1) -> None:
self.result.msg = f"number of sampling points invalid '{v1}'"
self.result.value = v1 | [] | [] | [] | 3 | from dataclasses import dataclass
from osa import factory
from handlers.file import get_valid_setting, set_setting
from handlers.result import BaseResult
@dataclass
class ChangeSamplingPoints:
"""
Change the Sampling Points in the settings.json file {51|101|251|501|1001|2001|5001|10001|20001|50001}
"""
... | null |
v0 | [
"list",
"dict"
] | Any | def v0(v1: list, v2: dict):
v1 = [cell.value.lower().strip() for v3 in v1]
return dict(((v, v1.index(k)) for (v4, v5) in v2.items())) | [] | [] | [] | 3 | """Landsbankinn of Iceland, Personal CSV file export
Sample Row/Headers are:
Dagsetning Vaxtadagur Tilvísun Skýring Texti Upphæð Staða Númer útibús Stutt tilvísun
5/15/20 0:00 5/15/20 0:00 GV165636 Fj.skatt gengishagnað Guðmundur Rúnar Pétursson -199.2 7,258.2 0152
"""
import datetime
import decimal
import typing
imp... | null |
v0 | [
"str"
] | Any | def v0(v1: str):
(v2, v3, v4) = v1.split('/')
v2 = v2.zfill(2)
v3 = v3.zfill(2)
v5 = '%Y'
if len(v4) == 2:
v5 = '%y'
v6 = datetime.strptime(v1, f'%d/%m/{v5}')
return v6.strftime('%m/%d/%YZ') | [] | [
"datetime"
] | [
"from datetime import datetime"
] | 9 | import os
import sys
from datetime import datetime
import csv
# Layer code, like parsing_lib, is added to the path by AWS.
# To test locally (e.g. via pytest), we have to modify sys.path.
# pylint: disable=import-error
try:
import parsing_lib
except ImportError:
sys.path.append(
os.path.join(
... | null |
v0 | [
"str"
] | Any | def v0(v1: str):
if v1 == 'M':
return 'Male'
elif v1 == 'F':
return 'Female'
elif v1 == 'I':
return 'Other' | [] | [] | [] | 7 | import os
import sys
from datetime import datetime
import csv
import json
# Layer code, like parsing_lib, is added to the path by AWS.
# To test locally (e.g. via pytest), we have to modify sys.path.
# pylint: disable=import-error
try:
import parsing_lib
except ImportError:
sys.path.append(
os.path.joi... | null |
v0 | [] | None | def v0(self) -> None:
self.close()
self.__file = v0(self.__file_path, mode='a') | [] | [] | [] | 3 | from typing import Optional, TextIO
from pyutils import exc
from . import echo, fileutils
class Logger:
"""A logger object that logs to both a file and stdout."""
# Properties
@property
def file_path(self) -> str:
"""Path of the log file."""
return self.__file_path
# Public met... | null |
v0 | [] | None | def v0(self) -> None:
if self.__file:
self.__file.close()
self.__file = None | [] | [] | [] | 4 | from typing import Optional, TextIO
from pyutils import exc
from . import echo, fileutils
class Logger:
"""A logger object that logs to both a file and stdout."""
# Properties
@property
def file_path(self) -> str:
"""Path of the log file."""
return self.__file_path
# Public met... | null |
v0 | [
"Any",
"Any"
] | bool | def v0(v1, v2) -> bool:
if isinstance(v1, float):
return False
v3 = v1.split(',')
for v4 in v3:
(v5, v6, v5) = v4.split(':')
if v2 == v6:
return True
return False | [] | [] | [] | 9 | from collections import Counter
from .gene_id_retrieval import GeneIDFetcher
from .loaders import load_snv_datasets
from pandas import DataFrame
from .protein_id_retrieval import ProteinIDFetcher
from ..mylogger import get_handler
import logging
from tqdm.auto import tqdm
import pandas as pd
from IPython.display impor... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.