content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def mul(a, b): """return the multiply of a and b""" return a * b
8de0602e05ce4e9be09e2c2b598a8b0f24bd446a
655,312
def _solve_expx_x_logx(tau, tol, kernel, ln, max_steps=10): """Solves the equation log(pi/tau) = pi/2 * exp(x) - x - log(x) approximately using Newton's method. The approximate solution is guaranteed to overestimate. """ # Initial guess x = kernel.log(2 / kernel.pi * ln(kernel.pi / tau)) ...
7bf52853949de19f7cac1f19173f6591129cfe6b
655,313
def create_dict_of_links(document, name): """ create a carcase for difficult structure of doc :param document: text :param name: of this doc :return: structure of the doc """ dict_of_links = {'name': name, 'solutions': []} for num_sol, solution in document: dict_of_links['solutio...
3f6365c2c27fe6f38e93e66ea893ebb7e7470095
655,314
def put_tensor_base_in_cache(tensor_base_list, tensor_protos, cur_step, tensor_stream): """Put tensor base in cache.""" update_data_flag = False for tensor_base, tensor_proto in zip(tensor_base_list, tensor_protos): name = ':'.join([tensor_proto.node_name, tensor_proto.slot]) step = cur_step...
5eab8cfeb986ab0ad1f3dd84695622e311d13b4e
655,315
import json def json_from_text(text_file): """JSON to dictionary from text file.""" tmp = open(text_file, "r") data = json.load(tmp) return data
ace88043662571103f989366bd9e186ce518255e
655,317
def student_ranking (student_scores, student_names): """Organize the student's rank, name, and grade information in ascending order. :param student_scores: list of scores in descending order. :param student_names: list of names in descending order by exam score. :return: list of strings in format ["...
40320644c68540b2676f89164e812d961eb85df2
655,318
def get_excess_connections(this_cxs, other_innovation): """returns connections in this_cxs that share an innovation number with a connection in other_innovation""" if(len(this_cxs) == 0 or len(other_innovation) == 0): return [] return [t_cx for t_cx in this_cxs if\ (t_cx.innovati...
a341493b54b5bb0564615d4d1273a7bd176c52ee
655,319
def find_heuristic_position(child_partition): """ This function finds the starting position of different heuristics in a combined game payoff matrix. :param child_partition: :return: """ position = {} i = 0 for method in child_partition: position[method] = (i, i+child_partition[m...
943582f95a2491ca6f2f02e3088a399e673f208f
655,320
import time import random def _custom_libname(filetype, salt_len=2): """ Choose a custom name for library file Format: filetype: file extensiion cur_time: current time salt: salt_len number of digits <cur_time>_<salt>.<filetype> Args: filety...
f6edf0c0ced94a0e418519a353c96d521934b763
655,321
def to_bytes(obj): """Convert object to bytes""" if isinstance(obj, bytes): return obj if isinstance(obj, str): return obj.encode('utf-8') return str(obj).encode('utf-8')
94435faaccc0ce43d5a3faf77b5319158c5b6cfa
655,322
def normalize_email(email): """Lowercase the domain part of the email""" email_part = email.split('@') domain = email_part[1].lower() email = email_part[0]+'@'+domain return email
f2004402d262c8b1b487b66f95dcee07e8bec918
655,323
def IsPureVirtual(fname): """ Returns true if a header file is a pure virtual (no implementation) Pure virtual header files are designated as such by the phrase "Pure virtual" at the first line Input: fname - File name """ f = open(fname) fl = f.readline() f.close() return f...
f92181a1a49fe2db4bbfc1e93191f61620378a41
655,324
def _validate_edi_lines(edi_lines): """ check for carriage returns or hard returns :param edi_lines: list of edi lines :type edi_lines: list :returns: list of edi lines :rtype: list """ if len(edi_lines) == 1: edi_lines = edi_lines[0].replace("\r", "\n").split("\n") if...
5980f0a1c4afb534bf7410f75b15c32d9a565ea2
655,325
def encode2char_safe(input_lines, char_dict): """ get char representation of lines args: input_lines (list of strings) : input corpus char_dict (dictionary) : char-level dictionary return: forw_lines """ unk = char_dict['<u>'] forw_lines = [list(map(lambda m: list(ma...
9a37a321db620a841077e41ed750b0e8c757e1e4
655,326
def get_basic_widget_stats(cnxn, factory_id): """ Returns tuple for totalwidgetcount, totalanomalycount, percent_anomalies """ cursor = cnxn.cursor() sql = "SELECT COUNT(*) AS count from dbo.classified_widgets where is_good = 0 and factory_id = '{}'".format(factory_id) bad_count = cursor.execute...
850011166e8156544fd26b60afc563d7b4d9b85a
655,327
import copy def topK(inputNums, k): """获得数组中值前k大的索引 @param inputNums python列表一维 @param k 前k大 @param ret 前k大的索引 """ nums = copy.deepcopy(inputNums) ret = [] for i in range(k): tmpMaxIndex, tmpMaxVal = 0, float('-inf') for index, val in enumerate(nums): if tm...
170ef72b53055a9f38b6fdc8f3155b87fad8b559
655,328
def _compose2(f, g): """Compose 2 callables""" return lambda *args, **kwargs: f(g(*args, **kwargs))
1e63b293657e31ad88da1b0b54ba5c78b3af2dbc
655,330
def Gethr(): """Get hit radio""" hit = 1.0 return hit
b585a4df40430c8adfa5c73ed66176622277b87e
655,331
import hashlib def get_md5_hash(value): """Returns the md5 hash object for the given value""" return hashlib.md5(value.lower().encode("utf-8"))
0238a169cd31b09ade156898511408f49de0eef7
655,333
def cap(value: float, minimum: float, maximum: float) -> float: """Caps the value at given minumum and maximum. Arguments: value {float} -- The value being capped. minimum {float} -- Smallest value. maximum {float} -- Largest value. Returns: float -- The capped value or the...
14d78f11a674b8dac5595621a09b237d5fb3a71d
655,334
def times_until_out_of_gp(gp: float) -> int: """Returns how often you can buy from the enchanted_armoire given some budget. \f :param gp: :return: """ enchanted_armoire_price = 100 times: float = gp / enchanted_armoire_price return int(times)
680c8fca691eb9493c605f9f7f6da1f2d120ba80
655,335
def is_valid_note_response(response): """ Returns true if a note response is valid. str -> bool """ return True
bdf9b178fd45ddaff7313f49279f935d2fb0e260
655,336
import re def partial_path_match(path1, path2, kwarg_re=r'\{.*\}'): """Validates if path1 and path2 matches, ignoring any kwargs in the string. We need this to ensure we can match Swagger patterns like: /foo/{id} against the observed pyramid path /foo/1 :param path1: path of a url ...
abf236654db3bae15a6bcf086f3b73f4e3d69b3f
655,337
def compute_checksum(datafile): """Checksum is the sum of the differences between the minimum and maximum value on each line of a tab delimited data file. """ checksum = 0 with open(datafile, 'rb') as f: for line in f: # Remove trailing newline, split on tabs nums...
0029db606cd7412a0f629d27923a09885c411a48
655,338
def binary(n): """Return a list representing the representation of a number in base 2. >>> binary(55055) [1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1] >>> binary(-136) ['-', 1, 0, 0, 0, 1, 0, 0, 0] """ if (n>0): if (n<2): return [n] else: return bi...
177b9007c8b0a99087b01cc5902412db13c86c25
655,339
def to_dict(**kwargs): """ Convierte un conjunto de parámetros en un diccionario cuyas claves son los nombres de los parámetros y sus valores son los que corresponde a cada uno :param kwargs: :return: """ return kwargs
6054a13c105f534d8b15a78b43a2040494f881ac
655,340
def comp_length(self): """Compute the length of the line Parameters ---------- self : Segment A Segment object Returns ------- length: float lenght of the line [m] Raises ------ PointSegmentError Call Segment.check() """ self.check() z1 =...
bceae383cfed23f113459676b950d7d58f7b6108
655,341
import torch def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0): """ Make causal mask used for bi-directional self-attention. """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), float("-inf")) mask_cond = torch.arange(ma...
cc8841f984963d8488bce1954a8a8c2bad2af6cc
655,342
def is_filtered(variant): """Returns True if variant has a non-PASS filter field, or False otherwise.""" return bool(variant.filter) and any( f not in {'PASS', '.'} for f in variant.filter)
e7795c87f84978b58eeedf88f71c599a18d55508
655,344
def _get_optional_flag_group_and_flag(asm_str): """decode a flag with optional flag group (e.g FG1.L or just M)""" substr = asm_str.split('.') if len(substr) > 2: raise SyntaxError('Malformed flag group and/or flag reference') if len(substr) == 2: if substr[0] == 'fg0': flag_...
60ba70cc4e124732e201be1a18b13a8ec7349f76
655,345
def Top_biomarkers(weights,n): """ Parameters ---------- weights : Average weight of a GNN architecture. n : number of biomarkers Description ---------- Extracts the top K biomarkers from 35 regions. """ result = [] w_sorted = weights.argsort() for i in ran...
1952b04b6628a28ef3c9692a53669678bd27327d
655,346
def _GetParameterOptions(specs): """Helper to build policy options.""" values = ["%s=%s" % (par, val) for (par, val) in specs.items()] return ",".join(values)
8b5c4e354ff7da56453d66dcb6a6119be5180ea2
655,347
import argparse def parse_args(args): """Parse arguments passed to the program at runtime. Parameters ---------- args : list A list of cammand-line arguments that were passed to the program. """ parser = argparse.ArgumentParser(description="Linux theme switcher") group = parser.ad...
3a90a3725e5db9460ce7e247f97abd84f512a8eb
655,348
import os def ENV_STR(name, default=None): """ Get a string value from environment variable. If the environment variable is not set, the default value is returned instead. """ return os.environ.get(name, default)
19ef6cd0f8503bdc967b3068b5845047bd029048
655,349
import time import logging def func_time_required(func_name): """Checking the Time Required for Function Running.""" def wrapper(*args, **kwargs): t0 = time.time() result = func_name(*args, **kwargs) t1 = time.time() logging.info("func_time_required func:%s, running:%lf seconds...
0088657aaaa14bb28d28774b2eb3d411998f3544
655,351
def subhourly_energy_delivered_rule(mod, prj, tmp): """ If no subhourly_energy_delivered_rule is specified in an operational type module, the default subhourly energy delivered is 0. """ return 0
00fd10d99e174f2b5b3dde7dcaf71ea424937232
655,352
def work_Status(soup1): """Gets if the work is complete, in-progress,etc""" return soup1.find_all('span', 'complete-no iswip')[0].string
0bc62f7c8812117744a0eb93d8dc6263767b3a41
655,354
def gini_index(data, feature_name): """ Calculates the gini index of the feature with the given name. :param data: the data to analyze :param feature_name: the name of the feature to anlyze :return: the gini index of the specified feature """ gini_index = 1 for value_count in data...
84ac1905b8e5a8436703b77b61c7f2e864dec266
655,355
def sum_stats(stats_data): """ Summarize the bounces, complaints, delivery attempts and rejects from a list of datapoints. """ t_bounces = 0 t_complaints = 0 t_delivery_attempts = 0 t_rejects = 0 for dp in stats_data: t_bounces += dp['Bounces'] t_complaints += dp['Com...
671f9f229432475ccfe27ded62ac6fafbb96c6e0
655,356
def subtrai(x, y): """Subtrai x e y >>> subtrai(10, 5) 5 >>> subtrai('10', 5) Traceback (most recent call last): ... AssertionError: x precisa ser int ou float """ assert isinstance(x, (int, float)), "x precisa ser int ou float" assert isinstance(y, (int, float)), "y precisa se...
60b93529b27a2eb0761dbae1e9519b4793547eb5
655,357
def epdir(episode: int) -> str: """ Returns the episode folder name given an episode number. :param episode: The episode number :return: A formatted string of the episode folder name. """ return f"ep{episode}"
1db504a507c18f443421f1744643705dab163982
655,358
def logistic_map(pop, rate): """ Define the equation for the logistic map. Arguments --------- pop: float current population value at time t rate: float growth rate parameter values Returns ------- float scalar result of logistic map at time t+1 """ ...
8e216b5958740d4762497939f6a73f858b7d80ad
655,359
def _indent(s_, numSpaces): """Indent string""" s = s_.split("\n") if len(s) == 1: return s_ first = s.pop(0) s = [first] + [(numSpaces * " ") + line for line in s] s = "\n".join(s) return s
f31c828adf475fb5bcc9497a0977e661a5af4e95
655,360
def version(): """ return the plugin version """ version = (2, 3, 0, '.dev13') v_format = ".".join([str(s) for s in version[:3]]) if(len(version) > 3): v_format += version[3] return v_format
33b4f6ab93d068d8a07f078204f509aa6017c1a1
655,361
import socket def open_port(host=''): """ Return a probably-open port There is a chance that this port will be taken by the operating system soon after returning from this function. """ # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python s = socket.socket(socket.AF_INET, ...
47adc831149b5bc5e4a6cde82b2ad7cd21c34d15
655,362
import math def eq2gal(ra,dec): """ Convert Equatorial coordinates to Galactic Coordinates in the epch J2000. Keywords arguments: ra -- Right Ascension (in radians) dec -- Declination (in radians) Return a tuple (l, b): l -- Galactic longitude (in radians) b -- Galactic latitude (in radians) """ # RA(rad...
a2413e65232003957d383d387eb124a00fe68e79
655,364
def lpad(s, l): """ add spaces to the beginning of s until it is length l """ s = str(s) return " "*max(0, (l - len(s))) + s
f903e9beea4cbc43bd2453f9f768923b3e088a07
655,365
import math def charge(character: dict, enemy: dict) -> int: """ Use Charge skill. This is a helper function for use_skill :param enemy: a dictionary :param character: a dictionary :precondition: character must be a dictionary :precondition: character must be a valid character created by...
f380be046a879a87333039c4955964eec5025515
655,366
import random def player_move(player_hand, snake, domino_set): """Handles the players Move""" proper_input = False while not proper_input: cmd = input() try: choice = int(cmd) except ValueError: print("Invalid input. Please try again.") except TypeE...
a24f8315a6b40bb80e19b9ff74c8801da5e7a95a
655,367
from datetime import datetime def parse_val(value): """ Infers the type of the value by trying to parse it to different formats. Returns: The parse value and the type. """ if not value: return value, None tests = [ # (Type, Test) ('int', int), #NEQP (No podria tambien haber integers con el s...
c26005d79c4798c06ee627fdbcefa9a68ab495a0
655,368
def sort_cells_closest(start_cell, cells): """ Description: Returns a sorted list of cells by 'closest' based on the given start cell Args: start_cell (tuple): Coordinates (x, y) of the reference cell cells (list): List of (x, y) tuples that are the cells to compare Returns: ...
72b2c591e8e0a1b70374779660ccb6e1884aab25
655,369
def checksum(number): """Calculate the checksum over the number.""" # replace letters by their ASCII number return sum(int(x) if x.isdigit() else ord(x) for x in number) % 9
58d6922163698a10146792d1c44b9459a26e7a9d
655,370
def _function6(value): """weird...""" if value != 8: return 0 return 1
d8fb556b34678de93e7da0f732d227f01d10bda2
655,371
def _SplitStep(user_name): """Given a user name for a step, split it into the individual pieces. Examples: _SplitStep('Transform/Step') = ['Transform', 'Step'] _SplitStep('Read(gs://Foo)/Bar') = ['Read(gs://Foo)', 'Bar'] Args: user_name: The full user_name of the step. Returns: A list repres...
bf8cc02a4efebeff284bba7cb5d86a43112b7998
655,372
import random def generate_response(options_dict): """ Return a response ID for the bot """ return random.randint(1, len(options_dict)) - 1
8136c640f7a1713170702baf5f31b524a25a59c6
655,373
from typing import Union from typing import List def _get_error_list(_errors: dict) -> Union[List, None]: """ This method return a list of errors, if any exists :param _errors: Dict of errors :return: List of errors or None """ errors = [] for err in _errors: errors.append({ ...
30c76c11aeab175d63066a5a29747c05ff7b550a
655,374
import torch def imbalanced_spec_config(weight_dic, spec_dic): """ Generate weights for geoms such that there is no balance with respect to species [p(A) != p(B)], but there is with respect to clusters in each species [p(A, c1) = p(A, c2), where c1 and c2 are two...
b592951bf563c0965dda7c78440b18be400b16d8
655,375
import os import re def parse_filename(filename): """Extract run parameters from a simtel.gz filename. Parameters ---------- filename : list A filename formatted as [particle_type]_[ze]deg_[az]deg_run[run_number] ___[production info].simtel.gz Returns ------- int ...
ba3dec0d14f3a2f74a2ca67a85259a0806709f11
655,376
def _get_version() -> str: """load version from VERSION file""" with open('./VERSION', 'r', encoding='utf-8') as f: return f.read().strip()
d673023aa57100562d2a77dbe4358cc8137ccbba
655,377
import os def SDCredentials(**kwargs): """ Convenience to hard code credentials for testing. Returns a dict. Picking up sdurl/sdapikey from the environment is redundant since the library already does this as a fallback. """ result = { "sdurl": os.getenv("OPENZGY_SDURL", ""), ...
3d3924fe7c722fa5c4e0e34ebaaa43c853e55523
655,378
def _add_key(example): """Add a key to this example by taking the hash of the values.""" return hash(example['audio'].tobytes()), example
d3312a987ad2dd10a3564b0a6bd093e19f50537f
655,379
def _levenshtein_distance(s1, s2): """ :param s1: A list or string :param s2: Another list or string :returns: The levenshtein distance between the two """ if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for index2, num2 in enumerate(s2): new_dis...
41b95a7978b486d050a0265908712762c2ce1a8d
655,380
def rank_drawr_property(final_spreadsheet_df, pg_network_n1_names): """ This is to rank properties for each user gene set. Args: final_spreadsheet_df: final smoothed dataframe. pg_network_n1_names: list of property names. Returns: prop_spreadsheet_df: a new spreadsheet with user gen...
62c5fe9932cd18cc41e04b31327f4da3b6ccbeb9
655,382
def format_commands(commands): """ This function format the input commands and removes the prepend white spaces for command lines having 'set' or 'delete' and it skips empty lines. :param commands: :return: list of commands """ return [ line.strip() if line.split()[0] in ("set", "del...
2a5e2032bac0b53e404fc72d5c5030cb736da1e9
655,383
def appendCoeffs(Coeffs, coeffv, coeffw, coeffx, coeffy): """ (list[], list[], list[], list[], list[], list[] size = 4each) -> NoneType description : Sends spline coeffcients to the MCU """ """ Coeffs = ("<"\ +cx2[1]+','+cx2[2]+','+cx2[3]+','+cx2[4]+','\ +cx3[1]+','+cx3[2]+','+cx3[3]+','+cx3[4]+','\...
115b871e410b8d23878561596e59b8b36099e7d2
655,384
import re def _validateStart(value, match): """ Make sure that the characters preceding an ISBN number do not invalidate the match. The match is considered to be invalid if it is preceded by any alphanumeric character. :param value: String that was being searched :param match: MatchObject ret...
07ddfc18198887cbd5e5dce4b3fc2448fbe12ad7
655,385
import itertools def build_fragments_list(boot_info): """ Return a list of (segment, fragment) for each fragment in the video """ res = [] segment_run_table = boot_info['segments'][0] fragment_run_entry_table = boot_info['fragments'][0]['fragments'] first_frag_number = fragment_run_entry_table[0][...
594474c7baacc2ea29d1c0e1b8fbb61dad389994
655,387
import operator def array_combine(a, b, op=operator.and_, func=lambda x: x): """ Returns op(func(a), func(b)) if a and b are both not None; if one is None, then returns func() on the non-None array; if both are None, then returns None. """ if a is not None and b is not None: return op(func...
caec67e8a75a082ddbafbc369473062923935bf6
655,388
def serializer_workbook_path() -> str: """ Path to excel workbook used by serializer tests. """ return 'tests/data/serializer/test.xlsx'
c11e38dc5581635261b13bb3b94022e16da29632
655,389
import pstats def GenerateOutput(cProfileLog): """ Takes a .txt file generated by cProfile and creates a human readable version of it sorted by cumulative use. ARGUMENTS cProfileLog : input filename from sys.argv, should be a .txt file, with the same name as the profiled script """ p = ...
3500a95031a3074bbe6ff943fca45834c7243187
655,390
def tags_to_dict(tags): """ Converts the tag set to a dictionary """ return {key: value for key, value in tags}
270c8c0196a4d0f4fb1477c2be032d35400e04a1
655,391
def get_journal_issn_in_issue(issue) -> str: """Retorna o ISSN ID de um periódico na perspectiva da issue""" return issue.data.get("issue").get("v35")[0]["_"]
4f3e510afbf5fa7aa8b2ac6d8052e2f5fa39eaca
655,393
import copy def three_way_partition(items: list[int], pivot: int, in_place=True) -> list[int]: """ Args: items: pivot: middle partition value; used to determine the partitions in_place: whether to perform partition in-place Complexity: Time: Θ(n) Space: O(1) (if i...
12847233ce2d8b7b98a2cfceb0d3323ab0d388f0
655,395
from datetime import datetime def get_date_based_folder(): """Function to return the folder path based on todays date. Parameters ---------- None Returns ------- str: `str` A string that contains the current date YYYY/MM/DD """ int_date = str(datetime.utcnow().date()) ...
45cdfc5e769b60cd368a1f5b85cc60e1359626d3
655,397
def _format_docstring(*args, **kwargs): """Format docString of a function: Substitute placeholders with (kw)args. Note: Formatting your docString directly won't work! It won't be a string literal anymore and Python won't consider it a docString! Replacing the docString (.__doc__) via th...
c1199770023e641dd39ff310dedd8c91ca8e6ee6
655,398
def dic_value(input_dic, key, default=None): """ Returns the value from the dic. If input_dic is not a dict, or there is no such key, then returns default """ if isinstance(input_dic, dict): value = input_dic.get(key, default) else: value = default return value
c88733e041acbb2ec61ab0d5f5d4bd90d9033b53
655,399
def list_dict(l): """ return a dictionary with all items of l being the keys of the dictionary """ d = {} for i in l: d[i]=None return d
c9f4fab5fb06246fa597ccf2bb45349b46ab39d3
655,401
def train_and_test_partition(inputs, targets, train_part, test_part): """ Splits a data matrix (or design matrix) and associated targets into train and test parts. parameters ---------- inputs - a 2d numpy array whose rows are the data points, or can be a design matrix, where rows are t...
a41829faecf34256ef2ae6d80c0fe72713832cb4
655,402
def filter_file(single_file): """ Method used to filter out unwanted files """ if(single_file.endswith(".txt") or single_file.endswith(".py") or single_file.endswith(".java") or single_file.endswith(".s")): return single_file
57687f5a7b2071232c3bc90e97662fb9a24bdd91
655,404
import numpy def wrap_predict_keras(X, fct, many, shapes): # pragma: no cover """ Checks types and dimension. Calls *fct* and returns the approriate type. A vector if *X* is a vector, the raw output otherwise. @param X vector or list @param fct function @param ...
ee940c584437f208cdf5b7817854e8755c4b4b80
655,405
import os def check_and_create_dir(root, dirName): """check if a directory exists and create if it doesn't Args: root (str): parent directory of dirName dirName (str): path to directory Returns: dir (str): returns path to directory as os.path.abspath """ if os.path.exists...
c937b406958b707c50e6af412834983dced57417
655,406
def map_to_bin(bin_inds, data, n_bins): """ takes bin indices, puts relevant data in relevant bin bins is 1+max value in bin_inds lists of lists """ assert len(bin_inds) == len(data), "data (len {}) and bin indices array (len {}) should be the same length".format(len(data), len(bin_inds)) bins =...
6f81c227037038ac9cc8a411789da9d2b7e60c97
655,407
import struct def parse_hdr(data): """ Parse L2CAP packet 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ----------------------------------------------------------------- | length | channel id | -------------------------------------...
447ca1530451824fac7e001c7c6cdebf83d44eb2
655,408
import re def get_capitalization_pattern(word, beginning_of_sentence=False): """Return the type of capitalization for the string. Parameters ---------- word : str The word whose capitalization is determined. beginning_of_sentence : Optional[bool] True if the word appears at the be...
53cfeecf92afa77ebb76602a1f619a18753dacf7
655,409
def add_evaluation_args(parser,is_sagemaker=False): """Evaluation arguments.""" group = parser.add_argument_group('validation', 'validation configurations') group.add_argument('--eval-batch-size', type=int, default=None, help='Data Loader batch size for evaluation datasets.' ...
817acb34c5e2c6af14851f8f7cee39a0cecda58f
655,410
def decode(line): """Takes bytes and returns unicode. Tries utf8 and iso-8859-1.""" try: return str(line, 'utf8') except UnicodeDecodeError: return str(line, 'iso-8859-1') except TypeError: # Already unicode return line
9f830b61ce4b10b25a6ac5f75dfccedec54821e8
655,411
def point_in_quadrilateral(pt_x, pt_y, corners): """point in quadrilateral""" ab0 = corners[2] - corners[0] ab1 = corners[3] - corners[1] ad0 = corners[6] - corners[0] ad1 = corners[7] - corners[1] ap0 = pt_x - corners[0] ap1 = pt_y - corners[1] abab = ab0 * ab0 + ab1 * ab1 abap =...
11c77e5b2b8f5d1b8e3e59929454ad45fde161ff
655,412
import tempfile import os def new_temp_file(suffix): """ Generate a new temporary filename """ handle, filename = tempfile.mkstemp(suffix=suffix) os.close(handle) return filename
dc115d7bf1cbf33d3feb44393196308d25cd6222
655,413
def plot_lines(ax, ob, color = []): """ plot lines with colors Parameters ---------- ax : matplotlib axis ob : list of lines color : list (optional) """ for ii,line in enumerate(ob): if color == []: if ii ==0 : c ='g' elif ii == len(ob...
a05c853fddf367ca55d689a3f31fdf4b2c059cfc
655,414
def readout_tbinfo(line): """ Builds the dict for tb info from line provided by qemu """ split = line.split("|") tb = {} tb["id"] = int(split[0], 0) tb["size"] = int(split[1], 0) tb["ins_count"] = int(split[2], 0) tb["num_exec"] = int(split[3], 0) tb["assembler"] = split[4].repla...
2384fb8ecb189116d959fa835a1a78ed8a7dc3f1
655,415
def symmeterize_matrix(mat): """ make a matrix symmetric :param matrix: :return: """ if mat.ndim != 2: raise TypeError("mat is not a matrix. dim is {}".format(mat.ndim)) return 0.5 * (mat + mat.T)
8b23f1a7f6d06e84a8c70b82c452317a42894308
655,416
def GetActivePartners(configSpec): """ Get a list of all the active partners specified in the given configuration specification. @note: QuickRelease provides a distinction between "partner" and "active partner" so that you may (re-)run various processes on individual partners without having ...
98d19ba9a42fba16082503fa0390bfcf5f3426a2
655,417
from typing import Any from pathlib import Path def tmp_path(tmpdir: Any) -> Path: """Convert py.path.Local() to Path() objects.""" return Path(tmpdir.strpath)
4abad0093eeff9c4e3721641b79cf0dd0e5e4c1e
655,418
import random def random_range(n, total): """Return a randomly chosen list of n positive integers summing to total. Each such list is equally likely to occur.""" dividers = sorted(random.sample(range(1, total), n - 1)) return [a - b for a, b in zip(dividers + [total], [0] + dividers)]
4ee02ffd2b5d96d344642cd92b51ad77bf3a46ca
655,419
import re def get_standard_name(name: str) -> str: """Return standard name.""" part_of_name = [x for x in re.findall("[A-Z]*[a-z0-9]*", name) if x] new_name = "_".join(part_of_name).lower() if re.search(r'^\d+', new_name): new_name = '_' + new_name return new_name
089268175a1efc777ff6196928f7c030602edc70
655,420
def file_to_list(file): """Take each line of a file, strip it, and append to a list""" return [line.strip() for line in open(file)]
3a8b05c8c1e0d9447c9098a8adce39ca382a166e
655,421
def magic(num_dict, k): """对 num_dict 使用 k 次魔力""" for i in range(k): tmp = num_dict['n1'] for j in range(1, len(num_dict)): num_dict[f'n{j}'] += num_dict[f'n{j+1}'] if num_dict[f'n{j}'] >= 100: num_dict[f'n{j}'] %= 100 num_dict['n5'] += tmp ...
ea087cc09588ed63ab4af888e4a2956d7172f29d
655,422
import random def hash_example(hash): """ fills initialised hash table with random data INPUTS: - hashtable variable - item in format {"key": "string", "value": int}; OUTPUTS: index of new item EXAMPLES: >>> hash_example(hash, 1, 1); """ for i in range(len(hash)): ...
c210954d7fc073f6bb250f9517612c626bfff86a
655,424
import torch def initialize(x,y,criterion,max_iters=1e3, bounds=(0,1)): """Generates random perturbations of clean images until images have incorrect label. If the image is already mis-classified, then it is not perturbed.""" xpert = x.clone() dt = 0.01 correct = criterion(xpert,y) k=0 w...
19775c44f0ab62d31dc9a0665b1616e247e3e1bf
655,426
def override(cls): """Decorator for documenting method overrides. Args: cls: The superclass that provides the overridden method. If this cls does not actually have the method, an error is raised. Examples: >>> from ray.rllib.policy import Policy >>> class TorchPolicy(Po...
d427593fde1cac4bf6cc582adcf909e46302ff7b
655,427