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" ]
typing.List[str]
def v0(self, v1: str) -> typing.List[str]: v2 = os.pathsep if v2 == ';': v1 = re.sub(':([^/\\\\])', ';\\1', v1) v3 = [p for v4 in v1.split(v2) if v4] v5 = [] for v4 in v3: v6 = pathlib.Path(v4) v7 = v6.as_posix() if v6.exists(): if v7 not in v5: ...
[]
[ "os", "pathlib", "re" ]
[ "import os", "import pathlib", "import re" ]
19
# Copyright 2019 The meson development team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
null
v0
[ "'Environment'", "str" ]
typing.List[str]
def v0(self, v1: 'Environment', v2: str) -> typing.List[str]: v3 = self._get_search_dirs(v1) for v4 in v3.split('\n'): if v4.startswith(v2 + ':'): return self._split_fetch_real_dirs(v4.split('=', 1)[1]) return []
[]
[]
[]
6
# Copyright 2019 The meson development team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
null
v0
[ "str" ]
typing.List[str]
def v0(self, v1: str) -> typing.List[str]: if v1 == 'none': return [] v2 = ['-fsanitize=' + v1] if 'address' in v1: v2.append('-fno-omit-frame-pointer') return v2
[]
[]
[]
7
# Copyright 2019 The meson development team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
null
v0
[ "str", "bool" ]
typing.List[str]
def v0(self, v1: str, v2: bool) -> typing.List[str]: if not v1: v1 = '.' if v2: return ['-isystem' + v1] return ['-I' + v1]
[]
[]
[]
6
# Copyright 2019 The meson development team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
null
v0
[ "str" ]
typing.Optional[str]
def v0(self, v1: str) -> typing.Optional[str]: if v1 in self.defines: return self.defines[v1] return None
[]
[]
[]
4
# Copyright 2019 The meson development team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
null
v0
[ "T.List[str]", "'Environment'", "str", "str" ]
T.Tuple[bool, bool]
def v0(self, v1: T.List[str], v2: 'Environment', v3: str, v4: str) -> T.Tuple[bool, bool]: with self._build_wrapper(v3, v2, v1, None, v4) as v5: v6 = v5.returncode == 0 if self.language in {'cpp', 'objcpp'} and 'is valid for C/ObjC' in v5.stderr: v6 = False if self.language in {'...
[]
[]
[]
8
# Copyright 2019 The meson development team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
null
v0
[ "Dict[str, Any]", "Tuple[str, ...]" ]
List[str]
def v0(v1: Dict[str, Any], v2: Tuple[str, ...]) -> List[str]: v3: List[str] = [] for v4 in v1['files']: if v4['path'].lower().endswith(v2): v3.append(v4['path']) return v3
[]
[]
[]
6
import json from typing import Any, Dict, List, Tuple import boto3 from topo_processor.util.aws_files import create_s3_manifest, s3_download from topo_processor.util.configuration import temp_folder from topo_processor.util.s3 import is_s3_path def load_manifest(manifest_path: str) -> Dict[str, Any]: if is_s3_p...
null
v0
[ "DataFrame", "DataFrame" ]
Any
def v0(self, v1: DataFrame, v2: DataFrame=None, **v3): if self.is_fit: raise AssertionError('Learner is already fit.') self._validate_fit_input(X=v1, X_val=v2, **v3) return self._fit(X=v1, X_val=v2, **v3)
[]
[]
[]
5
import copy import json import logging import os import random import time import warnings from collections import OrderedDict from collections.abc import Iterable import numpy as np import pandas as pd from pandas import DataFrame, Series from sklearn.metrics import classification_report from autogluon.core.constant...
null
v0
[ "DataFrame" ]
Any
def v0(self, v1: DataFrame, **v2): if self.label not in v1.columns: raise KeyError(f"Label column '{self.label}' is missing from training data. Training data columns: {list(v1.columns)}") v3 = v2.get('X_val', None) self._validate_sample_weight(v1, v3) self._validate_groups(v1, v3)
[]
[]
[]
6
import copy import json import logging import time from collections.abc import Iterable import numpy as np import pandas as pd from pandas import DataFrame, Series from sklearn.metrics import classification_report from autogluon.core.constants import BINARY, MULTICLASS, REGRESSION, QUANTILE, AUTO_WEIGHT, BALANCE_WEIG...
null
v0
[ "Any", "Any", "list", "Any" ]
Any
def v0(self, v1=None, v2=None, v3: list=None, v4=True): if v2 is not None or v3 is not None: if v2 is not None and v3 is not None: raise AssertionError('Only one of `model`, `base_models` is allowed to be set.') v5 = self.load_trainer() if v1 is None: if v5.bagged_mode: ...
[]
[]
[]
21
import copy import json import logging import os import random import time import warnings from collections import OrderedDict import numpy as np import pandas as pd from numpy import corrcoef from pandas import DataFrame, Series from sklearn.metrics import accuracy_score, balanced_accuracy_score, matthews_corrcoef, f...
null
v0
[ "Any", "Any", "Any", "list", "Any", "Any", "Any" ]
DataFrame
def v0(self, v1=None, v2=None, v3=None, v4: list=None, v5='original', v6=1000, v7=False, **v8) -> DataFrame: v9 = ['original', 'transformed', 'transformed_model'] if v5 not in v9: raise ValueError(f'feature_stage must be one of: {v9}, but was {v5}.') v10 = self.load_trainer() if v2 is not None: ...
[]
[]
[]
21
import copy import json import logging import os import random import time import warnings from collections import OrderedDict from collections.abc import Iterable import numpy as np import pandas as pd from pandas import DataFrame, Series from sklearn.metrics import classification_report from autogluon.core.constant...
null
v0
[ "Any", "Any", "Any", "Any" ]
list
def v0(self, v1=False, v2='all', v3=False, v4=None) -> list: self.trainer = self.load_trainer() if not v1: return self.trainer.persist_models(v2, with_ancestors=v3, max_memory=v4) else: return []
[]
[]
[]
6
import copy import json import logging import os import random import time import warnings from collections import OrderedDict from collections.abc import Iterable import numpy as np import pandas as pd from pandas import DataFrame, Series from sklearn.metrics import classification_report from autogluon.core.constant...
null
v0
[ "Dict", "List[Dict]", "int", "str", "Any", "Any" ]
Any
def v0(v1: Dict, v2: List[Dict], v3: int=5, v4: str='broader_counts', v5=False, v6=0.1): v7 = [] v8 = dict() for (v9, v10) in v1.items(): for v11 in v10: v8[v11] = v8.get(v11, 0) + 1 v12 = [] for v13 in v2: v14 = {x: y for (v15, v16) in v13[v4].items() if v16 > v6 * len(v...
[]
[ "math" ]
[ "import math" ]
32
import math from typing import List, Dict, Set from linking.entity_linker import EntityLinker from linking.utils import is_uri from linking.dummy_linker import DummyLinker as DuLi from scipy.stats import binom import numpy as np def link_and_find_broaders(candidates: List[Dict], linker: Ent...
null
v4
[ "v0" ]
Any
def v4(self, v5: v0): v6 = Queue() v6.put([v5]) v7 = [] while not v6.empty(): v8 = [] v9 = [] v10 = v6.get() for v11 in v10: if v11 is None: continue v8.append(v11.val) v9.append(v11.left) v9.append(v11.right...
[]
[ "queue" ]
[ "from queue import Queue" ]
19
# -*- coding: utf-8 -*- """ 107. Binary Tree Level Order Traversal II Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). """ from queue import Queue # Definition for a binary tree node. class TreeNode: def __init__(sel...
[ "class v0:\n\n def __init__(self, v1=0, v2=None, v3=None):\n self.val = v1\n self.left = v2\n self.right = v3" ]
v0
[ "int", "str", "int" ]
None
async def v0(self, v1: int, v2: str, v3: int) -> None: v4 = [v1, v2, v3] self.added_port_mappings.append(v4)
[]
[]
[]
3
"""Test UPnP/IGD setup process.""" from ipaddress import IPv4Address from asynctest import patch from homeassistant.components import upnp from homeassistant.components.upnp.device import Device from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.setup import async_setup_component from tests...
null
v0
[ "int" ]
None
async def v0(self, v1: int) -> None: v2 = v1 self.removed_port_mappings.append(v2)
[]
[]
[]
3
"""Test UPnP/IGD setup process.""" from ipaddress import IPv4Address from asynctest import patch from homeassistant.components import upnp from homeassistant.components.upnp.device import Device from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.setup import async_setup_component from tests...
null
v0
[ "List[int]" ]
int
def v0(self, v1: List[int]) -> int: v2 = len(v1) if v2 == 0: return 0 elif v2 < 3: return min(v1) else: for v3 in range(2, v2): v1[v3] = v1[v3] + min(v1[v3 - 1], v1[v3 - 2]) return min(v1[v3 - 1], v1[v3])
[]
[]
[]
10
import unittest from typing import List class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: len_cost = len(cost) if len_cost == 0: return 0 elif len_cost < 3: return min(cost) else: for i in range(2, len_cost): ...
null
v0
[ "List[int]" ]
None
def v0(self, v1: List[int]) -> None: v2 = 0 v3 = 0 v4 = len(v1) while v3 < v4: if v1[v3] == 0: v2 += 1 v4 -= 1 v3 += 1 v5 = v4 + 1 == v3 if v5: v2 -= 1 v3 = len(v1) - 1 - v2 v4 = v3 + 1 v6 = len(v1) for v3 in range(v3, -1, -1): ...
[]
[]
[]
27
import unittest from typing import List import utils # O(n) time. O(1) space. Array. class Solution: def duplicateZeros(self, arr: List[int]) -> None: """ Do not return anything, modify arr in-place instead. """ num_zeros = 0 lo = 0 hi = len(arr) while lo ...
null
v0
[]
argparse.Namespace
def v0() -> argparse.Namespace: v1 = argparse.ArgumentParser(description='Neural model for NLP') v1.add_argument('--joint_input', type=str, default='./data/onto/joint_char/', help='path of input data') v1.add_argument('--parsing_input', type=str, default='./data/onto/parsing_char/', help='path of input data...
[]
[ "argparse" ]
[ "import argparse" ]
53
# @Author : guopeiming # @Contact : guopeiming.gpm@{qq, gmail}.com import argparse def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description='Neural model for NLP') # [Data] parser.add_argument('--joint_input', type=str, default='./data/onto/joint_char/', help='path of input da...
null
v0
[ "str", "Any" ]
Any
def v0(self, v1: str, v2): v3 = os.environ[v1] if all([v1 in os.environ, self.envDistributed]) else v2 if isinstance(v2, int): v3 = int(v3) elif isinstance(v2, str): v3 = str(v3) return v3
[]
[ "os" ]
[ "import os" ]
7
import os import logging import torch from torch.backends import cudnn from datetime import datetime from lib import fileTool as FT from pathlib import Path from tensorboardX import SummaryWriter class Config(object): def __init__(self, gpuList=None, envDistributed=False, expName='gopro_gn_Test'): super(C...
null
v0
[ "Any" ]
bool
def v0(self, v1) -> bool: for v2 in self.leaves: if v2.beginDateTime < v1 and v2.endDateTime > v1 and (v2.status == 1): return True return False
[]
[ "datetime" ]
[ "from datetime import date, datetime" ]
5
import os from datetime import date, datetime from flask import Flask from flask_sqlalchemy import SQLAlchemy from werkzeug.security import check_password_hash, generate_password_hash from .. import db from ..exceptions import PasswordNotCorrectError from .Department import Department from .Leave import Leave from .O...
null
v0
[ "str" ]
None
def v0(v1: str) -> None: v2 = Image.open(f'media/{v1}') v3 = (300, 300) v2 = v2.resize(v3) print(f'media/{v1}') v2.save(f'media/{v1}')
[]
[ "PIL" ]
[ "from PIL import Image" ]
6
from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.urls import reverse_lazy from .forms import UserRegistrationForm, ProfileEditForm from .models import Customers from PIL import Image from django.views import generic from django.contrib.auth.decorators import ...
null
v0
[ "Any", "bool" ]
list[str]
def v0(self, v1=None, v2: bool=False) -> list[str]: if v2 == True: v3 = '{0}.*?(?<!\\\\){1}' else: v3 = '{0}.*?{1}' if type(v1) is not list and type(v1) is not tuple: v1 = [v1] v1 = [e for v4 in v1 if v4 is not None] if '' in v1: raise ValueError('empty enclosure') ...
[]
[ "re" ]
[ "import re" ]
24
import re from typing import SupportsIndex class sstr(str): def __init__(self, string: str) -> None: self = string def divide(self, enclosure=None, consider_escape: bool = False) -> list[str]: if consider_escape == True: template = "{0}.*?(?<!\\\\){1}" else: ...
null
v0
[ "Any" ]
bool
def v0(self, v1=None) -> bool: v2 = '{0}.*{1}' if type(v1) is not list and type(v1) is not tuple: v1 = [v1] v1 = [e for v3 in v1 if v3 is not None] if '' in v1: raise ValueError('empty enclosure') if v1 == []: return False v4 = '' for v3 in v1: if type(v3) is ...
[]
[ "re" ]
[ "import re" ]
18
import re from typing import SupportsIndex class sstr(str): def __init__(self, string: str) -> None: self = string def divide(self, enclosure=None, consider_escape: bool = False) -> list[str]: if consider_escape == True: template = "{0}.*?(?<!\\\\){1}" else: ...
null
v0
[ "str", "Optional[datetime]", "Optional[timedelta]" ]
str
def v0(self, v1: str, v2: Optional[datetime]=None, v3: Optional[timedelta]=None) -> str: v4 = self.decode_refresh(v1) v5 = v4.audience v6 = self.access.create_session(v5, v2, v3) return self.encode_access(v6)
[]
[]
[]
5
# -*- coding: utf-8 -*- import os from jwt import encode as jwt_encode from jwt import decode as jwt_decode from typing import Optional, Tuple from datetime import datetime, timedelta from recc.chrono.datetime import today VERIFY_AUDIENCE_OPTION_KEY = "verify_aud" VERIFY_ISSUED_AT_OPTION_KEY = "verify_iat" VERIFY_EXP...
null
v0
[ "str", "int" ]
socket.AddressFamily
def v0(v1: str, v2: int) -> socket.AddressFamily: if v1.startswith('unix://'): return socket.AF_UNIX elif ':' in v1 and hasattr(socket, 'AF_INET6'): return socket.AF_INET6 return socket.AF_INET
[]
[ "socket" ]
[ "import socket" ]
6
"""A WSGI and HTTP server for use **during development only**. This server is convenient to use, but is not designed to be particularly stable, secure, or efficient. Use a dedicate WSGI server and HTTP server when deploying to production. It provides features like interactive debugging and code reloading. Use ``run_si...
null
v7
[ "str", "Optional[int]" ]
Any
def v7(v8: str, v9: Optional[int]=None): v10 = v5(v8) v11 = v0(v8, v9, v10) with socket.socket(v10, socket.SOCK_STREAM) as v12: v12.bind(v11)
[ { "name": "v0", "input_types": [ "str", "Optional[int]", "int" ], "output_type": "Union[tuple, str, bytes]", "code": "def v0(v1: str, v2: Optional[int], v3: int) -> Union[tuple, str, bytes]:\n if v3 == af_unix:\n return v1.split('://', 1)[1]\n try:\n v4 = so...
[ "socket" ]
[ "import socket" ]
5
import socket import sys from importlib import import_module from os import walk, path, mkdir from os.path import abspath, dirname, exists, join from typing import Union, Optional, TYPE_CHECKING, Tuple import grpc_tools.protoc import pkg_resources from jinja2 import Environment, FileSystemLoader from grpcalchemy.conf...
null
v0
[ "str", "set", "str" ]
Any
def v0(v1: str, v2: set, v3: str): v4 = subprocess.Popen(shlex.split(v1), stdout=subprocess.PIPE) while True: v5 = v4.stdout.readline() if not v5 and v4.poll() is not None: break if v5: print(v5.strip().decode('utf-8')) if 'BUILD SUCCESSFUL' in v5.stri...
[]
[ "shlex", "subprocess" ]
[ "import subprocess", "import shlex" ]
10
#!/usr/bin/env python3 ########################################################################################## # Copyright 2020 Adobe. All rights reserved. # This file is licensed to you under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. You may ...
null
v5
[ "str" ]
Any
def v5(v6: str, **v7: bool): v8 = v0(**v7) v6 = v8.clean(v6) return v6
[ { "name": "v0", "input_types": [], "output_type": "Any", "code": "def v0(**v1: bool):\n v2 = bleach.Cleaner([], strip=True)\n for (v3, v4) in v1.items():\n if v3 not in HTMLSerializer.options:\n raise ValueError('Parameter %s is not a valid option for HTMLSerializer' % v3)\n ...
[]
[]
4
# Generated by Django 2.0.2 on 2018-03-11 18:54 import html import bleach from django.core.validators import MaxLengthValidator from django.db import migrations, models from django.template.defaultfilters import truncatechars from html5lib.serializer import HTMLSerializer def get_cleaner(**serializer_kwargs: bool): ...
null
v0
[ "str", "int", "Any" ]
None
def v0(self, v1: str, v2: int, *, v3=None) -> None: if not isinstance(v2, int): raise ValueError(f'Invalid int value for {v1}: {v2!r}') self._send(v1, b'g', int(v2), v3)
[]
[]
[]
4
# Copyright (c) 2019 Aiven, Helsinki, Finland. https://aiven.io/ """ myhoard - statsd Supports Telegraf's statsd protocol extension for 'key=value' tags: https://github.com/influxdata/telegraf/tree/master/plugins/inputs/statsd """ import datetime import enum import logging import os import socket import time from c...
null
v0
[ "str", "Union[float, int, datetime.timedelta]", "Any" ]
None
def v0(self, v1: str, v2: Union[float, int, datetime.timedelta], v3=None) -> None: if isinstance(v2, datetime.timedelta): v2 = v2.total_seconds() v2 = float(v2) self._send(v1, b'ms', v2, v3)
[]
[ "datetime" ]
[ "import datetime" ]
5
# Copyright (c) 2019 Aiven, Helsinki, Finland. https://aiven.io/ """ myhoard - statsd Supports Telegraf's statsd protocol extension for 'key=value' tags: https://github.com/influxdata/telegraf/tree/master/plugins/inputs/statsd """ import datetime import enum import logging import os import socket import time from c...
null
v0
[ "str", "Any", "Any", "Any" ]
Any
def v0(self, v1: str, v2, v3, v4): try: v5 = [v1.encode('utf-8'), b':', str(v3).encode('utf-8'), b'|', v2] v6 = self.tags.copy() v6.update(v4 or {}) for (v7, v8) in sorted(v6.items()): if isinstance(v8, enum.Enum): v8 = v8.value if v8 is None: ...
[]
[ "datetime", "enum" ]
[ "import datetime", "import enum" ]
25
# Copyright (c) 2019 Aiven, Helsinki, Finland. https://aiven.io/ """ myhoard - statsd Supports Telegraf's statsd protocol extension for 'key=value' tags: https://github.com/influxdata/telegraf/tree/master/plugins/inputs/statsd """ import datetime import enum import logging import os import socket import time from c...
null
v0
[ "Any", "Any" ]
np.ndarray
def v0(self, v1=5, v2='median', **v3) -> np.ndarray: if len(self.result.shape) == 1: v4 = self.result.reshape(-1, 1) else: v4 = self.result v5 = np.percentile(v4, q=v1, axis=0) v6 = np.percentile(v4, q=100 - v1, axis=0) if v2 == 'median': v7 = np.median(v4, axis=0) elif v...
[]
[ "numpy" ]
[ "import numpy as np" ]
23
import numpy as np from uncertainty_framework.report._report import Report class MarginReport(Report): """Margin report Report class for returning numerical result margins. The default behavior is to return the (low, high) tuples of the result 95% confidence interval """ def render(self, q...
null
v0
[ "str" ]
bytes
def v0(v1: str) -> bytes: import io v2 = io.BytesIO() with zipfile.ZipFile(v2, 'w', compression=zipfile.ZIP_DEFLATED) as v3: v3.writestr(zinfo_or_arcname='main.py', data=v1) v3.filelist[0].external_attr = 438 << 16 return v2.getvalue()
[]
[ "io", "zipfile" ]
[ "import io", "import zipfile" ]
7
import logging import io import uuid from typing import Dict, Union, Mapping, Generator, Optional from toolz import pipe, merge from toolz.curried import assoc from .basic import (scroll, AWSResource, AwaitableAWSResource, manager_tag_key, standard_tags, get_account_id) from .meta import get_operat...
null
v0
[]
Dict
def v0(self, **v1) -> Dict: v2 = {self.index_id_key: self.index_id} v2.update(v1) return self.service_client.get_function(**v2)
[]
[]
[]
4
import logging import io import uuid from typing import Dict, Union, Mapping, Generator, Optional from toolz import pipe, merge from toolz.curried import assoc from .basic import (scroll, AWSResource, AwaitableAWSResource, manager_tag_key, standard_tags, get_account_id) from .meta import get_operat...
null
v5
[ "ma.MaskedArray", "np.ndarray", "Any" ]
np.ndarray
def v5(self, v6: ma.MaskedArray, v7: np.ndarray, v8) -> np.ndarray: v9 = v8[0][0] v10 = self.thickness if self.thickness is not None else round(math.sqrt(v8.shape[0] * v8.shape[1]) / 150) v11 = round(v10 / 2) for (v12, v13) in zip(v6, v7): v14 = v13.tolist() v15 = 0 for v16 in se...
[ { "name": "v0", "input_types": [ "int" ], "output_type": "Any", "code": "@lru_cache(maxsize=None)\ndef v0(v1: int):\n v2 = c[v1 + idx]\n v3 = colors[v1 % len(component.colors)] * v2 + (1 - v2) * background_color\n return tuple([int(c) for v4 in v3])", "dependencies": [] } ]
[ "cv2", "math", "numpy" ]
[ "import math", "import cv2", "import numpy as np", "import numpy.ma as ma" ]
34
import itertools import math from functools import lru_cache from typing import Tuple, Iterator import cv2 import numpy as np import numpy.ma as ma from tqdm import tqdm from vidgear.gears import WriteGear from .pose import Pose class PoseVisualizer: def __init__(self, pose: Pose, thickness=None): self.pose =...
null
v0
[ "Tuple[int, int, int]", "int" ]
Any
def v0(self, v1: Tuple[int, int, int]=(255, 255, 255), v2: int=None): v3 = np.array(np.around(self.pose.body.data.data), dtype='int32') v4 = np.full((self.pose.header.dimensions.height, self.pose.header.dimensions.width, 3), fill_value=v1, dtype='uint8') for (v5, v6) in itertools.islice(zip(v3, self.pose.bo...
[]
[ "itertools", "numpy" ]
[ "import itertools", "import numpy as np", "import numpy.ma as ma" ]
5
import itertools import math from functools import lru_cache from typing import Tuple, Iterator import cv2 import numpy as np import numpy.ma as ma from tqdm import tqdm from vidgear.gears import WriteGear from .pose import Pose class PoseVisualizer: def __init__(self, pose: Pose, thickness=None): self.pose =...
null
v5
[ "Any", "int", "Any" ]
Any
def v5(self, v6, v7: int=None, v8=False): v9 = np.array(np.around(self.pose.body.data.data), dtype='int32') if v7 is None: v7 = len(v9) def v10(v11): v12 = cv2.VideoCapture(v11) while True: (v13, v14) = v12.read() if not v13: break ...
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n v2 = cv2.VideoCapture(v1)\n while True:\n (v3, v4) = v2.read()\n if not v3:\n break\n yield v4\n v2.release()", "dependencies": [] } ]
[ "cv2", "itertools", "numpy" ]
[ "import itertools", "import cv2", "import numpy as np", "import numpy.ma as ma" ]
20
import itertools import math from functools import lru_cache from typing import Tuple, Iterator import cv2 import numpy as np import numpy.ma as ma from tqdm import tqdm from vidgear.gears import WriteGear from .pose import Pose class PoseVisualizer: def __init__(self, pose: Pose, thickness=None): self.pose =...
null
v0
[]
Set[str]
def v0(self) -> Set[str]: v1 = set() for v2 in self.grammarelts.keys(): if v2 in self.dependency_closure(v2): v1.add(v2) return v1
[]
[]
[]
6
import sys from abc import ABCMeta, abstractmethod from collections import OrderedDict from typing import List, Set, Optional, Dict, Union, Tuple from .parser_utils import as_set from pyjsg.parser_impl.anonymousidentifierfactory import AnonymousIdentifierFactory class PythonGeneratorElement(metaclass=ABCMeta): @...
null
v0
[ "str" ]
Optional[tinydb.database.Document]
async def v0(self, v1: str) -> Optional[tinydb.database.Document]: if v1: v2 = await self.find_by_job_id(v1) if v2: v3 = self.jobs_db.remove(doc_ids=[v2.doc_id]) if v3: return v2
[]
[]
[]
7
# Copyright 2019-2021 Darren Weber # # 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 writ...
null
v0
[ "str" ]
Set[str]
async def v0(self, v1: str) -> Set[str]: if v1: v2 = await self.find_by_job_name(v1) if v2: v3 = {doc.doc_id: doc['job_id'] for v4 in v2} v5 = list(v3.keys()) async with self.db_semaphore: v6 = self.jobs_db.remove(doc_ids=v5) return...
[]
[]
[]
9
# Copyright 2019-2021 Darren Weber # # 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 writ...
null
v0
[ "int", "int", "int", "int" ]
bool
def v0(self, v1: int, v2: int, v3: int, v4: int) -> bool: while v1 < v3 and v2 < v4: (v3, v4) = (v3 % v4, v4 % v3) if v1 == v3 and v2 <= v4: return (v4 - v2) % v1 == 0 elif v2 == v4 and v1 <= v3: return (v3 - v1) % v2 == 0 return False
[]
[]
[]
8
class Solution: # https://leetcode.com/problems/reaching-points/discuss/375429/Detailed-explanation.-or-full-through-process-or-Java-100-beat def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool: while sx < tx and sy < ty: tx, ty = tx % ty, ty % tx # short cut to top pare...
null
v0
[ "np.ndarray", "int", "float" ]
Any
def v0(v1: np.ndarray, v2: int, v3: float): v4 = v3 v5 = 1.0 / v2 v6 = 1 - v5 for v7 in v1: v4 = v6 * v4 + v5 * v7 yield v4
[]
[]
[]
7
# # Indicators to show overbought or oversold position # ---------------------------------------------------- from functools import partial import numpy as np from .base import ( COMMANDS, CommandPreset, ReturnType, arg_period ) from stock_pandas.common import ( period_to_int ) from stock_pandas...
null
v0
[ "str" ]
float
def v0(v1: str) -> float: try: v2 = float(v1) except Exception: raise ValueError(f'init_value must be a float, but got `{v1}`') if v2 < 0.0 or v2 > 100.0: raise ValueError(f'init_value must be in between 0 and 100, but got `{v2}`') return v2
[]
[]
[]
8
# # Indicators to show overbought or oversold position # ---------------------------------------------------- from functools import partial import numpy as np from .base import ( COMMANDS, CommandPreset, ReturnType, arg_period ) from stock_pandas.common import ( period_to_int ) from stock_pandas...
null
v0
[ "Any" ]
None
def v0(v1) -> None: v2 = v1.b64() v3 = base64.decodebytes(v2.encode()) v4 = np.frombuffer(v3, dtype=np.float64) assert np.array2string(v4) == '[1.5 0. 0.25 1. 0. ]'
[]
[ "base64", "numpy" ]
[ "import base64", "import numpy as np" ]
5
import base64 from typing import Any, Mapping import graphql import numpy as np import pytest from graphql.error.graphql_error import GraphQLError from graphql.type.schema import GraphQLSchema, assert_schema from scanspec.service import Points, scanspec_schema from scanspec.specs import Line # Returns a dummy 'poin...
null
v0
[ "np.ndarray" ]
Any
def v0(self, v1: np.ndarray): if self.use_mu: v2 = v1[-self.length:] else: v2 = self.mu_arr (v3, v4, v5) = np.split(v1, self.split_index) v3 = v3.reshape(self.length, self.length) v4 = v4.reshape(self.phi_num, self.length, self.length) v6 = self.y_arr - np.matmul(v4, self.x_arr)....
[]
[ "numpy", "scipy" ]
[ "import numpy as np", "from scipy.optimize import minimize", "from scipy.stats import multivariate_normal" ]
11
import numpy as np from scipy.optimize import minimize from scipy.stats import multivariate_normal from TorchTSA.utils.op import stack_delay_arr_T class VARModel: def __init__( self, _length: int, _phi_num: int, _use_mu: bool = True, ): # fitter params self.length = _l...
null
v0
[ "Union[str, List[str]]" ]
Any
def v0(v1: Union[str, List[str]]): if isinstance(v1, str): return bytes(v1, 'utf-8') if isinstance(v1, list): v2 = (ctypes.c_char_p * len(v1))() v1 = [bytes(d, 'utf-8') for v3 in v1] v2[:] = v1 return v2 raise TypeError()
[]
[]
[]
9
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeV...
null
v0
[ "Any", "Any" ]
List[str]
def v0(v1, v2) -> List[str]: v3 = [] for v4 in range(v2.value): try: v3.append(str(v1[v4].decode('ascii'))) except UnicodeDecodeError: v3.append(str(v1[v4].decode('utf-8'))) return v3
[]
[]
[]
8
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeV...
null
v6
[ "'Booster'", "Optional[int]", "Optional[Tuple[int, int]]" ]
Optional[Tuple[int, int]]
def v6(v7: 'Booster', v8: Optional[int], v9: Optional[Tuple[int, int]]) -> Optional[Tuple[int, int]]: if v8 is not None and v8 != 0: warnings.warn('ntree_limit is deprecated, use `iteration_range` or model slicing instead.', UserWarning) if v9 is not None and v9[1] != 0: raise ValueError...
[ { "name": "v0", "input_types": [ "'Booster'" ], "output_type": "Tuple[int, int]", "code": "def v0(v1: 'Booster') -> Tuple[int, int]:\n v2 = json.loads(v1.save_config())\n v3 = v2['learner']['gradient_booster']['name']\n if v3 == 'gblinear':\n v4 = 0\n elif v3 == 'dart':\...
[ "json", "warnings" ]
[ "import json", "import warnings" ]
10
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" import collections # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any,...
null
v2
[]
Callable
def v2() -> Callable: v3 = ctypes.CFUNCTYPE(None, ctypes.c_char_p) return v3(v0)
[ { "name": "v0", "input_types": [ "bytes" ], "output_type": "None", "code": "def v0(v1: bytes) -> None:\n print(py_str(v1))", "dependencies": [] } ]
[ "ctypes" ]
[ "import ctypes" ]
3
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeV...
null
v0
[ "np.ndarray" ]
bytes
def v0(v1: np.ndarray) -> bytes: assert v1.dtype.hasobject is False, 'Input data contains `object` dtype. Expecting numeric data.' v2 = v1.__array_interface__ if 'mask' in v2: v2['mask'] = v2['mask'].__array_interface__ v3 = bytes(json.dumps(v2), 'utf-8') return v3
[]
[ "json" ]
[ "import json" ]
7
# pylint: disable=too-many-arguments, too-many-branches, too-many-lines # pylint: disable=too-many-return-statements, import-error '''Data dispatching for DMatrix.''' import ctypes from distutils import version import json import warnings import os from typing import Any, Tuple, Callable, Optional, List, Union, Iterato...
null
v3
[ "Any", "Any", "Any" ]
np.ndarray
def v3(v4, v5, v6) -> np.ndarray: v7 = v0(v6) if not isinstance(v4, ctypes.POINTER(v7)): raise RuntimeError(f'expected {v7} pointer') v8 = np.zeros(v5, dtype=v6) if not ctypes.memmove(v8.ctypes.data, v4, v5 * v8.strides[0]): raise RuntimeError('memmove failed') return v8
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n v2 = {np.float32: ctypes.c_float, np.float64: ctypes.c_double, np.uint32: ctypes.c_uint, np.uint64: ctypes.c_uint64, np.int32: ctypes.c_int32, np.int64: ctypes.c_int64}\n if np.intc is not np.int32...
[ "ctypes", "numpy" ]
[ "import ctypes", "import numpy as np" ]
8
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeV...
null
v0
[ "Any", "Any" ]
bytearray
def v0(v1, v2) -> bytearray: if not isinstance(v1, ctypes.POINTER(ctypes.c_char)): raise RuntimeError('expected char pointer') v3 = bytearray(v2) v4 = (ctypes.c_char * v2).from_buffer(v3) if not ctypes.memmove(v4, v1, v2): raise RuntimeError('memmove failed') return v3
[]
[ "ctypes" ]
[ "import ctypes" ]
8
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeV...
null
v0
[ "'Booster'" ]
Tuple[int, int]
def v0(v1: 'Booster') -> Tuple[int, int]: v2 = json.loads(v1.save_config()) v3 = v2['learner']['gradient_booster']['name'] if v3 == 'gblinear': v4 = 0 elif v3 == 'dart': v4 = int(v2['learner']['gradient_booster']['gbtree']['gbtree_model_param']['num_parallel_tree']) elif v3 == 'gbtre...
[]
[ "json" ]
[ "import json" ]
16
# pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals """Core XGBoost Library.""" from abc import ABC, abstractmethod from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeVar from typing import Callable, Tuple, cas...
null
v0
[ "bool", "bool" ]
Tuple[Callable, Callable]
def v0(self, v1: bool, v2: bool) -> Tuple[Callable, Callable]: assert hasattr(self, 'cache_prefix'), '__init__ is not called.' self._reset_callback = ctypes.CFUNCTYPE(None, ctypes.c_void_p)(self._reset_wrapper) self._next_callback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p)(self._next_wrapper) sel...
[]
[]
[]
7
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeV...
null
v0
[]
None
def v0(self) -> None: self._temporary_data = None if self._exception is not None: v1 = self._exception self._exception = None raise v1
[]
[]
[]
6
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeV...
null
v0
[ "None" ]
None
def v0(self, v1: None) -> None: self._temporary_data = None self._handle_exception(self.reset, None)
[]
[]
[]
3
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeV...
null
v0
[ "Union[Dict, List]" ]
Union[Dict, List]
def v0(v1: Union[Dict, List]) -> Union[Dict, List]: if isinstance(v1, dict) and 'eval_metric' in v1 and isinstance(v1['eval_metric'], list): v1 = dict(((k, v) for (v2, v3) in v1.items())) v4 = v1['eval_metric'] v1.pop('eval_metric', None) v5 = list(v1.items()) for v6 in v4: ...
[]
[]
[]
10
# pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals """Core XGBoost Library.""" from abc import ABC, abstractmethod from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeVar from typing import Callable, Tuple, cas...
null
v0
[ "Union[Dict[str, int], str]" ]
str
def v0(self, v1: Union[Dict[str, int], str]) -> str: if isinstance(v1, str): return v1 v2 = set(v1.keys()) if not v2.issubset(set(self.feature_names or [])): raise ValueError('Constrained features are not a subset of training data feature names') return '(' + ','.join([str(v1.get(feature...
[]
[]
[]
7
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeV...
null
v0
[ "Union[List, Dict]" ]
Union[List, Dict]
def v0(self, v1: Union[List, Dict]) -> Union[List, Dict]: if isinstance(v1, dict): v2 = v1.get('monotone_constraints') if v2 is not None: v1['monotone_constraints'] = self._transform_monotone_constrains(v2) v2 = v1.get('interaction_constraints') if v2 is not None: ...
[]
[]
[]
18
# pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals """Core XGBoost Library.""" from abc import ABC, abstractmethod from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeVar from typing import Callable, Tuple, cas...
null
v96
[ "v0", "str", "int" ]
str
def v96(self, v97: v0, v98: str='eval', v99: int=0) -> str: self._validate_features(v97) return self.eval_set([(v97, v98)], v99)
[]
[]
[]
3
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals, no-self-use """Core XGBoost Library.""" # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeV...
[ "class v0:\n\n @_deprecate_positional_args\n def __init__(self, v1, v2=None, *, v3=None, v4=None, v5: Optional[float]=None, v6=False, v7: Optional[List[str]]=None, v8: Optional[List[str]]=None, v9: Optional[int]=None, v10=None, v11=None, v12=None, v13=None, v14=None, v15: bool=False) -> None:\n \"\"\"P...
v98
[ "v0" ]
None
def v98(self, v99: v0) -> None: if v99.num_row() == 0: return if self.feature_names is None: self.feature_names = v99.feature_names self.feature_types = v99.feature_types if v99.feature_names is None and self.feature_names is not None: raise ValueError('training data did not ...
[]
[]
[]
17
# pylint: disable=too-many-arguments, too-many-branches, invalid-name # pylint: disable=too-many-lines, too-many-locals """Core XGBoost Library.""" from abc import ABC, abstractmethod from collections.abc import Mapping from typing import List, Optional, Any, Union, Dict, TypeVar from typing import Callable, Tuple, cas...
[ "class v0:\n\n @_deprecate_positional_args\n def __init__(self, v1, v2=None, *, v3=None, v4=None, v5: Optional[float]=None, v6=False, v7: FeatNamesT=None, v8: Optional[List[str]]=None, v9: Optional[int]=None, v10=None, v11=None, v12=None, v13=None, v14=None, v15: bool=False) -> None:\n \"\"\"Parameters...
v0
[ "int" ]
Any
def v0(self, v1: int): self.spi.open(0, v1) self.spi.mode = 0 self.spi.max_speed_hz = 8000000
[]
[]
[]
4
import spidev from .abstract_transport import AbstractTransport from .gpio_interrupt import GPIOInterrupt class SPITransport(AbstractTransport): __READ_FLAG = 0x80 __MAGNETOMETER_READ_FLAG = 0xC0 __DUMMY = 0xFF data_ready_interrupt: GPIOInterrupt def __init__(self, spi_device: int, m...
null
v0
[ "int" ]
bool
def v0(self, v1: int) -> bool: if self.data_ready_interrupt: return self.data_ready_interrupt.wait_for(v1) else: raise RuntimeError('SPITransport needs a GPIO pin to support data_ready().')
[]
[]
[]
5
import spidev from .abstract_transport import AbstractTransport from .gpio_interrupt import GPIOInterrupt class SPITransport(AbstractTransport): __READ_FLAG = 0x80 __MAGNETOMETER_READ_FLAG = 0xC0 __DUMMY = 0xFF data_ready_interrupt: GPIOInterrupt def __init__(self, spi_device: int, m...
null
v2
[ "int" ]
tf.data.Dataset
def v2(v3: int) -> tf.data.Dataset: def v4(v5: int): return {'data': v5} return tf.data.Dataset.range(v3).map(v4)
[ { "name": "v0", "input_types": [ "int" ], "output_type": "Any", "code": "def v0(v1: int):\n return {'data': v1}", "dependencies": [] } ]
[ "tensorflow" ]
[ "import tensorflow.compat.v2 as tf" ]
5
# Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
null
v0
[ "list" ]
int
def v0(self, v1: list) -> int: v2 = len(v1) if v2 == 1: return 1 v3 = 1 v4 = [1 for v5 in range(v2)] for v6 in range(1, v2): for v7 in range(0, v6): if v1[v7] < v1[v6]: v4[v6] = max(v4[v6], v4[v7] + 1) v3 = max(v4[v6], v3) return v3
[]
[]
[]
12
class Solution: def lengthOfLIS(self, nums:list) -> int: length = len(nums) if length == 1 : return 1 res = 1 # 初始化状态 dp = [1 for _ in range(length)] for i in range(1,length): for j in range(0,i): if nums[j] < nums[i]: ...
null
v0
[ "str" ]
str
def v0(v1: str) -> str: v2 = {'content': 'This is a test', 'discount_code': os.environ['DISCOUNT_CODE'], 'username': v1} return json.dumps(v2)
[]
[ "json", "os" ]
[ "import json", "import os" ]
3
""" Purpose Receives notification from shopify when a new subscriber signs up and sends an email using AWS SES """ import logging import boto3 import json import os logger = logging.getLogger() logger.setLevel(logging.INFO) VERSION = "0.1.0" def lambda_handler(event: dict, context) -> dict: """handles the aws ...
null
v1
[ "v0", "v0", "v0", "Optional[v0]", "Optional[v0]", "int" ]
Any
def v1(v2: v0, v3: v0, v4: v0, v5: Optional[v0], v6: Optional[v0], v7: int): if v2.dim() == 3: v8 = True assert v3.dim() == 3 and v4.dim() == 3, f'For batched (3-D) `query`, expected `key` and `value` to be 3-D but found {v3.dim()}-D and {v4.dim()}-D tensors respectively' if v5 is not None: ...
[]
[]
[]
21
r"""Functional interface""" from typing import Callable, List, Optional, Tuple import math import warnings import torch from torch import _VF from torch._C import _infer_size, _add_docstr from torch._torch_docs import reproducibility_notes, tf32_notes # A workaround to support both TorchScript and MyPy: from typing im...
[ "v0 = torch.Tensor" ]
v1
[ "v0" ]
bytes
def v1(self, v2: v0) -> bytes: v3 = BytesIO() self.render_to_file(v2, v3) return v3.getvalue()
[]
[ "io" ]
[ "from io import BytesIO" ]
4
from __future__ import annotations import urllib.request from abc import ABC, abstractmethod from dataclasses import dataclass from io import BytesIO from typing import IO, Any, Callable, Dict, Generic, Type, TypeVar, Union import dataclass_utils import dataclass_utils.error from .filters import Filters, default_fil...
[ "v0 = TypeVar('ParamsType', bound=Params)" ]
v0
[ "str" ]
Any
def v0(self, v1: str): if len(v1) > 0 and v1[-1] != ',': return v1 + ',\n' return v1 + '\n'
[]
[]
[]
4
#!/usr/bin/env python3 import platform import unittest from pathlib import Path import subprocess import sys import re class Flail: """ The flaing consists in converting a file to a C header containing all the contents as an uint array Example: Step 1: Object Dump #...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = subprocess.Popen(self.cat_cli_command().split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) v3 = subprocess.check_output(self.od_cli_command().split(), stdin=v2.stdout).decode().splitlines() v4 = [self._step_2(x) for v5 in v3] v6 = [self._step_3_4(v5) for v5 in v4] v...
[]
[ "subprocess" ]
[ "import subprocess" ]
7
#!/usr/bin/env python3 import platform import unittest from pathlib import Path import subprocess import sys import re class Flail: """ The flaing consists in converting a file to a C header containing all the contents as an uint array Example: Step 1: Object Dump #...
null
v0
[ "torch.Tensor", "int" ]
torch.Tensor
def v0(v1: torch.Tensor, v2: int) -> torch.Tensor: if v1.ndim < 2: raise ValueError('Input tensor must have ndimensions >= 2.') v3 = v1.shape[0] v4 = tuple(v1.shape[1:]) v5 = (-1,) * v1.ndim return v1.clone()[None, ...].expand(v2, *v5).transpose(0, 1).reshape(v2 * v3, *v4)
[]
[]
[]
7
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # Modified by Linyi Jin from typing import List, Optional, Union import torch import torchvision.transforms as T from .utils import padded_to_list, padded_to_packed """ This file has functions for interpolating textures after rasterization. ""...
null
v0
[ "List", "int" ]
List
def v0(v1: List, v2: int) -> List: v3 = [] for v4 in range(v2): v3.extend(v1.copy()) return v3
[]
[]
[]
5
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # Modified by Linyi Jin from typing import List, Optional, Union import torch import torchvision.transforms as T from .utils import padded_to_list, padded_to_packed """ This file has functions for interpolating textures after rasterization. ""...
null
v0
[]
io.BytesIO
def v0(self) -> io.BytesIO: v1 = self.storage.get('data') if not v1: return io.BytesIO() return io.BytesIO(bytes(v1))
[]
[ "io" ]
[ "import io" ]
5
import io import logging import os.path from aim.sdk.num_utils import inst_has_typename from aim.sdk.objects.io import wavfile from aim.storage.object import CustomObject from aim.storage.types import BLOB logger = logging.getLogger(__name__) @CustomObject.alias('aim.audio') class Audio(CustomObject): AIM_NAME ...
null
v0
[]
tp.Dict[str, str]
def v0(self) -> tp.Dict[str, str]: if self.cache_file and self.cache_file.exists(): try: return pickle.loads(self.cache_file.read_bytes()) or {} except Exception: self.cache_file.unlink(missing_ok=True) return {}
[]
[ "pickle" ]
[ "import pickle" ]
7
"""Module for caching command & alias names as well as for predicting whether a command will be able to be run in the background. A background predictor is a function that accepts a single argument list and returns whether or not the process can be run in the background (returns True) or must be run the foreground (re...
null
v0
[ "tp.Dict[str, tp.Any]" ]
tp.Dict[str, tp.Any]
def v0(self, v1: tp.Dict[str, tp.Any]) -> tp.Dict[str, tp.Any]: if self.cache_file: self.cache_file.write_bytes(pickle.dumps(v1)) self._cmds_cache = v1 return v1
[]
[ "pickle" ]
[ "import pickle" ]
5
"""Module for caching command & alias names as well as for predicting whether a command will be able to be run in the background. A background predictor is a function that accepts a single argument list and returns whether or not the process can be run in the background (returns True) or must be run the foreground (re...
null
v0
[ "str" ]
Any
def v0(v1: str): v2 = pd.read_csv(v1).dropna().drop_duplicates() v3 = ['price', 'floors', 'sqft_living', 'sqft_lot', 'sqft_above', 'sqft_living15', 'sqft_lot15'] v4 = ['sqft_basement', 'yr_renovated'] for v5 in v3: v2 = v2[v2[v5] > 0] for v5 in v4: v2 = v2[v2[v5] >= 0] v6 = v2.gr...
[]
[ "pandas" ]
[ "import pandas as pd" ]
19
from IMLearn.utils import split_train_test from IMLearn.learners.regressors import LinearRegression import os from typing import NoReturn import numpy as np import pandas as pd import plotly.io as pio import matplotlib.pyplot as plt import matplotlib.ticker as mtick pio.templates.default = "simple_white" def load_da...
null
v0
[ "pd.DataFrame", "pd.Series", "str" ]
NoReturn
def v0(v1: pd.DataFrame, v2: pd.Series, v3: str='.') -> NoReturn: for v4 in v1: v5 = np.cov(v1[v4], v2) v6 = np.std(v1[v4]) * np.std(v2) if v6 != 0: v7 = (v5 / v6)[0, 1] else: v7 = np.array(0) plt.scatter(v1[v4], v2) plt.title(f'Plot Feature {v...
[]
[ "matplotlib", "numpy", "os" ]
[ "import os", "import numpy as np", "import matplotlib.pyplot as plt", "import matplotlib.ticker as mtick" ]
15
from IMLearn.utils import split_train_test from IMLearn.learners.regressors import LinearRegression import os from typing import NoReturn import numpy as np import pandas as pd import plotly.io as pio import matplotlib.pyplot as plt import matplotlib.ticker as mtick pio.templates.default = "simple_white" def load_da...
null
v0
[ "dict", "list" ]
bool
def v0(v1: dict, v2: list) -> bool: v3 = v1['tweet']['full_text'] v4 = v3.lower() v5 = False for v6 in v2: v5 = v5 or v6 in v4 return v5
[]
[]
[]
7
import json import os from typing import Dict, List from datetime import datetime from dotenv import load_dotenv from src.extractors.time_extractor import TimeExtractor load_dotenv() year_offset = 1 year = str(datetime.today().year - year_offset) DATA_SEED_TWITTER_PATH = os.environ.get('DATA_SEED_TWITTER_PATH', './...
null
v0
[ "set", "dict" ]
set
def v0(v1: set, v2: dict) -> set: v3 = v2['tweet']['full_text'] v4 = v3.split(':')[1].split('\n')[0].strip() v1.add(v4) return v1
[]
[]
[]
5
import json import os from typing import Dict, List from datetime import datetime from dotenv import load_dotenv from src.extractors.time_extractor import TimeExtractor load_dotenv() year_offset = 1 year = str(datetime.today().year - year_offset) DATA_SEED_TWITTER_PATH = os.environ.get('DATA_SEED_TWITTER_PATH', './...
null
v0
[]
Optional[List[str]]
def v0() -> Optional[List[str]]: v1 = os.path.join(sys.prefix, 'pyvenv.cfg') try: with open(v1, encoding='utf-8') as v2: return v2.read().splitlines() except OSError: return None
[]
[ "os", "sys" ]
[ "import os", "import sys" ]
7
import logging import os import re import site import sys from typing import List, Optional logger = logging.getLogger(__name__) _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile( r"include-system-site-packages\s*=\s*(?P<value>true|false)" ) def _running_under_venv() -> bool: """Checks if sys.base_prefix and ...
null
v0
[]
bool
def v0() -> bool: v1 = os.path.dirname(os.path.abspath(site.__file__)) v2 = os.path.join(v1, 'no-global-site-packages.txt') return os.path.exists(v2)
[]
[ "os", "site" ]
[ "import os", "import site" ]
4
import logging import os import re import site import sys from typing import List, Optional logger = logging.getLogger(__name__) _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile( r"include-system-site-packages\s*=\s*(?P<value>true|false)" ) def _running_under_venv() -> bool: """Checks if sys.base_prefix and ...
null
v12
[]
bool
def v12() -> bool: if v11(): return v6() if v10(): return v3() return False
[ { "name": "v0", "input_types": [], "output_type": "Optional[List[str]]", "code": "def v0() -> Optional[List[str]]:\n v1 = os.path.join(sys.prefix, 'pyvenv.cfg')\n try:\n with open(v1, encoding='utf-8') as v2:\n return v2.read().splitlines()\n except OSError:\n retur...
[ "os", "site", "sys" ]
[ "import os", "import site", "import sys" ]
6
import logging import os import re import site import sys from typing import List, Optional logger = logging.getLogger(__name__) _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile( r"include-system-site-packages\s*=\s*(?P<value>true|false)" ) def _running_under_venv() -> bool: """Checks if sys.base_prefix and ...
null
v0
[ "List[List[str]]" ]
List[str]
def v0(self, v1: List[List[str]]) -> List[str]: v2 = [] for (v3, v4) in enumerate(v1): v5 = [trigger for v6 in v4 if not v6.endswith('__>')] v5 = sorted(v5) v2.append(('%d: %s' % (v3 + 2, ', '.join(v5))).strip()) return v2
[]
[]
[]
7
"""Test cases for fine-grained incremental checking. Each test cases runs a batch build followed by one or more fine-grained incremental steps. We verify that each step produces the expected output. See the comment at the top of test-data/unit/fine-grained.test for more information. N.B.: Unlike most of the other te...
null
v0
[ "str" ]
int
def v0(self, v1: str) -> int: if not self.use_cache: return 0 v2 = re.search('# num_build_steps: ([0-9]+)$', v1, flags=re.MULTILINE) if v2 is not None: return int(v2.group(1)) return 1
[]
[ "re" ]
[ "import re" ]
7
"""Test cases for fine-grained incremental checking. Each test cases runs a batch build followed by one or more fine-grained incremental steps. We verify that each step produces the expected output. See the comment at the top of test-data/unit/fine-grained.test for more information. N.B.: Unlike most of the other te...
null
v0
[ "str", "int" ]
List[Tuple[str, str]]
def v0(self, v1: str, v2: int) -> List[Tuple[str, str]]: v3 = '1?' if v2 == 1 else str(v2) v4 = '# suggest{}: (--[a-zA-Z0-9_\\-./=?^ ]+ )*([a-zA-Z0-9_.:/?^ ]+)$'.format(v3) v5 = re.findall(v4, v1, flags=re.MULTILINE) return v5
[]
[ "re" ]
[ "import re" ]
5
"""Test cases for fine-grained incremental checking. Each test cases runs a batch build followed by one or more fine-grained incremental steps. We verify that each step produces the expected output. See the comment at the top of test-data/unit/fine-grained.test for more information. N.B.: Unlike most of the other te...
null
v0
[ "list", "int" ]
int
def v0(v1: list, v2: int) -> int: v1.sort() v3 = float('inf') for v4 in range(len(v1) - 2): v5 = v4 + 1 v6 = len(v1) - 1 while v5 < v6: v7 = v1[v5] + v1[v4] + v1[v6] v8 = v7 - v2 if abs(v8) < abs(v3): v3 = v8 if v7 > v2:...
[]
[]
[]
21
def threeSumClosest(nums: list, target: int) -> int: nums.sort() sub = float("inf") for i in range(len(nums) - 2): lo = i + 1 hi = len(nums) - 1 while lo < hi: current_sum = nums[lo] + nums[i] + nums[hi] current_sub = current_sum - target if abs(cu...
null
v0
[ "str" ]
bool
def v0(v1: str) -> bool: if v1[0] != '#': return False if len(v1[1:]) != 6: return False try: int(v1[1:], 16) return True except ValueError: return False
[]
[]
[]
10
from typing import Any, Callable, Dict, List from core.validators import is_between from daily_solutions.base import BaseDailySolution from frozendict import frozendict """ You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extrem...
null
v0
[ "List[str]" ]
List[str]
def v0(v1: List[str]) -> List[str]: v2: List[str] = [] v3 = '' for v4 in v1: v4 = v4.strip() if v4 == '': v2.append(v3.strip()) v3 = '' else: v4 = v4.strip() v3 += ' ' + v4 if v3 != '': v2.append(v3.strip()) return v2
[]
[]
[]
14
from typing import Any, Callable, Dict, List from core.validators import is_between from daily_solutions.base import BaseDailySolution from frozendict import frozendict """ You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extrem...
null
v0
[ "str" ]
Dict[str, str]
def v0(v1: str) -> Dict[str, str]: v2 = list(filter(None, v1.split(','))) v3: Dict[str, str] = {} for v4 in v2: (v5, v6) = list(filter(None, v4.split('='))) v3[v5] = v6 return v3
[]
[]
[]
7
"""This module defines fixtures for testing Helm Charts.""" import logging import sys from typing import Callable, List, Iterable, Dict import pytest from _pytest.config import Config from .clusters import ExistingCluster, Cluster logger = logging.getLogger(__name__) @pytest.fixture(scope="module") def chart_path(...
null
v7
[ "str", "Dict[str, Callable]", "bool" ]
bool
def v7(v8: str, v9: Dict[str, Callable]=frozendict({'byr': is_byr_valid, 'iyr': is_iyr_valid, 'eyr': is_eyr_valid, 'hgt': is_hgt_valid, 'hcl': is_hcl_valid, 'ecl': is_ecl_valid, 'pid': is_pid_valid}), v10: bool=False) -> bool: v11 = v0(v8) for (v12, v13) in v9.items(): if v12 not in v11.keys(): ...
[ { "name": "v0", "input_types": [ "str" ], "output_type": "Dict[str, str]", "code": "def v0(v1: str) -> Dict[str, str]:\n v2 = v1.split(' ')\n v3: Dict[str, str] = {}\n for v4 in v2:\n (v5, v6) = v4.split(':')\n v3[v5] = v6\n return v3", "dependencies": [] } ...
[]
[]
8
from typing import Any, Callable, Dict, List from core.validators import is_between from daily_solutions.base import BaseDailySolution from frozendict import frozendict """ You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extrem...
null
v0
[ "int" ]
Any
def v0(v1: int): v1 = v1 * 3 return (37 * v1 % 255, 17 * v1 % 255, 29 * v1 % 255)
[]
[]
[]
3
import os def udf_collate_fn(batch): return batch def get_color(idx: int): idx = idx * 3 return (37 * idx) % 255, (17 * idx) % 255, (29 * idx) % 255 def make_dir(path): if not os.path.exists(path): os.mkdir(path)
null
v0
[ "'IList<Real>'", "'Real'" ]
'IList<int>'
def v0(self, v1: 'IList<Real>', v2: 'Real') -> 'IList<int>': v3 = [None] * len(v1) v4 = [] for v5 in range(len(v1)): for v6 in range(len(v4)): if v4[v6] >= v1[v5]: v3[v5] = v6 v4[v6] -= v1[v5] break if v3[v5] == None: v3...
[]
[]
[]
13
from algoritmia.problems.binpacking.nextfitbinpacker import NextFitBinPacker class FirstFitBinPacker(NextFitBinPacker):#[full def pack(self, w: "IList<Real>", C: "Real") -> "IList<int>": x = [None] * len(w) free = [] for i in range(len(w)): for j in range(len(free)): ...
null
v0
[]
bool
def v0() -> bool: v1 = shutil.which('state-get') return v1 is not None
[]
[ "shutil" ]
[ "import shutil" ]
3
# Copyright 2019-2020 Canonical Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
null
v0
[]
typing.Generator[str, None, None]
def v0(self) -> typing.Generator[str, None, None]: v1 = self._db.cursor() v1.execute('SELECT handle FROM snapshot') while True: v2 = v1.fetchmany() if not v2: break for v3 in v2: yield v3[0]
[]
[]
[]
9
# Copyright 2019-2020 Canonical Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
null
v0
[ "str", "str", "str" ]
Any
def v0(self, v1: str, v2: str, v3: str): v4 = self._load_notice_list() v4.append([v1, v2, v3]) self._save_notice_list(v4)
[]
[]
[]
4
# Copyright 2019-2020 Canonical Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
null
v0
[ "str" ]
Any
def v0(self, v1: str=None): v2 = self._load_notice_list() for v3 in v2: if v1 and v3[0] != v1: continue yield tuple(v3)
[]
[]
[]
6
# Copyright 2019-2020 Canonical Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
null
v0
[]
typing.List[typing.Tuple[str]]
def v0(self) -> typing.List[typing.Tuple[str]]: try: v1 = self._backend.get(self.NOTICE_KEY) except KeyError: return [] if v1 is None: return [] return v1
[]
[]
[]
8
# Copyright 2019-2020 Canonical Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
null
v0
[]
dict
def v0() -> dict: v1 = {} v1['symbol'] = input('Stock symbol:> ').upper().replace(' ', '').replace('$', '') v1['util'] = Decimal(input('Utilization rate:> ')) / 100 v1['borrow_rate'] = Decimal(input('Current borrow rate percentage:> ')) / 100 return v1
[]
[ "decimal" ]
[ "from decimal import Decimal" ]
6
from decimal import Decimal from datetime import datetime, timedelta from math import ceil from os import getcwd from pathlib import Path from collections import OrderedDict, defaultdict import requests #For progress bar in CLI. pip install tqdm import tqdm #Pretty columns for CLI display. pip install columnar from col...
null
v0
[]
dict
def v0(self) -> dict: print('Grabbing current stock price and options expirations.') v1 = {} v2 = self.expirations() v1['stock_quote'] = self.quotes() v1['options_data'] = [] for v3 in tqdm.tqdm(v2): v4 = self.options_chain(v3) v1['options_data'].append({v3: v4}) return v1
[]
[ "tqdm" ]
[ "import tqdm" ]
10
from decimal import Decimal from datetime import datetime, timedelta from math import ceil from os import getcwd from pathlib import Path from collections import OrderedDict, defaultdict import requests #For progress bar in CLI. pip install tqdm import tqdm #Pretty columns for CLI display. pip install columnar from col...
null