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
[]
Optional[tuple[str, int, int]]
def v0(self) -> Optional[tuple[str, int, int]]: v1 = self.upstream_angles() v2 = self.downstream_angles() if not self.clockwise and (self.start_atom.explicit or self.end_atom.explicit): if self.start_atom.explicit and self.end_atom.explicit: return None elif self.start_atom.expli...
[]
[]
[]
39
# -*- 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
[]
tuple[int, int]
def v0(self) -> tuple[int, int]: if self.start_atom.explicit: v1 = 0 else: v2 = list(self.upstream_angles().values()) if v2[0] is not None: v1 = self.cotan100(0.5 * min(v2)) else: v1 = 0 if self.end_atom.explicit: v3 = 0 else: v4 = ...
[]
[]
[]
18
# -*- 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
[ "Any" ]
dict
def v0(v1) -> dict: v2 = {} for v3 in v1.current_user_playlists()['items']: if v3['owner']['id'] == v1.me()['id']: v2[v3['name']] = {'id': v3['id'], 'image_url': v3['images'][0]['url'] if not v3['images'] == [] else './assets/error.ico', 'tracks': [song['track']['id'] for v4 in v1.playlist_t...
[]
[]
[]
6
import os from pprint import pprint as p from urllib.request import urlretrieve import json import logging logging.getLogger(__name__) def playlists_and_tracks(spotify) -> dict: """Returns a dict including tracks like: {"Playlist_name": { "id": "playlist_id", "image_url": "the_ur...
null
v0
[ "Any" ]
dict
def v0(v1) -> dict: v2 = {str(item['name']): {'id': item['id'], 'image_url': item['images'][0]['url'] if not item['images'] == [] else 'noIcon'} for v3 in v1.current_user_playlists()['items'] if v3['owner']['id'] == v1.me()['id']} return v2
[]
[]
[]
3
import os from pprint import pprint as p from urllib.request import urlretrieve import json import logging logging.getLogger(__name__) def playlists_and_tracks(spotify) -> dict: """Returns a dict including tracks like: {"Playlist_name": { "id": "playlist_id", "image_url": "the_ur...
null
v0
[ "Any" ]
None
def v0(v1) -> None: v2 = {y['id']: y['image_url'] for (v3, v4) in v1.items()} for (v5, v6) in v2.items(): if not os.path.exists(f'./assets/playlists/{v5}.ico'): if not v6 == 'noIcon': urlretrieve(v6, f'./assets/playlists/{v5}.ico') logging.info(f'Downloaded {v5}.i...
[]
[ "logging", "os", "urllib" ]
[ "import os", "from urllib.request import urlretrieve", "import logging" ]
8
import os from pprint import pprint as p from urllib.request import urlretrieve import json import logging logging.getLogger(__name__) def playlists_and_tracks(spotify) -> dict: """Returns a dict including tracks like: {"Playlist_name": { "id": "playlist_id", "image_url": "the_ur...
null
v0
[]
dict
def v0(self) -> dict: v1 = os.path.join(self.path_exp, 'config.json') with open(v1, 'r') as v2: v3 = json.load(v2) return v3
[]
[ "json", "os" ]
[ "import os", "import json" ]
5
# # logsmanager.py # # Author(s): # Matteo Spallanzani <spmatteo@iis.ee.ethz.ch> # # Copyright (c) 2020-2021 ETH Zurich. # # 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.ap...
null
v19
[ "Any" ]
dict
def v19(v20) -> dict: if v16()['fetch_playlists'] and v16()['fetch_songs']: v21 = v4(v20) elif v16()['fetch_playlists']: v21 = v0(v20) else: with open('./config/data.json') as v22: v21 = json.load(v22) v9(v21) for v23 in v21: v21[v23]['image_url'] = f"./as...
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "dict", "code": "def v0(v1) -> dict:\n v2 = {str(item['name']): {'id': item['id'], 'image_url': item['images'][0]['url'] if not item['images'] == [] else 'noIcon'} for v3 in v1.current_user_playlists()['items'] if v3['owner']['id'...
[ "json", "logging", "os", "urllib" ]
[ "import os", "from urllib.request import urlretrieve", "import json", "import logging" ]
12
import os from pprint import pprint as p from urllib.request import urlretrieve import json import logging logging.getLogger(__name__) def playlists_and_tracks(spotify) -> dict: """Returns a dict including tracks like: {"Playlist_name": { "id": "playlist_id", "image_url": "the_ur...
null
v0
[ "List[str]" ]
List[str]
def v0(self, v1: List[str]) -> List[str]: v2 = set('QWERTYUIOP') v3 = set('ASDFGHJKL') v4 = set('ZXCVBNM') v5 = [] for v6 in v1: v7 = set(v6.upper()) if v7 & v2 == v7 or v7 & v3 == v7 or v7 & v4 == v7: v5.append(v6) return v5
[]
[]
[]
10
from typing import List # 该方法最快 class Solution: def findWords(self, words: List[str]) -> List[str]: set_1 = set("QWERTYUIOP") set_2 = set("ASDFGHJKL") set_3 = set("ZXCVBNM") res = [] for word in words: word_set = set(word.upper()) if not (word_set - se...
null
v0
[ "Dict[str, torch.Tensor]" ]
Any
def v0(self, v1: Dict[str, torch.Tensor]): v2 = v1['joint_positions'] v3 = v1['joint_velocities'] if not self.running: self.joint_pos_desired[:] = v2[:] self.running = True v4 = self.impedance(v2, v3, self.joint_pos_desired, torch.zeros_like(self.joint_pos_desired)) return {'joint_to...
[]
[ "torch" ]
[ "import torch" ]
8
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Dict import torch import torchcontrol as toco from torchcontrol.utils import to_tensor class DefaultController(toco.Polic...
null
v2
[ "str" ]
Any
def v2(self, v3: str): if self._dynamodb_resource is None: self._dynamodb_resource = v0(v3) return self._dynamodb_resource
[ { "name": "v0", "input_types": [ "str" ], "output_type": "Any", "code": "def v0(v1: str):\n return boto3.resource('dynamodb', region_name=v1)", "dependencies": [] } ]
[]
[]
4
# Copyright 2021 The Feast Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
null
v0
[ "str" ]
Any
def v0(v1: str): v2 = hashlib.sha1() v2.update(v1.encode('utf-8')) v3 = v2.hexdigest() return v3
[]
[ "hashlib" ]
[ "import hashlib" ]
5
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "l...
null
v0
[ "socket.socket" ]
Any
def v0(v1: socket.socket) -> Any: v2 = bytearray() while True: v3 = v1.recv(100000) if not v3: break v2.extend(v3) if not v2: raise OSError('No data received') try: v4 = json.loads(v2.decode('utf8')) except Exception: raise OSError('Data re...
[]
[ "json" ]
[ "import json" ]
16
"""Shared code between dmypy.py and dmypy_server.py. This should be pretty lightweight and not depend on other mypy code. """ import json import socket from typing import Any STATUS_FILE = '.dmypy.json' def receive(sock: socket.socket) -> Any: """Receive JSON data from a socket until EOF. Raise a subclas...
null
v0
[ "str", "str" ]
None
def v0(v1: str, v2: str) -> None: v3 = v1.split() print(f'Checking for {v3[0]}...') try: subprocess.run(v3, check=True) except subprocess.CalledProcessError: print('Not found. Installing...') subprocess.run(['sudo', 'apt-get', 'install', '-y', '--no-install-recommends', v2], chec...
[]
[ "subprocess" ]
[ "import subprocess" ]
10
#!/usr/bin/env python3 # # ****************************************************************** # |docname| - Create a Docker container for the Runestone webservers # ****************************************************************** # This script provides a user-friendly install process for creating a multi-container Do...
null
v3
[ "str", "Dict[str, str]" ]
str
def v3(v4: str, v5: Dict[str, str]) -> str: def v6(v7: re.Match): v8 = v7.group(1) return str(v5[v8]) if v8 in v5 else v7.group(0) v9 = '\\${(\\w+)}' return re.sub(v9, v6, v4)
[ { "name": "v0", "input_types": [ "re.Match" ], "output_type": "Any", "code": "def v0(v1: re.Match):\n v2 = v1.group(1)\n return str(vars_[v2]) if v2 in vars_ else v1.group(0)", "dependencies": [] } ]
[ "re" ]
[ "import re" ]
7
#!/usr/bin/env python3 # # ****************************************************************** # |docname| - Create a Docker container for the Runestone webservers # ****************************************************************** # This script provides a user-friendly install process for creating a multi-container Do...
null
v0
[]
None
def v0(self) -> None: global main_pid v1 = os.getpid() signal.signal(signal.SIGINT, self._accept_signal) signal.signal(signal.SIGTERM, self._accept_signal) if platform == 'win32' or platform == 'cygwin': signal.signal(signal.SIGBREAK, self._accept_signal)
[]
[ "os", "signal", "sys" ]
[ "import os", "import signal", "from sys import platform" ]
7
import asyncio import os import logging import logging.config import signal from sys import platform from typing import Any, Callable, List, Optional, Tuple from mint.daemon.server import singleton, service_launch_lock_path from mint.server.ssl_context import mint_ssl_ca_paths, private_ssl_ca_paths try: import uv...
null
v1
[]
None
def v1(self) -> None: if not self._is_stopping.is_set(): self._is_stopping.set() for v2 in self._upnp_ports: if self.upnp is not None: self.upnp.release(v2) self._log.info('Cancelling reconnect task') for v3 in self._reconnect_tasks: v3.cancel(...
[ { "name": "v0", "input_types": [], "output_type": "None", "code": "async def v0() -> None:\n if self._rpc_task:\n await (await self._rpc_task)[0]()", "dependencies": [] } ]
[ "asyncio" ]
[ "import asyncio" ]
21
import asyncio import functools import os import logging import logging.config import signal from sys import platform from typing import Any, Callable, List, Optional, Tuple from chinilla.daemon.server import singleton, service_launch_lock_path from chinilla.server.ssl_context import chinilla_ssl_ca_paths, private_ssl...
null
v0
[]
None
async def v0(self) -> None: await self._is_stopping.wait() self._log.info('Waiting for socket to be closed (if opened)') self._log.info('Waiting for LittlelambocoinServer to be closed') await self._server.await_closed() if self._rpc_close_task: self._log.info('Waiting for RPC server') ...
[]
[]
[]
16
import asyncio import functools import os import logging import logging.config import signal from sys import platform from typing import Any, Callable, List, Optional, Tuple from littlelambocoin.daemon.server import singleton, service_launch_lock_path from littlelambocoin.server.ssl_context import littlelambocoin_ssl_...
null
v0
[]
None
async def v0() -> None: if self._rpc_task: await (await self._rpc_task)[0]()
[]
[]
[]
3
import asyncio import functools import os import logging import logging.config import signal from sys import platform from typing import Any, Callable, List, Optional, Tuple from chinilla.daemon.server import singleton, service_launch_lock_path from chinilla.server.ssl_context import chinilla_ssl_ca_paths, private_ssl...
null
v0
[]
int
def v0() -> int: with open('/home/thelichking/Desktop/adventOfCode/Day2/Opcodes', 'r') as v1: v2 = list(map(int, v1.readline().replace('\n', '').split(','))) (v2[1], v2[2]) = (1, 0) v3 = 0 while v3 < len(v2): v4 = v2[v3] if v4 == 99: return v2[...
[]
[]
[]
16
def opcodeI() -> int: with open("/home/thelichking/Desktop/adventOfCode/Day2/Opcodes",'r' ) as file: lines = list(map(int,file.readline().replace("\n","").split(","))) lines[1],lines[2] = 1,0 idx = 0 while idx < len(lines): cur_opcode = lines[idx] if cur_op...
null
v0
[ "Any", "Any" ]
int
def v0(v1, v2) -> int: with open('/home/thelichking/Desktop/adventOfCode/Day2/Opcodes', 'r') as v3: v4 = list(map(int, v3.readline().replace('\n', '').split(','))) (v4[1], v4[2]) = (v1, v2) v5 = 0 while v5 < len(v4): v6 = v4[v5] if v6 == 99: re...
[]
[]
[]
16
def opcodeI() -> int: with open("/home/thelichking/Desktop/adventOfCode/Day2/Opcodes",'r' ) as file: lines = list(map(int,file.readline().replace("\n","").split(","))) lines[1],lines[2] = 1,0 idx = 0 while idx < len(lines): cur_opcode = lines[idx] if cur_op...
null
v7
[]
int
def v7() -> int: for v8 in range(100): for v9 in range(100): if v0(v9, v8) == 19690720: return 100 * v9 + v8
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "int", "code": "def v0(v1, v2) -> int:\n with open('/home/thelichking/Desktop/adventOfCode/Day2/Opcodes', 'r') as v3:\n v4 = list(map(int, v3.readline().replace('\\n', '').split(',')))\n (v4[1], v4[2]) =...
[]
[]
5
def opcodeI() -> int: with open("/home/thelichking/Desktop/adventOfCode/Day2/Opcodes",'r' ) as file: lines = list(map(int,file.readline().replace("\n","").split(","))) lines[1],lines[2] = 1,0 idx = 0 while idx < len(lines): cur_opcode = lines[idx] if cur_op...
null
v0
[ "Any" ]
str
def v0(v1) -> str: v2 = open(v1, 'r', encoding='utf-8') v3 = v2.read() v2.close() return v3
[]
[]
[]
5
# Built-In Libraries/Modules/Packages import smtplib import ssl # Third Party Libraries/Modules/Packages import pandas as pd from email.mime.text import MIMEText from email.utils import formataddr from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders def read_...
null
v0
[ "str", "int" ]
Any
def v0(v1: str, v2: int=0): v3 = os.path.abspath(v1) for v4 in range(v2 + 1): v3 = os.path.dirname(v3) return v3
[]
[ "os" ]
[ "import os" ]
5
import os def read_file(file) -> str: stream = open(file, encoding="utf8") text = stream.read() stream.close() return text def get_base_dir(file: str, level: int = 0): base_dir = os.path.abspath(file) for _ in range(level + 1): base_dir = os.path.dirname(base_dir) return base_dir...
null
v0
[ "str", "Dict[str, Any]" ]
Dict[str, Any]
def v0(self, v1: str, v2: Dict[str, Any]={}) -> Dict[str, Any]: if v1 not in ('returnTicker', 'returnChartData', 'return24Volume'): raise RuntimeError(f'unsupported command: {v1}') v3 = {'command': v1, **v2} v4 = requests.get(self.endpoint, params=v3) v4.raise_for_status() return v4.json()
[]
[ "requests" ]
[ "import requests" ]
7
from typing import Dict, Any, Type, List import datetime import requests from exchange.rate import ExchangeRate class Poloniex: endpoint = "https://poloniex.com/public" def _api_query(self, command: str , params: Dict[str, Any] = {}) -> Dict[str, Any]: if command not in ("returnTicker", "returnCha...
null
v0
[ "Sequence[Any]", "Sequence[Any]" ]
float
def v0(self, v1: Sequence[Any], v2: Sequence[Any], *v3, **v4) -> float: v5 = 0.0 for v6 in v1[:self.eval_at]: if v6 in v2: v5 += 1.0 v7 = min(self.eval_at, len(v2)) if v7 == 0.0: 'TODO: Agree on a behavior' return 0.0 else: return v5 / v7
[]
[]
[]
11
from typing import Sequence, Any from ..rank import BaseRankingEvaluator class PrecisionEvaluator(BaseRankingEvaluator): """A :class:`PrecisionEvaluator` evaluates the Precision of the search. It computes how many of the first given `eval_at` matches are found in the groundtruth """ @property ...
null
v0
[ "Any" ]
int
def v0(v1) -> int: v2 = 1 v3 = 1 while v3 == True: v3 = 0 for v4 in range(1, len(v1) - 1): for v5 in range(1, len(v1[0]) - 1): if v1[v4, v5] == -1: v1[v4, v5] = -2 v6 = {(v4 + 1, v5): v1[v4 + 1, v5], (v4 - 1, v5): v1[v4 - 1,...
[]
[]
[]
16
import pandas as pd import numpy as np data = pd.read_csv("data/day9.csv", header = None, dtype=str) mp = np.array([[int(word[0][i]) for i in range(len(word[0]))] for word in data.values]) # Challenge 1 mp = np.pad(mp,pad_width=1,mode='maximum') l = [] for i in range(1,len(mp)-1): for j in range(1,len(mp[0])-1)...
null
v0
[ "Any", "Any" ]
float
def v0(v1, v2) -> float: if v2.end > v1.end and v2.start >= v1.start: return (v1.end - v2.start + 1) / (v2.end - v1.start + 1) elif v1.end > v2.end and v1.start >= v2.start: return (v2.end - v1.start + 1) / (v1.end - v2.start + 1) if v2.end >= v1.end and v2.start > v1.start: return (...
[]
[]
[]
23
from brainex.classes.Sequence import Sequence # def merge_gclusters(gclusters): # # gclusters validation # try: # iterator = iter(gclusters) # except TypeError as te: # raise Exception('Given Gclusters is not iterable.') # # try: # for gc in gclusters: # assert type...
null
v20
[ "List[v0]" ]
None
def v20(v21: List[v0]) -> None: v22 = Counter([r.id for v23 in v21]) v24 = [guid for (v25, v26) in v22.items() if v26 > 1] if v24: raise ValueError(f'Slate GUIDs appears more than once in slate config: {v24}')
[]
[ "collections" ]
[ "from collections import Counter" ]
5
from collections import Counter import os from typing import List, Optional from enum import Enum from app.config import JSON_DIR from app.json.utils import parse_to_dict from app.models.slate_experiment import SlateExperimentModel class CuratorTopic(Enum): BUSINESS = 'Business' CAREER = 'Career' EDUCAT...
[ "class v0:\n v1 = {}\n\n def __init__(self, v2: str, v3: str, v4: str, v5: Optional[str]=None, v6=None):\n self.id = v2\n self.displayName = v3\n self.description = v4\n self.experiments = v6 or []\n self.curator_topic_label = v5\n\n @staticmethod\n def v7(v8: dict) ->...
v0
[]
None
def v0(self) -> None: v1 = 'Only start the AlarmTask after it has been primed with the first_run' assert self.is_primed(), v1 v2 = self.sleep_time while self._stop_event and self._stop_event.wait(v2) is not True: v3 = self.rpc_client.get_block(block_identifier='latest') self._maybe_run_c...
[]
[]
[]
7
import re from typing import TYPE_CHECKING, Dict import click import gevent import requests import structlog from eth_utils import to_checksum_address, to_hex from gevent.event import AsyncResult from pkg_resources import parse_version from web3 import Web3 from raiden.constants import ( CHECK_GAS_RESERVE_INTERVA...
null
v0
[ "Union[str]", "int" ]
str
def v0(v1: Union[str], *, v2: int=80) -> str: warnings.warn('`truncate` is no-longer used by pydantic and is deprecated', DeprecationWarning) if isinstance(v1, str) and len(v1) > v2 - 2: return (v1[:v2 - 3] + '…').__repr__() try: v1 = v1.__repr__() except TypeError: v1 = v1.__cla...
[]
[ "warnings" ]
[ "import warnings" ]
11
import warnings import weakref from collections import OrderedDict, defaultdict, deque from copy import deepcopy from itertools import islice, zip_longest from types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType from typing import ( TYPE_CHECKING, AbstractSet, Any...
null
v0
[ "List[Type['BaseModel']]", "str" ]
None
def v0(v1: List[Type['BaseModel']], v2: str) -> None: for v3 in v1: if getattr(v3, v2, None): raise NameError(f"""Field name "{v2}" shadows a BaseModel attribute; use a different field name with "alias='{v2}'".""")
[]
[]
[]
4
import inspect import platform import sys import warnings from importlib import import_module from pathlib import Path from typing import ( TYPE_CHECKING, AbstractSet, Any, Callable, Dict, Generator, Iterator, List, Optional, Set, Tuple, Type, TypeVar, Union, ...
null
v0
[]
bool
def v0() -> bool: try: eval('__IPYTHON__') except NameError: return False else: return True
[]
[]
[]
7
import inspect import platform import sys import warnings from importlib import import_module from pathlib import Path from typing import ( TYPE_CHECKING, AbstractSet, Any, Callable, Dict, Generator, Iterator, List, Optional, Set, Tuple, Type, TypeVar, Union, ...
null
v0
[]
Iterator[Tuple[str, List[Any]]]
def v0(self) -> Iterator[Tuple[str, List[Any]]]: for v1 in super().__iter__(): yield (v1, self[v1])
[]
[]
[]
3
from collections import defaultdict from copy import copy, deepcopy from enum import Enum, auto from typing import ( Any, DefaultDict, Dict, Generic, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, overload, ) from dynamo_query...
null
v0
[ "Dict[str, Any]" ]
Dict[str, Any]
def v0(self, v1: Dict[str, Any]) -> Dict[str, Any]: v1.update({'server_name': 'example.com', 'tou_url': 'dummy-url', 'testing': True, 'dashboard_bundle_path': 'dummy-dashboard-bundle', 'dashboard_bundle_version': 'dummy-dashboard-version', 'signup_bundle_path': 'dummy-signup-bundle', 'signup_bundle_version': 'dummy...
[]
[]
[]
3
# -*- coding: utf-8 -*- # # Copyright (c) 2016 NORDUnet A/S # Copyright (c) 2019 SUNET # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain...
null
v0
[]
str
def v0(self) -> str: v1 = [self.sumo_command, '-V'] v2 = subprocess.Popen(v1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (v3, v4) = v2.communicate() v5 = v2.returncode assert v5 == 0 return v3.decode('utf-8')
[]
[ "subprocess" ]
[ "import subprocess" ]
7
from pathlib import Path, WindowsPath import subprocess import shutil from sumo_docker_pipeline import static from sumo_docker_pipeline.logger_unit import logger from sumo_docker_pipeline.operation_module.base_operation import BaseController from sumo_docker_pipeline.commons.sumo_config_obj import SumoConfigObject from...
null
v0
[]
str
def v0() -> str: with open('README.md', 'r', encoding='utf-8') as v1: return v1.read()
[]
[]
[]
3
import setuptools def long_description() -> str: with open("README.md", "r", encoding="utf-8") as fh: return fh.read() setuptools.setup( name="funchacks", version="1.0.1", keywords=[ "FUNCTIONAL PROGRAMMING", "FUNCTION TOOLS", "FUNCTION UTILS", "UTILS", ],...
null
v0
[]
List[str]
def v0() -> List[str]: with open('requirements.txt', 'r') as v1: return v1.read().splitlines()
[]
[]
[]
3
""" setup """ import os from typing import List import semver import setuptools def versioning(version: str) -> str: """ version to specification Author: wj-Mcat <wjmcater@gmail.com> (https://github.com/wj-Mcat) """ sem_ver = semver.parse(version) major = sem_ver['major'] minor = sem_ver...
null
v0
[]
bool
def v0(self) -> bool: if self.ws: return self.ws.is_ratelimited() return False
[]
[]
[]
4
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
null
v0
[ "Callable[..., Coroutine[Any, Any, Any]]", "str" ]
None
async def v0(self, v1: Callable[..., Coroutine[Any, Any, Any]], v2: str, *v3: Any, **v4: Any) -> None: try: await v1(*v3, **v4) except asyncio.CancelledError: pass except Exception: try: await self.on_error(v2, *v3, **v4) except asyncio.CancelledError: ...
[]
[ "asyncio" ]
[ "import asyncio" ]
10
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
null
v0
[ "Callable[..., Coroutine[Any, Any, Any]]", "str" ]
asyncio.Task
def v0(self, v1: Callable[..., Coroutine[Any, Any, Any]], v2: str, *v3: Any, **v4: Any) -> asyncio.Task: v5 = self._run_event(v1, v2, *v3, **v4) v6 = self.loop.create_task(v5) v6.set_name(f'discord.py: {v2}') return v6
[]
[]
[]
5
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
null
v0
[ "str" ]
None
async def v0(self, v1: str, /, *v2: Any, **v3: Any) -> None: print(f'Ignoring exception in {v1}', file=sys.stderr) traceback.print_exc()
[]
[ "sys", "traceback" ]
[ "import sys", "import traceback" ]
3
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
null
v0
[ "Optional[int]", "bool" ]
None
async def v0(self, v1: Optional[int], *, v2: bool=False) -> None: if not v2: await asyncio.sleep(5.0)
[]
[ "asyncio" ]
[ "import asyncio" ]
3
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
null
v0
[]
None
async def v0(self) -> None: if self._closed: return self._closed = True self.dispatch('close') for v1 in self.voice_clients: try: await v1.disconnect(force=True) except Exception: pass if self.ws is not None and self.ws.open: await self.ws.clos...
[]
[]
[]
14
""" The MIT License (MIT) Copyright (c) 2015-2021 Rapptz Copyright (c) 2021-present tag-epic 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 ...
null
v0
[]
None
def v0(self) -> None: self._closed = False self._ready.clear() self._connection.clear() self.http.recreate()
[]
[]
[]
5
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
null
v0
[ "str", "bool" ]
None
async def v0(self, v1: str, *, v2: bool=True) -> None: await self.login(v1) await self.setup() await self.connect(reconnect=v2)
[]
[]
[]
4
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
null
v2
[ "str", "Optional[Callable[..., bool]]", "Optional[float]" ]
Any
def v2(self, v3: str, *, v4: Optional[Callable[..., bool]]=None, v5: Optional[float]=None) -> Any: print(v3) v6 = self.loop.create_future() if v4 is None: def v7(*v8): return True v4 = v7 v9 = v3.lower() try: v10 = self._listeners[v9] except KeyError: ...
[ { "name": "v0", "input_types": [], "output_type": "Any", "code": "def v0(*v1):\n return True", "dependencies": [] } ]
[ "asyncio" ]
[ "import asyncio" ]
17
""" MIT License Copyright (c) 2020-present shay (shayypy) 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,...
null
v1
[]
v0
def v1(self, cls: v0) -> v0: self._application_command_store._internal_add(cls) return cls
[]
[]
[]
3
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
[ "v0 = TypeVar('ApplicationCommand', bound=Type[Command])" ]
v0
[ "Any", "Mapping", "List[str]" ]
Any
def v0(v1, v2: Mapping, v3: List[str]): if len(v3) > 0: v4 = '_'.join(('{}-{!s}'.format(k, v2.get(k, 'na')) for v5 in v3)) v4 = v4.replace('/', '_') else: v4 = '_' return f'{v1}/{v4}'
[]
[]
[]
7
import collections.abc import glob import itertools import os.path import shutil import typing from abc import abstractmethod from typing import Dict, List, Mapping import yaml from experitur.helpers.dumper import ExperiturDumper from experitur.helpers.merge_dicts import merge_dicts from experitur.recursive_formatter...
null
v0
[ "str" ]
Any
async def v0(self, v1: str): v2 = await self.fetch_invite_by_code(v1) if v2: await v2.delete() await self.load() return v2
[]
[]
[]
6
import re from Levenshtein import distance from typing import Optional from utils.models import FilteredWord, LevenshteinWord, ApprovedInvite, WhitelistWord async def check_collisions() -> Optional[dict[str, list]]: filtered_words = await FilteredWord.query.gino.all() levenshtein_words = await LevenshteinWor...
null
v0
[ "str" ]
tuple[str, dict]
def v0(self, v1: str) -> tuple[str, dict]: v2 = {} for v3 in self.kinds[:-1]: v2[v3] = [] for v4 in self.filter[v3]: if (v5 := self.word_exp[v4].search(v1)): v2[v3].append(v5) (v6, v7) = v5.span(0) v1 = f'{v1[:v6]}**{v5.group(0)}**{v1[v...
[]
[]
[]
11
import re from Levenshtein import distance from typing import Optional from utils.models import FilteredWord, LevenshteinWord, ApprovedInvite, WhitelistWord async def check_collisions() -> Optional[dict[str, list]]: filtered_words = await FilteredWord.query.gino.all() levenshtein_words = await LevenshteinWor...
null
v0
[ "str" ]
tuple[bool, bool]
def v0(self, v1: str) -> tuple[bool, bool]: v2 = re.findall('((?:https?://)?(?:www.)?)(?:(youtube\\.com/watch\\?v=)|(youtu\\.be/))([aA-zZ_\\-\\d]{11})', v1) v3 = any(v2) v4 = False if not v3 else any((x for v5 in v2 if v5 in self.filter['piracy video'])) return (v3, v4)
[]
[ "re" ]
[ "import re" ]
5
import re from Levenshtein import distance from typing import Optional from utils.models import FilteredWord, LevenshteinWord, ApprovedInvite, WhitelistWord async def check_collisions() -> Optional[dict[str, list]]: filtered_words = await FilteredWord.query.gino.all() levenshtein_words = await LevenshteinWor...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = [] v3 = [] v4 = re.findall('(?:discordapp\\.com/invite|discord\\.gg|discord\\.com/invite)/([\\w]+)', v1) for v5 in v4: if (v6 := self.get_invite_by_code(v5)): v2.append(v6) else: v3.append(v5) return (v2, v3)
[]
[ "re" ]
[ "import re" ]
10
import re from Levenshtein import distance from typing import Optional from utils.models import FilteredWord, LevenshteinWord, ApprovedInvite, WhitelistWord async def check_collisions() -> Optional[dict[str, list]]: filtered_words = await FilteredWord.query.gino.all() levenshtein_words = await LevenshteinWor...
null
v0
[ "Optional[str]" ]
ChromeOptions
def v0(v1: Optional[str]=None) -> ChromeOptions: v2 = ChromeOptions() v2.add_argument('--log-level=3') v2.add_argument('--disable-dev-shm-usage') v2.add_argument('--no-sandbox') os.environ['LANGUAGE'] = 'zh' if v1 is None else v1 v2.add_argument(f"--lang={os.getenv('LANGUAGE', '')}") return ...
[]
[ "os", "selenium" ]
[ "import os", "from selenium.webdriver import Chrome", "from selenium.webdriver import ChromeOptions" ]
8
# -*- coding: utf-8 -*- # Time : 2022/1/16 0:27 # Author : QIN2DIM # Github : https://github.com/QIN2DIM # Description: import os import shutil import sys from datetime import datetime, timedelta from typing import List, Union, Dict, Optional, Any import pytz import undetected_chromedriver as uc import y...
null
v0
[ "torch.Tensor", "torch.Tensor", "int" ]
Any
def v0(v1: torch.Tensor, v2: torch.Tensor, v3: int): v4 = torch.zeros(v3).scatter_add_(0, v2.flatten().long(), v1.flatten()) v5 = torch.clamp_min_(torch.bincount(v2.flatten(), minlength=v3), 1) v6 = v4 / v5 return v6
[]
[ "torch" ]
[ "import torch" ]
5
import math import os from abc import ABC, abstractmethod from concurrent.futures import ThreadPoolExecutor from typing import Tuple import numpy as np import torch from hivemind.compression.base import CompressionBase, CompressionInfo from hivemind.proto import runtime_pb2 EXECUTOR = ThreadPoolExecutor(max_workers=...
null
v0
[ "int", "int" ]
List[int]
def v0(v1: int, v2: int) -> List[int]: if v2 >= v1: v3 = [v1] else: v3 = [v1 // v2 + 1] * (v1 % v2) + [v1 // v2] * (v2 - v1 % v2) return v3
[]
[]
[]
6
import logging import numpy as np import tensorflow as tf import tensorflow_probability as tfp from typing import Callable, Dict, Optional, Tuple, Union, List from alibi_detect.cd.base import BaseContextMMDDrift from alibi_detect.utils.tensorflow.kernels import GaussianRBF from alibi_detect.cd._domain_clf import _SVCDo...
null
v24
[ "torch.Tensor", "bool" ]
Tuple[np.ndarray, np.ndarray]
def v24(self, v25: torch.Tensor, v26: bool=False) -> Tuple[np.ndarray, np.ndarray]: v25 = v25.detach().float() v27 = torch.as_tensor(v12(v25.numpy(), self.n_bins + 1)[1:-1]) v28 = torch.clamp_(torch.bucketize(v25, v27), 0, self.n_bins - 1) v29 = v0(v25, v28, self.n_bins) return (v28.numpy().astype(n...
[ { "name": "v0", "input_types": [ "torch.Tensor", "torch.Tensor", "int" ], "output_type": "Any", "code": "def v0(v1: torch.Tensor, v2: torch.Tensor, v3: int):\n v4 = torch.zeros(v3).scatter_add_(0, v2.flatten().long(), v1.flatten())\n v5 = torch.clamp_min_(torch.bincount(v...
[ "numpy", "torch" ]
[ "import numpy as np", "import torch" ]
6
import math import os from abc import ABC, abstractmethod from concurrent.futures import ThreadPoolExecutor from typing import Tuple import numpy as np import torch from hivemind.compression.base import CompressionBase, CompressionInfo from hivemind.proto import runtime_pb2 EXECUTOR = ThreadPoolExecutor(max_workers=...
null
v0
[ "runtime_pb2.Tensor" ]
torch.Tensor
def v0(self, v1: runtime_pb2.Tensor) -> torch.Tensor: v2 = int(np.frombuffer(v1.buffer, count=1, dtype=np.int64)) v3 = np.frombuffer(v1.buffer, offset=8, count=v2, dtype=self.codebook_dtype) v4 = np.frombuffer(v1.buffer, offset=8 + v3.nbytes, dtype=self.indices_dtype) v4 = torch.as_tensor(v4, dtype=torc...
[]
[ "numpy", "torch" ]
[ "import numpy as np", "import torch" ]
7
import math import os from abc import ABC, abstractmethod from concurrent.futures import ThreadPoolExecutor from typing import Tuple import numpy as np import torch from hivemind.compression.base import CompressionBase, CompressionInfo from hivemind.proto import runtime_pb2 EXECUTOR = ThreadPoolExecutor(max_workers=...
null
v0
[]
Optional['ProperType']
def v0(self) -> Optional['ProperType']: (v1, v2) = self._partial_expansion() if v2: return None return v1
[]
[]
[]
5
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
null
v0
[]
int
def v0(self) -> int: if self.is_var_arg or self.is_kw_arg: return sys.maxsize return sum([kind.is_positional() for v1 in self.arg_kinds])
[]
[ "sys" ]
[ "import sys" ]
4
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
null
v15
[]
List[v0]
def v15(self) -> List[v0]: v16: List[v0] = [] for v17 in self.variables: v16.append(v17.id) return v16
[]
[]
[]
5
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0:\n v1: int = 0\n v2: int = 0\n v3: ClassVar[int] = 1\n\n def __init__(self, v4: int, v5: int=0) -> None:\n self.raw_id = v4\n self.meta_level = v5\n\n @staticmethod\n def v6(v7: int) -> 'TypeVarId':\n v8 = v0.next_raw_id\n v0.next_raw_id += 1\n return v...
v0
[]
'TypedDictType'
def v0(self) -> 'TypedDictType': if self.fallback.type.fullname() == 'typing.Mapping': return self assert self.fallback.type.typeddict_type is not None return self.fallback.type.typeddict_type.as_anonymous()
[]
[]
[]
5
"""Classes for representing mypy types.""" from abc import abstractmethod import copy from collections import OrderedDict from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Generic, Set, Sequence, Optional, Union, Iterable, NamedTuple, ) import mypy.nodes from mypy.nodes import ( INVARIANT, Symbo...
null
v27
[]
v0
def v27(self) -> v0: v28 = self.as_anonymous() return v28.fallback
[]
[]
[]
3
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(ProperType):\n v1 = ('type', 'args', 'invalid', 'type_ref', 'last_known_value')\n\n def __init__(self, v2: mypy.nodes.TypeInfo, v3: Sequence[Type], v4: int=-1, v5: int=-1, *, v6: Optional['LiteralType']=None) -> None:\n super().__init__(v4, v5)\n self.type = v2\n self.args = tup...
v11
[ "'TypedDictType'" ]
Iterable[Tuple[str, Optional[v0], Optional[v0]]]
def v11(self, v12: 'TypedDictType') -> Iterable[Tuple[str, Optional[v0], Optional[v0]]]: v13 = self for (v14, v15) in v13.items.items(): v16 = v12.items.get(v14) yield (v14, v15, v16) for (v14, v16) in v12.items.items(): if v14 in v13.items: continue yield (v14, N...
[]
[]
[]
9
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(mypy.nodes.Context):\n v1 = ('can_be_true', 'can_be_false')\n\n def __init__(self, v2: int=-1, v3: int=-1) -> None:\n super().__init__(v2, v3)\n self.can_be_true = self.can_be_true_default()\n self.can_be_false = self.can_be_false_default()\n\n def v4(self) -> bool:\n ...
v0
[]
str
def v0(self) -> str: v1 = repr(self.value) v2 = self.fallback.type.fullname() if self.is_enum_literal(): return '{}.{}'.format(v2, self.value) if v2 == 'builtins.bytes': return 'b' + v1 elif v2 == 'builtins.unicode': return 'u' + v1 else: return v1
[]
[]
[]
11
"""Classes for representing mypy types.""" import sys from abc import abstractmethod from collections import OrderedDict from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence, Iterator, ) from typing_extensions import ClassVar, Final, TYPE_CHECKING i...
null
v33
[ "v11" ]
v0
def v33(self, v34: v11) -> v0: if v34.name in self.replacements: return self.replacements[v34.name] return v34
[]
[]
[]
4
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(mypy.nodes.Context):\n v1 = ('can_be_true', 'can_be_false')\n\n def __init__(self, v2: int=-1, v3: int=-1) -> None:\n super().__init__(v2, v3)\n self.can_be_true = self.can_be_true_default()\n self.can_be_false = self.can_be_false_default()\n\n def v4(self) -> bool:\n ...
v13
[ "v0" ]
str
def v13(self, v14: v0) -> str: v15 = v14.typ.accept(self) if v14.name is None: return '{}({})'.format(v14.constructor, v15) else: return '{}({}, {})'.format(v14.constructor, v15, v14.name)
[]
[]
[]
6
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(ProperType):\n v1 = ('typ', 'name', 'constructor')\n v2: Type\n v3: Optional[str]\n v4: Optional[str]\n\n def __init__(self, v5: Type, v6: Optional[str], v7: Optional[str], v8: int=-1, v9: int=-1) -> None:\n super().__init__(v8, v9)\n self.typ = v5\n self.name = v6\n ...
v11
[ "v0" ]
str
def v11(self, v12: v0) -> str: if v12.source is None: return '<Deleted>' else: return "<Deleted '{}'>".format(v12.source)
[]
[]
[]
5
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(ProperType):\n v1 = ('source',)\n v2: Optional[str]\n\n def __init__(self, v3: Optional[str]=None, v4: int=-1, v5: int=-1) -> None:\n super().__init__(v4, v5)\n self.source = v3\n\n def v6(self, v7: 'TypeVisitor[T]') -> T:\n return v7.visit_deleted_type(self)\n\n def v8...
v27
[ "v0" ]
str
def v27(self, v28: v0) -> str: if v28.last_known_value and (not v28.args): v29 = '{}?'.format(v28.last_known_value) else: v29 = v28.type.fullname or v28.type.name or '<???>' if v28.args: if v28.type.fullname == 'builtins.tuple': assert len(v28.args) == 1 v29 +...
[]
[]
[]
14
"""Classes for representing mypy types.""" import contextlib import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence, Generator ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload...
[ "class v0(ProperType):\n v1 = ('type', 'args', 'invalid', 'type_ref', 'last_known_value')\n\n def __init__(self, v2: mypy.nodes.TypeInfo, v3: Sequence[Type], v4: int=-1, v5: int=-1, *, v6: Optional['LiteralType']=None) -> None:\n super().__init__(v4, v5)\n self.type = v2\n self.args = tup...
v25
[ "v0" ]
str
def v25(self, v26: v0) -> str: if v26.name is None: v27 = f'`{v26.id}' else: v27 = f'{v26.name_with_suffix()}`{v26.id}' return v27
[]
[]
[]
6
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(TypeVarLikeType):\n v1 = ('flavor',)\n v2: int\n\n def __init__(self, v3: str, v4: str, v5: Union[TypeVarId, int], v6: int, v7: Type, *, v8: int=-1, v9: int=-1) -> None:\n super().__init__(v3, v4, v5, v7, line=v8, column=v9)\n self.flavor = v6\n\n @staticmethod\n def v10(v11: ...
v23
[ "v0" ]
str
def v23(self, v24: v0) -> str: v25 = [] for v26 in v24.items: v25.append(v26.accept(self)) return 'Overload({})'.format(', '.join(v25))
[]
[]
[]
5
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(FunctionLike):\n v1 = ('_items', 'fallback')\n v2: List[CallableType]\n\n def __init__(self, v3: List[CallableType]) -> None:\n super().__init__(v3[0].line, v3[0].column)\n self._items = v3\n self.fallback = v3[0].fallback\n\n @property\n def v4(self) -> List[CallableTy...
v31
[ "v0" ]
str
def v31(self, v32: v0) -> str: v33 = self.list_str(v32.items) if v32.partial_fallback and v32.partial_fallback.type: v34 = v32.partial_fallback.type.fullname if v34 != 'builtins.tuple': return 'Tuple[{}, fallback={}]'.format(v33, v32.partial_fallback.accept(self)) return 'Tuple[{...
[]
[]
[]
7
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(ProperType):\n v1 = ('items', 'partial_fallback', 'implicit')\n v2: List[Type]\n v3: Instance\n v4: bool\n\n def __init__(self, v5: List[Type], v6: Instance, v7: int=-1, v8: int=-1, v9: bool=False) -> None:\n self.partial_fallback = v6\n self.items = v5\n self.implicit ...
v9
[ "v0" ]
str
def v9(self, v10: v0) -> str: v11 = v10.type.accept(self) return '*{}'.format(v11)
[]
[]
[]
3
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(ProperType):\n v1 = ('type',)\n v2: Type\n\n def __init__(self, v3: Type, v4: int=-1, v5: int=-1) -> None:\n super().__init__(v4, v5)\n self.type = v3\n\n def v6(self, v7: 'TypeVisitor[T]') -> T:\n assert isinstance(v7, SyntheticTypeVisitor)\n return v7.visit_star_t...
v36
[ "v0" ]
str
def v36(self, v37: v0) -> str: v38 = self.list_str(v37.items) return 'Union[{}]'.format(v38)
[]
[]
[]
3
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(ProperType):\n v1 = ('items', 'is_evaluated', 'uses_pep604_syntax')\n\n def __init__(self, v2: Sequence[Type], v3: int=-1, v4: int=-1, v5: bool=True, v6: bool=False) -> None:\n super().__init__(v3, v4)\n self.items = flatten_nested_unions(v2)\n self.can_be_true = any((item.can_b...
v10
[ "v0" ]
str
def v10(self, v11: v0) -> str: if v11.type is None: return '<partial None>' else: return '<partial {}[{}]>'.format(v11.type.name, ', '.join(['?'] * len(v11.type.type_vars)))
[]
[]
[]
5
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(ProperType):\n v1 = ('type', 'var', 'value_type')\n v2: Optional[mypy.nodes.TypeInfo]\n v3: mypy.nodes.Var\n v4: Optional[Instance]\n\n def __init__(self, v5: 'Optional[mypy.nodes.TypeInfo]', v6: 'mypy.nodes.Var', v7: 'Optional[Instance]'=None) -> None:\n super().__init__()\n ...
v11
[ "Iterable[v0]" ]
str
def v11(self, v12: Iterable[v0]) -> str: v13 = [] for v14 in v12: v13.append(v14.accept(self)) return ', '.join(v13)
[]
[]
[]
5
"""Classes for representing mypy types.""" import copy import sys from abc import abstractmethod from typing import ( Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple, Sequence ) from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias f...
[ "class v0(mypy.nodes.Context):\n v1 = ('can_be_true', 'can_be_false')\n\n def __init__(self, v2: int=-1, v3: int=-1) -> None:\n super().__init__(v2, v3)\n self.can_be_true = self.can_be_true_default()\n self.can_be_false = self.can_be_false_default()\n\n def v4(self) -> bool:\n ...
v0
[ "List[int]" ]
int
def v0(self, v1: List[int]) -> int: v2 = 9999999 v3 = 0 v4 = 0 for v5 in v1: if v5 < v2: v2 = v5 v3 = v2 if v5 > v3: v3 = v5 v4 = max(v4, v3 - v2) return v4
[]
[]
[]
12
from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: """ 只能交易一次 """ min_price = 9999999 max_price = 0 res = 0 for n in prices: # 如果更新了 min_price,那之前的 max_price 就不能用了 if n < min_price: ...
null
v0
[ "list", "Any" ]
Any
def v0(v1: list, v2=get_position_attractiveness_by_position): print('\nQuantity of states {}\n\n{}'.format(len(v1), '#' * 50)) for v3 in v1: v3.beautiful_print_position() print('\nAttractiveness: ', v2(v3)) print('\n\n{}'.format('#' * 50))
[]
[]
[]
6
from state import State GOAL_POSITION = [ [1, 2, 3], [-1, 8, 4], [7, 6, 5] ] STARTING_POSITION = [ [2, 8, 3], [1, 6, 4], [7, -1, 5] ] H_LIMIT = 100_000 def check_optimum2(position: State) -> bool: return True if position.data == GOAL_POSITION else False def check_optimum(position: Sta...
null
v0
[ "torch.Tensor", "torch.Tensor" ]
Any
def v0(self, v1: torch.Tensor, v2: torch.Tensor): self.net.zero_grad() v3 = self.net(v1) v4 = self.loss(v3, v2) v4.backward() self.optimizer.step()
[]
[]
[]
6
import collections import inspect import typing import numpy as np import pandas as pd import torch from river import base __all__ = ["PyTorch2RiverBase", "PyTorch2RiverRegressor", "PyTorch2RiverClassifier"] class PyTorch2RiverBase(base.Estimator): """An estimator that integrates neural Networks from PyTorch."...
null
v0
[ "dict", "base.typing.ClfTarget" ]
base.Classifier
def v0(self, v1: dict, v2: base.typing.ClfTarget, **v3) -> base.Classifier: self.classes.update([v2]) if self.net is None: self._init_net(len(list(v1.values()))) if len(self.classes) != self.n_classes: self._update_classes() v4 = {c: 0.0 for v5 in self.classes} v4[v2] = 1.0 v1 = ...
[]
[ "torch" ]
[ "import torch" ]
14
import collections import inspect import typing import numpy as np import pandas as pd import torch from river import base __all__ = ["PyTorch2RiverBase", "PyTorch2RiverRegressor", "PyTorch2RiverClassifier"] class PyTorch2RiverBase(base.Estimator): """An estimator that integrates neural Networks from PyTorch."...
null
v0
[ "dict" ]
typing.Dict[base.typing.ClfTarget, float]
def v0(self, v1: dict) -> typing.Dict[base.typing.ClfTarget, float]: if self.net is None: self._init_net(len(list(v1.values()))) v1 = torch.Tensor(list(v1.values())) self.last_prediction = self.net(v1) v2 = self.last_prediction.detach().numpy().ravel() v3 = {c: 0.0 for v4 in self.classes} ...
[]
[ "torch" ]
[ "import torch" ]
10
import collections import inspect import typing import numpy as np import pandas as pd import torch from river import base __all__ = ["PyTorch2RiverBase", "PyTorch2RiverRegressor", "PyTorch2RiverClassifier"] class PyTorch2RiverBase(base.Estimator): """An estimator that integrates neural Networks from PyTorch."...
null
v0
[ "pd.DataFrame" ]
pd.DataFrame
def v0(self, v1: pd.DataFrame) -> pd.DataFrame: if self.net is None: self._init_net(len(v1.columns)) v2 = torch.Tensor(list(v1.to_numpy())) v3 = self.net(v2).detach().numpy() v4 = {c: [0.0] * len(v1) for v5 in self.classes} for (v6, v7) in enumerate(self.classes): v4[v7] = v3[v6] ...
[]
[ "pandas", "torch" ]
[ "import pandas as pd", "import torch" ]
9
import collections import inspect import typing import numpy as np import pandas as pd import torch from river import base __all__ = ["PyTorch2RiverBase", "PyTorch2RiverRegressor", "PyTorch2RiverClassifier"] class PyTorch2RiverBase(base.Estimator): """An estimator that integrates neural Networks from PyTorch."...
null
v0
[ "pd.DataFrame", "pd.Series" ]
Any
def v0(self, v1: pd.DataFrame, v2: pd.Series, **v3): if self.net is None: self._init_net(n_features=len(v1.columns)) v4 = torch.Tensor(v1.to_numpy()) v2 = torch.Tensor([v2]) self._learn_one(x=v4, y=v2) return self
[]
[ "torch" ]
[ "import torch" ]
7
import collections import inspect import typing import numpy as np import pandas as pd import torch from river import base __all__ = ["PyTorch2RiverBase", "PyTorch2RiverRegressor", "PyTorch2RiverClassifier"] class PyTorch2RiverBase(base.Estimator): """An estimator that integrates neural Networks from PyTorch."...
null
v0
[ "pd.DataFrame" ]
pd.Series
def v0(self, v1: pd.DataFrame) -> pd.Series: if self.net is None: self._init_net(len(v1.columns)) v2 = torch.Tensor(v1.to_numpy()) return pd.Series(self.net(v2).item())
[]
[ "pandas", "torch" ]
[ "import pandas as pd", "import torch" ]
5
import collections import inspect import typing import numpy as np import pandas as pd import torch from river import base __all__ = ["PyTorch2RiverBase", "PyTorch2RiverRegressor", "PyTorch2RiverClassifier"] class PyTorch2RiverBase(base.Estimator): """An estimator that integrates neural Networks from PyTorch."...
null
v0
[ "Optional[basic.DateTime]", "str" ]
Optional[datetime]
def v0(v1: Optional[basic.DateTime], v2: str='%Y-%m-%dT%H:%M:%S%z') -> Optional[datetime]: if v1 is None: return return datetime.strptime(str(v1.__root__), v2)
[]
[ "datetime" ]
[ "from datetime import datetime, timedelta" ]
4
# Copyright 2021 Collate # 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, software...
null
v0
[]
ItemsView
def v0(self) -> ItemsView: v1 = self.get_head() for (v2, v3) in self.__references.items(): v4 = self.__floor_to_version(v3, v1) if v4 is not None: yield (v2, self.__get_obj(v4))
[]
[]
[]
6
from __future__ import print_function import hashlib import os import socket import threading import time import weakref from collections import Mapping from typing import ValuesView, ItemsView import dill from pysyncobj import replicated, SyncObjConsumer from pysyncobj.batteries import ReplDict class ReplEventDict...
null
v0
[ "str", "List[List[int]]" ]
str
def v0(self, v1: str, v2: List[List[int]]) -> str: v3 = [xter for v4 in v1] for v5 in v2: if v5[0] == 0: v6 = 0 while v6 < v5[1]: v7 = v3.pop(0) v3.append(v7) v6 += 1 elif v5[0] == 1: v6 = 0 while v6 ...
[]
[]
[]
17
from typing import List class Solution: def stringShift(self, s: str, shift: List[List[int]]) -> str: sList = [xter for xter in s] for shiftx in shift: if shiftx[0] == 0: position = 0 while position < shiftx[1]: tempPop = sList.pop(0) ...
null
v0
[]
logging.Logger
def v0(self) -> logging.Logger: if self.__logger is None: self.__logger = logging.getLogger('code2vec') self.__logger.setLevel(logging.INFO) self.__logger.handlers = [] self.__logger.propagate = 0 v1 = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s') if se...
[]
[ "logging", "sys" ]
[ "import logging", "import sys" ]
18
from math import ceil from typing import Optional import logging from argparse import ArgumentParser import sys import os class Config: @classmethod def arguments_parser(cls) -> ArgumentParser: parser = ArgumentParser() parser.add_argument("-d", "--data", dest="data_path", ...
null
v0
[]
'PostgresModelState'
def v0(self) -> 'PostgresModelState': v1 = super().clone() return self._pre_clone(v1)
[]
[]
[]
3
from collections.abc import Mapping from typing import Type from django.db.migrations.state import ModelState from django.db.models import Model from psqlextra.models import PostgresModel class PostgresModelState(ModelState): """Base for custom model states. We need this base class to create some hooks int...
null
v0
[ "list", "float" ]
float
def v0(v1: list, v2: float) -> float: v3 = 0.0 v4 = 0.0 v5 = len(v1) for v6 in v1: v3 += v6 v4 += v6 * v6 v3 = v3 / 2 v4 = v4 / 12 v7 = (v2 - v3) / sqrt(v4) return norm.cdf(v7)
[]
[ "math", "scipy" ]
[ "from scipy.stats import norm", "from math import sqrt, log, exp" ]
11
from algorithm import DC_Checker from stn import STN, loadSTNfromJSONfile from relax import relaxSearch from scipy.stats import norm from math import sqrt, log, exp from typing import List ## # \file probability.py # \brief Computing some probabilities for degree of dynamic controllability ## # \fn prob_small_sum(l...
null
v0
[ "list", "float" ]
float
def v0(v1: list, v2: float) -> float: v3 = len(v1) v4 = v3 * log(sum(v1) - v2) v5 = [log(l) for v6 in v1] v7 = [log(m) for v8 in range(1, v3 + 1)] v9 = sum(v5) + sum(v7) v10 = v4 - v9 v11 = exp(v10) return v11
[]
[ "math" ]
[ "from math import sqrt, log, exp" ]
9
from algorithm import DC_Checker from stn import STN, loadSTNfromJSONfile from relax import relaxSearch from scipy.stats import norm from math import sqrt, log, exp from typing import List ## # \file probability.py # \brief Computing some probabilities for degree of dynamic controllability ## # \fn prob_small_sum(l...
null
v8
[ "List[list]", "List[float]" ]
Any
def v8(v9: List[list], v10: List[float]): v11 = 1.0 v12 = len(v9) assert len(v10) == v12, 'The input lists have different lengths!' for v13 in range(v12): v11 = v11 * v0(v9[v13], v10[v13]) return v11
[ { "name": "v0", "input_types": [ "list", "float" ], "output_type": "float", "code": "def v0(v1: list, v2: float) -> float:\n v3 = 0.0\n v4 = 0.0\n v5 = len(v1)\n for v6 in v1:\n v3 += v6\n v4 += v6 * v6\n v3 = v3 / 2\n v4 = v4 / 12\n v7 = (v2 - v3) ...
[ "math", "scipy" ]
[ "from scipy.stats import norm", "from math import sqrt, log, exp" ]
7
from algorithm import DC_Checker from stn import STN, loadSTNfromJSONfile from relax import relaxSearch from scipy.stats import norm from math import sqrt, log, exp from typing import List ## # \file probability.py # \brief Computing some probabilities for degree of dynamic controllability ## # \fn prob_small_sum(l...
null
v14
[ "telegram.Bot" ]
None
def v14(v15: telegram.Bot) -> None: if datetime.now().hour != 22: return v6(v15)
[ { "name": "v0", "input_types": [ "telegram.Bot" ], "output_type": "None", "code": "def v0(v1: telegram.Bot) -> None:\n if 'anon_chat_id' not in CONFIG:\n return\n v2 = f'{Khaleesi.khaleesi(get_hour(datetime.now()))} 🐉'\n v1.send_message(CONFIG['anon_chat_id'], v2)", "d...
[ "datetime", "random", "threading" ]
[ "import random", "from datetime import datetime", "from threading import Timer" ]
4
""" Рядовой ночной стражи """ import random from datetime import datetime from threading import Timer import pytils import telegram from src.config import CONFIG from src.commands.khaleesi.khaleesi import Khaleesi def go_go_watchmen(bot: telegram.Bot) -> None: """ Стражник смотрит на часы: а пора ли уже идт...
null
v10
[ "telegram.Bot" ]
None
def v10(v11: telegram.Bot) -> None: v12 = v3() v13 = Timer(v12, v0, args=[v11]) v13.start()
[ { "name": "v0", "input_types": [ "telegram.Bot" ], "output_type": "None", "code": "def v0(v1: telegram.Bot) -> None:\n if 'anon_chat_id' not in CONFIG:\n return\n v2 = f'{Khaleesi.khaleesi(get_hour(datetime.now()))} 🐉'\n v1.send_message(CONFIG['anon_chat_id'], v2)", "d...
[ "datetime", "random", "threading" ]
[ "import random", "from datetime import datetime", "from threading import Timer" ]
4
""" Рядовой ночной стражи """ import random from datetime import datetime from threading import Timer import pytils import telegram from src.config import CONFIG from src.commands.khaleesi.khaleesi import Khaleesi def go_go_watchmen(bot: telegram.Bot) -> None: """ Стражник смотрит на часы: а пора ли уже идт...
null
v0
[]
int
def v0() -> int: v1 = 60 * 60 v2 = random.randint(1 * v1, 6 * v1) return v2
[]
[ "random" ]
[ "import random" ]
4
""" Рядовой ночной стражи """ import random from datetime import datetime from threading import Timer import pytils import telegram from src.config import CONFIG from src.commands.khaleesi.khaleesi import Khaleesi def go_go_watchmen(bot: telegram.Bot) -> None: """ Стражник смотрит на часы: а пора ли уже идт...
null
v0
[ "str", "int" ]
str
def v0(v1: str, v2: int=0) -> str: v3 = binascii.hexlify(v1.encode()).decode() v4 = len(v3) if v4 < v2: return v3 + '0' * (v2 - v4) return v3
[]
[ "binascii" ]
[ "import binascii" ]
6
import binascii import logging import time from typing import Dict, Optional, Mapping, Iterable, Sequence import re from opentrons.drivers.types import ( Temperature, PlateTemperature, RPM, HeaterShakerPlateLockStatus, ) log = logging.getLogger(__name__) # Number of digits after the decimal point for...
null
v0
[ "int" ]
list[tuple[int, int, int, int, int, int]]
def v0(v1: int) -> list[tuple[int, int, int, int, int, int]]: if v1 == 2: return [(1, 0, 0, 0, 0, 0), (0, 1, 0, 0, 0, 0), (0, 0, 1, 0, 0, 0), (0, 0, 0, 2, 0, 0), (0, 0, 0, 0, 2, 0), (0, 0, 0, 0, 0, 2)] if v1 == 3: return [(1, 0, 0, 0, 0, 0), (0, 1, 0, 0, 0, 0), (0, 0, 1, 0, 0, 0), (0, 0, 0, 2, 0...
[]
[]
[]
6
"""Tools for calculating elastic tensors.""" from __future__ import annotations __all__ = ["get_default_strain_states"] def get_default_strain_states(order: int) -> list[tuple[int, int, int, int, int, int]]: """ Generate a list of strain-states for calculating 2nd or 3rd order elastic tensors. Paramete...
null
v0
[ "str", "List[str]" ]
str
def v0(v1: str, v2: List[str]) -> str: v3 = '' for v4 in v2: (v5, v6) = os.path.split(v4) if v1.startswith(v6[:-3]): v3 = v4 return v3
[]
[ "os" ]
[ "import os" ]
7
"""This module provides functions that relate to link.""" import os import re from html.parser import HTMLParser from typing import Any, Dict, List from mkapi.core.object import get_fullname from mkapi.core.regex import LINK_PATTERN def link(name: str, href: str) -> str: """Reutrns Markdown link with a mark that...
null
v0
[ "str", "Dict[int, List[str]]", "bool" ]
None
def v0(self, v1: str, v2: Dict[int, List[str]], v3: bool=False) -> None: self.ignored_lines[v1] = v2 if v3: self.ignored_files.add(v1)
[]
[]
[]
4
import os.path import sys import traceback from mypy.ordered_dict import OrderedDict from collections import defaultdict from typing import Tuple, List, TypeVar, Set, Dict, Optional, TextIO, Callable from typing_extensions import Final from mypy.scope import Scope from mypy.options import Options from mypy.version im...
null
v0
[]
Optional[str]
def v0(self) -> Optional[str]: if self.scope is not None: return self.scope.current_target() return self.target_module
[]
[]
[]
4
import os.path import sys import traceback from mypy.ordered_dict import OrderedDict from collections import defaultdict from typing import Tuple, List, TypeVar, Set, Dict, Optional, TextIO, Callable from typing_extensions import Final from mypy.scope import Scope from mypy.options import Options from mypy.version im...
null
v29
[ "str", "v0" ]
None
def v29(self, v30: str, v31: v0) -> None: assert v30 not in self.flushed_files if v30 not in self.error_info_map: self.error_info_map[v30] = [] self.error_info_map[v30].append(v31)
[]
[]
[]
5
import os.path import sys import traceback from mypy.ordered_dict import OrderedDict from collections import defaultdict from typing import Tuple, List, TypeVar, Set, Dict, Optional, TextIO, Callable from typing_extensions import Final from mypy.scope import Scope from mypy.options import Options from mypy.version im...
[ "class v0:\n v1 = None\n v2 = ''\n v3 = None\n v4 = ''\n v5 = ''\n v6 = 0\n v7 = 0\n v8 = ''\n v9 = ''\n v10 = None\n v11 = False\n v12 = False\n v13 = None\n v14 = None\n\n def __init__(self, v15: List[Tuple[str, int]], v16: str, v17: Optional[str], v18: Optional[str], ...