content
stringlengths
42
6.51k
def get_leaf_node_attribute(tree, attribute): """Recursively find an attribute of the leaf nodes of a tree. Parameters ---------- tree : dict A dictionary of dictionaries tree structure attribute : str The attribute to find at the root nodes Returns ------- list A list of attributes """ leaf_nodes = [] def get_leaf_node_attribute_helper(subtree, attribute): """Helper function to recursively find root node attributes. Parameters ---------- subtree : dict A dictionary of dictionaries tree structure attribute: str The attribtue to find at the root nodes Returns ------- None (either another function call is made or an item is appended to a list) """ keys = subtree.keys() if keys == [attribute]: leaf_nodes.append(subtree[attribute]) else: for key in keys: if key != attribute: get_leaf_node_attribute_helper(subtree[key], attribute) get_leaf_node_attribute_helper(tree, attribute) return leaf_nodes
def _heuristic_is_identifier(value): """ Return True if this value is likely an identifier. """ first = str(value)[0] return first != '-' and not first.isdigit()
def getattr_chain(obj, attr_chain, sep='.'): """Get the last attribute of a specified chain of attributes from a specified object. E.g. |getattr_chain(x, 'a.b.c')| is equivalent to |x.a.b.c|. @param obj: an object @param attr_chain: a chain of attribute names @param sep: separator for the chain of attribute names """ # if sep is None: sep = '.' # attr_name_s = attr_chain.split(sep) # new_obj = obj for attr_name in attr_name_s: new_obj = getattr(new_obj, attr_name) # return new_obj
def index_batch_iterator(batch_size, n_sents): """ Return batch indices """ n_batches = n_sents//batch_size if (n_sents % batch_size) != 0: n_batches += 1 low = 0 high = 0 range_list = [] for i in range(n_batches): high = low + batch_size if high > n_sents: high = n_sents range_list.append((low, high)) low = high return range_list
def normalise_period(val): """Return an integer from 1 to 12. Parameters ---------- val : str or int Variant for period. Should at least contain numeric characters. Returns ------- int Number corresponding to financial period. Examples -------- >>> normalise_period('P6') 6 >>> normalise_period(202106) 6 """ val = ''.join(c for c in str(val) if c.isdigit()) return int(val[-2:])
def getShortestPaths(paths): """ Returns a list containing only the shortest paths. The list may contain several shorters paths with the same length. """ shortestPaths = [] shortestLength = 99999 for path in paths: if len(path) < shortestLength: shortestLength = len(path) for path in paths: if len(path) == shortestLength: shortestPaths.append(path) return shortestPaths
def first_non_zero(arr): """ Return the index of the first element that is not zero, None, nan, or False (basically, what ever makes "if element" True) The other way to do this would be where(arr)[0][0], but in some cases (large array, few non zeros)) this function is quicker. Note: If no element is "non zero", the function returns None """ for i, a in enumerate(arr): if a: return i return None
def flatten(l): """ Concatentates and flattens all numbers together in list of lists """ final = [] for i in range(0, len(l)): if isinstance(l[i], list): final = final + flatten(l[i]) else: final.append(l[i]) return final
def legal(puzzle, i, j, k, diagonal=False): """ Check if k can be placed at the jth column of ith row. Parameters: puzzle (nested list): sudoku grid i (int): row to be checked j (int): column to be checked k (int): number to be placed in puzzle[i][j] diagonal (bool): True if diagonal sudoku, False otherwise (default: False) Returns: bool: True if k can be placed in puzzle[i][j], False otherwise. """ for a in range(9): if a != j and puzzle[i][a] == k: return False if a != i and puzzle[a][j] == k: return False for a in range((i//3)*3, (i//3)*3+3): for b in range((j//3)*3, (j//3)*3+3): if puzzle[a][b] == k: return False if diagonal: diag_left = [0]*10 diag_right = [0]*10 temp = puzzle[i][j] puzzle[i][j] = k for a in range(9): diag_left[puzzle[a][a]] += 1 diag_left[puzzle[a][8-a]] += 1 puzzle[i][j] = temp if not all([diag_left[a] <= 1 for a in range(1, 10)]): return False if not all([diag_right[a] <= 1 for a in range(1, 10)]): return False return True
def get_dataset_size(data_cfg): """ Note that this is the size of the training dataset """ name = data_cfg['name'] if name == 'mnist': if data_cfg['binary']: N = 10397 else: N = 54000 elif name in ['cifar10', 'cifar10_pretrain','cifar10_cnn']: if data_cfg['binary']: N = 9000 else: assert data_cfg['subset'] N = 20000 elif name == 'adult': N = 29305 elif name == 'forest': N = 378783 else: raise NotImplementedError return N
def get_indices_of_A_in_B(A, B): """Return the set of indices into B of the elements in A that occur in B Parameters ---------- A : list The "needles" B : list The "haystack" Returns ------- list Indices into B of elements in A occuring in B """ s = set(B) return [i for i, e in enumerate(A) if e in s]
def _all_none(*args): """Returns a boolean indicating if all arguments are None""" for arg in args: if arg is not None: return False return True
def parse_csl(value, lower=True): """ reads a string that is a comma separated list and converts it into a list of strings stripping out white space along the way :param value: the string to parse :param lower: should we also lowercase everything (default true) :return: a list of strings """ value = value.strip() if not value: return [] if lower: return [t.strip() for t in value.lower().strip().split(",")] return [t.strip() for t in value.strip().split(",")]
def convert_faces_into_triangles(faces): """ Converts the faces into a list of triangles :param faces: List of faces containing the triangles :return: A list of the triangles that make a face """ triangles = [] for face in faces: triangles_in_face = len(face) - 2 triangles.extend( [[face[0], face[i + 1], face[i + 2]] for i in range(triangles_in_face)] ) return triangles
def merge_input_bam(info_dict,path_start): """ Find the input files in the sample info sheet and merge them into one single bam file """ input_files = [] NA_index = [i for i, x in enumerate(info_dict["Input"]) if x == "NA"] all_files = info_dict["Sample"] #full file name with path for i in NA_index: file = path_start+all_files[i]+"/bwa_out/"+all_files[i]+".bam" input_files.append(file) ffiles = " ".join(str(x) for x in input_files) return ffiles
def filter_staff(thread_url): """ Dirty and quick way to trim some stuff off the end of a url """ if "/page" in thread_url: index = thread_url.rfind("/page") elif "#p" in thread_url: index = thread_url.rfind("#p") else: return thread_url + "/filter-account-type/staff" return thread_url[:index] + "/filter-account-type/staff"
def get_string_value(value_format, vo): """Return a string from a value or object dictionary based on the value format.""" if "value" in vo: return vo["value"] elif value_format == "label": # Label or CURIE (when no label) return vo.get("label") or vo["id"] elif value_format == "curie": # Always the CURIE return vo["id"] # IRI or CURIE (when no IRI, which shouldn't happen) return vo.get("iri") or vo["id"]
def get_response_text(response): """ Combines message and errors returned by a function to create an HTML to be displayed in a modal """ messageHTML = "" if "message" in response: messageHTML += "<h4>" + response["message"] + "</h4>" if "error" in response: for key in response["error"]: for error in response["error"][key]: messageHTML += "<h4>" + error + "</h4>" return messageHTML
def is_same_rectangle(node1, node2, use_ids=False): """ :param node1: :param node2: :param use_ids: :return: """ return (node1["in_element"] == "rectangle" and node1["in_element_ids"] == node2["in_element_ids"] and use_ids) or node1["box"] == node2["box"]
def get_named_parent(decl): """ Returns a reference to a named parent declaration. :param decl: the child declaration :type decl: :class:`declaration_t` :rtype: reference to :class:`declaration_t` or None if not found """ if not decl: return None parent = decl.parent while parent and (not parent.name or parent.name == '::'): parent = parent.parent return parent
def parse_ps_results(stdout): """Parse result of `ps` command Parameters ---------- stdout : str Output of running `ps` command Returns ------- list A List of process id's """ # ps returns nothing if not stdout.replace('\n', '').strip(): return [] # ps returns something return [ int(line.split()[0]) for line in stdout.split('\n') if line.replace('\n', '').strip() ]
def sls_cmd(command, spec): """Returns a shell command string for a given Serverless Framework `command` in the given `spec` context. Configures environment variables (envs).""" envs = ( f"STAGE={spec['stage']} " f"REGION={spec['region']} " f"MEMORY_SIZE={spec['memory_size']} " ) # NOTE: prefix with "SLS_DEBUG=* " for debugging return f"{envs}serverless {command} --verbose"
def get_level_name(verbose): """Return the log levels for the CLI verbosity flag in words.""" if verbose > 3: verbose = 3 level_dict = { 0: 'ERROR/FATAL/CRITICAL', 1: 'WARNING', 2: 'INFO', 3: 'DEBUG', } return level_dict[verbose]
def get_sum3(a: int, b: int) -> int: """ My third version, that is just an even more concise version of the first one. """ return sum([i for i in range(min(a, b), max(a, b)+1)])
def sc(txt): """ >>> print(sc('gentle shout')) <span class="sc">gentle shout</span> >>> print(sc('I wish I could be in small caps', tags=False)) I wish I could be in small caps """ return f'<span class="sc">{txt}</span>'
def parse_codesys(info): """ Operating System: Nucleus PLUS Operating System Details: Nucleus PLUS version unknown Product: 3S-Smart Software Solutions """ infos = info.split('\n') data = {} for info in infos: if ':' not in info: continue k, v = info.split(':', 1) if '.' in k: continue data[k] = v.strip() return data
def streams_to_named_streams(*streams): """ >>> stream_0 = [1, 2, 3, 4, 5, 6] >>> stream_1 = [-1, -2, -3, 0, -5, -6] >>> streams_to_named_streams(stream_0, stream_1) {0: [1, 2, 3, 4, 5, 6], 1: [-1, -2, -3, 0, -5, -6]} """ return dict(enumerate(streams))
def is_key_matured(key, key_params): """ key_params provides full information for key or not """ try: key.format(**key_params) except KeyError: return False else: return True
def replace_in_list(my_list, idx, element): """Replace an element of a list at a specific position.""" if idx >= 0 and idx < len(my_list): my_list[idx] = element return (my_list)
def meanPoint(coordDict): """Compute the mean point from a list of cordinates.""" x, y, z = zip(*list(coordDict.values())) mean = (float(format(sum(x) / len(coordDict), '.2f')), float(format(sum(y) / len(coordDict), '.2f'))) return mean
def humanize_duration(seconds: float) -> str: """Format a time for humans.""" value = abs(seconds) sign = "-" if seconds < 0 else "" if value < 1e-6: return f"{sign}{value*1e9:.1f}ns" elif value < 1e-3: return f"{sign}{value*1e6:.1f}us" if value < 1: return f"{sign}{value*1e3:.1f}ms" elif value < 60: return f"{sign}{value:.3f}s" else: return f"{sign}{value:.1f}s"
def tuple_pull_to_front(orig_tuple, *tuple_keys_to_pull_to_front): """ Args: orig_tuple: original tuple of type (('lS', 5.6), ('lT', 3.4000000000000004), ('ZT', 113.15789473684211), ('ZS', 32.10526315789474)) *tuple_keys_to_pull_to_front: keys of those tuples that (in the given order) should be pulled to the front of the orig_tuple """ orig_lst = list(orig_tuple) new_lst = [] new_lst2 = [] for otup in orig_lst: if otup[0] in tuple_keys_to_pull_to_front: new_lst.append(otup) else: new_lst2.append(otup) new_lst.extend(new_lst2) return new_lst
def indexLinePivot(tableaux, minOrMax, _colPivot, _linePivot): #seach index var from base that'll come out """ [seach the index of the variable that is come out] Arguments: tableaux {[matrix]} -- [matrix with all elements] minOrMax {[int]} -- [<= or >=] _colPivot {[int]} -- [index of actual column pivot] _linePivot {[int]} -- [index of the last line pivot] Returns: [int] -- [index of actual pivot line] """ piv = -1 if minOrMax == 1:#max print("new column pivot: "+str(_colPivot)) i = 0 maxI = 9999 for line in tableaux: j = 0 if i != _linePivot and i < len(tableaux)-1: for col in line: if j == _colPivot and col > 0 and (float(line[-1])/float(col)) < maxI: #SPLIT TEST maxI = (float(line[-1])/float(col)) piv = i j += 1 i += 1 elif minOrMax == 2: #min i = 0 minI = 9999 for line in tableaux: j = 0 if i != _linePivot: if i < len(tableaux)-1: for col in line: if j == _colPivot and col > 0 and (float(line[-1])/float(col)) <= minI: #SPLIT TEST minI = (float(line[-1])/float(col)) piv = i j += 1 i += 1 print("Variavel que sai: X"+str(tableaux[piv][0])) return piv
def convert_into_nb_of_days(freq: str, horizon: int) -> int: """Converts a forecasting horizon in number of days. Parameters ---------- freq : str Dataset frequency. horizon : int Forecasting horizon in dataset frequency units. Returns ------- int Forecasting horizon in days. """ mapping = { "s": horizon // (24 * 60 * 60), "H": horizon // 24, "D": horizon, "W": horizon * 7, "M": horizon * 30, "Q": horizon * 90, "Y": horizon * 365, } return mapping[freq]
def unsigned_int(param): """validate if the string param represents a unsigned integer, raises a ValueError Exception on failure""" if param.isdigit(): return True error = 'unsigned integer expected got "{0}" instead'.format(param) raise ValueError(error)
def replace_unknown_letter_in_ref(ref_seq, residue_seq): """ replace unknown letters in the reference sequence, such as "X" or "N" :return: the updated reference sequence which only contains "ACGU" """ if len(ref_seq) != len(residue_seq): return None ref_seq_list = list(ref_seq) for i in range(len(ref_seq_list)): if ref_seq_list[i] not in ["A", "C", "G", "U"] and residue_seq[i] in ["A", "C", "G", "U"]: ref_seq_list[i] = residue_seq[i] elif ref_seq_list[i] not in ["A", "C", "G", "U"] and residue_seq[i] not in ["A", "C", "G", "U"]: # if ref_seq_list[i] not in unknown_letter_dict: # unknown_letter_dict[ref_seq_list[i]] = [] # unknown_letter_count[ref_seq_list[i]] = 0 # if pdb_id not in unknown_letter_dict[ref_seq_list[i]]: # unknown_letter_dict[ref_seq_list[i]].append(pdb_id) # unknown_letter_count[ref_seq_list[i]] += 1 # ref_seq_list[i] = random.choice(["A", "C", "G", "U"]) ref_seq_list[i] = "X" ref_seq_replaced = "".join(ref_seq_list) return ref_seq_replaced
def _find_union(lcs_list): """Finds union LCS given a list of LCS.""" return sorted(list(set().union(*lcs_list)))
def merge_elements(el1, el2): """ Helper function to merge 2 element of different types Note: el2 has priority over el1 and can override it The possible cases are: dict & dict -> merge keys and values list & list -> merge arrays and remove duplicates list & str -> add str to array and remove duplicates str & str -> make a list and remove duplicates all other cases will raise a ValueError exception """ if isinstance(el1, dict): if isinstance(el2, dict): # merge keys and value el1.update(el2) return el1 else: raise ValueError('Incompatible types when merging databases: element1 of type {}, element2 of type {}'.format(type(el1).__name__, type(el2).__name__)) elif isinstance(el1, list): if isinstance(el2, list): # merge arrays and remove duplicates el1.extend(el2) return list(set(el1)) elif isinstance(el2, str): # add string to array and remove duplicates el1.append(el2) return list(set(el1)) else: raise ValueError('Incompatible types when merging databases: element1 of type {}, element2 of type {}'.format(type(el1).__name__, type(el2).__name__)) elif isinstance(el1, str): if isinstance(el2, str): # make a list and remove duplicates return list(set([el1, el2])) else: return merge_elements(el2, el1) raise ValueError('Wrong type in database: only "dict", "list" or "str" are permitted - element of type {}'.format(type(el1).__name__))
def content_is_image(maintype): """Check if HTML content type is an image.""" return maintype in ("image/png", "image/jpeg", "image/gif")
def index_map(args): """Return a dict mapping elements to their indices. Parameters ---------- args : Iterable[str] Strings to be mapped to their indices. """ return {elm: idx for idx, elm in enumerate(args)}
def analyticalMSD(D, t, d): """ Analytical Mean Squared Displacement D = diffusion coefficient t = time step d = dimesion """ return 2 * d * D * t
def bisect_root(f, x0, x1, err=1e-7): """Find a root of a function func(x) using the bisection method""" f0 = f(x0) #f1 = f(x1) while (x1 - x0) / 2.0 > err: x2 = (x0 + x1) / 2.0 f2 = f(x2) if f0 * f2 > 0: x0 = x2 f0 = f2 else: x1 = x2 #f1 = f2 return (x0 + x1) / 2.0
def solution(array_size, queries): # O(M * N) """ Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in your array. For example, the length of your array of zeros. Your list of queries is as follows: a b k 1 5 3 4 8 7 6 9 1 Add the values of between the indices and inclusive: index-> 1 2 3 4 5 6 7 8 9 10 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [3, 3, 3, 3, 3, 0, 0, 0, 0, 0] [3, 3, 3, 10, 10, 7, 7, 7, 0, 0] [3, 3, 3, 10, 10, 8, 8, 8, 1, 0] The largest value is 10 after all operations are performed. >>> solution(10, [(1, 5, 3), (4, 8, 7), (6, 9, 1)]) 10 >>> solution(5, [(1, 2, 100), (2, 5, 100), (3, 4, 100)]) 200 """ array = [0] * array_size # O(M) max_value = float('-inf') # O(1) for (a, b, k) in queries: # O(N) i = a - 1 # O(1) j = b - 1 # O(1) while i < j: # O(M) array[i] += k # O(1) max_value = max(array[i], max_value) # O(1) i += 1 # O(1) return max_value # O(1)
def broadcast(dct): """Convenience function for broadcasting a dictionary of lists. Parameters ---------- dct : dict Input parameter ranges. All parameter ranges must have only 1 or N values. Returns ------- list List of N dictionaries; the input parameters with N values are 'zipped' together """ N = 1 for k, v in dct.items(): if len(v) > N: N = len(v) ret = [] for i in range(N): entry = {} for k, v in dct.items(): if len(v) != N: entry[k] = v[0] else: entry[k] = v[i] ret.append(entry) return ret
def get_up_down_filter(filters, field, direction): """ This function returns the appropriate mask to filter on the given field in the given direction. It assumes the filters are in the same order as the output of get_up_and_down_masks. Parameters ---------- filters : tuple The result of the call to get_up_and_down_masks field : string The name of the field on which to filter. Valid options are: * ribo * rna * te direction : string The direction in which to filter. Valid options are: * up * down Returns ------- significance_mask : boolean mask The appropriate mask for filtering for significance based on the given field. """ # just map from the field to the index of the significant filters field_map = { "te": 0, "rna": 2, "ribo": 4 } direction_map = { "up": 0, "down": 1 } index = field_map[field] + direction_map[direction] return filters[index]
def _small_mie(m, x): """ Calculate the efficiencies for a small sphere. Typically used for small spheres where x<0.1 Args: m: the complex index of refraction of the sphere x: the size parameter of the sphere Returns: qext: the total extinction efficiency qsca: the scattering efficiency qback: the backscatter efficiency g: the average cosine of the scattering phase function """ m2 = m * m x2 = x * x D = m2 + 2 + (1 - 0.7 * m2) * x2 - (8 * m**4 - 385 * m2 + 350) * x**4 / 1400.0 + \ 2j * (m2 - 1) * x**3 * (1 - 0.1 * x2) / 3 ahat1 = 2j * (m2 - 1) / 3 * (1 - 0.1 * x2 + (4 * m2 + 5) * x**4 / 1400) / D bhat1 = 1j * x2 * (m2 - 1) / 45 * (1 + (2 * m2 - 5) / 70 * x2) / (1 - (2 * m2 - 5) / 30 * x2) ahat2 = 1j * x2 * (m2 - 1) / 15 * (1 - x2 / 14) / \ (2 * m2 + 3 - (2 * m2 - 7) / 14 * x2) T = abs(ahat1)**2 + abs(bhat1)**2 + 5 / 3 * abs(ahat2)**2 temp = ahat2 + bhat1 g = (ahat1 * temp.conjugate()).real / T qsca = 6 * x**4 * T if m.imag == 0: qext = qsca else: qext = 6 * x * (ahat1 + bhat1 + 5 * ahat2 / 3).real sback = 1.5 * x**3 * (ahat1 - bhat1 - 5 * ahat2 / 3) qback = 4*abs(sback)**2/x2 return [qext, qsca, qback, g]
def getFolder(file): """ Gets folder of a specific file """ if "/" in file: return file[:file.rfind("/")+1] else: return ""
def format_decimal(value, mask): """ Format an integer as a decimal string """ if mask is None: return str(value) return "{:d}/{:d}".format(value, mask)
def value2TagName(value): """ The @value2TagName@ class method converts the *value* object into a value XML tag name. """ tagname = [] if not isinstance(value, str): value = str(value) if value.lower().startswith('xml'): tagname.append('_') for c in value: if c in ' !?@#$%^&*()[]\t\r\n/\\': pass elif c.upper() in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890:.': tagname.append(c) else: tagname.append('_') return ''.join(tagname)
def eh_labirinto (maze): """Esta funcao indica se o argumento dado eh um labirinto \ nas condicoes descritas no enunciado do projeto""" if not isinstance(maze,tuple): return False else: for coluna in range(len(maze)): if maze[coluna] == () or type(maze[coluna]) != tuple: #Verifica se o labirinto eh um tuplo de tuplos return False for el in maze[coluna]: #Verifica se cada coluna contem apenas 0 ou 1 if type(el) != int or not (el == 0 or el == 1): return False def dimensao_labirinto (maze): #Verifica se o labirinto tem o formato correto valor_logico = True if len(maze) >= 3: for i in range(len(maze)-1): if len(maze[i]) < 3 or len(maze[i]) != len(maze[i+1]): valor_logico = False else: valor_logico = False return valor_logico def paredes_verticais (maze): #Verifica se as paredes verticais estao bem definidas valor_logico2 = True for el in maze[0]: if el != 1: return False for el in maze[len(maze)-1]: if el != 1: return False return valor_logico2 def paredes_horizontais (maze): #Verifica se as paredes horizontais estao bem definidas valor_logico3 = True for coluna in maze: if coluna[0] != 1 or coluna[len(coluna)-1] != 1: valor_logico3 = False return valor_logico3 return dimensao_labirinto (maze) and paredes_verticais (maze) and paredes_horizontais (maze)
def count_words(text): """A function to count the number of times each word occurs in a text. All punctuation marks are skipped. The function returns a dictionary object whose keys are the unique words and values are word counts This function is adapted from the HarvardX course - using python for research """ text = text.lower() skips = [".", ",", ";",":","?","'",'"', '-', '_', '&', '*', '(', ')'] for ch in skips: text = text.replace(ch, "") word_counts = {} for word in text.split(" "): if word in word_counts: word_counts[word] += 1 else: word_counts[word] = 1 return(word_counts)
def csr_ctype(field_data): """ The type passed to, or returned from, the assembler instruction. """ if "width" in field_data: width=str(field_data["width"]) if width.find("xlen") > 0: return "uint_xlen_t" else: return "uint_csr" + str(width) + "_t" return "uint_xlen_t"
def _set_main_iv_label(main_iv, main_iv_label): """ Set default main iv label as main iv """ if main_iv_label is None: return main_iv else: return main_iv_label
def TailFile(fname, lines=20): """Return the last lines from a file. @note: this function will only read and parse the last 4KB of the file; if the lines are very long, it could be that less than the requested number of lines are returned @param fname: the file name @type lines: int @param lines: the (maximum) number of lines to return """ fd = open(fname, "r") try: fd.seek(0, 2) pos = fd.tell() pos = max(0, pos - 4096) fd.seek(pos, 0) raw_data = fd.read() finally: fd.close() rows = raw_data.splitlines() return rows[-lines:]
def is_negated_term(term): """ Checks if a provided element is a term and is a negated term. """ return isinstance(term, tuple) and len(term) > 0 and term[0] == 'not'
def auto_intercept(with_intercept, default): """A more concise way to handle the default behavior of with_intercept""" if with_intercept == "auto": return default return with_intercept
def convert_int(value): """ Try to convert value to integer and do nothing on error :param value: value to try to convert :return: value, possibly converted to int """ try: return int(value) except ValueError: return value
def treeify(node, tree_id, pos=1, level=0): """Set tree properties in memory. """ node['tree_id'] = tree_id node['level'] = level node['left'] = pos for child in node.get('children', []): pos = treeify(child, tree_id, pos=pos + 1, level=level + 1) pos = pos + 1 node['right'] = pos return pos
def hello(name='you'): """The function returns a nice greeting Keyword Arguments: name {str} -- The name of the person to greet (default: {'you'}) Returns: [str] -- The greeting """ return 'Hello, {0}!'.format(name)
def dateIsBefore(year1, month1, day1, year2, month2, day2): """Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False.""" if year1 < year2: return True if year1 == year2: if month1 < month2: return True if month1 == month2: return day1 < day2 return False
def GetCircleArea(r): """Get a circle area. Args: r: the radius. Returns: the area of the circle. """ return 3.14 * r * r
def mean(nums): """ Computes and returns mean of a collection. """ return sum(nums)/len(nums)
def _GreedyMatch(er): """er is list of (weight,e,tl,tr). Find maximal set so that each triangle appears in at most one member of set""" # sort in order of decreasing weight er.sort(key=lambda v: v[0], reverse=True) match = set() ans = [] while len(er) > 0: (_, _, tl, tr) = q = er.pop() if tl not in match and tr not in match: match.add(tl) match.add(tr) ans.append(q) return ans
def _get_key_str(key): """ returns full name for collections in TM API """ keys = { 'TM_ID': 'Trismegistos', 'EDB': 'Epigraphic Database Bari', 'EDCS': 'Epigraphik-Datenbank Clauss / Slaby', 'EDR': 'Epigraphic Database Roma', 'CIL': 'Corpus Inscriptionum Latinarum', 'RIB': 'Roman Inscriptions of Britain', 'PHI': 'PHI Greek Inscriptions', 'LUPA': 'Ubi Erat Lupa', 'ISic': 'Inscriptions of Sicily', 'IRT': 'Inscriptions of Roman Tripolitania', 'HispEpOl': 'Hispania Epigraphica', 'Ashmolean_latin_inscriptions': 'Ashmolean Latin Inscriptions', 'Vindolanda': 'Vindolanda Tablets Online II', 'atticinscriptions': 'Attic Inscriptions Online (AIO)', 'US_Epigraphy': 'U.S. EPIGRAPHY PROJECT', 'FerCan': 'Fontes epigraphici religionum Celticarum antiquarum', } if key in keys: return keys[key] else: return key
def normalize_grobid_id(grobid_id: str): """ Normalize grobid object identifiers :param grobid_id: :return: """ str_norm = grobid_id.upper().replace('_', '').replace('#', '') if str_norm.startswith('B'): return str_norm.replace('B', 'BIBREF') if str_norm.startswith('TAB'): return str_norm.replace('TAB', 'TABREF') if str_norm.startswith('FIG'): return str_norm.replace('FIG', 'FIGREF') if str_norm.startswith('FORMULA'): return str_norm.replace('FORMULA', 'EQREF') return str_norm
def is_unknown_license(lic_key): """ Return True if a license key is for some lesser known or unknown license. """ return lic_key.startswith(('unknown', 'other-',)) or 'unknown' in lic_key
def SumTotals(dictTotal): """ Summing values in a dictionary. Parameters ---------- dictTotal : TYPE DESCRIPTION. Returns ------- TYPE DESCRIPTION. """ totalVal = 0.0 for keyVal in dictTotal.keys(): for keyVal2 in dictTotal[keyVal].keys(): totalVal += dictTotal[keyVal][keyVal2] return round(totalVal, 2)