content
stringlengths
42
6.51k
def toc2plaintext(toc: list) -> str: """ :param toc: table of content <- DOCUMENT.get_toc() :return: plaintext """ plaintext = [] for content in toc: head = f'{int(content[0])*"*"}-->{content[1]}-->{content[2]}' plaintext.append(head) plaintext = '\n'.join(plaintext)...
def convert_to_binary(x: int) -> str: """Convert a base-ten integer into its binary equivalent.""" # divide x by 2 # the remainder is the last binary digit # divide the quotient of x // 2 by 2 # the remainder is the second-to-last binary digit # repeat until quotient == 0 def inner(x): ...
def get_length(node): """ vstup: 'node' prvni uzel seznamu, ktery je linearni, nebo kruhovy vystup: pocet prvku v zadanem seznamu casova slozitost: O(n), kde 'n' je pocet prvku seznamu """ if node is None: return 0 length = 1 first_node = node while node.next: node = ...
def is_int(s): """ returns true, if the string is a proper decimal integer value """ if len(s) > 0 and s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit()
def keep_string(boolean): """ Changes true and false back to yes and no (Jinja2 template workaroud) :param boolean: true or false :return: yes or no """ if boolean: return "yes" else: return "no"
def _name(ii): """Use this to make the model name for source number `ii`.""" return 'gauss2d.source_{0:02d}'.format(ii)
def replace_insensitive(string, target, replacement): """ Similar to string.replace() but is case insensitive Code borrowed from: http://forums.devshed.com/python-programming-11/case-insensitive-string-replace-490921.html """ no_case = string.lower() index = no_case.rfind(target.lower()) if ...
def _flatten(lst): """Flatten sublists in list. see https://stackoverflow.com/a/952952/130164 """ from collections.abc import Sequence entries = [] for sublist in lst: # may be a sublist if isinstance(sublist, Sequence) and not isinstance( sublist, (str, bytes, bytea...
def rot_13(char_in: str) -> str: """Character offset by 13 positions. Parameters: char_in : function Character of the source text. Returns: char_out : str Character of the encrypted text. """ num = ord(char_in[0]) if (97 <= num <= 109) or (65 <= num <=...
def decode_to_unicode(content): """decode ISO-8859-1 to unicode, when using sf api""" if content and not isinstance(content, str): try: # Try to decode ISO-8859-1 to unicode return content.decode("ISO-8859-1") except UnicodeEncodeError: # Assume content is uni...
def _get_global_var(global_obj, key): """locate element in a etree object (in this case, child of global tag in testdata file) """ return global_obj.find(key) if global_obj is not None else None
def _fmt_pos(pos): """Return position in non-Python indexing""" new_pos = [pi + 1 for pi in pos] new_pos = ['{:2d}'.format(pi) for pi in new_pos] return f'({new_pos[0]},{new_pos[1]})'
def flip_list(lists, flip): """Return list as-is or in reversed order Keyword arguments: lists -- input data to process, expects a list of lists flip -- boolean to flip icon 180 degrees """ if flip == True: return reversed(lists) return lists
def get_intersection_difference(runs): """ Get the intersection and difference of a list of lists. Parameters ---------- runs set of TestSets Returns ------- dict Key "intersection" : list of Results present in all given TestSets, Key "difference" : list of Resu...
def valid_name(s): """See readme for what's valid. :type s: str """ for c in s: if not (c.isalnum() or c in ' -_'): return False return True
def yellow(s): """ Decorates the specified string with character codes for yellow text. :param s: Text to decorate with color codes. :return: String containing original text wrapped with color character codes. """ return '\033[93m{}\033[0m'.format(s)
def _labels_col(ktk_cube_dataset_id): """ Column that is used internally to track labels present for a given dataset. Parameters ---------- ktk_cube_dataset_id: str Ktk_cube Dataset ID: Returns ------- labels_col: str Column name. """ return "__ktk_cube_labels_{...
def check_evidence_skip_evaluation(evidence_cutoff, varTypes, benign_tot, path_tot): """evidence_cutoff is used as, 'less than this, and no evaluation' varTypes is pathogenic, benign, or both. when both, I check evidence_cutoff for pathogenic and benign """ if varTypes == 'both': if be...
def is_same_match(m1, m2): """ Compare two OpenFlow Matches :param m1: :param m2: :return: """ if not m1 or not m2: return False for k, v in m1.items(): if k not in m2: return False if m2[k] != v: return False for k, v in m2.items():...
def requiredsourcerequirements(repo): """Obtain requirements required to be present to upgrade a repo. An upgrade will not be allowed if the repository doesn't have the requirements returned by this function. """ return { # Introduced in Mercurial 0.9.2. 'revlogv1', # Introd...
def comp_binary(s1, s2): """ :param s1: :param s2: :return: """ found_one = False pos = None for i in range(len(s1)): if s1[i] != s2[i]: if found_one: return False, None pos = i found_one = True return found_one, pos
def wrap(obj, *wrappers): """Sequentially wraps object.""" for wrapper in wrappers: obj = wrapper(obj) return obj
def format_query(query, *args): """Turns query and arguments into a structured format Args: query (string): The query to be run against the database Returns: dict: An ordered format of query keys and corresponding arguments """ query_args = {} start_idx = query.find("(") en...
def extend_empty_sets(empty: dict, grammar: dict) -> dict: """ Determine which nonterminals of an LL(1) grammar can be empty. Must be applied repeatedly until converging. :param empty: nonterminal -> bool :param grammar: nonterminal -> [productions...] :returns: Extended copy of ``empty`` "...
def replace_OOV(text, replace, vocab): """ Replace OOV words in a text with a specific word. """ tokens = str(text).split() new_tokens = [] for word in tokens: if word in vocab: new_tokens.append(word) else: new_tokens.append(replace) new_text = " ".jo...
def SliceBits(num, msb, lsb=None): """ Slice bits from an integer from the msb to the lsb (inclusive) and 0-indexed If no lsb is provided it will only grab the one bit at the msb specified num - the number msb - the most significant bit to keep lsb - the least significant bit to keep ex. SliceBits(0xF000, 15, 12...
def doped_glass_name(x): """ Create a string the name describing the GeO_2 doped glass. Args: x: molar fraction of GeO_2 in the system Returns: string describing the doped glass """ if x == 0: return r'SiO$_2$' if x == 1: return r'GeO$_2$' return r'%.2f ...
def factorial(n): """ Input: a number. Output: find the factorial of the input number via iteration. """ product = 1 if n == 0: return 0 for thing in range(1, n+1): product *= thing return product
def get_cellname (ch): """Return name of cell used to store character data""" prefix = 'font_' if (ord(ch) < 0x100): cellname = '{:02X}'.format(ord(ch)) elif (ord(ch) < 0x10000): cellname = '{:04X}'.format(ord(ch)) elif (ord(ch) < 0x1000000): cellname = '{:06X}'.format(ord(...
def _drop_columns(feats, additional=None): """ This function takes a list of features and removes DETAILS and ID. The user can provide an additional list to remove more features """ to_drop = ['DETAILS', 'ID'] if additional: to_drop = to_drop + additional feats = [feat for feat in fe...
def exponential_power_calculation(base, exponent=1.0): """ Calculation of exponential power of number i.e. base^exponent. Parameters ---------- base : float Base number. exponent : float, optional Exponent of the base. The default is 1.0. Returns ------- ...
def build_tags(item): """ Build the row of tags for a CSV file :param item: A test item, normally the first test item in responses of a test :return: CSV format string """ if item['type'] == 1: # Question return '' elif item['type'] == 2 or item['type'] == 3: # Example or training ...
def filetype(file: str): """ Returns the file type based on the suffix of the filename.""" suffix = file.split('.')[-1] if suffix == 'yml' or suffix == 'yaml': return 'yaml' elif suffix == 'json' or suffix == 'jsn': return 'json' else: raise Exception('Invalid filetype!')
def IntConv(value): """Returns the integer value of a string, if possible.""" try: int_val = int(value) return int_val except ValueError: return value
def parse_report_for_epoch_metrics(report_dict, metrics=["train_mIoU"]): """ Parse report for given metric information over epoch and add them to list Arguments: report_dict: dictionalry with raw report data metrics: list of metrics to search over epoch Returns: result: the dicti...
def retrieve_leaf_nodes(node, leaf_list): """ A recursive algorithm to extract leaf nodes. """ if node is not None: if node.is_leaf(): leaf_list.append(node) for item in node.children: retrieve_leaf_nodes(item, leaf_list) return leaf_list
def _prepare_shape_for_squeeze(shape, axes): """ Creates the squeezed new shape based on the tensor and given axes. Args: shape (tuple): the shape of the tensor axes Union[None, int, tuple(int), list(int)]: the axes with dimensions squeezed. Returns: new_shape(tuple): the shape...
def exe(name: str) -> str: """ For distribution, once I've merged into master: look for ROSETTA in os.environ and return exe path based on that. """ import os if os.path.exists("/home/andy"): return "/home/andy/Rosetta/main/source/bin/" + name else: return "/Users/amw579/dev...
def get_sig_label(primary_p, secondary_p, n_nominal, primary_q, primary_p_cutoff, secondary_p_cutoff=0.05, n_nominal_cutoff=2, secondary_or_nominal=True, fdr_q_cutoff=0.05, secondary_for_fdr=False): """ Checks if a window should be considered exome-wide or...
def make_functional_name(funccall): """ Given the way the functional was invoked as a function work out what the name of the subroutine to call is. The subroutine name is returned. """ data = funccall data = data.split("(") data = data[0] data = data.replace("nwxc_","nwxcm_") return data
def bin_to_decimal(bin_string: str) -> int: """ Convert a binary value to its decimal equivalent >>> bin_to_decimal("101") 5 >>> bin_to_decimal(" 1010 ") 10 >>> bin_to_decimal("-11101") -29 >>> bin_to_decimal("0") 0 >>> bin_to_decimal("a") Traceback (most recent call l...
def overlap(a, b): """Intersection of sets "Mention-based" measure in CoNLL; #3 in CEAF paper """ return len(a & b)
def utf8(obj): """ This helper function attempts to decode a string like object to utf-8 encoding. For Python2 it just works. For Python3 a string object does not have decode mehtod whilst a byte object does. """ try: value = obj.decode('utf-8') except AttributeError: value =...
def dialogue_matches_prev_line(line1, line2): """Checks if the dialogue matches the previous line's.""" parts1 = line1.split(" ") parts2 = line2.split(" ") for i in range(6, min(len(parts1), len(parts2))): if parts1[i] == "YOU:" or parts1[i] == "THEM:": if parts1[i] == "YOU:" and parts2[i] != "THEM:":...
def tan2sin(tan: float) -> float: """returns Sin[ArcTan[x]] assuming -pi/2 < x < pi/2.""" return tan * (tan ** 2 + 1) ** (-0.5)
def filter(input_list: list, allowed_elements: list): """ Function that filters out only the chosen elements of a list """ output_list = [] for element in input_list: if element in allowed_elements: output_list.append(element) return output_list
def pretty_name(text): """Returns a rewrite like: "snakes_and_ladders" -> "Snakes And Ladders".""" return text.replace('_', ' ').title()
def get_headers(profile): """Get the HTTP headers needed to make Github API requests. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect wit...
def is_true(boolstring: str): """ Converts an environment variables to a Python boolean. """ if boolstring.lower() in ('true', '1'): return True return False
def _new_board(board_width, board_height): """Return a emprty tic-tac-toe board we can use for simulating a game. Args: board_width (int): The width of the board, a board_width * board_height board is created board_height (int): The height of the board, a board_width * board_height board is cre...
def mask_pipe_mw(text: str) -> str: """ Mask the pipe magic word ({{!}}). :param text: Text to mask :return: Masked text """ return text.replace("{{!}}", "|***bot***=***param***|")
def aggregate_list_sum(data, groupKey, sumKey, ignoreKeys = None): """ Loop through a list and sum up the `sumKey` values while treating `groupKey` as a unique ID. The `ignoreKeys` allows for a list of keys to ignore and not return """ output = {} for item in data: key = item[groupKey] ...
def filter_by_extension(filenames, extensions): """Takes two lists of strings. Return only strings that end with any of the strings in extensions. """ filtered = [] for extension in extensions: filtered = filtered + [f for f in filenames if f.endswith(extension)] return filtered
def depth_from_pressure(mbars): """Return a depth (in meters) from a pressure in millibars. Calculated using 1 atm = 1013.25 millibar and assuming 1 atm for every 9.9908 meters of sea water. I'm also assuming that we're diving at sea level and that the ambient presure is 1atm. """ return (mbars - 10...
def topological_order_dfs(graph): """Topological sorting by depth first search :param graph: directed graph in listlist format, cannot be listdict :returns: list of vertices in order :complexity: `O(|V|+|E|)` """ n = len(graph) order = [] times_seen = [-1] * n for start in range(n):...
def is_block_range(start, end): """Checks for a valid block number.""" return ( start.isdigit() and 0 <= int(start) <= 99999999 and end.isdigit() and 0 <= int(end) <= 99999999 )
def string_to_floats(input_string): """Convert comma-separated floats in string form to list of floats. Parameters ---------- input_string : string Comma-separated floats values encoded as a string. Returns ------- list of floats Returns converted list of floats. """ ...
def is_number(input_str): """Check if input_str is a string number Args: input_str (str): input string Returns: bool: True if input_str can be parse to a number (float) """ try: float(input_str) return True except ValueError: return False
def plural(n: int, def_one: str = '', def_many: str = 's') -> str: """ Returns the plural form of a noun based on the number n. By default, this function assumes a simple "s" can be used to make a noun plural. If the plural word needs to change completely, the two options may be given in the ...
def get_gcb_url(build_id, cloud_project='oss-fuzz'): """Returns url where logs are displayed for the build.""" return (f'https://console.cloud.google.com/cloud-build/builds/{build_id}' f'?project={cloud_project}')
def factorial(n): """Calcula el factorial de n. n int > 0 returns n! """ print(n) if n == 1: return 1 return n * factorial(n - 1)
def is_posix_time(POSIX_TIME_MAYBE): """ Checks if a string matches POSIX time format """ # secondary imports here to reduce startup time when this function is unused. import time try: time.localtime(POSIX_TIME_MAYBE) return True except ValueError: return False
def make_subsection(text): """Format text as reStructuredText subsection. Args: text: Text string to format. Returns: Formatted text string. """ return '{}\n{}\n'.format(text, '-' * len(text))
def calc_rso(ra, frac=0.75): """ Clear-sky solar radiation. Parameters ---------- ra : numpy ndarray Extraterrestrial solar radiation. frac : float <= 1 Fraction of extraterrestrial solar radiation that reaches earth on clear-sky days. """ s = 'Please enter a fr...
def ipIsV4(ip): """ Checks whether an IP address is IPv4. Assumes that it's known the parameter is an IP address. """ return "." in ip
def construct_in_clause_list(key_dict): """ Construnct a list of IN clauses. Args: key_dict: a dictionary where key is the database column key and value is the values to filter for. Return: a list of constructed clauses Example: >>> out = construct_in_clause_list...
def _rreplace(s, a, b, n=1): """Replace a with b in string s from right side n times.""" return b.join(s.rsplit(a, n))
def seq_to_str(seq_sol): """From a sequence solution (e.g.: ['r2']) returns its string form (e.g.: 'r2')""" return ' '.join(seq_sol)
def parse_recvd_data(data): """ Break up raw received data into messages, delimited by null byte """ parts = data.split(b'\0') msgs = parts[:-1] rest = parts[-1] return (msgs, rest)
def encode_mongo_obj(obj): """Convert a Mongo object into a dict for Flask-RESTful""" obj['_id'] = str(obj['_id']) return obj
def get_location(rows): """ :param rows: lst, letter input from user :return locates: lst, tuples represent position of characters in rows """ locates = [] for i in range(len(rows[0])): for j in range(len(rows)): locates.append((i, j)) return locates
def get_cve_id(cve): """ Attempts to extract the cve id from the provided cve. If none is found, returns a blank string. Parameters ---------- cve : dict The dictionary generated from the CVE json. Returns ------- str This will be either the cve id, or a blank strin...
def str_to_bool(bool_str: str) -> bool: """ Convert a string to a bool. Accepted values (compared in lower case): - `True` <=> `yes`, `true`, `t`, `1` - `False` <=> `no`, `false`, `f`, `0` .. code-block:: python >>> str_to_bool("yes") == True # Works with "yes", "true", "t", "y", "1...
def index_str(text, sub, start=None, end=None): """ Finds the lowest index of the substring ``sub`` within ``text`` in the range [``start``, ``end``]. Optional arguments ``start`` and ``end`` are interpreted as in slice notation. However, the index returned is relative to the original string ``text...
def extract_salient_features(dict1, dict2, alpha=1.0): """ Score salient features given to dictionaries. Args: dict1: First set of feature coutns dict2: Second set of feature counts alpha: The amount of smoothing (default 1 to Laplace smoothed probabilities) Returns: Laplace smoothed differenc...
def match(s1, s2): """ :param s1: str, the long DNA sequence to be compared :param s2: str, the short DNA sequence to match :return: str, the most similar segment from the long DNA sequence """ ans = '' maximum = 0 # The maximum of match rate for i in range(len(s1) - len(s2) + 1): ...
def int_to_bool(value): """Turn integer into boolean.""" if value is None or value == 0: return False else: return True
def first_word(text: str) -> str: """ returns the first word in a given text. """ d = [".",","] for k in d: text = text.replace(k," ") return text.split()[0]
def get_int_from_str(number: str) -> int: """ :param number: a string containing an integer, in hex (0x prefix) or decimal format :return: parsed integer """ if type(number) == int: return number return int(number, 16) if '0x' in number else int(number)
def _Insert(text): """Appends a space to text if it is not empty and returns it.""" if not text: return '' if text[-1].isspace(): return text return text + ' '
def adjust_gravity_volume(vol, og, ng): """ Returns the new volume needed to achieve the desired new gravity. This is unit independent and the return value can be used for liters and or gallons. New Volume = (Volume * original Gravity) / new Gravity :arg vol: Original volume of wort :arg o...
def filenotfound_error_assert(func,*args): """ if raises error, return True """ try: func(*args) except FileNotFoundError: return True except: return False else: return False
def print_with_count(resource_list): """Print resource list with the len of the list.""" if isinstance(resource_list, str): return resource_list resource_list = [str(elem) for elem in resource_list] return f"(x{len(resource_list)}) {str(resource_list)}"
def url_path_join(*items): """ Make it easier to build url path by joining every arguments with a '/' character. Args: items (list): Path elements """ return "/".join([item.lstrip("/").rstrip("/") for item in items])
def repeat(s, exclaim): """ Returns the string 's' repeated 3 times. If exclaim is true, add exclamation marks. """ result = s * 3 # can also use "s * 3" which is faster (Why?) if exclaim: result = result + '!!!' return result
def calculate_pagepool(memory_size): """ Calculate pagepool """ # 1 MiB = 1.048576 MB mem_size_mb = int(int(memory_size) * 1.048576) # 1 MB = 0.001 GB pagepool_gb = int(mem_size_mb * 0.001) if pagepool_gb <= 1: pagepool = 1 else: pagepool = int(int(pagepool_gb)*int(25)*0.01) ...
def _parse_command_rbioc(command, param_set): """ Parse command in Rbioc. Find a r-bioc command and replace the inputs and outputs with appropriate galaxy template. """ cmd = command.split(" ") count = 0 for i in range(len(cmd)): if "--" in cmd[i]: cmd[i + 1] = "$" +...
def get_embedded(result_object, link_relation): """ Given a result_object (returned by a previous API call), return the embedded object for link_relation. The returned object can be treated as a result object in its own right. 'result_object' a JSON object returned by a previous API call. The ...
def diff_pixel(P1,P2): """ P = (r,g,b) """ diff_r = abs(P1[0]-P2[0]) diff_g = abs(P1[1]-P2[1]) diff_b = abs(P1[2]-P2[2]) return diff_r + diff_g + diff_b
def calculate_power(current_power, percentage_decrease): """ calculates the new power. """ required_power = current_power - (current_power * percentage_decrease)/100. return int(required_power)
def convert_keys_and_booleans(dictionary): """ Local recursive helper method to convert 'all caps' keys to lowercase :param dictionary: the dict for whom's keys need lowercase :return: the new dictionary with lowercase keys """ lower_case = {} for key in dictionary: value = dictionar...
def ELinkResultParser(text): """Gets the linked ids out of a single ELink result. Does not use the XML parser because of problems with long results. Only handles cases where there is a single set of links between databases. """ result = [] in_links = False for line in text.splitlines():...
def write_obj(filename, points=None, mesh=None): """ Parameters ---------- filename: str The created file will be named with this points: pd.DataFrame mesh: pd.DataFrame Returns ------- boolean True if no problems """ if not filename.endswith('ob...
def is_not_phage_func(x): """ These are some annotations that are definitely not phages, but often look like them. :param x: the function to test :return: True if it is NOT a phage function. Note that False suggests it maybe a phage function, but may not be (we are not sure)! """ x = x...
def format_bytes(num, decimal_places=3): """Converts a number of bytes (float/int) into a reader-friendly format. Rounds values off to decimal_places decimal places, or to 0 decimal places if num < 1000.""" if num >= 1e9: return f"{num/1e9:,.{decimal_places}f} GB" elif num >= 1e6: re...
def apply_key(cryptogram, key): """Applies a key to the cryptogram. """ return ["".join(key[x] for x in word) for word in cryptogram]
def data_for_keys(data_dict, data_keys): """ Return a dict with data for requested keys, or empty strings if missing. """ return {x: data_dict[x] if x in data_dict else '' for x in data_keys}
def complex_lorentzian_k(x, gamma=1., amplitude=1.j): """ Complex Lorentzian kernel function. """ return (gamma/2.)/(gamma/2.+1j*x)*amplitude
def word_sorter(x): """ Function to sort the word frequency pairs after frequency Lowest frequency collocates first - highest frerquency collocates last """ # getting length of list of word/frequency pairs lst = len(x) # sort by frequency for i in range(0, lst): for j i...
def polyderiv(a): """ p'(x) = polyderiv(a) = b[0] + b[1]x + b[2]x^2 +...+ b[n-2]x^{n-2} + b[n-1]x^{n-1} where b[i] = (i+1)a[i+1] """ b = [] for i in range(1, len(a)): b.append(i * a[i]) return b