content
stringlengths
42
6.51k
def _bound_mean_difference_ci(lower_ci, upper_ci): """Bound mean difference and normalized mean difference CI. Since the plausible range of mean difference and normalized mean difference is [-1, 1], bound the confidence interval to this range. """ lower_ci = lower_ci if lower_ci > -1 else -1 up...
def cvss_to_severity(cvss): """ Map CVSS score to Carrier severity """ if cvss >= 9.0: return "Critical" if cvss >= 7.0: return "High" if cvss >= 4.0: return "Medium" if cvss >= 0.1: return "Low" return "Info"
def check_table_name_length(table_name): """ Function to check if a table name length is below PostgreSQL 63 byte limit Returns table name below this limit, truncating original name if necessary (table_name, str) args: host: database server corresponding host (str) database: database na...
def get_fk_description(obj, field, value): """ Returns a human readable representation (name, description etc.) for a foreign key id Checks for presence of a 'name' or 'description' field on the related object. If not present, defaults back to the object's id (e.g. the guid) obj: an instance of a ...
def _sizeof_fmt(num, suffix='B'): """Format size with metric units (like nvvp)""" for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 1000.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1000.0 return "%.1f%s%s" % (num, 'Y', suffix)
def polygon(neatline): """Polygon coordinates from USGS NEATLINE metadata.""" neatline = neatline.replace("POLYGON ((", "").replace("))", "") p = [] for xy in neatline.split(","): x, y = [float(i) for i in xy.split(" ")] p.append([x, y]) return [p]
def findModuleIndex(pcbLineList, ref): """ Returns the line index at which the moduels starts """ lastModuleIndex = -1 moduleIndex = None for i, line in enumerate(pcbLineList): if 'module' in line: lastModuleIndex = i continue refStr = ' {0} '.format(ref) ...
def sortedSum(a): """ array of ints non-desc order = least to greatest ASSUME all pos ints at least 1 int dupes are allowed a is mutable module the answer w/ (10e9 + 7) Intuition: - iteratively sorting + summing nums, at the end we cum_sum Approach: 1. So...
def count_on_screen(screen, wanted): """Count occurrences of wanted on the screen.""" return list(screen.values()).count(wanted)
def direct(f, *args, **kwargs): """Runs a task in the current process. This is a very thin wrapper around a direct function call.""" return f(*args, **kwargs)
def get_interaction(element_1, element_2, matrix_dimension): """Gets singular interaction between 2 elements of an ising matrix and returns the hamiltonion Args: element_1 ([int, int]): x, y coordinate of element 1 on the ising matrix element_2 ([int, int]): x, y coordinate of element 2 on the ...
def symmetric_difference(value: list, other: list) -> list: """Symmetric difference (exclusive OR) of two lists. .. code-block:: yaml - vars: new_list: "{{ [2, 4, 6, 8, 12] | symmetric_difference([3, 6, 9, 12, 15]) }}" # -> [2, 3, 4, 8, 9, 15] .. ...
def parser_extended_event_Descriptor(data,i,length,end): """\ parser_extended_event_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "extended_event", "contents" : unparsed_descriptor_contents } ...
def kmer_count(k, rc=False): """ Counts the number of possible k-mers Args: k (int): kmer size rc (bool): Use canonical k-mers Returns: int: number of possible kmers """ if not rc: return 4**k n_palindromes = 0 if k % 2 == 0: n_palindromes = 4**(...
def _count_univals(root): """ Count the amount of subtrees that are univals, as well as the value of unival tree the node is a root of or null if it's not """ if not root: return (0, None, None) left = _count_univals(root.left) right = _count_univals(root.right) is_unival = (righ...
def url_scheme_is_secure(url): """Check if the URL is one that requires SSL/TLS.""" scheme, _dest = url.split('://') return scheme == 'elks'
def parse_number(x): """Parse a number from a string.""" return round(float(x), 6)
def _time_ago(t: int) -> str: """Get time ago information from duration.""" if t < 3600: return f'{int(t/ 60)} minutes ago' else: return f'{int(t / 3600)} hours and {int(t/60) - int(int(t/60)/60)*60} minutes ago'
def HEXtoRGB(Hex): """ convert HEX to RGB color :param Hex: HEX color integer or string :return: RGB tuple """ if isinstance(Hex, str): Hex = int(Hex[1:], 16) R = (Hex >> 16) & 255 G = (Hex >> 8) & 255 B = Hex & 255 return R, G, B
def reverse_dict(dictionary: dict) -> dict: """ Return a reversed dictionary ie {value: key} """ return {value: key for key, value in dictionary.items()}
def _get_ip_addresses(ip_addresses): """ Construct a list of ip address """ ret = [] for item in ip_addresses: ret.append(item) return ret
def get_workerpool_address(workerpool: str) -> str: """Creates a late-binding that is mapped at runtime.""" return f'%objectname({workerpool})%'
def get_any(obj, keys, default=None): """ Return the first non-None value from any key in `keys`, in order If all are None, then returns `default` """ for key in keys: val = obj.get(key) if val is not None: return val return default
def check_boundaries_overlap( x_start: int, x_end: int, y_start: int, y_end: int) -> bool: """Check if the boundaries of both elements overlap. Given the starting and end characters of two text spans, check if the X's span overlaps with Y's span. This function is used to decide if a given token bel...
def reFormatSubject(data): """ Reorganize subjects in case there is more than one class per ID """ id_class = {} for element in data: if element['ID'] == 'nan': continue elif element['ID'] in id_class: id_class[element['ID']].append(element['Class']) e...
def all_none(*args): """Return True if all arguments passed in are None.""" return all(a is None for a in args)
def unsigned_to_signed(unsigned, size): """Convert unsigned to signed""" if (unsigned & (1 << size - 1)) != 0: unsigned = -1 * ((1 << size - 1) - (unsigned & ((1 << size - 1) - 1))) return unsigned
def safe_concat(*nullable_strings): """if all values are None than returns None""" not_null_strings = [s for s in nullable_strings if s] if not_null_strings: return ' '.join(not_null_strings) return None
def color_track_map(color_track): """ Returns a map of labels to ints, and a map of ints to labels. """ colors = sorted(list(set(color_track))) return {c: i for i, c in enumerate(colors)}, {i: c for i, c in enumerate(colors)}
def clean_indent(txt): """ Useful because parameters descriptions are not always properly indented at the end of parsing. """ return "\n".join(x.strip() for x in txt.splitlines())
def first(collection, test, default=None): """ Return the first item that, when passed to the given test function, returns True. If no item passes the test, return the default value. """ return next((c for c in collection if test(c)), default)
def choice_verification(choice): """Check choice and return True according.""" if choice.upper() == "O": return True
def isSignatureValid(expected, received): """ Verifies that the received signature matches the expected value """ if expected: if not received or expected != received: return False else: if received: return False return True
def sort_data(unsorted_list, metric, limit = 10000, reverse=True): """ Sorts a list of dictionaries by the "metric" key given """ sorted_list = sorted(unsorted_list, key = lambda k: k[metric], reverse = reverse) top_results = sorted_list[:limit] return top_results
def xy_to_mb(pt1, pt2): """convert two points of line into y = mx + b form. if line is vertical, return (None, x-intercept)""" (x1, y1) = pt1 (x2, y2) = pt2 if abs(x1 - x2) > 0.001: m = float(y1 - y2) / (float(x1 - x2) + 0.0000001) b = y1 - m * x1 else: m, b =...
def calculate_recall(total_correct: int, total_acronyms: int) -> float: """ Calculate reall as the ratio of correct acronyms to all acronyms. :param total_correct: :param total_acronyms: :return: """ return total_correct / total_acronyms if total_acronyms != 0 else 0
def remove_table(secs, tbls): """Remove table from section text. Parameters ---------- secs : list of str List of section texts. tbls : List of str List of pairs of section id and table text. Returns ------- list of str """ for sec_i, tbl in tbls: secs[s...
def parse_abi_from_filename(filename): """This parses out the abi from a wheel filename. For example, `configparser-3.5.0-py2-abi3-any.whl` would return `abi3`. See https://www.python.org/dev/peps/pep-0425/#use for how wheel filenames are defined.""" return filename.split("-")[-2]
def onHoverStartGetAccept(comp, info): """ Called when comp needs to know if dragItems are acceptable as a drop. Args: comp: the panel component being hovered over info: A dictionary containing all info about hover, including: dragItems: a list of objects being dragged over comp callbackPanel: the panel C...
def reverse(string): """Reverse a given string.""" return string[::-1]
def unscale(img, float_range=(0, 1), orig_range=(0, 255)): """ unscale data values from float range (0, 1) or (-1, 1) to original range (0, 255) :param img: (numpy array) Image to be scaled :param float_range: (0, 1) or (-1, 1). :param orig_range: (0, 255) or (0, 65535). :return: (numpy array) U...
def sizeof_df(num, size_qualifier=""): """returns size in human readable format""" for x in ["bytes", "KB", "MB", "GB", "TB"]: if num < 1024.0: return "%3.1f%s %s" % (num, size_qualifier, x) num /= 1024.0 return "%3.1f%s %s" % (num, size_qualifier, "PB")
def wstrip(s, word, left=True, right=True): """Strip word from the beginning or the end of the string. By default strips from both sides. """ step = len(word) start_pos = None end_pos = None if not word: return s while True: found = False if left and s.startswit...
def unquote(text): """Unqoute the text from ' and " text: str - text to be unquoted return text: str - unquoted text >>> unquote('dfhreh') 'dfhreh' >>> unquote('"dfhreh"') 'dfhreh' >>> unquote('"df \\'rtj\\'"') == "df 'rtj'" True >>> unquote('"df" x "a"') '"df" x "a"' >>> unquote("'df' 'rtj'") == "'df...
def rgb2hex(color): """ Converts RGB array to Hex string Parameters ------ color: list RGB colour. Returns ------ str Converted hexidecimal code. """ return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))
def cell_id_to_token(cell_id: int) -> str: """ Convert S2 cell ID to a S2 token. Converts the S2 cell ID to hex and strips any trailing zeros. The 0 cell ID token is represented as 'X' to prevent it being an empty string. See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_i...
def mover_unidade (m, u, n): """Esta funcao permite mover, se existir, a unidade u do mapa m para a posicao n""" for chave in m: for un in range(len(m[chave])): if u == m[chave][un]: m[chave][un][0] = n return m
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 agent_name_to_idx(agent_num, self_id): """split agent id around the index and return its appropriate position in terms of the other agents""" agent_num = int(agent_num) if agent_num > self_id: return agent_num - 1 else: return agent_num
def toggle_id_warnings_collapse(n, is_open): """ Shows/hides id warnings on toggle click :param n: num clicks on toggle button :param is_open: open state of id warnings :return: negated open state if click, else open state """ if n: return not is_open return is_open
def format_ip_address(container_group): """Format IP address. """ ip_address = container_group.get('ipAddress') if ip_address is not None: ports = ','.join(str(p['port']) for p in ip_address['ports']) return '{0}:{1}'.format(ip_address.get('ip'), ports) return None
def compute_pareto_set(objective1_list, objective2_list): """ Return objective values for the subset of solutions that lie on the pareto front. """ assert len(objective1_list) == len(objective2_list), \ "Each solution must have a value for each objective." n_solutions = len(objective1_...
def fast_relpath_optional(path, start): """A prefix-based relpath, with no normalization or support for returning `..`. Returns None if `start` is not a directory-aware prefix of `path`. """ if len(start) == 0: # Empty prefix. return path # Determine where the matchable prefix ends. pref_end = len...
def format_output(error_type, error_message): """ Formats the errors to look standard """ return "[{}] {}".format(error_type, error_message)
def stringify_list(list): """Convert every item to string.""" return [str(i) for i in list]
def beta(v,c=1.*1.e8): """ Bx = B[1]/c By = B[2]/c Bz = B[3]/c """ return (v/c)
def current_velocity(x_new, x_prev, h): """ returns current velocity of a particle from next position at timestep. """ """ parameters ---------- x_new : array new x-position of particle x_prev : array previous x-position of particle h : float simulation timestep ...
def _str_to_bool(s): """Convert string to bool (in argparse context).""" if s.lower() not in ['true', 'false']: raise ValueError('Need bool; got %r' % s) return {'true': True, 'false': False}[s.lower()]
def seq_to_string(seq): """Return a string representation of the codepoint sequence.""" return "_".join("%04x" % cp for cp in seq)
def _ensureListLike(item): """ Return the item if it is a list or tuple, otherwise add it to a list and return that. """ return item if (isinstance(item, list) or isinstance(item, tuple)) \ else [item]
def get_cols_and_rows(payoff_entries): """Determine how many columns and rows the output plot should have based on how many parameters are being swept.""" # make a list of the lengths of each parameter list that are more than one # value for that parameter lengths = [len(x) for x in payoff_entries ...
def make_matrix(num_rows, num_cols, entry_fn): """returns a num_rows x num_cols matrix whose (i,j)-th entry is entry_fn(i, j)""" return [[entry_fn(i, j) for j in range(num_cols)] for i in range(num_rows)]
def conceptFilter(c): """Criteria by which to filter concepts from the lattice""" # stabilities larger then min_st keepConcept = c[2] > 0.3 or c[3] > 0.3 return keepConcept
def encode_integer_uleb128(value: int) -> bytes: """Encode an integer with unsigned LEB128 encoding. :param int value: The value to encode. :return: ``value`` encoded as a variable-length integer in ULEB128 format. :rtype: bytes """ if value < 0: raise ValueError( "The ULEB...
def get_pair_direction(pd): """Validate and return pair_direction param value.""" if pd is None: raise RuntimeError("Failed to find pre or Post Direction") if pd in ('backward', 'forward', 'both', 'none'): return pd else: raise RuntimeError("Invalid pair direction %s." % pd)
def TimeFormatter(milliseconds: int) -> str: """ Adjust the time from milliseconds to the right measure. milliseconds (``int``): Number of milliseconds. SUCCESS Returns the adjusted measure (``str``). """ seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds =...
def get_distinguished_name(queue_entry): """ Returns the distinguished_name of the queue entry. """ sawtooth_entry = queue_entry["data"] return sawtooth_entry["distinguished_name"][0]
def convert_to_camelcase(input_string: str): """ Algorithm to convert snake_case to CamelCase """ return "".join([string.capitalize() for string in input_string.split("_")])
def field_operator(key): """ Given, like, submitted__gte, return ('submitted', 'gte') """ if key.find('__') >= 0: return key.split('__') return (key, None)
def td_flipx(txtdict, w, h): """Mirror along x axis""" ret = {} for y in range(h): for x in range(w): ret[(x, h - y - 1)] = txtdict[(x, y)] return ret
def bias_function(bias): """ Simply returns the bias. Closes win before raising the error to prevent win from getting stuck. Parameters ---------- bias : float the bias of the computer chosen by the experimenter. Raises ------ ValueError raises an exception if the b...
def form_bowtie_build_cmd_list(bowtie_build_fp, input_contigs_fasta, output_index_fp): """ format arguments received to generate list used for bowtie_build subprocess call Args: bowtie_build_fp(str): the string representing the path to the bowtie program input_contigs_fasta(list): list of files...
def same(aList): """ determines if all the elements in a list are the same """ if(aList[1:] == aList[:-1]): return True else: return False
def get_top10(recommendations_list): """ Returns the first 10 elements of a list""" return recommendations_list[:10]
def sort_dict_of_paths(d): """ Sort a dict containing paths parts (ie, paths divided in parts and stored as a list). Top paths will be given precedence over deeper paths. """ # Find the path that is the deepest, and count the number of parts max_rec = max(len(x) if x else 0 for x in d.values()) # Pad ot...
def bytes2int(bytes): """ convert byte list to int """ num = 0 for byte in bytes: num <<= 8 num ^= byte return num
def safe_mod(a, b): """ only allow modulo on numbers, not string formating """ if isinstance(a, str): raise NotImplementedError("String formating is not supported") return a % b
def choose_window_type(measure): """ # Chose Window Type Args: measure (float): dB value. Returns: str: name of window type. """ reference = { 'rectangular': -21, 'barlett': -25, 'hanning': -44, 'hamming': -53, 'blackman': -74 } allow...
def wikiPre(s: str, nowiki: bool = False) -> str: """Return string wrapped in <pre ...>.""" if nowiki: s = f'<nowiki>{s}</nowiki>' return f"<pre style='white-space: pre'>{s}</pre>"
def get_tokens_from_idx(token_list, indexes): """Method to take a list of tokens and a list of indexes and extract the tokens with the corresponding index. Args: token_list (list): list with tokens desired to be extracted. indexes (list): desired locations of the tokens. Returns: ...
def fractional_mass(m1, m2): """ computes fractional mass getB(m1,m2) returns m2/(m1+m2) :param m1: :param m2: :return: """ return m2/(m1+m2)
def RiPrimeIntermediate(timinus, ti, tiplus, ri, riplus, riminus): """Gradient vector in Hermite Interpolation: General Case""" term1 = (ri - riminus) * (tiplus - ti) / (ti - timinus) term2 = (riplus - ri) * (ti - timinus) / (tiplus - ti) return (term1 + term2) / (tiplus - timinus)
def f(a:int,b:int)->int: """ Retourne la somme de a et b""" #x:int #x:int return a+b
def clean_agency(agency_name): """ Clean up the agency names in the dataset to make them consistent. """ agency_name = agency_name.strip() if 'Oceanic' in agency_name: return 'National Oceanic and Atmospheric Administration' return agency_name
def flatmap(fn, seq): """ Map the fn to each element of seq and append the results of the sublists to a resulting list. """ result = [] for lst in map(fn, seq): for elt in lst: result.append(elt) return result
def print_pair(claim1: str, claim2: str, score: float, round_num: int = 3): """ Print the claims pair in a nicely formatted way. :param claim1: claim 1 string :param claim2: claim 2 string :param score: score associated with the pair :param round_num: number of places to round to :return: s...
def triangle(n): """ This function forms a triangle that will help act as tree lives :param n: n is an integer for rows to be used :return: it returns no space ie "" """ for i in range(n): # for catering the decreasing space as the triangle is formed for j in range(n-i):...
def get_axis_indexes(kernel_axis_length, center_index): """Calculate the kernel indexes on one axis depending on the kernel center. Args: kernel_axis_length (int): The length of the single axis of the convolutional kernel. center_index (int): The index of the kernel center on on...
def module_name_join(names): """Joins names with '.' Args: names (iterable): list of strings to join Returns: str: module name """ return '.'.join(names)
def rapmap_pseudo_unpaired(job, config, name, samples, flags): """Run RapMap Pseudo-Mapping procedure on unpaired sequencing data :param config: The configuration dictionary. :type config: dict. :param name: sample name. :type name: str. :param samples: The samples info and config dictionary. ...
def _suppress_none(val): """Returns an empty string if None is passed in, otherwide returns what was passed in""" if val is None: return '' return val
def reverse(words): """Reverse a string containing several words Arguments: words {str} -- The words to reverse Returns: str -- The reversed words """ if words is None: return "" else: words = list(filter(lambda w: w != "", words.split(" "))) wo...
def check_fields_to_join(fields_to_join): """Check which fields have been passed to be joined """ if 'oa' in fields_to_join: oa = True else: oa = False if 'lad' in fields_to_join: lad = True else: lad = False if 'gor' in fields_to_join: gor = True else: gor = False ret...
def assemble_minimal_helices(min_helices): """ Gathers overlapping helices """ helices = { "3-helices": [], "4-helices": [], "5-helices": [] } # gather the n-helices that start at less than n residues for n in [3, 4, 5]: input_name = str(n) + "-min_heli...
def rename(record, rename_page_id): """Rename page_id.""" record['rev_id'] = record['revid'] del record['revid'] record['user_text'] = record['user'] del record['user'] record['user_id'] = record['userid'] del record['userid'] record['text'] = record['*'] del record['*'] record['page_id'] = rename_p...
def RGBtoHSL(R, G, B): """ convert RGB to HSL color :param R: red value (0;255) :param G: green value (0;255) :param B: blue value (0;255) :return: HSL (TSL) tuple """ rgb = [i / 255.0 for i in (R, G, B)] # scale 8bits values to float 0;1 maxi, mini = max(rgb), min(rgb) delta = maxi ...
def damerau_levenshtein(s1: str, s2: str, limit: int) -> bool: """Whether Damerau-Levensthein distance is less than limit.""" if len(s1) < len(s2): return damerau_levenshtein(s2, s1, limit) if not s2: return len(s1) < limit if not limit: return s1 == s2 if abs(len(s1) - le...
def mxprofit(array): """Determines the maximum profit that could be gained by buying low and selling high""" #initialize variables minimum_val = 10000 profit = 0 # edge cases if len(array) <= 1: return 0 # iterate through list and store minimum value for i in range(len(array...
def expand(buf): """ Returns a new bytearray containing the contents of buf expanded with space for parity bit on each byte. The parity bit is not set and is always zero. :param bytes buf: 168-bit key :rtype: bytearray """ out = bytearray(24) out[0] = buf[0] & 0xFE out[1] = (buf[0] ...
def my_function(a, b=2): """ This function ... Parameters ---------- a : float First operand. b : float, optional Second operand. The default is 2. Returns ------- Sum of operands. Example ------- >>> my_function(3) 5 """ # Add a with b (thi...