content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def error_compatibility_score(h1_output_labels, h2_output_labels, expected_labels): """ The fraction of instances labeled incorrectly by h1 and h2 out of the total number of instances labeled incorrectly by h1. Args: h1_output_labels: A list of the labels outputted by the model h1. h2_o...
3ab007b4608d43830576ce905687a74777ba8de6
662,522
import warnings def calculate_average(power_data, start_time=None, end_time=None, start_index=1): """Calculate average value of the power_data using the left Riemann sum. Arguments: power_data {InterfaceData} -- Instance of InterfaceData with power samples. Keyw...
b6769b07f1d7e424553d1748d2045275ef9d98d1
662,523
def is_json_metadata(text): """Is this a JSON metadata?""" first_curly_bracket = text.find("{") if first_curly_bracket < 0: return False first_equal_sign = text.find("=") if first_equal_sign < 0: return True return first_curly_bracket < first_equal_sign
5d67e5d6f79cd81e30f1726c9184300e59ad9ff2
662,524
def external_edges(graph, nbunch): """ Get the edges external to a set of nodes """ return (edge for edge in graph.edges(nbunch) if any(node not in nbunch for node in edge))
501c724cf4ec6268bd6706515f3be52fdc5057b8
662,525
def html_table(list_of_lists): """ Overridden list class which takes a 2-dimensional list of the form [[1,2,3],[4,5,6]], and renders an HTML Table in IPython Notebook. Taken from: http://calebmadrigal.com/display-list-as-table-in-ipython-notebook/ """ html = ["<table>"] for row in list_o...
7dd7b01e90975bbc048817c3d00e5c775973dbdf
662,526
import os def compile_x_wrfpnnl2018_raw_locations(time_increments, domain='http://cses.washington.edu', subdomain='rocinante/WRF/PNNL_NARR_6km'): """ Compile a list of file URLs for PNNL 2018 raw WRF data time_increments: (lis...
5825a86823e5307037b1290a8c05dae3ca3af1eb
662,527
def get_bin_path(*args, **kwargs): """Function to return path of hdbsql""" return "/usr/sap/HDB/HDB01/exe/hdbsql"
27dda769d727a6aafc5b68fcf0f3e4c594e6e3fd
662,528
def convert_sqlite_version(version): """ Return a version converted from the sqlite human version format to the download version format. For instance: >>> convert_sqlite_version('3.36.0') '3360000' >>> convert_sqlite_version('3.36.0.2') '3360002' See also: https://www.sqlite.org/ve...
afa72cf1fcdce2330b70163b827292e4aac360d7
662,529
def effectifs_vague(vague): """Fonction qui retourne le nombre d'etudiant a faire apparaitre dans la prochaine vague. :param vague: Entier : Numero de vague. :return: Tableau d'entiers : Nombre d'etudiants par type. """ resultat = [(vague * 3) % 15, (vague - 1) % 20, vague // 5] return result...
87a13eb0058817950444918bc98812dc6afd90cb
662,530
import subprocess def get_git_repo_version_info(): """Describe the current version of this script as known by Git.""" repo_name = 'ESMG/PyCNAL' git_command = ['git', 'describe', '--all', '--long', '--dirty', '--abbrev=10'] description = subprocess.check_output(git_command, universal_newlines=True).rs...
19587dfa62c6ed62253d7cbd0f600f0d16dc4e80
662,531
def new_grid_size(grid, kernel_size, stride=1, padding=0): """ Calculate new images size after convoling. Function calculated the size of the grid after convoling an image or feature map. Used formula from: https://adeshpande3.github.io/A-Beginner%27s-Guide-To-Understanding-Convolutional-Neural-Networks-Pa...
cb6607a7fa0927ae90aceb170f0c69acfcbb1b76
662,532
def convert_timetable(start, end): """ Function to convert rows to time :param start: Starting row number :param end: Ending row number :return: Tuple with all correct starting and ending times """ timetable = { 1: ("8:30", "9:20"), 2: ("9:20", "10:10"), 3: ("10:30",...
69790dd28b69dc62ebba613d4b55a7627e43cafc
662,533
def convert_tuples_to_bitstrings(tuples): """Given a set of measurement tuples, convert each to a little endian string. Args: tuples (list of tuples): the measurement tuples Returns: A list of bitstrings """ # Convert from tuples to bitstrings bitstrings = [] for tuple_i...
a2da6c8191032f1530ceb490ad33510a6d7152cb
662,535
def create_triangle_opts(inp): """ Create input options for Triangle. Refer to https://www.cs.cmu.edu/~quake/triangle.html :param inp: :return: """ tri_options = '-p' try: tri_options = tri_options + 'q' + str(inp.tri_min_angle) except: pass try: tri_opt...
9c234b9ff3c3779e355961ad6640417b3c6d7500
662,536
def get_restaurant_names(soup): """ Gets restaurant names from soup """ restaurants = [] for restaurant in soup.find_all("a", class_="result-title" ): restaurants.append(restaurant.string[:20]) return restaurants
9ed3056bfb00be41ad118a11b491a36a03c9adf9
662,537
def chunk(data, index): """ Split a string into two parts at the input index. """ return data[:index], data[index:]
04026ec0e09c831ddc478117f75a6e77fd06393b
662,538
def getSession(project_name, gpu, unique_id): """ Create a name for the container to be started. Returns "<project_name><gpu_nr+1>". The +1 is to start counting at 1 because 0 creates weird problems. """ nr = gpu['gpu_nr'] + 1 nr += int(gpu['occupation']) * 10 nr += unique_id * 100 #...
d3370127042e4fd59d760c4dd6feec9eebe5d023
662,539
def specialDataTypesEncoderSparkCode(): """ return the spark code which provide the specialDataTypesEncoder class to be used. """ return ''' import json import decimal import datetime class SpecialDataTypesEncoder(json.JSONEncoder): def default(self, obj): if isinst...
21eb581be54aa3d8252a9addd83e2abd96c5145e
662,540
def parse_document(document, user): """ Loop permissions, resources, and conditions """ if isinstance(document['Statement'], dict): document['Statement'] = [document['Statement']] for statement in document['Statement']: if statement['Effect'] == 'Allow': if 'Action' in stateme...
f66a08c5c2968a10964a51a5dbd792d53166cc3f
662,541
import re def is_complete_url(url): """ 验证 url 是否完整 :param url: :return: """ re_result = re.match("http.*", url) if re_result is None: return False return True
3215b3cd56857fe85f77473267d6e44894809461
662,542
import csv def retrieve_persistence_distances( path: str, delimiter: str = ",", decimals: int = 2): """ Customized retrieval function for the bottleneck distances. Retrieves elements from a 3-tuple, named by the iteration step it_i. Works for CSV files only. :param path: Path of the re...
ac4f928547ba44779fc791a8d9e8effbfacddec4
662,543
def zigZagDecode(z): """ Reverses ZigZag encoding """ return (z >> 1) ^ (-(z & 1))
360a338087f83b4f51a0bf722a97468d33bbb61d
662,544
import glob import os def files_in_folder(folder): """Returns a list of files in the folder and all its subfolders recursively. The folder can be written with wildcards as with the Unix find command. """ files = [] for f in glob.glob(folder): if os.path.isdir(f): files.exte...
5dbf8270de1a3bf8e1c89705614039489ab91088
662,545
def parse_auth(username): """ Extract actual username and target if provided from authentication identity string format is <secondaryuser>@<target>:<service>:<group>:<primaryuser> always return primaryuser and either secondary target or None Note: primary user can be a path instead when this f...
9d7f498b6677451224b3969c778a4cfee5a37ddd
662,546
from typing import OrderedDict def merge(settings_list): """ 合并配置 :param settings_list: :return: """ if not isinstance(settings_list, list): return settings_list settings = OrderedDict() for item in settings_list: for k, v in item.items(): if settings.get(k)...
c0a57f6a2db38797cceae46a43e2fc35e3a19025
662,547
import random def random_selection(population, fitness, eq): """ Selection of the best two candidates given fitness function :param population: list of numpy array :param fitness: function to fit :param eq: params to fitness function :return: tuple of two more promising individuals (numpy vect...
208f6d958bfdaf339233abd69c4918cf6a75cf5b
662,549
def herz_me(val): """Return integer value for Hz, translated from (MHz|kHz|Hz).""" result = 0 if isinstance(val, bytes): val = str(val) if val.endswith("MHz"): stripped = val.replace("MHz", "") strip_fl = float(stripped) result = strip_fl * 1000000 elif val.endswith("...
115d02d76a5bda916acf89e6c4b111f6135308b9
662,550
import os def api_url_stub(): """api url starting stub""" return os.environ.get('DF_API_URL_STUB', 'https://clientapi.dfnapp.com/')
2954b17e23d5f82dcd2ff3dba5fc31fa3037aeb7
662,551
def object_to_dict(xmp): """ Extracts all XMP data from a given XMPMeta instance organizing it into a standard Python dictionary. """ dxmp = dict() if not xmp: return {} for item in xmp: if item[-1]['IS_SCHEMA']: dxmp[item[0]] = [] else: dxmp...
e0cf7f56b8a9e4819485f60d853c0175b2123e67
662,554
import os def calc_sleep(n_new, n_fetched, new_per): """Return a float number of hours to sleep based on the number of new items (from a total of n_fetched items download), or the percentage.""" if False: # So, my fancy way of doing this wasn't really better than the # simple way below. ...
a62882e1bac40d0c2ddb1da7dd1fb4cb42095628
662,555
def round_gls(gls, precision=None): """Returns genotype likelihoods rounded to the desired precision level. Args: gls: A list of floats. The input genotype likelihoods at any precision. precision: Positive int. The number of places past the decimal point to round to. If None, no rounding is performed...
12a04d646830a2c32da3d8c377d57e3c1aeddb8a
662,557
def getNetezzaPrecisionLevels(): """Netezza int precision levels are kept here.""" return {8: 'BYTEINT', 16: 'SMALLINT', 32: 'INTEGER', 64: 'BIGINT'}
0acce1d61f76c9b9a7bfa293d36ef7172cb6b9cd
662,558
import unicodedata def remove_accents(text: str) -> str: """Remoção de ascentos e caracteres especiais Args: text (str): texto a ser processado Returns: str: texto sem ascento """ nfkd_form = unicodedata.normalize("NFKD", text) ascii_form = nfkd_form.encode("ASCII", "igno...
8f1682d524890e0acf6c16286644c6bb32da11d9
662,559
import pathlib def peer_save_path(current_path: pathlib.Path, append: str) -> pathlib.Path: """ get save path of concatenated result. this path is peer to current prediction file and append string: <prd.name>_<append>.<suffix> :param current_path: pathlib.Path: current prediction file Path object ...
8c4b2b02743c86ebf3db102ab0c67c0d7c41c74d
662,560
def mult(m, n): """ return the smallest multiple of m that is >= n """ return m * ((n+m-1) // m)
e59d82accd5bc5422806d45728521f6a9d420d96
662,561
import numpy def read_occurence_file(name): """ Read an occurence matrix from a file. It will return the matrix as a numpy array and the indexes of residues. Parameters ---------- name : str Name of the file. Returns ------- count_mat : numpy array the occurence m...
ceb99987ba0dec7f9ac64cea9f03bef0ddc3f91d
662,562
import re def _tls_trailer_length( data_length: int, protocol: str, cipher_suite: str, ) -> int: """Gets the length of the TLS trailer. WinRM wrapping needs to split the trailer/header with the data but the length of the trailer is dependent on the cipher suite that was negotiated. On Win...
98ccf856254ca2d151c551a6e7f6cbaaa693f392
662,563
import os def FilePath(filename): """ 文件路径 :return: """ filePath = os.path.join(os.getcwd(), filename) if os.path.isfile(filePath):#如果当前路径下有filePath,就运行 return filePath # else: # moduleFolder = os.path.abspath(os.path.dirname(moduleFile)) # moduleJsonPath = os.path....
b98adb3608f1a27ff41d63823f42c7e2bb804b19
662,564
def fix_alpha(with_alpha, without_alpha): """ Given two of the same image, one with an alpha channel and one without, add the alpha channel back into the image without, and return it. :param with_alpha: :param without_alpha: :return: """ alpha_added = with_alpha.copy() alpha_added[:...
abd2c81d5569983ce8a30233112e1d5b5bf48b89
662,566
import os import subprocess def LSPresult_name(station,year,doy,extension): """ given station name, year, doy, and extension returns the location of the LSP result also returns boolean if it already exists (so that information can be used) extension is now used """ # for testing xd...
0642ad9632aaf07cbc70de06ceb3cdff72007330
662,567
from typing import Union def g(t: float) -> Union[int, float]: """ :param t: an input. :return: the value of the expression g(t) """ return t**2 - 1
eb29ebd25b2e7b950b0e4da3d892059a1e2aa249
662,568
def get_model_weights(model): """ Returnsa copy of the weights of a model as a dictionary (layer_name: wieght vector) """ param_dict = dict() for name, param in model.named_parameters(): name = name.split('.')[0] if model.layer_names and name in model.layer_names: par...
fd0945b468741ff414d09f85f23a852769896d5e
662,569
def spc_code2name(projects, spc_dict, dbase=None): """A helper function to take the species codes contained in the project dictionaries and convert them to lists of species names. Optionally, the database name is also added to list of species names - it will be a key word too and is dertemined by the so...
252bd05a0be81fe77ca61c5c0abc0eda81e708a2
662,570
def number_day_to_name_day(number): """ Receives a number where 0 is sunday and returns the name of the day :param number: :return: """ weekDay = {0: 'Domingo', 1: 'Segunda', 2: 'Terça', 3: 'Quarta', 4: 'Quinta', 5: 'Sexta', 6: 'Sábado', 7: 'Domingo'} return weekDay[number]
62aed7b9d944650ecc79c167d7b71b0f0c505ca8
662,571
def get_color_commands(indices, colors): """Returns postscript coloring string given indices and colors. - indices: base 1 index of color. NOT BASE 0. - colors: color name corresponding to color name used to generate color_map. - indices and colors must be lists of the same...
3b111463146cf3e2d7025074dbd86e4c576a9013
662,572
def is_subset(subset, set): """ Determines if 'subset' is a subset of 'set' :param subset: The subset :param set: The set :return: True if 'subset' is a subset of 'set, False otherwise """ cpos = 0 for c in set: if c == subset[cpos]: cpos += 1 # Found the char if cpos == le...
6a81019a8ee8cbf192182d89c9deb71e6d55d49e
662,573
def legend(type=None, is_legend_show=True, legend_orient="horizontal", legend_pos="center", legend_top='top', **kwargs): """ 图例组件。 图例组件展现了不同系列的标记(symbol),颜色和名字。可以通过点击图例控制哪些系列不显示。 :param type: 图例类型 :param is_legend_show: 是否显示顶端图例 ...
31e0eb24afdf90f178dff1be4a9cb36a97149664
662,574
def get_tasks(): """swarm_sizes = [20, 30, 40, 50, 60] maze_sizes = [(21, 21), (31, 31), (41, 41), (51, 51), (61, 61)] repeats = 2 solver = "CPU" """ swarm_sizes = [21] maze_sizes = [(41, 41)] repeats = 1 solver = "CPU" return swarm_sizes, maze_sizes, repeats, solver
23a424a4fa3d93a0d7ebea764ea8c7024f4e2b7e
662,575
def _blank_text(active): """Return text for line history""" text = [] for value in active: if value: text.append(" |") else: text.append(" ") return "".join(text)
b34e7762d0801923f33765dec3fce456d3674512
662,576
def is_device_capable(dev_caps: dict, needed_caps: dict): """Compare device capabilities to the required capabilities mapping.""" for cap_type in needed_caps: if cap_type not in dev_caps.keys(): continue for cap in needed_caps[cap_type].keys(): if cap in dev_caps.get(cap_...
adb505725d1bae4f50681a5c024b7a16fec7480b
662,577
from typing import Dict def deep_update_dict(first: Dict, other: Dict) -> Dict: """ Perform in place deep update of the first dictionary with the values of second :param first: The dictionary to be updated :param other: The dictionary to read the updated values :return: A reference to first dictio...
b32308f8f921fcb949c820a688bf01566ea4f351
662,578
import sys def frozen(): """Determine if script is running in a frozen environment.""" if getattr(sys, 'frozen', False): # Running in a bundle return True else: # Running in a development Python environment return False
4efa42d1e554f8593537ab5a354a8a33f1134f55
662,579
def get_lastkey(path, delimiter="/"): """ Return name of the rightmost fragment in path """ return path.split(delimiter)[-1]
0e2287c95974466fae70b15c75aca11d5ed02795
662,580
def getColor(isInside): """ Returns color of points depending on if they're close to rect """ if isInside: return 'green' else: return 'red'
0eef7cb71c9be495969e90871bf4dfdb6c484de1
662,581
def _xml_escape(data): """Escape &, <, >, ", ', etc. in a string of data.""" # ampersand must be replaced first from_symbols = '&><"\'' to_symbols = ('&' + s + ';' for s in "amp gt lt quot apos".split()) for from_, to_ in zip(from_symbols, to_symbols): data = data.replace(from_, to_) re...
b6b2db648a8dd7321498ac2e7df77b8823b7593b
662,582
import re def _make_pretty_usage(infos): """ Makes the usage description pretty and returns a formatted string. Expected input: func(*) - ... func(expr[, expr...]) - ... Expected output: <table class="table"> <thead> <tr> <th style="width:25%">Function</...
afe9717fedfec86905aa40ca6e8aeab03b8a293d
662,583
import os def get_doc_files(files, start_path): """walk and sync all doctypes and pages""" files = files or [] # load in sequence - warning for devs document_types = [ "doctype", "page", "report", "dashboard_chart_source", "print_format", "web_page", "website_theme", "web_form", "web_template"...
3563c3bdf5a88e507068db8872fa948dd536afa1
662,584
def seconds2time(sec): """ 秒数转时间 """ """ sec是整型, 如32399, sec取值范围是[0, 86399], 对应的时间是'00:00:00'到'23:59:59' """ if sec < 0 or sec > 86399: raise ValueError( 'Invalid value: %s. The value interval of param sec is [0, 86399].' % sec) m, s = divmod(sec, 60) h, m...
9826936fafb3d576e77a03f0f1062e3c3f7a406d
662,585
def def_element(element): """Define an object 'element' in a template.""" return element
248ba2c1f1fab6acd0850589ed8226221321c334
662,586
def compute_II_fr(stretch,muscActivation,species): """ Compute the firing rates of the II afferent fibers. Uses the experimetnally derived model devloped by Prochazka (1999 (2)). Keyword arguments: stretch -- muscle stretch in mm. muscActivation -- normalized muscle activation [0 , 1]. """ bias = 80 xCoef = 1...
1411109acc3cda06606ff4741b602613fcf7be4a
662,587
def get_ep_next(ep_latest, ep_num): """ for provided episode name and number return which should be the next episode Parameters ---------- ep_latest: string the full name of the episode ep_num: the current episode number Returns ------- : string the name of the nex...
8c8ee9c4becce9d6bfc8401f086053a026d40439
662,588
def format_response(res): """Format response to have type of food and address""" response = "Here are some options: \n" for r in res: response += r['fooditems'] response += " at " response += r['address'] response += "\n" return response
52777eaba825c763b4adfa1a8f2619093d704a26
662,589
def effective_prior(p_tar, c_miss, c_fa): """This function adjusts a given prior probability of target p_targ, to incorporate the effects of a cost of miss, cmiss, and a cost of false-alarm, cfa. Args: p_tar: target prior c_miss: cost of miss c_fa: cost of false alarm Returns: ...
a9fd665d626dd5384824b43ce2aca6a41ee2d7e8
662,590
import socket def get_local_internet_ip(): """ get the ip address that can access internet """ p = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) p.connect(('www.baidu.com', 80)) return p.getsockname()[0]
87d2e2fbcbc6f98e18612a83a56fd6e231bb3aaf
662,591
def pad_contract(chain): """Token contract we are buying.""" contract, hash = chain.provider.deploy_contract('TestSolidityAddressHash') return contract
2259c035cb0fa1fd18b07b5fdd29cbcf80d60393
662,592
from datetime import datetime import random def gen_trans_id(): """生成交易流水""" now = datetime.now() str_date = now.strftime('%Y%m%d%H%M%S%f') return str_date + str(random.randint(1000, 9999))
4bf4a540c96f997f8858cda6fc9ac5063486a908
662,593
import collections def _get_odim_root_attributes(nch, grps): """Retrieve root attributes according CfRadial2 standard. Parameters ---------- grps : dict Dictionary of root hdf5 groups ('how', 'what', 'where') Returns ------- attrs : dict Dictionary of root attributes ...
5c99a54cf97d2cc2592e5442f6671c374af5655d
662,594
def version_tuple(v): """Get an integer version tuple from a string.""" return tuple(map(int, (str(v).split("."))))
2a89af9bff389d143afe554bec9287ae6cc3d98c
662,595
def clean_frame(df): """ for each column in the frame with dtype==object, return the list of decoded cell in the Series instead This presumes any type of object is intended to be a string. Be careful. This feels inefficient as hell, but it freaking works. """ def clean_ascii(cell): ...
46ae2be1e7ef4cf5e4c71d6689ceb8d1c5d565ea
662,597
def get_seq_part_from_assembly( content, contig_name, start, end ): """! @brief get seq from start to end; returns modified start and end position, if contig is shorter than requested sequence """ if end > len( content[ contig_name ] ): if start < 0: return content[ contig_name ], 0, len( content[ contig_name ...
497115294776da672ac7f7d92bd9cbc614c1004c
662,598
def norm(X, n=2): """Return the n-norm of vector X""" return sum([x**n for x in X])**(1/n)
101941824728e5eb28ce40d9ddae7a0f5c6acc5d
662,599
def _word_ngrams(ngram_range, tokens, stop_words=None): """Turn tokens into a sequence of n-grams after stop words filtering""" # handle stop words if stop_words is not None: tokens = [w for w in tokens if w not in stop_words] # handle token n-grams min_n, max_n = ngram_range if max_n !...
2856517f87cf62416122384b84af3551aff68409
662,600
import os def export_hdf_metadata(export_path, code, frequence='60min', metadata=None): """ 训练用隶属特征数据导出模块 """ if (isinstance(code, list)): code = code[0] if (metadata is None): #print('{}没有数据'.format(code)) pass else: print(os.path.join(export_path, '{}_{}.hdf5...
a69234a4a83e650a4cf92902064b94fc4f578a8a
662,601
def _in_chunks(seq, size): """ Return sequence in 'chunks' of size defined by size """ return (seq[pos:pos + size] for pos in range(0, len(seq), size))
c5e1f2c95e2cac7543ca312d60e346b1cc3c3141
662,602
import torch def get_boundary_kernel_new(kernel_size=32, boundary_width=6): """ Will return something like this: ============ = = = = ============ size will be (kernel_size, kernel_size) """ filter = torch.zeros(kernel_size, kernel_size) filter[:, :] = 1.0 / (...
f03bdae9aa217ae9c7f983d142da59f6f72e070b
662,603
import torch def env_step(N, board, xy): # → board """Given a one-hot board encoding and a 2-number action, returns a new board state, cyclically-shifted in the correct direction.""" board = board.reshape(*board.shape[:-1], N, N) sh = [*board.shape[:-2], N*N] board_px = torch.cat((board[..., :, -1:], ...
3bf41530f091dd332ef805753c0fe9cfceca9221
662,605
from typing import Type import yaml from typing import OrderedDict def ordered_dump(data, stream=None, Dumper: Type[yaml.SafeDumper] = yaml.SafeDumper, **kwds): """Dump key-value elements in correct order""" class OrderedDumper(Dumper): # pylint: disable=too-many-ancestors pass def _dict_repres...
8c4d652dcfb3aeb31708dd4fa08d9075853a5922
662,606
def bubble_sort(input_list): """ Compare each element with each other element to provide a sorted array. :param input_list A list of objects to be reversed. :return A sorted version/copy of the list. """ for i in range(0, len(input_list)): for j in range(i + 1, len(input_list)): ...
28a051eb8bb1448f8756c33a5af65010a4c39a06
662,607
def coalesce(*fields, **kwargs): """ Return a function which accepts a row and returns the first non-missing value from the specified fields. Intended for use with :func:`petl.transform.basics.addfield`. """ missing = kwargs.get('missing', None) default = kwargs.get('default', None) de...
eef78039912fc28cf4d7d20a361b583fcb9bf755
662,608
import json def parse_desc(rec): """ Parses annotations from a sequence description """ ann = {} desc = rec.description # Nothing to parse. if rec.id == desc: return ann, '' # Attempts to split the description for parsing into JSON payload = rec.description.split(" ", ma...
9e0922939dd693ab4d0374d7473610d73c9ac2f3
662,609
def node(l, v, r, b): """Make an AVL tree node, consisting of a left tree, a value, a right tree, and the "balance factor": the difference in lengths between the right and left sides, respectively.""" return (l, v, r, b)
87a934ab9f4d49c772b4e8900916d75a7868c323
662,610
import torch def numpy2tensor(array, dtype='float'): """ :param array: :param dtype: :return: """ if dtype == 'float': array = torch.from_numpy(array.copy()).float() elif dtype == 'double': array = torch.from_numpy(array.copy()).double() elif dtype == 'half': a...
c608cfebb68329e19cd9c94f29cdd2dde21e14f8
662,611
def get_best_technical_set(df): """Identify set with greatest AUROC in dataframe. Args: df (pd Dataframe): must contain 'auroc_mean' and 'full_label'. Returns: best_set (str): label of best technical set. """ df = df.sort_values(by=['auroc_mean'], ascending=False, ...
a332fe45a674526aae65d23c0fa643bf6c478cd7
662,612
import numpy def distribute( nodes: int, guess: list ) -> list: """ guess (list) MUST contain at least the initial (coor_0) and end (coor_f) coordinate numpy.arrays """ delt = [] for i in range( 1, len( guess ) ): delt.append( numpy.linalg.norm( guess[i] - guess[i-1] ) ) dtot = sum( de...
f659e3f464d8958860ce58f7b572620215e2d71b
662,613
def uM_to_mgml(species_mws, species_concs, scale=1000000): """ Args: species_mws: (dict) For example {'enzyme_1' : 33000, 'substrate_1' : 150} species_concs: (dict) For example {'enzyme_1' : 10, 'substrate_1' : 10000} scale: (int) The scale we are working on. 1=M, 1000=mM, 1000,000=uM....
fa9121d354978bc0d1e5d5cc7033d37b4f0b6df2
662,616
import pkg_resources import json def MOD13Q1(): """Return the MOD13Q1 metadata.""" resource_package = __name__ doc = pkg_resources.resource_string(resource_package, 'json/describe_coverage_response.json') return json.loads(doc)
e37ce884b7630e1f1f6e86d6f9b67291457515a4
662,617
def public_dict(d): """ if type(d) is dict: return dict((k, public_dict(v)) for k, v in d.items() if not k.startswith('_')) elif type(d) is list: return [public_dict(v) for v in d] else: return d """ if isinstance(d, dict): safe_dict = dict((key, public_dict(value)) ...
bf42637ef0aefc9c998945b245a67e2685c9f67c
662,619
from typing import OrderedDict def do_something_on_the_parsed_log(values: OrderedDict): """ this is an example post-processing hook. """ # if 'exit' in values: # # do return values
a0a0ec3a8c3ede1ab2c53ffc4ab4aac2402d0b85
662,620
def load(f): """ read a file into a string """ fh = open(f) text = fh.read() fh.close() return text
6f8efa32c48309c8768e71b7fa0a46791c83746b
662,621
def string_to_bits(string: str) -> str: """将01字符串转换为01比特流。 Args: string: 01字符串。 Returns: 转换后的01比特流。 """ return "".join(list(map(lambda char: chr(ord(char) - ord("0")), string)))
06118d70d69087b9bf5adcfa0ae5e9d88a229ee0
662,622
import inspect def get_params(f): """ Returns parameters and default values to class constructor Example: get_params(_classifier['RandomForestClassifier']) >> {'n_estimators': 100, 'criterion': 'gini', ... 'ccp_alpha': 0.0, ...
c489d1b5296fc116fd83d492eb656b1d1cb524d2
662,623
def load_seq(fasta_file): """ Reads a FASTA file and returns the DNA sequence as a string. fasta_file: the path to the FASTA file containing the DNA sequence returns: the DNA sequence as a string """ retval = "" f = open(fasta_file) lines = f.readlines() for l in lines[1:]: retv...
b472b8e5eff63b5c988204f73c339120d059fae7
662,626
def _build_gene_embedded_list(): """ Helper function intended to be used to create the embedded list for gene """ return [ 'gene_lists.title', 'interpretations.classification', 'interpretations.acmg_rules_invoked.*', 'interpretations.conclusion', 'interpretations.note_tex...
5a29ef41eda40feff076aa73fbd1319b7a929285
662,627
import os def _find_pofiles(top): """Make a list of all po files in dirctory top, or any subdir""" matches = [] for dirpath, dirnames, filenames in os.walk(top): # only add files that are named <something>.po and that is in # a dir named <something>. As in, dirname and filename must match....
f574127c58e4be4757a5985078d56b51ef08b18e
662,628
def list_to_str(lst, space=False): """ convers list as a comma seperated string""" if space: base_str = ', ' else: base_str = ',' return base_str.join((str(c) for c in lst)).rstrip()
d9ed5854d72b0fb64aff2e9888bb55957bf26a38
662,629
import resource def get_current_maxrss(): """ Get the current python process maxrss(high water mark of rss) usage the command: man getrusage for more information Return: maxrss in unit of Mib """ # In Linux, maxrss is in unit of kilobyte mem_kb = resource.getrusage(resourc...
08f600a9ffa74737b713e56cc97fc92f6d971e74
662,630
def get_nonce_bytes(n): """BOLT 8 requires the nonce to be 12 bytes, 4 bytes leading zeroes and 8 bytes little endian encoded 64 bit integer. """ return b"\x00"*4 + n.to_bytes(8, 'little')
3c35dd968d2b92a38937a14a1cecf73a40bd16d2
662,632
def humanize_bytes(num_bytes): """ Convert a number of bytes to human version :param num_bytes: int: bytes to be converted to :return: str """ val = num_bytes suffix = "B" factor = 1000 if val >= factor: val = val / factor suffix = "KB" if val >= factor: v...
a78b16ab91ba639bc7e6e98ca66c72c2d2b4cbea
662,633
def match_score(col1, col2): """ Compute the match score between two columns. We use the overlapping elements as a scoring system. Even the slightest overlap is good enough """ matching_items = 0 for item in list(set(col1)): for item2 in col2: if item == item2 or str(item).lower() == str(item2).lower(): ...
0d17d5d6cda31c1b4865a43dafff997802b8cb09
662,634
def categorical_fillna(data, col, value="N"): """ Fills a categorical features Nan Values with the provided value, returns a new column. The pandas function sometimes does not work """ def helper(x): if isinstance(x, float): return value return x return data[col].app...
5ebfb76e5090e3d149ab6f6e28ebc6987479b483
662,635