content
stringlengths
42
6.51k
def make_collapsible(html_str, collapsible_idx=0): """ Create collapsible button to selectively hide large html items such as images """ pref = ( f'<button data-toggle="collapse" data-target="#demo{collapsible_idx}">' "Toggle show image</button>" f'<div id="demo{collapsible_idx}"...
def factorial(n: int) -> int: """ >>> factorial(5) 120 >>> factorial(6) 720 :param n: :return: factorial of n """ if n <= 2: return n return n * factorial(n - 1)
def _get_index_range(start, stop, length, step=1): """Given start, stop, step and array length, return absolute values of start, stop, and step for generating index range. The returned values have been compensated by adding length if they are less than zero for all the cases but slice(None, None, -1). ...
def is_func_bound(method, instance=None): """ check function is bound in class instance. >>> is_func_bound(lambda :None) False >>> is_func_bound(dict().get) True >>> x = dict(a=1) >>> is_func_bound(x.get, x) True >>> y = dict(a=1) >>> is_func_bound(x.get, y) False :param...
def __guess_key(key, keys, default_value): """Attempts to retrieve a key from a set of keys. There's a somewhat insane amount of domain specific knowledge here. The keys often change subtley, and therefore need some tweaking to find the right keys. This is extremely error prone and should not be trusted...
def sections_split(string): """Given string 'string', return a list of strings for every new section, subsection, subsubsection, etc """ sections = [] this = [] for line in string.splitlines(): if len(line) > 0 and line[0] == '*': # new section starts ## save old ...
def get_spaced_colors(n): """Given number, n, returns n colors which are visually well distributed """ max_value = 255**3 interval = int(max_value / n) colors = [hex(I)[2:].zfill(6) for I in range(0, max_value, interval)] return [(int(i[:2], 16) / 255.0, int(i[2:4], 16) / 255.0, int(i[4:], 16) ...
def locate_snps(reads, snps): """ :param reads: list of Reads :param snps: list of SNPS :return list of READS that have snps in """ return [read.detect_snps(snps) for read in reads]
def byteSized(size: int) -> str: """ Takes a size (in bytes) given by 'size' and returns a human-readable measure of the same number """ if size < 999: return "%dB" % size if size / 0x400 < 999: return "%1.1fkB" % (size/0x400) if size / 0x100000 < 999: return "%1.1fMB" % (size/0x100000) return "%1.2fGB" % ...
def cleanStr(s: str): """Remove characters that the pronouncing dictionary doesn't like. This isn't very efficient, but it's readable at least. :-) >>> cleanStr('fooBar123') 'fooBar123' >>> cleanStr('Hello ([world])') 'Hello world' >>> cleanStr('{hello-world}') 'hello world' Arg...
def to_google_drive_download_url(view_url: str) -> str: """ Utility function to transform a view URL of google drive to a download URL for google drive Example input: https://drive.google.com/file/d/137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp/view Example output: https://drive.google.com/uc?...
def catch_parameter(opt): """Change the captured parameters names""" switch = {'-h': 'help', '-f': 'file'} try: return switch[opt] except: raise Exception('Invalid option ' + opt)
def _dict_slice_remove(a, b, cols=["model_index", "param_set"]): """ Remove dictionary records from list 'a' if the records appear in 'b' for the given columns 'cols'. """ b_ = [{k: d[k] for k in cols} for d in b] a_ = [] for d in a: if {k: d[k] for k in cols} not in b_: ...
def dominant_clade(idx, prev_cutoff=1): """ Which is the dominant clade? """ for k in sorted(idx, key=lambda item: item[0], reverse=True): if idx[k][0] < prev_cutoff: return None else: return k
def convert_to_base_type(input: str, json_mode=False): """ Totally dumb function that does nothing else as to try to convert a string to some basic type * 'False' | 'True' -> Bool * 123456789 -> int * 1.23456789 -> float * everything else -> str :param input: :type input: str :para...
def rgb_to_hex(rgb_array): """! @brief Convert rgb array [r, g, b] to hex string 'ffffff'. @details RGB where r, g, b are in the set [0, 255]. Hex string in set ["000000", "ffffff"]. @param rgb_array RGB array [r, g, b]. @return Hex string 'ffffff' """ r, g, b = rgb_ar...
def _items_remaining(measures, v): """Return whether there are more measures to process Used when converting a complex measure to the primary measure Checks the complex measure the user entered to see if there's more items to process. """ for key in measures: if key in v: ...
def unit_keyed_by_geo(row): """ args: row - should look like ((geo, hhgq), cnt) returns: tuple keyed by geo, joinkey is dropped """ assert len(row) == 2, f"Unit row tuple {row} is not of length 2" (geo, hhgq), cnt = row return ((geo,), ((hhgq,), cnt))
def merge_two_dicts(x, y): """ Given two dicts, merge them into a new dict as a shallow copy. """ z = x.copy() z.update(y) return z
def FXR_calc(item): """ Calculate FNR,FPR,FDR,FOR. :param item: item In expression :type item:float :return: result as float """ try: result = 1 - item return result except Exception: return "None"
def GetExcelStyleColumnLabel(ColNum): """Return Excel style column label for a colum number. Arguments: ColNum (int): Column number Returns: str : Excel style column label. """ Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ColLabelList = [] while ColNum: ColNum, ...
def FormatKeyValue(data): """Formats a dictionary as "key=value" parameters. The keys are sorted to have a stable order. @type data: dict @rtype: list of string """ return ["%s=%s" % (key, value) for (key, value) in sorted(data.items())]
def heaviside(x): """Heaviside step function""" theta = None if x < 0: theta = 0. elif x == 0: theta = 0.5 else: theta = 1. return theta
def rescale_center_wh(obj, config): """ obj: dictionary containing x_min, x_max, y_min, y_max config : dictionary containing IMAGE_W, GRID_W, IMAGE_H and GRID_H """ # unit: grid cell center_w = (obj['xmax'] - obj['xmin']) / (float(config['image_w']) / config['grid_w']) # unit: grid cel...
def duration_from_seconds(seconds): """Converts a number of seconds to a time like format string.""" minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) timelapsed = "{:d}:{:02d}:{:02d}".format(int(hours), int(minutes), ...
def repcount(interp): """ REPCOUNT outputs the repetition count of the innermost current REPEAT or FOREVER, starting from 1. If no REPEAT or FOREVER is active, outputs -1. """ try: return interp._repcount except AttributeError: return -1
def extract_h5_paths(current_layer, next_layer): """ Given a layer name, extract the weights, biases, next layer weights and batchnorm params """ path_dict = {} layer_idx = current_layer[-1] print("changing batchnorm for layer --> ", layer_idx) path_dict['wts'] = 'model_weights/' + \ ...
def change_type(x, func): """ change_type(x, func) Change object type Parameters: ----------- x: object Object to be converted. func: function Function for conversion. Return: ------- func(x) or None if there are value or type error. """ try: r...
def ktau_weighted_distance(r_1, r_2): """ Computes a weighted kendall tau distance. Runs in O(n^2) Args: r_1, r_2 (list): list of weighted rankings. Index corresponds to an item and the value is the weight Entries should be positive and sum to 1 ...
def is_html(type): """"determine whether a mimetype says a resource is a html file. """ return type in {'text/html', 'application/xhtml+xml'}
def _replace_revision(raw_header: bytes, revision: bytes) -> bytes: """Replace the 'revision' field in a raw header.""" return raw_header[:8] + revision + raw_header[8 + 4 :]
def _is_file_valid(name: str) -> bool: """Decide if a file is valid.""" return not name.startswith('.')
def get_constraint_transform_applied_scaling_factor(c, default=None): """Get a the scale factor that was used to transform a constraint. Args: c: constraint data object default: value to return if no scaling factor exists (default=None) Returns: The scaling factor that has been...
def add_newline_to_end_of_each_sentence(x: str) -> str: """This was added to get rougeLsum scores matching published rougeL scores for BART and PEGASUS.""" if "<n>" in x: return x.replace("<n>", "\n") # remove pegasus newline char else: return x
def process(path): """ This function takes a path to a file and does stuff. [For documentation example.] :type path: string :param path: a path to the file which contains the features :return: None """ print(path) return None
def add_property_to_feature(feature, property_key, property_value): """ :param feature: :type property_key: str :param property_key: :type property_value: str :param property_value: :return: """ if "feature_property" not in feature: feature["feature_property"] = {} featu...
def _check_sequence(graph_seq, known_seq): """ Check that the sequence matches up to a certain point for the known sequence. If it does return the index to where it matches. If it doesn't return 0. :param graph_seq: Actual sequence in the graph :param known_seq: One of the known sequences :retur...
def round_to_next_multiple_of(number, divisor): """ Return the lowest x such that x is at least the number and x modulo divisor == 0 """ number = number + divisor - 1 number = number - number % divisor return number
def format_walk_time(walk_time): """ takes argument: float walkTime in seconds returns argument: string time "xx minutes xx seconds" """ if walk_time > 0.0: return str(int(walk_time / 60.0)) + " minutes " + str(int(round(walk_time % 60))) + " seconds" else: return "Walk time is ...
def SerializeAttributesToJsonDict(json_dict, instance, attributes): """Adds the |attributes| from |instance| to a |json_dict|. Args: json_dict: (dict) Dict to update. instance: (object) instance to take the values from. attributes: ([str]) List of attributes to serialize. Returns: json_dict ""...
def _get_template_service_account(template): """Get service account from template.""" return template['properties']['serviceAccounts'][0]['email']
def pad(val: str) -> str: """Pad base64 values if need be: JWT calls to omit trailing padding.""" padlen = 4 - len(val) % 4 return val if padlen > 2 else (val + "=" * padlen)
def _beautify_message(msg): """ Function for cleaning the received message. Removes everything not allowed by the specification, adds some required fields and renames some to follow the specification. :param msg: Received message as dictionary :return: Cleaned message. """ msg["type"] = "...
def doc_brief(s): """ Returns the first line of an operator's docstring to use as a summary of how the operator works. The line in question must contain *brief*. """ return " ".join(s.split("\n\n")[0].split()[1:]) if s.startswith("*brief*") else s
def normalize_key(key: str): """ Normalize CSV header values """ key = key.lower().replace('_', '').replace('-', '').replace(' ', '') return { 'startdatetime': 'start_date_time', 'enddatetime': 'end_date_time', 'resultslocation': 'results_location' }.get(key, key)
def identify_var_units(label): """ This function parses the x-label or y-label to figure out the variable name and unit if possible. Parameters ---------- label : str The label of x- or y-axis. Returns ------- var : str The name of the variable. unit :str ...
def digits(n, reverse=False, base=10, string=False): """ List of the individual digits that comprise the given number. Providing a base will convert the number to that base. When string is True, a string is returned where alphabetic characters are used intead of integers (works up to and including base ...
def ir(some_value): """Int-round function for short array indexing """ return int(round(some_value))
def tuple2int(t, cnames, op_widths_dict): """Convert list of values in the input parameter t to a hash key by shifting and adding (OR'ing really) the values together. Must factor in the max width of each field. The max width of each component comes from the cnames and op_widths_dict parameters)...
def highest_role_position(arr: list): """ Function that takes in an array of discord Roles and return the int of the highest position from all those roles Parameters ---------- arr: list the array of discord roles Returns ------- int the highest position found within th...
def mult_over_list(l): """ Doc string. """ product = 1 for e in l: product *= int(e) return product
def full_path(filename): """convert local file name to full path.""" import os.path folder = os.path.dirname(os.path.realpath(__file__)) return os.path.join(folder, filename)
def generate_machine_netplan_config(config, machine): """ Generates a Netplan config based on the machine configuration :param config: dict: The config generates by get_config() :param machine: str: The machine name to generate the netplan config for :return: dict: The netplan config """ no_...
def has_findings(active_scans, scanned_file): """ Return True if the `scanned_file` has findings for any of the `active_scans` names list (excluding basic file information). """ return any(scanned_file.get(scan_name) for scan_name in active_scans)
def is_container(item): """Checks if item is a container (list, tuple, dict, set) Parameters ---------- item : object object to check for .__iter__ Returns ------- output : Boolean True if container False if not (eg string) """ if isinstance(item, str): ...
def get_query_kwargs(es_defs): """ Reads the es_defs and returns a dict of special kwargs to use when query for data of an instance of a class reference: rdfframework.sparl.queries.sparqlAllItemDataTemplate.rq """ rtn_dict = {} if es_defs: if es_defs.get("kds_esSpecialUnion"): ...
def is_meta_pair(word1, word2): """Return true if word1 and word 2 are metathesis pairs, i.e. if you can transform one into the other by switching two letters. word1, word2: string """ # Run through ever pair of letters in word1. Take the first letter and # the second, first and third, ...then s...
def write_rule(sizes, is_header=False): """ - sizes: (Array int), the column widths (of contents) RETURN: string """ mark = '=' if is_header else '-' return '+' + ''.join([(mark*n + '+') for n in sizes]) + '\n'
def strip_hash_bookmark_from_url(url): """Strip the hash bookmark from a string url""" return (url or '').split('#')[0]
def allow_coef0_specification(value): """Dash callback for enabling/disabling the 0th coefficient input widget for support vector classification. Given a kernel from the dropdown menu, allow the user to specify a 0th coefficient if the selected kernel is polynomial ("poly") or sigmoid. Otherwise, d...
def indexes(alist, srch): """return a list of all the indexes of srch in alist""" res = [] work = alist while srch in work: itm = work.index(srch) if len(res): res.append(itm+res[-1]+1) else: res.append(itm) work=work[itm+1:] return res
def data_set_exists(name, run_command): """Checks for existence of data set.""" rc, stdout, stderr = run_command('head "//\'{0}\'"'.format(name)) if rc != 0 or (stderr and 'EDC5049I' in stderr): return False return True
def combine_spans(span1, span2): """Merge two text span dictionaries """ new_span = {} new_span['CharacterSpanList'] = span1['CharacterSpanList'] + span2['CharacterSpanList'] new_span['SpanList'] = span1['SpanList'] + span2['SpanList'] new_span['RawText'] = span1['RawText'] + span2['RawText'] ...
def get_type_name(typ) -> str: """The code generated is put in the totkn module (totkn.py) so it can not reference itself with a fully qualified name""" if hasattr(typ, "__name__"): return typ.__name__ s = str(typ) return s.replace("totkn.", "")
def trim_float(f): """ returns a trimmed string from a float: 4.20000000000000000 -> 4.2 """ return str(f).rstrip('0').rstrip('.')
def greedify(strategy, multiple_actions_allowed=False): """ Greedifies the given strategy. -1 is the minumum value and 1 is the maximum. Args: strategy: The strategy to greedify. multiple_actions_allowed: Whether multiple actions are allowed. Returns: A greedified version of the ...
def selectSupportedKeyswitch(switchType): """ Returns footprint name of the supported switch, returns an error if not supported Returned object will have this form: { "lib_dir":"", "footprint_ref": "", } """ def selectMXParts(): ...
def check_box(iou, difficult, crowd, order, matched_ind, iou_threshold, mpolicy="greedy"): """ Check box for tp/fp/ignore. Arguments: iou (np.array): iou between predicted box and gt boxes. difficult (np.array): difficult of gt boxes. order (np.array): sorted order of iou's. ...
def get_content_type(file_extension): """ getting content_type via file_type. :param file_extension :return: content_type """ file_extension = file_extension.lower() if file_extension == 'pdf': content_type = 'application/pdf' elif file_extension == 'bmp': content_type = ...
def build_idef_regexp( curr_idef ): """ build regexp quering collection """ level_num= curr_idef.count('-') if level_num > 0: # deeper than 'a' idef_srch= curr_idef.rsplit('-', 1)[0] lookup_idef= "^%s\-\d+$" % idef_srch curr_idef= idef_srch level= 1 while level < leve...
def is_int_in_inclusive_range(value, min_value, max_value): """ Is the given value an int in the range [min_value, max_value] :param value: value being checked :type value: Any :param min_value: minimum allowed int :type min_value: int :param max_value: maximum allowed int :type max_value: i...
def f_string_1(value): """Round value with 1 decimals.""" return f'{value:.1f}'
def getModFromCipher(key: int, cipher: int, rest: int): """ get the base from the sipher, the key and the rest values :param key: a temporary integer key :param cipher: the ciphered base retreived from the file :param rest: the rest of the equation (see Utilities:generateCipher) :return: a inte...
def to565(pixel): """ convert 24bit to 16bit """ red = pixel[0] green = pixel[1] blue = pixel[2] return ((red & 0x00F8) << 8) | ((green & 0x00FC) << 3) | ((blue & 0x00F8) >> 3)
def normalize(coordinate: int, length: int) -> float: """Convert a pixel coordinate to normalized float coordinate between 0 and 1""" if not (0 <= coordinate <= length): raise ValueError('Coordinate exceeds bounds') return coordinate / length
def format_elapsed_seconds(elapsed_seconds): """ Helper function to convert number of seconds to a string of hours, minutes, and seconds :param elapsed_seconds: float or int of the number of elapse seconds to format into a string :return: formatted time string """ hours = int(elapsed_seconds / ...
def quote_value(value): """ Quote a Python object if it is string-like. """ if value in ("True", "False", "None"): return str(value) try: float(value) return str(value) except ValueError: pass if isinstance(value, str): return '"{}"'.format(value) ...
def read_file(filepath: str) -> str: """Read entire data from file.""" with open(filepath) as file: return file.read()
def make_auxfilenames(list_iter: list, case_name: str, aux_ext: str) -> list: """Create a TRACE files with customized extension (used as auxiliary files) :param list_iter: (list) the iterator converted to a list of integer :param case_name: (str) the case name :param aux_ext: (str) the extension of aux...
def merge_dicts(*dicts): """Merge two or more dicts, later ones replacing values of earlier ones. Note that only shallow copies are made of the dicts. @b Examples ``` a = dict(a=1, b=2, c=3) b = dict(c=-3, d=-4) c = merge_dicts(a, b) # Result: dict(a=1, b=2, c=-3, d=-4...
def _is_number( strg ): """ Helper function which determines whether the given string parameter contains a valid number. Returns True if the string is a number and False otherwise. """ try: isitanumber = float( strg ) return True except (ValueError, TypeError): ...
def add_spans(span_list_A, span_list_B): """givin two lists of spans, return anouther list where the spans are combined. Essentially A or B.""" ## math notes: algorithm is symetric between two lists. Adding only produces one or two spans current_spans = span_list_A + span_list_B good_spans = [...
def get_all_inds(string, substr): """Returns indices of all occurrences of a substring.""" # initialize list of indices of occurrences with dummy entry inds = [0] # find first occurrence i_curr = string.find(substr) # while end of string has not been reached while i_curr != -1: # det...
def solution(n): """ This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3. Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 ...
def itos2(integer1, integer2): """Convert two 2-byte integers to math_library 32-bit number""" return chr(integer1>>8) + chr(integer1&0xFF) + chr(integer2>>8) + chr(integer2&0xFF)
def modulename(filename): """ Find the modulename from filename. filename string, name of a python file """ return filename.split('/')[-1].replace('.pyc', '').replace('.py', '')
def reverse3(lst): """ Returns a new list containing the same elements in reverse order. >>>lst = [10, 11, 12] [12, 11, 10] >>>lst = [11, 12, 13] [13,12,11] """ lst.reverse() return lst
def only_keep_fields(data,fields): """Filter out fields from a user for security reasons""" datakeep = {} for bb in fields: try: datakeep[bb] = data[bb] except: pass return datakeep
def parse_time(time): """Parse a time string into (hour, minute, second, microsecond), including AM/PM. >>> parse_time('12:00') (12, 0, 0, 0) >>> parse_time('01:02AM') (1, 2, 0, 0) >>> parse_time('01:02PM') (13, 2, 0, 0) >>> parse_time('13:02PM') (13, 2, 0, 0) >>> p...
def myformat(s,l,indent=0,breakon=" "): """ Try to pretty print lines - this is a pain... """ lines = s.rstrip().split("\n") out="" for line in lines: if len(line)==0: continue # skip blank lines if len(line)>l: words = line.split(breakon) newline=words[0] ...
def commonPaths(paths): """ Returns the common component and the stripped paths It expects that directories do always end with a trailing slash and paths never begin with a slash (except root). @param paths: The list of paths (C{[str, str, ...]}) @type paths: C{list} @retu...
def mirrorLayers( TopLayers ): """ The functions mirrors the input list placing the last entry of the input list at the center of the output list. If the input list contains only one entry the function returns just a float number :param TopLayers: list of float values :return: list of float numb...
def get_target_years(start, end, options_list): """Return a string based list of the year range :param start: Start Year :type start: str :param end: End year :type end: str :param options_list months from dropdown :...
def divisors(num): """ m < n ==> m = k n | k in (0, 1) T = T1 + T2 + n (T3 + T4) + k n T5 ==> O(n) = Tb + n (T3 + T4 + k T5) = Tb + n Ta T = n Ta + Tb O(n/2) = O(0.5 n) ==> O(n) T = 0.5 n Ta + Tb """ assert isinstance(num, int) # T1 divs = [] # T2 #...
def dict_put_nested(d, key, value, type=dict): """Put a (potentially nested) key to a dict-like. A nested key is of the format 'a.b.c', which will generated a dict of type `type` with three levels: >>> d = {} >>> dict_put_nested(d, 'a.b.c.', 1) >>> print(d) {'a': {'b': {'c'...
def compare(word1, word2): """Function Compare 2 word """ i = 0 if len(word2) == 0: return 0 if 0.6 <= (len(word1) / len(word2)) <= 1.65: for char1, char2 in zip(word1, word2): if char1 == char2: i += 1 if len(word1) < len(word2): if word1[...
def div(a, b): """ Function that divides 2 arguements """ a = float(a) b = float(b) return a / b
def _get_factors(n): """return all the factors of n""" factors = set() for i in range(1, int(n ** (0.5)) + 1): if not n % i: factors.update((i, n // i)) return factors
def binary_search_oprns(a, d, lo, hi, asc_order=True,\ oprns=[0]): """ Binary search, but counts the number of operations for complexity analysis. """ if a[lo]>d: oprns[0]+=1 return lo-1 elif a[hi]<d: oprns[0]+=1 return hi while lo < h...
def linear_search(iterable, item): """Returns the index of the item in the unsorted iterable. Iterates through a collection, comparing each item to the target item, and returns the index of the first item that is equal to the target item. * O(n) time complexity * O(1) space complexity Args: iterable:...