content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def readfile(file_dir): """ readfile(file_dir:str) Returns the content of a file in an array. """ f = open(file_dir) content = [line.rstrip('\n') for line in f] return content
2b05d1edb4e3d6dc31f8a18c29f42c2f3a68dd37
644,937
def _to_skip(branch, pruned_branches): """Skip pruned branches before explore it""" for p in pruned_branches: if branch[:len(p)] == p: return True return False
cf74271a4328ce3f3b9a855adbde6481d68f4ccb
644,938
def translate_image(data): """ Translates data where data["Type"]=="Image" """ return ""
f40d0eb2a4927779abc89a9584d5020218f2ad03
644,939
import os def file_exists(file_path): """ Returns True if the image file already exists and throws an exception if the path is a directory :return: """ expanded_path = os.path.expanduser(file_path) if os.path.exists(expanded_path): if os.path.isdir(expanded_path): retur...
24153acd3ae97d76d937884ccba02a9101f94368
644,940
import argparse def get_parser(parser=None): """ config args """ if parser is None: parser = argparse.ArgumentParser() # setting setting_arg = parser.add_argument_group('Data') setting_arg.add_argument('--dataset_dir', type=str, default='./data/zinc_moses/train.csv') setting_arg.a...
fb0ec9e53b1b99dfc35417ac05291ae134060136
644,941
def rec_opt(arr, i): """ 数据[1,2,4,1,7,8,3] 条件: 1. 选择对应的不相邻的数据 2. 确保选出的数最大 """ if i == 0: return arr[0] elif i == 1: return max(arr[0],arr[1]) else: A = rec_opt(arr,i-2) + arr[i] B = rec_opt(arr,i-1) return max(A,B)
c2f16934ec63bfa61bca69ef823a3eee083f6ba9
644,942
def isAbundant(x): """Returns whether or not the given number x is abundant. A number is considered to be abundant if the sum of its factors (aside from the number) is greater than the number itself. Example: 12 is abundant since 1+2+3+4+6 = 16 > 12. However, a number like 15, where the sum of the...
45a42385c80aee3be5c06156347e69ea2b43461e
644,943
from operator import truediv def expectation_value(n, k, m, hyper_e_cache={}): """ Returns expectation value of class count in given hypergeometric distribution :param m: represents the size of whole dataset :param k: represents the size of the sample taken from the dataset :param n: represents...
26987331e140576e99220d119e33d548e6126b84
644,944
from typing import Iterable def unzip(iterable: Iterable) -> Iterable: """ """ return zip(*iterable)
a395380064de52b6d1729dab17f6f9f90e22585e
644,945
def _get_trading_day_start_time(trading_day): """给定交易日, 获得交易日起始时间""" begin_mark = 631123200000000000 # 1990-01-01 start_time = trading_day - 21600000000000 # 6小时 week_day = (start_time - begin_mark) // 86400000000000 % 7 if week_day >= 5: start_time -= 86400000000000 * (week_day - 4) r...
5334579f16382559cbc93469dc1140e9d3ae4ea9
644,946
def convert_input_to_list(in_file): """ :return: """ with open(in_file) as f: con = f.readlines() con = [co.replace("\n", "").split("\t") for co in con] sentence_list = list() label_list = list() sentence = list() label = list() for co in con: if len(co) == 2: ...
320d864212f8259f68b21094740c5d088b5193ad
644,947
def strip_and_get(val, fallback=""): """ Return the enclosing text or provided fallback value :param val: item to get text and strip whitespace :param fallback: fallback when val is None :return: stripped text value """ if val: return val.text.strip(' \t\n\r') else: retur...
2290859e342d1fd7ca0e897f1b92c35252028caf
644,948
from typing import List def parse_train_numbers(train_numbers: str) -> List[str]: """Parse train numbers. Args: train_numbers: Not parsed train numbers from db. Returns: parsed_numbers: Parsed train numbers. """ parsed_numbers = [ train_number.strip() for train_nu...
b824d8af3ce8f1021f514cf5dde867d5b3146209
644,949
from datetime import datetime def create_access_code(passport_series_and_number: str) -> str: """Return access code.""" access_code = ( f'{passport_series_and_number}' f'{int(datetime.now().timestamp())}' ) return access_code
b8b16e60beeab905098eaa5169f85567fd7b484b
644,950
def windows2img(img_splits_hw, H_sp, W_sp, H, W): """ img_splits_hw: B' H W C """ B = int(img_splits_hw.shape[0] / (H * W / H_sp / W_sp)) img = img_splits_hw.view(B, H // H_sp, W // W_sp, H_sp, W_sp, -1) img = img.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return img
8f2261739d54ed5ca6ba1364e6b89e5818038cb5
644,951
def find_longest_element(element_list): """find longest element in the list Parameters ---------- element_list : list Returns ------- longest element in the list """ longest_element = '' for element in element_list: if len(element) > len(longest_element): ...
e0ff2ffc32c8a4a35e03d7bfdf194cd42c70137a
644,952
def cut_content_by_doublecode(text: str, leftCode: str='[', rightCode: str=']', prefix='') -> str: """获取成对的中括号中的文本(不包含两侧成对符号) 当提供前缀 prefix 时,将包含 双侧括号 输出 """ # 如:[asd[cvb]] 会获取到 asd[cvb] stack = [] cut_text = "" for _ in text: if len(stack) > 0: cut_text += _ ...
2555ab2dbd02cb3a8a806abce80b37cefe56cc96
644,953
import binascii def hexlify(x): """Return the hexadecimal representation of the binary data. Decode from ASCII to UTF-8.""" return binascii.hexlify(x).decode('ascii')
096b177ba0dde2fe7d1b2e087648500e80a4c501
644,954
def get_epsilons(max_attr): """ Given all explanations of one SNN model across both data subjects, find the epsilons at 25, 50 and 75% of the attribution range of positive attributions :param max_attr: maximum absolute attribution value :return: """ epsilons = [(0), (0.25 * max_attr), (0.5 *...
4e1fbab2af3d8a342f149cc55569968c18465136
644,955
def scan_project_name(project_info, summary): """ 从summary中寻找项目信息 :param project_info: 项目信息 :param summary: summary :return: 项目名称 """ for _pj in project_info: if _pj[u'别名'] in summary: return _pj[u'名称'] # print(u">>> summary: %s" % summary) return None
1d53f76e52755394c0f22e319d881cab6b88f4c9
644,956
import re def rm_special_chars(x, colname=None): """Remove all special characters from column in pandas data.frame (in-place edit) """ regex = re.compile(r'[^A-Za-z0-9_ ]') if colname is None: x = regex.sub('_', x) else: try: x[colname] = x[colname].astype(str).apply(la...
bef9abd005ab6fbfa40dc57c70630278009a29e0
644,957
def xml_to_condition(l): """ Returns a list of values from a list of 'weather-condition' XML data. """ new = [] for element in l: if isinstance(element, dict): key = list(element.keys())[0] if key.endswith('nil'): new.append(None) elif key ...
6f1490587cedda61a04a5e7dfcb7e3d811f2aac1
644,958
def solve_for_scale(a_scale, a_n_bits, b_scale, b_n_bits, y_n_bits): """ Finds the scale factor for the following case: y = a * b We know the scale factor and the number of bits of a, as well as b. We also know the number of bits for y. This function computes the resulting scale factor for y ...
f1f516b6b3be6edc5af4cede96d290636bee0fe6
644,959
def process_form_data_flat(self, request, encoding = "utf-8", nullify = False): """ Processes the form data (attributes), creating a map containing the hierarchy of defined structure for the "form" contents. This method runs in flat mode for hierarchies defined with "dot notation". :type request: R...
e509f0364cd5c897d43659af7fa453909a418bbc
644,960
def to_bool(value=None): """ https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python >>> import json >>> json.loads("false".lower()) False >>> json.loads("True".lower()) True """ if isinstance(value, bool): return value return { #if lower_value in valid: retur...
3fc3173b0b5d1791db41026e4a6ec80091462ffa
644,961
import os def php_basename(_path, _suffix=None): """ >>> php_basename("/etc/sudoers.d", ".d") 'sudoers' >>> php_basename("/etc/sudoers.d") 'sudoers.d' >>> php_basename("/etc/passwd") 'passwd' >>> php_basename("/etc/") 'etc' >>> php_basename(".") '.' >>> php_basename("/"...
324e12a17d0070016f5e85a6399bfd61d743b1de
644,962
def gen_b_cb(): """ Generate the B-Cb table. """ b_cb = [0] * 256 for i in range(256): b_cb[i] = int((1.77204 * (i - 128))) return b_cb
e6fa30c4f15008234ba6c9d8233f34c3995dddd3
644,963
def isbit(integer, nth_bit): """Tests if nth bit (0,1,2..) is on for the input number. Args: integer (int): A number. nth_bit (int): Investigated bit. Returns: bool: True if set, otherwise False. Raises: ValueError: negative bit as input. Examples: >>> isb...
a94f6b81284ac484a8441f96ac8b374c2cb9b6ae
644,964
def preprocess_zenodo_metadata(raw_metadata: dict): """Method to pre-process metadata into the Zenodo format for upload.""" # If metadata comes from the UI, need to get some data into the right format. # Creators must be a JSON array # A list of dictionaries makes a JSON array type. creators = [] ...
5283f567cedc8a32e48bbc95f35dd6dcec99a3be
644,965
import json def getQuestionsId(uuid, courseId, recruitId, s, numberOfQuestions) -> list: """ 获取前50条问题 """ questionid_list = [] questionUrl = "https://creditqa.zhihuishu.com/creditqa/web/qa/getHotQuestionList" headers = {"Host": "creditqa.zhihuishu.com"} params = { "uuid": uuid, ...
227ddf085733704410406587c8be2a41d8b998b0
644,966
import string import re def remove_punctuation(text): """ Remove punctiation from piece of text """ text = [t for t in text if t not in string.punctuation] text = [t for t in text if t not in ['...']] text = [re.sub(r'(?:\@|https?\://)\S+', '', (t)) for t in text] # text = [re.sub(r'[^\w\s...
e9b36daa286273145d04d942ba940472efafb33f
644,967
import os def ipat(pat): """Convert glob pattern to case insensitive form.""" (dirname, pat) = os.path.split(pat) # Convert '/path/to/test.fpt' => '/path/to/[Tt][Ee][Ss][Tt].[]' newpat = '' for c in pat: if c.i...
051d417b9091b02f590b441b06fd8931428c0b5c
644,968
def clusters_from_blast_uc_file(uc_lines, otu_id_field=1): """ Parses out hit/miss sequences from usearch blast uc file All lines should be 'H'it or 'N'o hit. Returns a dict of OTU ids: sequence labels of the hits, and a list of all sequence labels that miss. uc_lines = open file object of uc file ...
a6bf15f496a84421dc51ee4a56efbcbaa3580f39
644,969
def get_tablename(model): """return the model's table name""" return model._m.table_name
3a04f6d03f4c43aa094ebbcd35bf2d6e430bf312
644,970
import os import glob def finding_channels(classes, data_dir): """ this function finds the existing channels in the folder and returns a list of them """ channels = ["Ch1", "Ch2", "Ch3", "Ch4", "Ch5", "Ch6", \ "Ch7", "Ch8", "Ch9", "Ch10", "Ch11","Ch12", \ ...
5768bab2063ad475e90308077d8f90a47b4604b0
644,971
import numpy def convert_to_ndarry(cur_list): """Takes a list of ndarrys for images, and converts to a len(list) dimensional ndarray.""" p = numpy.expand_dims(cur_list[0],0) print("Shape " , p.shape) for i in range(len(cur_list)): nd_item = cur_list[i] #print(p.shape) #print(i)...
1bc6089909cda7115a29424c9bd2df895eaf95ad
644,972
def print_fail_stat(func): """ Print current containers info and processes info on test fail """ def exec_print(*args): try: result = func(*args) except: args[0].print_containers_info() args[0].print_processes() raise return result ...
479012b4fca474524945a36126bd906dc0a603b8
644,973
def print_attrs(attr, celebA_dataset): """ human-readable format for CelebA attributes vector """ legible = '' for i, a in enumerate(list(attr)): if a == 1: legible += celebA_dataset.attr_names[i] + ", " return legible
b973d4899d3a1361b63bc38a79b5ed3f12ef9741
644,974
def calc_t_int(n_group, t_frame, n_frame, n_skip): """Calculates the integration time. Parameters ---------- n_group : int Groups per integration. t_frame : float Frame time (in seconds). n_frame : int Frames per group -- always 1 except maybe brown dwarves. n_sk...
0d8a302e9c0caa54fd187f12de905efa8f63b221
644,975
def filter_blast_result(alignment, record): """ The binding pocket of the target structure should be covered by identical residues in the test sequence. We don't know where the target-sequence binding pocket is located. To increase the chances that the test sequence and target sequence have identical bi...
ae1c3280a832acc6ec2d77e9043bc3626e57d578
644,976
from typing import List import os def gather_files(paths: List[str], openc: bool) -> List[str]: """ Finds all files contained in a directory and filter them based on their extensions. :param paths: Paths to the folder containing the files or to a single file :param openc: True if opcode based enco...
1f151b7928d7abb6b45e37849ceddf9a919cb254
644,977
def apStar_identify(origin, *args, **kwargs): """ Check whether given filename is FITS. This is used for Astropy I/O Registry. """ return (isinstance(args[0], str) and args[0].lower().split('.')[-1] == 'fits' and args[0].startswith('apStar'))
0044b942a9074379683e1264f9cadbbd8100fbdc
644,978
def triangular_root(x): """Inverse of triangular_number(n). Given a triangular number x (int or float), return n (float), such that the nth triangular number is x. Since values of x that are not perfectly triangular will not have an integer n value, but will fall between two integer n-offsets, we return...
25b9351b174ae32d74053a57971e50a313ed44b5
644,979
def calculate_integration_error( max_forth_derivative: float, low: float, high: float, length: int) -> float: """Find integration error if Simpson method is used. Args: max_forth_derivative: precalculated value. low: left range boundary. high: right range boundary. lengt...
4f4103f136bda7c1b3ba6017dcc0023255fea440
644,980
def defined_submodule(arr): """ Check if model uses submodules """ return any([el.endswith('_module]') for el in arr])
d195d98bffb7418fbb0e7a55525e3b6c4d488439
644,981
import re def replace(pat, repl, line, cnt=-1, p=""): """string replace parms: pattern, replace_str, line, cnt=inf p = [v] v: using python module re.sub """ if "v" not in p: if type(pat) == str: return line.replace(pat, repl, cnt) else: for pp in pat: ...
094bfc4b4345a8af0bbcbd12a5844d4f5cc2001f
644,982
import math def calc_triangle_area(a,b,c): """ 使用海伦公式计算三角形面积 a、b、c为三角形边长 :return: 三角形面积 """ p=(a+b+c)/2 return math.sqrt(p*(p-a)*(p-b)*(p-c))
bc7499009f93125d58cda13a76f9b15b4a7f98e5
644,983
def im2mat(img): """Converts and image to matrix (one pixel per line)""" return img.reshape((img.shape[0] * img.shape[1], img.shape[2]))
9d4727d3284645707c3f2632c46fb24096b2cf17
644,986
import functools import time def simple_timer(func): """Simple decorator to give a rough estimate of calculation time. Thank you to RealPython for the help -- https://realpython.com/primer-on-python-decorators/""" @functools.wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter()...
2fe48aa691d2e4cf8528c951fa6c74eda6d390ee
644,987
import sqlite3 def build_type_dict_from_row(row: sqlite3.Row): """This function takes a row from a sqlite3 query, and returns a dict of damage modifers by type.""" type_dict = {'type': row[0], "effectiveness": {}} for i in range(len(row.keys())): if i == 0: continue else: ...
c664dc0a40a58c8777a98f0ff5d7ab2f14f99199
644,988
def exclude_complex_attrs(graph): """Exclude complex attributes from graph.""" # make copy of graph to count neighbors per node res_graph = graph.copy() for node_id, node_data in graph.nodes(data=True): for attr in node_data: if type(node_data[attr]) in (list, dict): ...
65191444e6069cfaad038e18edf4687731d52aa4
644,989
def eval_char(c): """Returns the character code of the string s, which may contain escapes.""" if len(c) == 1: return ord(c) elif c[-1] == "'": return ord("'") elif c[0] == "\\" and c[1] not in "abtrnvfxuU01234567\\": c = c[1:] # unnecessary backslash? elif c == "\\u": ...
7d1686eb9823a6cfbab68f4ccf730bc6a6000680
644,990
def _iso_datetime(value): """ If value appears to be something datetime-like, return it in ISO format. Otherwise, return None. """ if hasattr(value, 'strftime'): if hasattr(value, 'hour'): return value.isoformat() else: return '%sT00:00:00' % value.isoformat(...
f30581205661d514e7c62a9e4f880531863ac01f
644,991
import argparse def argparser(): """parse command line arguments""" parser = argparse.ArgumentParser(prog='get_stats') parser.description = 'Get cProfile stats' parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter parser.add_argument('--pstats', type=str, help=...
df648cf1d4a76a90929d1b060c0e1d50ca86539a
644,992
import json import sys def stdin_to_json(): """Compiles piped stdin into a json object""" return json.load(sys.stdin)
5601d2c4cf72697aadc6a523046327f162fcc708
644,994
import click def prompt_password(ctx, param, use_password): # pylint: disable=W0613 """Prompt for password.""" if use_password: mysql_password = ctx.params.get("mysql_password") if not mysql_password: mysql_password = click.prompt("MySQL password", hide_input=True) return...
afe4e2876e35cb36fdbff2538f9f409b282db662
644,995
def get_api_key(): """ Get the api key from file """ api_file = open("api.key", "r") api_key = api_file.readline().rstrip("\n") api_file.close() return api_key
fc26563a85e8a65035f41ef7ec2a8929baa59f0d
644,996
import math def intersect_two_circles(x0, y0, r0, x1, y1, r1): """ Finding the intersections of two circles. Thanks to: https://stackoverflow.com/questions/55816902/finding-the-intersection-of-two-circles """ # circle 1: (x0, y0), radius r0 # circle 2: (x1, y1), radius r1 d = math.sq...
8bae603623e284105741fcf4e2c9132d159ca39d
644,997
def parse_and_validate_longitude(request): """Extract and Check the validity of longitude. Args: request: HTTP request. Returns: longitude(float) if valid. Raises: ValueError: if longitude is not float, or outside range [-180, 180]. """ lon = float(request.rel_url.quer...
3a9d191be67e3b091ddcb7354bb8fc0ff2985b43
644,998
def calculate_outlier_bounds(df, column_name): """ Calculates outlier bounds based on interquartile range of distribution of values in column 'column_name' from data set in data frame 'df'. :param df: data frame containing data to be analyzed :param column_name: column name to analyze :return: d...
c9fab21820569fa1759f0a12706448ad7711fd2b
644,999
import sys def _check_py37() -> bool: """ Check Python version is >= 3.7. Returns: bool: If version < 3.7, return True. Otherwise, return False. """ if sys.version_info < (3, 7): print( 'This program needs Python >= 3.7.', 'Please upgrade Python version and...
7e81a47a9a52b9b9d94b630e3248c9df71a58648
645,000
import types def get_function(callable_): """If given a method, returns its function object; otherwise a no-op.""" if isinstance(callable_, types.MethodType): return callable_.__func__ return callable_
e662cdde35cf40f330f2e846255ba9c206ed0e38
645,002
import re def normalize_underscore_case(name): """Normalize an underscore-separated descriptor to something more readable. i.e. 'NAGIOS_SERVER' becomes 'Nagios Server', and 'host_components' becomes 'Host Components' """ normalized = name.lower() normalized = re.sub(r'_(\w)', ...
b3aa00e94f1429b994f20f98f42419dfb62d313d
645,003
def iterate_through_submeters_of_two_metergroups(master, slave): """ Parameters ---------- master, slave : MeterGroup Returns ------- list of 2-tuples of the form (`master_meter`, `slave_meter`) """ zipped = [] for master_meter in master.submeters().meters: slave_identif...
2a49210953ccb93e492fb287ca015c701437c06e
645,004
def values(dict): """Returns a list of all the enumerable own properties of the supplied object. Note that the order of the output array is not guaranteed across different JS platforms""" return list(dict.values())
0ab6e82797de6e7c5cbc61f5e90836560fd7f4d3
645,005
def _update_validation_response(error, response): """Actualiza la respuesta por default acorde a un error de validación.""" new_response = response.copy() # El status del catálogo entero será ERROR new_response["status"] = "ERROR" # Adapto la información del ValidationError recibido a los fine...
4574e2fbc328606fcb60e6ff28a95eaa198b702c
645,006
import math def int_log(x: float, base: float = math.e) -> int: """Finds the nearest integer to ``log(x, base)``. Args: x: The number whose logarithm will be found. base: The numeric base of the logarithm. Returns: The result of rounding ``log(x, base)`` to the nearest integer. ...
f8095584333ea6bae78111570014d8a63a732fc6
645,007
from typing import Dict from typing import Optional def get_new_name(attrs: Dict[str, str], mark_name: str = '', name_map: Optional[Dict[str, str]] = None) -> str: """Get new name for a node. Args: attrs (Dict[str, str]): A dict contains attributes of an ONNX node. ...
a541b05a4cd0021815062698d48a2fb155d60f01
645,008
import getpass def get_password(args): """Set the password or getpass it in a secure way""" if not args.password: password = getpass.getpass(prompt="Password for {} @ {}: ".format(args.username, args.server)) else: password = args.password return args, password
ef1c5a91fd273eb88633f64134664cdfd96262fa
645,009
def get_username_from_summary(summary): """ If the summary string ends with `@someone`, return `someone` """ lastword = summary.rsplit(None, 1)[-1] if lastword[0] == '@': return summary[:-len(lastword)-1], lastword[1:] return summary, None
9323809ee8afe972a36f9abaf7638a1a215c2efd
645,010
import ast def node_hash(node): """ Helper function to compute a unique hashable representation of a node """ if isinstance(node, ast.Name): return node.id, if isinstance(node, ast.Num): return str(node.n), if isinstance(node, ast.BinOp): children = node_hash(node.left)...
f0586b080c4871ce1aa04d8a1c7a51411ef191cb
645,011
def join(*args): """Forms join instruction.""" inputs = [arg[0] for arg in args] return { 'cmd': 'join', 'inputs': inputs, 'args': args, }
cb20ae8629ef6d36678bc3b16849302456570a4d
645,012
def in_right_closed_range(s, min_val, max_val): """ Check if a value lies in the right-closed interval (min_val, max_val]. :param s: Value to check. :param min_val: Lower boundary of the interval. :param max_val: Upper boundary of the interval. :return: True/False whether or not the value lies ...
45609cb244c1b73daa1a0da1102478ba948dbfd4
645,013
def cles(lessers, greaters): """ # code from https://github.com/ajschumacher/cles # explanation from https://janhove.github.io/reporting/2016/11/16/common-language-effect-sizes the probability that a score sampled at random from one distribution will be greater than a score sampled from some other distr...
3d0cae193d9977a594110086560eeefc3f3ecd11
645,014
def a_multi_column_apply_fn(batch, columns): """Simple function that applies to multiple columns.""" assert len(columns) == 2 return [e[0] * 0.1 + e[1] * 0.3 for e in zip(batch[columns[0]], batch[columns[1]])]
f7db950e12c2d03aa4d086691892492d506bd6d3
645,015
from datetime import date def get_current_week(): """ return: the current week number value from (1-52) """ return date.today().isocalendar()[1]
b717f186aed2634e88097e2a7aff7df70bdf0bef
645,016
def make_E_matrix(dist_matrix): """takes a distance matrix (dissimilarity matrix) and returns an E matrix input and output matrices are numpy array objects of type Float squares and divides by -2 each element in the matrix """ return (dist_matrix * dist_matrix) / -2.0
e76a79af422a942260858358fb3901e4bcb13494
645,017
def decodeBits (len, val): """ Calculate the value from the "additional" bits in the huffman data. """ return val if (val & (1 << len - 1)) else val - ((1 << len) - 1)
582de85fa9042ccea91fb239797c2fc5d441c01c
645,018
def find_cheapest_fuel_use(positions: list[int]) -> int: """ Returns the amount of fuel used for the cheapest alignment position. Args: positions (list[int]): The list of starting positions. Returns: int: Fuel usage. """ positions = sorted(positions) median = positions[...
f3a00e96ad4fc81a5527786fe6cc0afbb2474253
645,019
def display_body_parts(image, image_draw, coordinates, image_height=1024, image_width=1024, marker_radius=5): """ Draw markers on predicted body part locations. Args: image: PIL Image The loaded image the coordinate predictions are inferred for image_draw: PIL ImageDraw m...
b7da1c98a11bde3876749979f483bd09ee5d327b
645,020
def ssh(sargs): """ rm jobs/*.sh jobs/log/* -f && python grid_run.py --grid G --run_name X pattern=""; for i in 1 2; do ./kill.sh $i $pattern; done ./start.sh """ jobs_0 = ['machine0_gpu0', 'machine0_gpu1', 'machine1_gpu0', 'machine1_gpu1', ] # validate start.sh ...
505a14ac2a5127d787aba696da33f4acc70dcc7e
645,021
def compare_digest(x, y): """Create a hmac comparison. Approximates hmac.compare_digest (Py 2.7.7+) until we upgrade. """ if not (isinstance(x, bytes) and isinstance(y, bytes)): raise TypeError("both inputs should be instances of bytes") if len(x) != len(y): return False result ...
f10ff5eb8b2ef800e2f6a97531bfcd25cc1cf3f4
645,022
def groupAndSort(result_list): """ sort result list: input: result_list - [102, '98', ('102', '98'), ('97', '99'), ('101', '99'), '101', '97', '99', ('97', '98'), ('98', '99')] output: group = {1: ['101', '102', '97', '98', '99'], 2: [('101', '99'), ('102', '98'), ('97', '98'), ('97', '99'), ('9...
4fab05ab0d1b6385a6aa06cea78f3546b8082ab9
645,023
def end_text_with_single_terminating_newline_character(text: str) -> str: """Ensure the text ends with a single terminating newline character.""" return text.rstrip() + '\n'
f8e8e6b4dd3d985c913b43a54a4c69cd5065995b
645,025
from sys import stderr def str2list(str_list): """ Parses a string that supposed to contain a list (or something that has len). Returns a list. """ try: l = eval(str_list) if hasattr(l, "__len__"): return l else: print("Warning: cannot parse '%s'. " % s...
a01ec9df4e9b92672222a7ecb948d1cf1ad51c5e
645,026
def get_temp_table_name(cfg, eng, base_name): """Specify table name for creating a temporary Table. Dialect-specific implementations of this method will return the name to use when creating a temporary table for testing, e.g., in the define_temp_tables method of the ComponentReflectionTest class in...
ce00ad9c73a0a8c4d1cfc8f197f31ddfc366753b
645,028
def init_costs_table(w1, w2): """Construct and return table with identities and empty start.""" costs_table = [] # Notice we add 1, to account for the 'empty' cell at the start for i in range(len(w1) + 1): row = [] for j in range(len(w1) + 1): row.append(0) costs_t...
048cb45b481e0ff0f03f6df530c93663bacec394
645,029
import math def truncate(number, digits) -> float: """ Truncates number to a specified number of digits Args: number (float): Number to truncate digits (int): No. of digits to truncate to Returns: Truncated number (float) """ stepper = 10.0 ** digits return math.trunc...
8b19614173fccb2615a96d2f8951e0e9858c6921
645,030
def diff(limits): """ compute the difference between two values or array of values return a value if input is a two elements array or tuple return a list of differences if input is a more than two elements array """ try: d = [ a[1]-a[0] for a in zip(limits[:-1],limits[1:])] exce...
8c5844b79f0caeba07f30f3375524efadbc7d217
645,031
import ast def mod(*arguments): """ Module function. """ return ast.Mod(*arguments)
848316a5e271ee308cb0f5cd42b8f0646b7dbbbe
645,032
import os def parse_test_filepath(filepath): """ Parses fullpath of test file to obtain platform, command, and filename info. Args: filepath (str): The path to a test file from platform directory or earlier. Returns: tuple: Strings of platform, command, and the filename without the e...
a067be98ce7b3205f6f3589f738e3bccfc85ab94
645,033
import sys import math def convergent_round(value, ndigits=0): """Convergent rounding. Round to neareas even, similar to Python3's round() method. """ if sys.version_info[0] < 3: if value < 0.0: return -convergent_round(-value) epsilon = 0.0000001 integral_part, _...
b1d902f2382c50caabd322d52d5ae87836b629d2
645,034
def _asciizToStr(s): """Transform a null-terminated string of any length into a Python str. Returns a normal Python str that has been terminated. """ i = s.find('\0') if i > -1: s = s[0:i] return s
5670ef331888be44af59745a96496c7a045f6e4f
645,035
def preprocess_features(master_dataframe, used_features): """Prepares input features from the master training dataset. Args: master_dataframe: a pd dataframe that should contain the master training data. Returns: A DataFrame that contains the features to be used for the model, including s...
1759e73e4dffd2d1fc1bead66b7ff2c5d22fa108
645,036
def batch_culture_self_replicator_ppGpp_shift(params, time, gamma_max, nu_max, prefactor, tau = 1, Kd_TAA_star = 0...
7b2ecffebe11d44933da64f0597ba46a708a1f49
645,037
from typing import Any import pickle def load_file_from_disk(loc_folder: str, filename: str) -> Any: """Loads a file that was previously saved to the disk. :param loc_folder: The location of the containing folder. :param filename: The name of the file to be loaded. :return: The contents of the loaded...
8be6ab9cb9e24bc8ecc363750a04ef2f1fcb19c0
645,038
def normalizeDictionary(d): """ take in any single one of the model-dictionaries d and return a normalized version, numbers adding to 1""" values = d.values() # lists value in dictionary d sumValues = sum(values) for k in d: s = d[k]/sumValues # divide value by sum of values to normalize...
29eeaa65f0a993875aa5cb4e7f0b1585e7ee8684
645,039
def get_num_params(params, sys_num_params): """Require all parameters to be converted to float; each parameter must either be converted by the float function or the val must be a key in sys_num_params so that sys_num_params[val] returns a number.""" params_out = {} for key, val in params.iterit...
17f2c235ccf561abb5445168c8c606ee25eed349
645,040
def scientific_notation(value: float | str, precision: int = 2) -> str: """Return number in string scientific notation z.wq x 10ⁿ. Examples: >>> scientific_notation(float(0.3)) '3.00 x 10⁻¹' >>> scientific_notation(int(500)) '5.00 x 10²' >>> scientific_notation(-1000) ...
1120c1ff58a3018a2ae6addc5a3b83d24316511c
645,041
import os import json def load_json_file(filename): """ Loads a json file. Params: - filename (string) : The name of the file to load. Must include file extension. Returns: - (json) : The json file. Raises: - IOError : If the file does not exist. """ try: with open(o...
eaf8206828cc47c52ba8c05959cc448d4dedaef3
645,042