content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Dict import torch def get_token_ids_from_text_field_tensors( text_field_tensors: Dict[str, Dict[str, torch.Tensor]], ) -> torch.Tensor: """ Our `TextFieldTensors` are complex output structures, because they try to handle a lot of potential variation. Sometimes, you just want to grab...
4898da3be21bac6011fe3d559d772da31c31f730
703,316
import re def parse_life_105(file): """Parse a Life 1.05 file, returning a tuple: positions: list of (x,y) co-ordinates comments: all comments in file, as a list of strings, one per line. """ lines = file.split("\n") comments = [] positions = [] ox, oy = 0, 0 x, y = ox, oy...
3faf204bb52f5c1dd5b350401afdaa2a021f80d4
703,317
def eliminate_nonvalid_coords(coords, mapshape): """ Eliminate nonvalid indices Args: coords(set of tuples): input set of positions h(int): height w(int): width Returns: set of valid coordinates """ h, w = mapshape valid = [] for j, i in coords: if j < 0 or j >= h:...
a872f551c072f0e36e10d7aac02d68a370cdfdf1
703,318
def getPosUntilRoot(object): """ Go through the hierarchy of the object until reaching the top level, increment the position to get the transformation due to parents. @type object: hostObject @param object: the object @rtype: list @return: the cumulative translation along the ...
00ed1bbb3cce4c8f1309d2ee4b24025e767f7df9
703,319
def _trash_ratio(text): """ Return ratio of non-common symbols. """ trash_count = 0 for char in text: if char in list(u'.\'"+-!?()[]{}*+@#$%^&_=|/\\'): trash_count += 1 return trash_count / float(len(text))
135bcabaa36a565b2e998932c70aaf4caf943af9
703,320
def index_of_spaces(text): """ Given text, return all space indices @param text is the string to analyze @returns a list of integers representing the indices """ res = [] for i in range(0, len(text)): if text[i] == ' ': res.append(i) return res
97b3618ffa54ee6d1b50c5bca3e196d3a6ae7f2a
703,321
def get_default_hparams(): """ Return default hyper-parameters """ params_dict = { # Experiment Params: 'is_training': True, # train mode (relevant only for accelerated LSTM mode) 'data_set': 'cat', # datasets to train on 'epochs': 50, # how many times to go over the full trai...
803cc08fc9de77b7c2608d10f6eca457ac175ab8
703,323
def bbcMicro_partPhonemeCount(pronunc): """Returns the number of 'part phonemes' (at least that's what I'm calling them) for the BBC Micro phonemes in pronunc. The *SPEAK command cannot take more than 117 part-phonemes at a time before saying "Line too long", and in some cases it takes less than that (I'm not sure...
bd1337214f8c0d39c79a7cd94e5720717335aad8
703,324
def insert_at_midpoint(item, iterable): """ Inserts an item at the index of the midpoint of a list Returns that list with the item inserted """ midpoint = int(len(iterable) / 2) iterable.insert(midpoint, item) return iterable
9801e2f4cd1011914f15634898ed4d502edfee34
703,325
def get_filenames_request(products, download_directory): """Get local files url corresponding to a Copernicus request (must be already downloaded). :param products: (dict) Copernicus Hub query :param download_directory: (str) Url of folder for downloaded products :return: (list) List of strings with lo...
5591948ce2445399d06da6c84f3fe1f6b8b4b128
703,326
def create_stream(data_type, transaction_id): """ Construct a 'createStream' message to issue a new stream on which data can travel through. :param data_type: int the RTMP datatype. :param transaction_id: int the transaction id in which the message will be sent on. """ msg = {'msg': data_type, ...
6ceb6f259c590bdb21589c57ba053fad5c7e1851
703,327
def _version_string_to_tuple(version_string): """Convert a version_string to a tuple (major, minor, patch) of integers.""" return (int(n) for n in version_string.split('.'))
d2fe2a3d9f6f23d1d80c2808436386c18893828f
703,328
import re def get_major_version(version): """ Enable checking that 2 versions are within the same major version """ components = re.findall(r"\d+", version) major = components[0] return major
b3d017b3dbe49b0a30d9919272906e8936c14f83
703,329
from typing import Any def is_action(value: Any) -> bool: """Returns ``True`` if the value is an action.""" return isinstance(value, dict) and "action" in value
46c691c7afd221c0f77869428535f6b943332905
703,330
def get_parse_args_definitions(wanted=None): """ Parse the args the script neeeds :param: wanted: list of args the application will use :returns: A list with the options for the wanted args """ definitions = { 'kolibri_dev': [ '-kd', '--kolibri-dev', { 'requir...
9215b13917652fe23c053f24ec3ce42b1a9fd924
703,331
import os def expand_path(path): """Get the canonical form of the absolute path from a possibly relative path (which may have symlinks, etc.)""" return os.path.expandvars(os.path.expanduser(path))
d1e58069f5547e8f5452a5c0a5888c08475033c5
703,332
import os def get_path_rel_to_proj(full_path): """ """ #| - get_path_rel_to_proj subdir = full_path PROJ_dir = os.environ["PROJ_irox_oer"] ind_tmp = subdir.find(PROJ_dir.split("/")[-1]) path_rel_to_proj = subdir[ind_tmp:] path_rel_to_proj = "/".join(path_rel_to_proj.split("/")[1:]) ...
f575a0725ab090ea55091ce74610df2f1ab62010
703,333
def name_to_components(name): """Converts a name to a list of components. Arguments: name - Name in the format /name1=value1/name2=value2/.. Returns: list of (name, value) tuples """ ret = [] components = [x for x in name.split('/') if x] components = [x.split('=') for x in componen...
5683e3c4fdce53b53431484a46cd23c8959d20a2
703,334
from typing import Optional import readline def clear_tab_complete_vocabulary() -> None: """ Resets vocabulary used for tab completion. It's important to either use the cleanup argument in tab_complete, or call this function after setting a vocabulary. This will prevent irrelevant options displaying when ...
2014e996474742d956566cc95887ba4c868398a6
703,335
import re def fixupAnchor(anchor): """Miscellaneous fixes to the anchors before I start processing""" # This one issue was annoying if anchor.get("title", None) == "'@import'": anchor["title"] = "@import" # css3-tables has this a bunch, for some strange reason if anchor.get("uri", "").st...
ba352cc5b18f82000be3943cf03db8ebcb41ddff
703,336
def deep_merge(base, updates): """ apply updates to base dictionary """ for key, value in updates.iteritems(): if key in base and isinstance(value, dict): base[key] = deep_merge(base[key] or {}, value) else: base[key] = value return base
6add1c048368f1547aa6ce5ebea1fe17b373fb87
703,337
def has_trailing_character_return(str_multiline: str) -> bool: """ >>> has_trailing_character_return('jhgjh\\n') True >>> has_trailing_character_return('jhgjh\\ntestt') False """ if len(str_multiline) and str_multiline[-1] == '\n': preserve_trailing_linefeed = True else: ...
21e6a7c9bb76e37ee05ed61b2012ec3a92413540
703,338
def get_genotype(read, ref_position, snp_position, cigar_tuple): """ Input read position, read sequence, SNP position, cigar Return the base in read that is aligned to the SNP position """ cigar = { # alignement code, ref shift, read shift 0: ["M", 1, 1], # match, progress both 1: ["...
bf6b212b318ab8425124bbdd40d5ab54d05e8858
703,339
def get_blowout_properties(): """ Return the properties for the base blowout case Return the fluid properties and initial conditions for the base case of a blowout from the Model Inter-comparison Study for the case of 20,000 bbl/d, 2000 m depth, GOR of 2000, and 30 cm orifice. """ ...
1521c62fac787e10ca6e7beaa356c82914043cc8
703,340
import torch def box_refinement(box, gt_box): """Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)] """ height = box[:, 2] - box[:, 0] width = box[:, 3] - box[:, 1] center_y = box[:, 0] + 0.5 * height center_x = box[:, 1] + 0.5 * width gt_h...
a10380c4a80de52bf7145fe134e12e49b5cf66a6
703,342
def thrush(x, f): """ Applies function M{f} to value M{x} @type x: Any @type f: function @rtype: Any """ return f(x)
7819bfa4e0b394ac94acbd057c6d69e449fb18dc
703,343
import argparse def _init_args(): """ :return: """ parser = argparse.ArgumentParser() parser.add_argument('--net', type=str, default='xception') parser.add_argument('--dataset', type=str, default='ilsvrc_2012') return parser.parse_args()
68fbb00a704968ce082fd8495d0d9a9fe5ee875a
703,344
def top(values, number=5): """ Return the dict containg the top number(defaults to 5) values. If we ask for the top 2 and the data looks like {"A": 5, "B": 5, "C": 5} we will sort on the keys and take A and B. Args: values: the dict with data number: how many we include (default=5) ...
aaa8516c3074f0cc2bc3c37f24ae27acc2844029
703,345
def force_line_char_limit(line, indent): """ If line is longer than limit then create new line at a space in the text :param line: :return: """ clim = 120 if len(line) <= clim: return line rem = line oline = '' for i in range(clim): j = clim - i if rem[j]...
21858c137cb3c75771bbe911e1c13aa7782acfa6
703,346
import os def _eval_optenv(name, default=''): """ Eval_optenv Returns the value of the environment variable or default @name: name of the environment variable @return: enviroment variable value or default """ if name in os.environ: return os.environ[name] return default
06a126274ed9091e7e545ec5bc6d9fa99c093445
703,347
import random import string def get_random_file_name(length: int) -> str: """Returns a random file name. File name consists of lowercase letters, uppercase letters, and digits. :param length: File name length. """ return ''.join(random.choice(string.ascii_lowercase ...
c6a7b2f58bc6d2eb457cee2c01222757c50f7eb9
703,348
def is_valid_followup_permutation(perm, prev_perm): """ Checks if a given permutation is a valid following permutation to all previously known permutations. (only one more) """ for p in prev_perm: if len(perm - p) == 1: return True return False
7195f48ec57273af6f5bf3942e501360558678ab
703,349
def sentihood_strict_acc(y_true, y_pred): """ Calculate "strict Acc" of aspect detection task of Sentihood. """ total_cases=int(len(y_true)/4) true_cases=0 for i in range(total_cases): if y_true[i*4]!=y_pred[i*4]:continue if y_true[i*4+1]!=y_pred[i*4+1]:continue if y_true...
82b8f35fd449fb112f12c263c6fa40c4efdf381e
703,350
import os import shutil def check_if_dir_exists_create_it_if_not_remove_content(preprocessed_data_dir): """ A helper function used mainly by: - prepare_and_dispatch_lion_detection_data - prepare_and_dispatch_lion_counting_data """ # Check if CONST_PREPROCESSED_DATA_DIR exists. pdd = os.p...
54a35a1c6ebbce571e2380c842839133409a4288
703,351
def reverse_string(a_string: str): """Take the input a_string and return it reversed (e.g. "hello" becomes "olleh".""" reversed_string = "" for i in range(len(a_string)): reversed_string += a_string[~i] return reversed_string
888127122856a3537eea99d4e2bad0aa0f1921d1
703,352
def _iterations_implicit_bwd(res, gr): """Runs Sinkhorn in backward mode, using implicit differentiation. Args: res: residual data sent from fwd pass, used for computations below. In this case consists in the output itself, as well as inputs against which we wish to differentiate. gr: gradients...
8617b6bd8cab2535409e863dae31a928f4de81db
703,353
import torch def huber_loss_temporal(dvf): """ Calculate approximated temporal Huber loss Args: dvf: (Tensor of shape (N, 2, H, W)) displacement vector field estimated Returns: loss: (Scalar) huber loss temporal """ eps = 1e-8 # numerical stability # magnitude of the d...
12329846e15c18ff9d59aee2f27377ce38eb8208
703,354
def handler(msg): """ Writes input argument back-out to the standard output returning input as output. Generated by: `SQL Server Big Data Cluster` :param msg: The message to echo. :type msg: str :return: The input message `msg` as output `out`. """ print(msg) out = msg return ...
b90133e486092c6277f63c2a4f5aa0c2317fa44e
703,355
import sys def _get_remote_or_bail(repo, name): """Get remote by name. name may be None. _get_remote_or_bail(Repo, str) -> Remote """ remote_name = name if not remote_name: # Default to origin since it's the convention. remote_name = 'origin' try: return repo.remo...
e709c57fa46e0fe232a30ca21b97d40030e36ee9
703,356
from pathlib import Path def get_file_path(): """ 固有名詞のdfのpathのリスト """ p = Path(__file__).parent.resolve() / ".." / "toots_log" file_paths = sorted([f for f in p.iterdir() if f.is_file()]) return(file_paths)
e51c2683f3ebd40f6d4b05b72e82273c153aa014
703,357
import math def RerangeEulerAngle(angle,deadzone,max1): """ Rerange the angles to [-1 - +1] If one angle is in the deadzone it is set to 0 Angles are cubed for better control Deadzone and max is configurable max1 ---/ /: / : ...
a8443cfd9f1c234e16e15efa97db6d7cead5ab46
703,358
def processMultiline(string, removeEmpty=True, removeComments=False, doStrip=True): """split a string into lines, with some default post-processing. Caution if using removeEmpty=False and removeComments==True, it will fail if empty lines are present""" lines = string.split('\n') if doStrip: lines = (f.strip()...
e1367f5094a17363872c297ee898168c0378c5fe
703,359
import argparse from pathlib import Path def parse_arguments() -> argparse.Namespace: """ Parse arguments from the command line using argparse. :return: command line arguments :rtype: argparse.Namespace """ parser = argparse.ArgumentParser(__file__) parser.add_argument('base_conf', type=P...
f3fbdcbda119669d25287b410c63b59d5e513b07
703,360
import re def remove_words(text, pattern): """ This function removes words based on those found in the pattern. test: String of text pattern: List of words to remove returns: new string with specified words removed """ new_string = re.sub(r"\b(%s)\b" % "|".join(pattern), "", tex...
90499bb65dff72065cc118eeb186b6c0cd30b0c5
703,361
def _get_valid_filename(string): """Generate a valid filename from a string. Strips all characters which are not alphanumeric or a period (.), dash (-) or underscore (_). Based on https://stackoverflow.com/a/295146/4798943 Args: string (str): String file name to process. Returns: ...
93777a5458c00a0a751f77953d718080cf51088e
703,362
def parse_output(filename): """ This function parses the output of a test run. For each run of the test, the program should print the following: ## ID: result: [OK|FAIL] ## ID: cycles: N_CYCLES ## ID: instructions: N_INSTR ## ID: Key: Value Multiple runs are allowed. ...
e24e961e5222d952e79369d22365723919cc3bfa
703,363
def sample_from_scipy_distribution(dist, size, **kwargs): """ use a given distribution to and extract size samples from it.""" if kwargs: return dist.rvs(**kwargs, size=size) return dist.rvs(size=size)
deefc047d0d8c44d38b055a86fabe7c8fdc73064
703,364
def get_atoms_list(mmtf_dict): """Creates a list of atom dictionaries from a .mmtf dictionary by zipping together some of its fields. :param dict mmtf_dict: the .mmtf dictionary to read. :rtype: ``list``""" return [{ "x": x, "y": y, "z": z, "alt_loc": a or None, "bvalue": b, "occupancy": o, ...
3b5f29362c077585ebc659b8d8a9ff5d60908ead
703,366
def trimesh_swap_edge(mesh, u, v, allow_boundary=True): """Replace an edge of the mesh by an edge connecting the opposite vertices of the adjacent faces. Parameters ---------- mesh : :class:`compas.datastructures.Mesh` Instance of mesh. u : int The key of one of the vertices of ...
43f150bb52b1f4a9180f6c40a9d420fbe5e67e30
703,367
import os import contextlib import shutil def set_up_directory(day): """Make a new directory for working on an advent of code problem Args: day: int day of the month to work on Returns: new_dir: str path to the directory for that day """ this_dir = os.path...
ba76d4abe7ab40517adcfd54af66b8946df31886
703,368
def prompt_vial_range(): """Prompt user for first and last vial of run""" first_ic_vial = int(input('First IC vial? ')) last_ic_vial = int(input('Last IC vial? ')) return first_ic_vial, last_ic_vial
bf5cf536c0aae3808bf16dd6d87a9d83bfbdab04
703,369
import argparse import sys def argparse_setup(): """Initialize the argument parser. Parameters: None Return: None """ parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() # Subparser for implementation listing info_parser = subparsers.add_parser("i...
10dbea13f782e9fd19371537984001d300a289ee
703,370
import numpy as np import io import torch def read_txt_embeddings(logger, path): """ Reload pretrained embeddings from a text file. """ word2id = {} vectors = [] # load pretrained embeddings # _emb_dim_file = params.emb_dim _emb_dim_file = 0 with io.open(path, 'r', encoding='utf-8', newline='\n', e...
1d7cc0845488bb3bd37eef4ca0cdeff67787f6e8
703,371
from typing import Any from typing import List def ensure_list(data: Any) -> List: """Ensure input is a list. Parameters ---------- data: object Returns ------- list """ if data is None: return [] if not isinstance(data, (list, tuple)): return [data] ret...
58016feaf49d63255944fa615e7e2e1dac6dcc76
703,372
def var_recode(TEDS_A_Imputed, user_target, TEDS_Af): """Recodes categorical variables present in the data. Returns A recoded data frame.""" # Identify the variable types col_list = list(TEDS_A_Imputed.columns) col_list_cat = [s for s in col_list if s != 'CASEID' and s != 'ADMY...
cc656e9a6840af4d95a6a114073459d815c533dc
703,373
def init_split(df, featname, init_bins=100): """ 对df下的featname特征进行分割, 最后返回中间的分割点刻度 为了保证所有值都有对应的区间, 取两个值之间的中值作为分割刻度 注意这里的分割方式不是等频等常用的方法, 仅仅是简单地找出分割点再进行融合最终进行分割 注意, 分出的箱刻度与是否闭区间无关, 这个点取决于用户,这个函数仅考虑分箱的个数 同时, 分箱多余的部分会进入最后一个箱, 如101个分100箱, 则最后一个箱有两个样本 Parameters: ---------- df: dataframe,...
172f48bb019fd4cf4941b2ff0fefcb24709fe7a4
703,375
import numpy def gower_distance_numpy(point1, point2, max_range): """! @brief Calculate Gower distance between two vectors using numpy. @param[in] point1 (array_like): The first vector. @param[in] point2 (array_like): The second vector. @param[in] max_range (array_like): Max range in each data di...
b97c40cd62654172b0d502e35bbef8ce9e9175c5
703,376
def can_register(extra, password_meta): """ :param extra: {str: any?}, additional fields that the user will fill out when registering such as gender and birth. :param password_meta: {'count': int, 'count_number': int, 'count_uppercase': int, 'count_lowercase': int, 'count_special'...
a6ba8cc6fc4a4180bbbceb9a8ae14b07d7dad809
703,377
from typing import OrderedDict def filter_excluded_fields(fields, Meta, exclude_dump_only): """Filter fields that should be ignored in the OpenAPI spec :param dict fields: A dictionary of of fields name field object pairs :param Meta: the schema's Meta class :param bool exclude_dump_only: whether to ...
a39a7665052cde0ba9f694696a57f2b1f6ca0603
703,378
def findNearestNeighbourPixel(img, seg, i, j, segSize, fourConnected): """ For the (i, j) pixel, choose which of the neighbouring pixels is the most similar, spectrally. Returns tuple (ii, jj) of the row and column of the most spectrally similar neighbour, which is also in a clump of size...
e205652d7b39c922a203162f3cdc58672347b938
703,379
import json def _load_json_as_list(path: str) -> list: """Load json file and convert it into list. :param path: path to json file :type path: str :return: dict :rtype: dict """ with open(path, "r") as json_data: data = json.load(json_data) if isinstance(data, list): re...
d7aa301a830a826937522dc9c737bf84bf6f4f9a
703,380
from typing import List def readFile(filename: str) -> List[str]: """ Reads a file and returns a list of the data """ try: with open(filename, "r") as fp: return fp.readlines() except: raise Exception(f"Failed to open {filename}")
a5817ab563b83d5cf4999290d10a14a0b68954b6
703,381
def calculate_residuals(df, fit, names): """Calculates residuals values by comparing values in df and in fit. Arguments: df (pandas.DataFrame): Holds the data to be fitted. Either concentrations vs time or charge passed vs time depending on the situation. fit (numpy.nda...
5b597dd8ff83241993bee8cae27e6f85c43b1959
703,382
def get_trunc_hour_time(obstime): """Truncate obstime to nearest hour""" return((int(obstime)/3600) * 3600)
8379aafc76c1987f537ea294c7def73ad32f1b23
703,384
import re def normalize_package_name(python_package_name): """ Normalize Python package name to be used as Debian package name. :param python_package_name: The name of a Python package as found on PyPI (a string). :returns: The normalized name (a string). >>> from py2deb impor...
47a850c601e64b570470a339769742d8f3732e28
703,385
def delete_prtg_device(prtg_single_device_obj): """ deletes the host at PRTG WITHOUT confirmation """ result = prtg_single_device_obj.delete(confirm=False) return result
4cb9b2a35294f0c56a62a7dbd220ab2ada81a15d
703,386
def fuse_bg_features(feats): """ :param feats: :return: """ fused_feats = [] for feat in feats: feat = feat.flatten(1) feat = feat.mean(dim=0) fused_feats.append(feat) return fused_feats
e268f925b0b54c12c0270a1df6345950f5b21f5f
703,387
def url_join(*args): """Join combine URL parts to get the full endpoint address.""" return '/'.join(arg.strip('/') for arg in args)
2b8409910186d3058c2e49bbf6f974a7cfceeffb
703,389
def filter_word_ids_with_non_zero_probability(word_ids, probas, pad_id=None): """ Filter out entries of word_ids that have exactly zero probability or are mapped to pad positions (if pad_id is not None). Args: word_ids (torch.LongTensor): tensor with word ids. Shape of (batch_size, ...
4e3e79c087dc0a3396dc23468091e8cf58f474a3
703,390
def is_pairwise_disjoint(sets): """ This function will determine if a collection of sets is pairwise disjoint. Args: sets (List[set]): A collection of sets """ all_objects = set() for collection in sets: for x in collection: if x in all_objects: retur...
4d5c434b2db2cb167f51aa4c04534a9b12239547
703,391
def project_has_hook_attr_value(project, hook, attr, value): """Finds out if project's hook has attribute of given value. :arg project: The project to inspect :type project: pagure.lib.model.Project :arg hook: Name of the hook to inspect :type hook: str :arg attr: Name of hook attribute to insp...
f275c8877d9df2a58a0812d657879b370220532a
703,392
def type_to_python(typename, size=None): """type_to_python(typename: str, size: str) -> str Transforms a Declarations.yaml type name into a Python type specification as used for type hints. """ typename = typename.replace(' ', '') # normalize spaces, e.g., 'Generator *' # Disambiguate explici...
ae7131d40e9e8da9d5543d57577661cce5c68d28
703,394
import os def GetExecutable(executable, location=None): """Returns the path to the given executable or None if it is not found. This algorithm provides a reasonably accurate determination of whether or not the given executable is on the machine and can be used without knowing its full path. An optional path...
1b4e695e683a81400798cc11c82e0821358a7ccc
703,395
from typing import Tuple from typing import List from typing import Dict def _tasks_scheduler_config(venv_path, project_config) -> Tuple[List[Dict], List[str]]: """ tasks_scheduler supervisor config """ async_tasks_config = { 'name': 'async_tasks', 'command': f"{venv_path}/bin/python run.py a...
f308ca9661c3ecdde35b76d48a034102b1e39373
703,399
import functools def caching_module_getattr(cls): """ Helper decorator for implementing module-level ``__getattr__`` as a class. This decorator must be used at the module toplevel as follows:: @caching_module_getattr class __getattr__: # The class *must* be named ``__getattr__``. ...
17a05df9556947a5760a2341e35395af5376047e
703,400
def min_query(): """Convert sentence to query """ return {'hello', 'world', 'of', 'geek'}
98ff87ecc8397c38ecd96eda368153905436a9de
703,401
def format_timedelta(days: int = 0, hours: int = 0, minutes: int = 0, seconds: int = 0) -> str: """Returns a simplified string representation of the given timedelta.""" s = '' if days == 0 else f'{days:d}d' if hours > 0: if len(s) > 0: s += ' ' s += f'{hours:...
6414e2be5a01f178d6515ab6f21ea7c5ab4d5004
703,402
def _try_encode(text, charset): """Attempt to encode using the default charset if none is provided. Should we permit encoding errors?""" if charset: return text.encode(charset) else: return text.encode()
ce418ff0b5e2ee938781fe2074bf146b9ba89447
703,403
def accuracy(letters, target_string): """ Comparing accuracy to the correct answer. Args: letters(np.array): (num_chars, ) target_string(str) Return: float: accuracy. """ count = 0 assert len(letters) == len(target_string) for i in range(len(target_string)): ...
5898a086997d3b9ff9f9bcf84b747dd553a0e4cb
703,404
from typing import List async def cringo_card(list_of_emojis: List[List[str]]) -> List[List[str]]: """This makes the Cringo! card complete with headers.""" top_row = ['🇦', '🇧', '🇨', '🇩', '🇪', '🇫'] side_column = ['<:lemonface:623315737796149257>', '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣'] list_...
44421d02c8b9c0b7f873e6d5ad5e8de803ac70d6
703,405
import random def lucky_enough(luck=0): """ Check if you lucky enough. :param luck: should be an int between 0-100 :return: Bool """ return random.randint(0, 99) < luck
158179ab5da330561f6d3b7be06697b0b319b1db
703,406
def relu(attrs, inputs, proto_obj): """Computes rectified linear function.""" return 'relu', attrs, inputs
d45c7f517c2cef57206db56b1ed7402127e72a01
703,407
import importlib import argparse def application_type(value): """ Return aiohttp application defined in the value. """ try: module_name, app_name = value.split(":") except ValueError: module_name, app_name = value, "app" module = importlib.import_module(module_name) try: ...
0de6fb898edc48d319415fb48c9d2f51e210d1db
703,408
import logging def check_multiple_insert_param(columns_to_insert, insert_values_dict_lst): """ Checks if the pararmeter passed are of correct order. :param columns_to_insert: :param insert_values_dict_lst: :return: """ column_len = len(columns_to_insert) for row in insert_values_dict_l...
ffb5a4eb595b84a439f3a910d81d699289c1d69a
703,410
import random import string def random_string(length=16): """Generate a random string of the given length.""" result = "" while len(result) < length: result += random.choice(string.ascii_letters + string.digits) return result
04bf92658ce8d9535aa91c751c5d9f1746827eaf
703,412
import os def basename(filename): """ Return basename of given filename. Parameters ---------- filename : :class:`str` Name of the file (may contain absolute path and extension) the basename should be returned for. Returns ------- basename : :class:`str` Basen...
d10f50c4f0264e6b1e8ce3bc82fea97230708a3b
703,413
def generate_kml_end_str(): """ Generates the footer for a KML file """ kml_str = '</Document>' kml_str += '</kml>' return kml_str
b67ed779e29f0c358a7e76c7662c36a714e50649
703,414
def relationship(flights, planes): """ Here we are having two columns common between flights and planes tables, which are tailnum and year. from above two common fields we consider tailnum column as keys in both the table. In """ print(planes.shape) # (3322, 9) print(planes.tailnum.nuni...
da1f31a4afa1720caeb01fc4bbec445999da4f56
703,415
def numpy_unpad(x, pad_width): """Unpad an array. Args: x (numpy.ndarray): array to unpad pad_width (tuple): padding Returns: numpy.ndarray """ slices = [] for c in pad_width: e = None if c[1] == 0 else -c[1] slices.append(slice(c[0], e)) return x[tu...
31f41a7a741d7efa870670c95a8acf8be365975a
703,416
def linear(a, b, c): """exec a * b + c""" print('exec linear') ret = a * b + c print('linear: %s * %s + %s = %s' % (a, b, c, ret)) return ret
fc5c1c99bd03f61e5f8fd87d4d1863002469c57d
703,417
def validate_spec(index, spec): """ Validate the value for a parameter specialization. This validator ensures that the value is hashable and not None. Parameters ---------- index : int The integer index of the parameter being specialized. spec : object The parameter specializa...
3612d927ef7e61613e0991ffc04ea76555d1b115
703,418
import hashlib def password_hasher(password): """ Just hashes the password :param password: :return: 32 byte hash :rtype: bytes """ return hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), b'salt', 100000)
44e921903c63f1703bbc79869f1a63a25bfe5916
703,419
import logging def logmethod(func): """ Decorator to add logging information around calls for use with . """ def _wrapper(self, *args, **kwds): logging.info("Start::%s.%s:%s", func.__module__, self.__class__.__name__, func.__name__) ...
7f8223ab99d6f9101088bff050f79fd0669231d4
703,421
def _replace_suffix(string, old, new): """Returns a string with an old suffix replaced by a new suffix.""" return string.endswith(old) and string[:-len(old)] + new or string
4e487f62126b130d973f249cd34abc5a75df3eaa
703,422
def is_empty_json_response_from_s3(context): """Check if the JSON response from S3 is empty (but not None).""" return context.s3_data == {}
6ec3a41646de74d82f3786e772228da55d91b63a
703,423
def mock_validator_execute_validator(*args, **kwargs): """ Mock method to just return the builded command line without executing it. """ cls = args[0] command = args[1] return command
d03cc70f1f0a5bd59e7a116e3774b99aa8db5a03
703,424
def has_gap(k1, k2, min_gap=0.002): """判断 k1, k2 之间是否有缺口""" assert k2['dt'] > k1['dt'] if k1['high'] < k2['low'] * (1-min_gap) \ or k2['high'] < k1['low'] * (1-min_gap): return True else: return False
642d9793dcc6f85d3bf21e1abf6f481292c053f1
703,425
import logging def _set_logger( logger_file_path: str, logger_name: str = "default_logger", write_to_console: bool = True, ) -> logging.Logger: """Set logger to log to the given path. Modified from https://docs.python.org/3/howto/logging-cookbook.html Args: logger_file_path (str): Fi...
338999fbcd34367f1dc4140143688965663bf486
703,426
def sort_and_print(body, num): """ Sorts the values of dictionaries and prints respective top sentences :param body: list of dictionaries of 'sentence': score :param num: no of sentences to be printed :return: prints """ result = [] rank = [] for sentdict in body: for sen...
400b11f84d0e68fb393c261736856257b4681c52
703,427
import torch def dagger(x: torch.Tensor) -> torch.Tensor: """Conjugate transpose of a batch of matrices. Matrix dimensions are assumed to be the final two, with all preceding dimensions batched over.""" return x.conj().transpose(-2, -1)
672d26333182803b18f3d1d10e49ef393e216f5f
703,428