content
stringlengths
42
6.51k
def convert_missing_indexer(indexer): """ reverse convert a missing indexer, which is a dict return the scalar indexer and a boolean indicating if we converted """ if isinstance(indexer, dict): # a missing key (but not a tuple indexer) indexer = indexer['key'] if isinstance(indexer, bool): raise KeyError("cannot use a single bool to index into setitem") return indexer, True return indexer, False
def getANSIbgarray_for_ANSIcolor(ANSIcolor): """Return array of color codes to be used in composing an SGR escape sequence. Using array form lets us compose multiple color updates without putting out additional escapes""" # We are using "256 color mode" which is available in xterm but not # necessarily all terminals # To set BG in 256 color you use a code like ESC[48;5;###m return ['48', '5', str(ANSIcolor)]
def print_diff(a1,a2): """ Print not similar elements """ diff = [] for i in a1: if a2.count(i) == 0: diff.append(i) for i in a2: if a1.count(i) == 0: if diff.count(i) == 0: diff.append(i) return diff
def rect_intersect_area(r1, r2): """ Returns the area of the intersection of two rectangles. If the rectangles do not intersect, the area returned is 0. :param r1: A 4-tuple representing a rectangle: (top_left_x, top_left_y, width, height) :param r2: A 4-tuple representing a rectangle: (top_left_x, top_left_y, width, height) :return: Area of intersection of r1 and r2. :rtype: Integer """ x1, y1, w1, h1 = r1 x2, y2, w2, h2 = r2 if x2 < x1 + w1 and x2 + w2 > x1 and y2 < y1 + h1 and y2 + h2 > y1: iw = min(x1 + w1 - 1, x2 + w2 - 1) - max(x1, x2) + 1 ih = min(y1 + h1 - 1, y2 + h2 - 1) - max(y1, y2) + 1 return iw * ih return 0
def _qualname(cls): """ Returns a fully qualified name of the class, to avoid name collisions. """ return u'.'.join([cls.__module__, cls.__name__])
def get_context(template, line, num_lines=5, marker=None): """ Returns debugging context around a line in a given string Returns:: string """ template_lines = template.splitlines() num_template_lines = len(template_lines) # In test mode, a single line template would return a crazy line number like, # 357. Do this sanity check and if the given line is obviously wrong, just # return the entire template if line > num_template_lines: return template context_start = max(0, line - num_lines - 1) # subt 1 for 0-based indexing context_end = min(num_template_lines, line + num_lines) error_line_in_context = line - context_start - 1 # subtr 1 for 0-based idx buf = [] if context_start > 0: buf.append("[...]") error_line_in_context += 1 buf.extend(template_lines[context_start:context_end]) if context_end < num_template_lines: buf.append("[...]") if marker: buf[error_line_in_context] += marker return "---\n{}\n---".format("\n".join(buf))
def clip_position(pt, x_range, y_range): """ Utility function to clip the position and avoid overflows. """ x, y = pt x = x % ( x_range[1] + 1 ) y = y % ( y_range[1] + 1 ) return (x, y)
def classAtributesLoader(objeto, cfg, lista_excessao=[], prefix=None): """[Carrega atributos do dict no self] Arguments: objeto {[[Class.self]]} -- [self da classe que se quer carregar os atributos] cfg {[dict]} -- [dictionary com os atributos a serem carregados] Keyword Arguments: lista_excessao {[List<string>]} -- [lista com nomes dos atributos de excessao] (default: {[]}) prefix {[string>]} -- [prefix usado na classe apontada no objeto] (default: {None}) Raises: Exception: [Atributo no dict nao existe no self do objeto e nao esta na lista de excessao] Return: [(Boolean,string)] Tupla true(item 0): msg(item 1) de log debug, false(item 0): msg(item 1) log de erro """ excessoes = [] tot_carregados = 0 for keyAbs in cfg: key = keyAbs if prefix is None else prefix + keyAbs if key in objeto.__dict__: tot_carregados += 1 setattr(objeto, key, cfg[keyAbs]) else: excessoes.append(key) if not excessoes: return True, 'Carga automatica de atributos Classe:{0} atributos:{1} ignorados:0'.format(str(objeto.__class__.__name__), tot_carregados) nova = list(set(excessoes) - set(lista_excessao)) if not nova: return True, 'Carga automatica de atributos Classe:{0} atributos:{1} ignorados:{2}'.format(str(objeto.__class__.__name__), tot_carregados, len(lista_excessao)) return False, 'Campo(s):{0} nao existe(m) na classe:{1}'.format(str(nova), objeto.__class__.__name__)
def prettify(value, postfix, value_format="%0.2f"): """ return prettified string of given value value may be None postfix can be used for unit for example """ if value is None: value_str = "--" else: value_str = value_format % value return "%s %s" % (value_str, postfix)
def remove_from_definition(definition, node): """Return quorum slice definition with the given node removed and the threshold reduced by 1""" threshold = definition['threshold'] nodes = definition['nodes'] if node in nodes: nodes = nodes.copy() nodes.remove(node) threshold = max(0, threshold - 1) children_definitions = [ remove_from_definition(children_definition, node) for children_definition in definition['children_definitions'] ] return { 'threshold': threshold, 'nodes': nodes, 'children_definitions': children_definitions }
def fib_recursive(n): """[summary] Computes the n-th fibonacci number recursive. Problem: This implementation is very slow. approximate O(2^n) Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n must be a positive integer' if n <= 1: return n return fib_recursive(n-1) + fib_recursive(n-2)
def parse_move(move): """ pulls the column and row out of the move """ if not (len(move) == 2): return None, None try: row = ord(move[0].upper()) - 65 col = int(move[1]) except: return None, None return row, col
def ordered_sequential_search(ordered_list, item): """Ordered Sequential search Complexity: item is present: best case=1, worst case=n, avg=n/2 item not present: best case=1, worst case=n, avg=n/2 Args: ordered_list (list): An ordered list. item (int): The item to search. Returns: bool: Boolean with the answer of the search. Examples: >>> alist = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> sequential_search(alist, 3) False >>> sequential_search(alist, 13) True """ pos = 0 found = False stop = False while pos < len(ordered_list) and not found and not stop: if ordered_list[pos] == item: found = True else: if ordered_list[pos] > item: stop = True else: pos += 1 return found
def _build_poolq_shell_executable( poolq_shell_path, barcode_file, condition_file, barcode_reads, reads, row_barcode_policy="PREFIX:CACCG@12", col_barcode_policy="FIXED:0", verbose=False, ): """ Parameters: ------------ poolq_shell_path path to poolq3.sh barcode_file path to barcode/rows/reference.csv file. condition_file path to columns/conditions.csv file. barcode_reads condition_reads row_barcode_policy col_barcode_policy verbose type: bool default: False Returns: -------- poolq_shell_executable Notes: ------ """ poolq_shell = "bash {} ".format(poolq_shell_path) rows = "--row-reference {} ".format(barcode_file) cols = "--col-reference {} ".format(condition_file) row_reads = "--row-reads {} ".format(reads) col_reads = "--col-reads {} ".format(barcode_reads) row_bc_policy = "--row-barcode-policy {} ".format(row_barcode_policy) col_bc_policy = "--col-barcode-policy {}".format(col_barcode_policy) poolq_shell_executable = ( poolq_shell + rows + cols + row_reads + col_reads + row_bc_policy + col_bc_policy ) return poolq_shell_executable
def listsplit(liststr=u''): """Return a split and stripped list.""" ret = [] for e in liststr.split(u','): ret.append(e.strip()) return ret
def photoUrl(prefix, suffix): """Construct the GET request for a foursquare photo.""" return prefix+"original"+suffix
def reverse_region (region): """ Reverse a given region """ return [region[1][::-1], region[0][::-1]]
def filterForXml(value): """ Replaces control characters with replace characters @param value: The value to filter @type value: C{unicode} @return: The filtered value @rtype: C{unicode} """ try: regex = filterForXml._regex except AttributeError: import re chars = u''.join([chr(num) for num in range(32) if num not in (9, 10, 13) # XML 1.0 ]) regex = filterForXml._regex = re.compile("[%s]" % chars) return regex.sub(u'\ufffd', value)
def descriptor(data): """Parameter list as string data: binary data a string""" from struct import unpack descriptor = "" i = 0 while i < len(data): type,version,length = unpack(">BBH",data[i:i+4]) if type == 3: payload = data[i+4:i+length] descriptor = payload break i += length return descriptor
def text_block(text, margin=0): """ Pad block of text with whitespace to form a regular block, optionally adding a margin. """ # add vertical margin vertical_margin = margin // 2 text = "{}{}{}".format( "\n" * vertical_margin, text, "\n" * vertical_margin ) lines = text.split("\n") longest_len = max(len(l) for l in lines) + margin # pad block and add horizontal margin text = "\n".join( "{pre}{line}{post}".format( pre=" " * margin, line=l, post=" " * (longest_len - len(l))) for l in lines) return text
def varint_bytes(int_value): """Serialize `int_value` into varint bytes and return them as a byetarray.""" buf = bytearray(9) if int_value < 0: raise TypeError('Negative values cannot be encoded as varint.') count = 0 while True: next = int_value & 0x7f int_value >>= 7 if int_value: buf[count] = next | 0x80 count += 1 else: buf[count] = next count += 1 break return buf[:count]
def is_guarded(point, queens, n): """Check if a given point is guarded by any queens in a given list. A point is guarded iff there are any queens in `queens` that are on the same row or column, or are on the same sum or difference diagonals. :queens: A list of (row, col) points where queens are on the board. :point: A (row, col) point to check. :n: A nonnegative integer denoting the size of the board. """ # There are probably a couple different ways to do this. # # For now, this is the naive "look if any points that could attack us are # in the list" method. row, col = point for queen in queens: queen_row, queen_col = queen # Check the rows and columns. if queen_row == row or queen_col == col: return True # Check the sum and difference diagonals. if (queen_row + queen_col == row + col or queen_row - queen_col == row - col): return True return False
def trial_name_cmp_func(x,y): """ Comparison function for sorting trial names """ num_x = int(x.split('_')[1]) num_y = int(y.split('_')[1]) if num_x > num_y: value = 1 elif num_y > num_x: value = -1 else: value = 0 return value
def parse_model_config(path): """ Parses the configuration file. :param path: YOLOv3 configuration file path. :return: Module definitions as an ordered list. """ with open(path, 'r') as fp: lines = fp.read().split('\n') lines = [x.rstrip().lstrip() for x in lines if x and not x.startswith('#')] module_defs = [] for line in lines: if line.startswith('['): module_defs.append({}) module_defs[-1]['type'] = line[1:-1].rstrip() if module_defs[-1]['type'] == 'convolutional': module_defs[-1]['batch_normalize'] = 0 else: key, value = line.split('=') value = value.strip() module_defs[-1][key.rstrip()] = value.strip() return module_defs
def nthstr(n): """ Formats an ordinal. Doesn't handle negative numbers. >>> nthstr(1) '1st' >>> nthstr(0) '0th' >>> [nthstr(x) for x in [2, 3, 4, 5, 10, 11, 12, 13, 14, 15]] ['2nd', '3rd', '4th', '5th', '10th', '11th', '12th', '13th', '14th', '15th'] >>> [nthstr(x) for x in [91, 92, 93, 94, 99, 100, 101, 102]] ['91st', '92nd', '93rd', '94th', '99th', '100th', '101st', '102nd'] >>> [nthstr(x) for x in [111, 112, 113, 114, 115]] ['111th', '112th', '113th', '114th', '115th'] """ assert n >= 0 if n % 100 in [11, 12, 13]: return '%sth' % n return {1: '%sst', 2: '%snd', 3: '%srd'}.get(n % 10, '%sth') % n
def fix_latex_command_regex(pattern, application='match'): """ Given a pattern for a regular expression match or substitution, the function checks for problematic patterns commonly encountered when working with LaTeX texts, namely commands starting with a backslash. For a pattern to be matched or substituted, and extra backslash is always needed (either a special regex construction like ``\w`` leads to wrong match, or ``\c`` leads to wrong substitution since ``\`` just escapes ``c`` so only the ``c`` is replaced, leaving an undesired backslash). For the replacement pattern in a substitutions, specified by the ``application='replacement'`` argument, a backslash before any of the characters ``abfgnrtv`` must be preceeded by an additional backslash. The application variable equals 'match' if `pattern` is used for a match and 'replacement' if `pattern` defines a replacement regex in a ``re.sub`` command. Caveats: let `pattern` just contain LaTeX commands, not combination of commands and other regular expressions (``\s``, ``\d``, etc.) as the latter will end up with an extra undesired backslash. Here are examples on failures. >>> re.sub(r'\begin\{equation\}', r'\[', r'\begin{equation}') '\\begin{equation}' >>> # match of mbox, not \mbox, and wrong output >>> re.sub(r'\mbox\{(.+?)\}', r'\fbox{\g<1>}', r'\mbox{not}') '\\\x0cbox{not}' Here are examples on using this function. >>> from doconce.latex import fix_latex_command_regex as fix >>> pattern = fix(r'\begin\{equation\}', application='match') >>> re.sub(pattern, r'\[', r'\begin{equation}') '\\[' >>> pattern = fix(r'\mbox\{(.+?)\}', application='match') >>> replacement = fix(r'\fbox{\g<1>}', application='replacement') >>> re.sub(pattern, replacement, r'\mbox{not}') '\\fbox{not}' Avoid mixing LaTeX commands and ordinary regular expression commands, e.g., >>> pattern = fix(r'\mbox\{(\d+)\}', application='match') >>> pattern '\\\\mbox\\{(\\\\d+)\\}' >>> re.sub(pattern, replacement, r'\mbox{987}') '\\mbox{987}' # no substitution, no match >>> # \g<1> and similar works fine """ import string problematic_letters = string.ascii_letters for letter in problematic_letters: problematic_pattern = '\\' + letter if letter == 'g' and application == 'replacement': # no extra \ for \g<...> in pattern if r'\g<' in pattern: continue ok_pattern = '\\\\' + letter if problematic_pattern in pattern and not ok_pattern in pattern: pattern = pattern.replace(problematic_pattern, ok_pattern) return pattern
def anonymize_number(number): """ Anonymize 3 last digits of a number, provided as string. """ if number.isdigit() and len(number) >= 3: return number[:-3] + "xxx" else: # Not a number or e.g. "unknown" if caller uses CLIR return number
def detokenize_enzymatic_reaction_smiles(rxn: str) -> str: """Detokenize an enzymatic reaction SMILES in the form precursors|EC>>products. Args: rxn: a tokenized enzymatic reaction SMILES. Returns: the detokenized enzymatic reaction SMILES. """ rxn = rxn.replace(" ", "") if "[v" in rxn and "|" not in rxn: pipe_index = rxn.index("[v") if pipe_index > -1: rxn = rxn[:pipe_index] + "|" + rxn[pipe_index:] if "[v" not in rxn and "|" in rxn: rxn = rxn.replace("|", "") if "|" not in rxn: return rxn precursor_split = rxn.split("|") if len(precursor_split) < 2: return "" reaction_split = precursor_split[1].split(">>") if len(reaction_split) < 2: return "" ec = ( reaction_split[0] .replace("][", ".") .replace("[v", "") .replace("u", "") .replace("t", "") .replace("q", "") .replace("]", "") ) return precursor_split[0] + "|" + ec + ">>" + reaction_split[1]
def _find_channel_index(data_format): """Returns the index of the channel dimension. Args: data_format: A string of characters corresponding to Tensor dimensionality. Returns: channel_index: An integer indicating the channel dimension. Raises: ValueError: If no channel dimension was found. """ for i, c in enumerate(data_format): if c == "C": return i raise ValueError("data_format requires a channel dimension. Got: {}" .format(data_format))
def profile(point, context, user, owner, viewer): """ """ return {'is_owner': owner == viewer }
def get_user(app_configs): """ Looks for either 'api_key_id' or 'email' in the provided dict and returns its value. Returns None if neither are found or set to a valid value :param app_configs: a dictionary of all the values in the app.config file :type app_configs: dict :rtype: [str/None] """ usr = app_configs.get("api_key_id", None) if not usr: usr = app_configs.get("email", None) if not usr: return None return usr
def _strip_nul(text): """Remove NUL values from the text, so that it can be treated as text There should likely be no NUL values in human-readable logs anyway. """ return text.replace('\x00', '<NUL>')
def _get_full_attr_name(attr_name_stack, short_attr_name=None): """Join the attr_name_stack to get a full attribute name. :param attr_name_stack: List of attribute names sitting on our processing stack while building MQL queries. :param short_attr_name: The trailing attr_name to be appended to the end of our full dot separated attr name. :return: A dot separated data key. :rtype: str """ return ".".join( attr_name_stack + [short_attr_name] if short_attr_name else [])
def number_else_string(text): """ Converts number to an integer if possible. :param text: Text to be converted :return: Integer representation of text if a number. Otherwise, it returns the text as is """ return int(text) if text.isdigit() else text
def IsUserHeader(decorated_name): """Returns true if decoraed_name looks like a user header.""" return decorated_name[0] == '"' and decorated_name[-1] == '"'
def proc_to_seconds(val, entry): """Process a value in minutes to seconds""" return 60 * int(val)
def format(dict): """ itype: Dict rtype: String, formatted dict """ res = ['\t\t<object>'] for (key, val) in dict.items(): line = '\t\t\t<{}>"{}"</{}>'.format(key, val, key) res.append(line) res.append('\t\t</object>\n') return '\n'.join(res)
def _is_subpath(path, ancestors): """Determines if path is a subdirectory of one of the ancestors""" for ancestor in ancestors: if not ancestor.endswith('/'): ancestor += '/' if path.startswith(ancestor): return True return False
def length_of(l): """Get number of elements in list or None for singletons.""" return len(l) if isinstance(l, list) else None
def _is_password_valid(pw): """Returns `true` if password is strong enough for Firebase Auth.""" return len(pw) >= 6
def do_date(dt, format='%Y-%m-%d - %A'): """Jinja template filter to format a datetime object with date only.""" if dt is None: return '' # Only difference with do_datetime is the default format, but that is # convenient enough to warrant its own template filter. return dt.strftime(format)
def to_list(obj): """ Return a list containing obj if obj is not already an iterable""" try: iter(obj) return obj except TypeError: return [obj]
def in_range(in_num, minimum, maximum): """ Sees if the entered value is within the given range :param in_num: The number to check :type in_num: float :param minimum: The minimum value of the range (inclusive) :type minimum: float :param maximum: The maximum value of the range (inclusive) :type maximum: float :returns: ``'lt'`` if less than, ``'gt'`` is greater than, and ``None`` if in :rtype: str """ if minimum is not None and in_num < minimum: return 'lt' elif maximum is not None and in_num > maximum: return 'gt' else: return None
def solution(n: int, a: list) -> list: """ >>> solution(5, [3, 4, 4, 6, 1, 4, 4]) [3, 2, 2, 4, 2] """ counters = [0] * n max_counter = n + 1 cur_max = 0 for num in a: if num == max_counter: counters = [cur_max] * n else: counters[num - 1] += 1 if counters[num - 1] > cur_max: cur_max += 1 return counters
def dequote(s): """ If a string has single or double quotes around it, remove them """ if (s[0] == s[-1]) and s.startswith(("'", '"')): return s[1:-1] return s
def format(formatter, payload): """Returns a list of formatted strings Example: >>> formatter = "{} is {}" >>> data = {"name":"donnees", "age":1} >>> result = format(formatter, data) >>> print(result[0]) name is donnees >>> print(result[1]) age is 1 Or >>> formatter = lamdba x: "{} haha".format(x) >>> data = ["name", "age"] >>> result = format(formatter, data) >>> print(result[0]) name haha >>> print(result[1]) age haha """ if not isinstance(payload, (list, tuple, dict)): raise ValueError("Unexpected Payload Type {} expected either dict, list or tuple".format(type(payload))) if isinstance(payload, (list, tuple)): if callable(formatter): return [formatter(k) for k in payload] return [formatter.format(k) for k in payload] # At this point the payload is dict return [formatter.format(k, v) for k, v in payload.items()]
def get_headers(environ): """ Returns headers from the environ """ headers = {} for name in environ: if name[0:5] == "HTTP_": headers[name[5:]] = environ[name] return headers
def orthonormal_exp(variables: list) -> list: """ orthonormal expansion of a list of distinct variables >>> orthonormal_exp([1,2,3]) [(1,), (-1, 2), (-1, -2, 3), (-1, -2, -3)] """ result = [] last = [] for var in variables: if last: last[-1]*=-1 last.append(var) result.append(last.copy()) last[-1]*=-1 result.append(last) return [tuple(i) for i in result]
def difference(num1, num2): """ Find the difference between 2 numbers. :type num1: number :param num1: The first number to use. :type num2: number :param num2: The second number to use. >>> difference(1, 4) 3 """ # Return the calculated value return abs(num1 - num2)
def determine_interp_factor(value, before, after): """Determine interpolation factor for removal of division in follow-on code For the formula: v = v0 + (v1 - v0) * ((t - t0) / (t1 - t0)) I'm defining the interpolation factor as this component of the formula: ((t - t0) / (t1 - t0)) Args: value <number>: The value to interpolate for before <number>: The value before after <number>: The value after Returns: <float>: The interpolation factor """ f_value = float(value) f_before = float(before) f_after = float(after) return (f_value - f_before) / (f_after - f_before)
def shrink_path(full_path: str, max_len: int = 70) -> str: """ Shrinks the path name to fit into a fixed number of characters. Parameters ----------- full_path: String containing the full path that is to be printed. \n max_len: Integer containing the maximum length for the final path. Should be more than 10 characters. Default: 15 \n Returns -------- String containing path after shrinking it. Will be at most `max_len` characters in length. """ if len(full_path) <= max_len: # Directly return the path if it fits within the maximum length allowed. return full_path allowed_len = max_len - 6 return f'{full_path[:int(allowed_len / 2)]}......{full_path[-int(allowed_len / 2):]}'
def meta_name(obj): """ Returns meta type name of the given object. """ return obj.__class__.__name__
def is_digit(value: str) -> bool: """Return if ``value`` is number (decimal or whole)""" if value.count('.') == 1 and value.replace('.', '').isdigit() or value.isdigit(): return True return False
def box_to_rect(box, width, height): """ :param box: center_x, center_y, bbox_w, bbox_h :param width: image width :param height: image height :return: x1, y1, x2, y2(in pixel) """ x, y, w, h = box x1 = (x - w * 0.5) * width y1 = (y - h * 0.5) * height x2 = (x + w * 0.5) * width y2 = (y + h * 0.5) * height return [int(x1), int(y1), int(x2), int(y2)]
def flatten_dict_vals(dict_): """ Flattens only values in a heirarchical dictionary, keys are nested. """ if isinstance(dict_, dict): return dict([ ((key, augkey), augval) for key, val in dict_.items() for augkey, augval in flatten_dict_vals(val).items() ]) else: return {None: dict_}
def isEqual(lhs, rhs): """types should be a either a list, tuple, etc""" print(lhs) print(rhs) for x,y in zip(lhs, rhs): if x == y: continue else: return False return True
def is_image_file(filename): """Check if it is an valid image file by extension.""" return any( filename.endswith(extension) for extension in ['jpeg', 'JPEG', 'jpg', 'png', 'JPG', 'PNG', 'gif'])
def is_sequence(arg): """Returns True only if input acts like a sequence, but does not act like a string. """ return (not hasattr(arg, "strip") and hasattr(arg, "__getitem__") or hasattr(arg, "__iter__"))
def build_user_agent(octavia_version: str, workspace_id: str) -> str: """Build user-agent for the API client according to octavia version and workspace id. Args: octavia_version (str): Current octavia version. workspace_id (str): Current workspace id. Returns: str: the user-agent string. """ return f"octavia-cli/{octavia_version}/{workspace_id}"
def arithmetic_series(n): """Arithmetic series by Gauss sum formula. Time complexity: O(1). Space complexity: O(1) """ return (1 + n) * n / 2
def exists(field): """ Only return docs which have 'field' """ return {"exists": {"field": field}}
def parser_NVOD_reference_Descriptor(data,i,length,end): """\ parser_NVOD_reference_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "NVOD_reference", "contents" : unparsed_descriptor_contents } (Defined in ETSI EN 300 468 specification) """ return { "type" : "NVOD_reference", "contents" : data[i+2:end] }
def daily_severity_rating(fwi): """Daily severity rating. Parameters ---------- fwi : array Fire weather index Returns ------- array Daily severity rating. """ return 0.0272 * fwi ** 1.77
def _get_plot_style(i, selected_case_idx, num_cases): """ Return plot attributes based on the index of the selected case and the number of cases. Parameters ---------- i : int Index of the current case. selected_case_idx : int Index of the selected case. num_cases : int Total number of cases being plotted. Returns ------- lw : float The linewidth attribute for matplotlib line. ms : float The markersize attribute for matplotlib line. s : float The s (marker size) attribute for matplotlib scatter. alpha : float The alpha (transparency) attribute for matplotlib line and scatter. """ if selected_case_idx >= num_cases: # Settings when all plots should be displayed "equally". alpha = 1.0 lw = 1 ms = 2 s = 10 else: alpha = 0.1 if i != selected_case_idx else 1.0 lw = 0.5 if i != selected_case_idx else 2 ms = 2. if i != selected_case_idx else 6. s = 10 if i != selected_case_idx else 40 return lw, ms, s, alpha
def flatten(array): """ Returns a list of flattened elements of every inner lists (or tuples) ****RECURSIVE**** """ import numpy res = [] for el in array: if isinstance(el, (list, tuple, numpy.ndarray)): res.extend(flatten(el)) continue res.append(el) return list( res )
def dotmm(A, B, check=True): """ Matrix-matrix dot product, optimized for small number of components containing large arrays. For large numbers of components use numpy.dot instead. Unlike numpy.dot, broadcasting rules only apply component-wise, so components may be a mix of scalars and numpy arrays of any shape compatible for broadcasting. """ m = len(A) n = len(B[0]) p = len(B) if check and m * n * p > 512: raise Exception('Too large. Use numpy.dot') D = [] for j in range(m): C = [] for k in range(n): c = 0.0 for i in range(p): c += A[j][i] * B[i][k] C.append(c) D.append(C) return D
def ComputeAngleDifference(angle1, angle2): """ This function computes the difference between two angles. :rtype : float :param angle1: float with the first angle :param angle2: float with the second angle :return: """ if angle1 < 0: inicial = angle1 + 360 else: inicial = angle1 if angle2 < 0: final = angle2 + 360 else: final = angle2 diff = inicial - final return diff
def compose_username(nick, email, provider): """ @brief Compose the username The username policy via openid is as follow: * Try to use the nick name * If not available fall back to email * Append the the openid provider as domain. Delimiter is % in order to diferentiate from @ (if email is used) @param nick The nick name or None @param email The email or None @param provider the Authentication provider @return Non in case no user name was derived, otherwise the username """ if nick: return '{0}%{1}'.format(nick, provider) else: if email: return '{0}%{1}'.format(email, provider) return None
def converttodiamondmatrix(m): """ Convert to a diamond shaped matrix. a a b c d b d e f -> g e c g h i h f i """ d = [ [ "" for _ in range(len(m)*2-1) ] for _ in range(2*len(m)-1) ] for y in range(1, 2*len(m)): for x in range(len(m)): if 0 <= y+x-len(m) < len(m): d[2*len(m)-y-1][2*x+y-len(m)] = m[x][y+x-len(m)] return d
def dsv_of_list(d, sep=","): """ Converting a list of strings to a dsv (delimiter-separated values) string. Note that unlike most key mappers, there is no schema imposing size here. If you wish to impose a size validation, do so externally (we suggest using a decorator for that). Args: d: A list of component strings sep: The delimiter text used to separate a string into a list of component strings Returns: The delimiter-separated values (dsv) string for the input tuple >>> dsv_of_list(['a', 'brown', 'fox'], sep=' ') 'a brown fox' >>> dsv_of_list(('jumps', 'over'), sep='/') # for filepaths (and see that tuple inputs work too!) 'jumps/over' >>> dsv_of_list(['Sat', 'Jan', '1', '1983'], sep=',') # csv: the usual delimiter-separated values format 'Sat,Jan,1,1983' >>> dsv_of_list(['First', 'Last'], sep=':::') # a longer delimiter 'First:::Last' >>> dsv_of_list(['singleton'], sep='@') # when the list has only one element 'singleton' >>> dsv_of_list([], sep='@') # when the list is empty '' """ return sep.join(d)
def analyze_discriminant(lookup, word1, word2): """Find patterns that include word1 but not word2.""" ret = [] for pattern, words in lookup.items(): # XOR presence of these words if (word1 in words) != (word2 in words): ret.append(pattern) return ret
def generate_resource_link(pid, resource_path, static=False, title=None): """ Returns a valid html link to a public resource within an autogenerated instance. Args: pid: the problem id resource_path: the resource path static: boolean whether or not it is a static resource title: the displayed text. Defaults to the path Returns: The html link to the resource. """ return '<a target=_blank href="/api/autogen/serve/{}?static={}&pid={}">{}</a>'.format( resource_path, "true" if static else "false", pid, resource_path if not title else title )
def intcode_parse(code): """Accepts intcode. Parses intcode and returns individual parameters. """ actual_code = code % 100 parameter_piece = code - actual_code parameter_piece = parameter_piece // 100 parameter_code_list = [] while parameter_piece > 0: parameter_code_list.append(parameter_piece % 10) parameter_piece = parameter_piece // 10 return (actual_code, parameter_code_list)
def calc_system_multiplier(grow_system): """ System Multiplier Notes ----- Standard yield isn't 100% accurate and doesn't consider high density vertical farming systems. The estimated yield from ZipGrow Ziprack_8 is 66,825 kg/year for 235m2 plant area. Adjusted yield without multiplier is 18447.5 kg/year 66,825/18447.5 kg = 3.622442065320504 """ if grow_system == 'ziprack_8': system_multiplier = 3.622442065320504 else: raise RuntimeError("Unknown grow system {}".format(grow_system)) return system_multiplier
def move_zeros(array): """Algorithm to move zeros to end of array while preserving positions of other elements""" count = abs(array.count(0) - sum(x is False for x in array)) nozeros = [elem for elem in array if elem != 0 or elem is False] return nozeros+[0 for i in range(count)]
def get_bin_linesep(encoding, linesep): """ Simply doing `linesep.encode(encoding)` does not always give you *just* the linesep bytes, for some encodings this prefix's the linesep bytes with the BOM. This function ensures we just get the linesep bytes. """ if encoding == 'utf-16': return linesep.encode('utf-16')[2:] # [2:] strips bom else: return linesep.encode(encoding)
def float_to_rational(value: float): """Casts a float to a DcRationalNumberType. :param value: The value to cast. :return: DcRationalNumberType -- the cast result. """ if value == 0: return 0, 0 string = format(value, ".2e") if abs(value) < 1: string = string.split("e") # Keep the sign else: string = string.split("e+") try: value = int(string[0]) exponent = int(string[1]) except ValueError: value = int(string[0].replace('.', '')) exponent = int(string[1]) - 2 return value, exponent
def get_mean(data): """Return the sample arithmetic mean of data.""" n = len(data) if n < 1: raise ValueError('mean requires at least one data point') return sum(data)/float(n)
def convert_int_minutes_to_militar_time_format(list): """ Convert the list of minutes ranges to a list of hour ranges. >>> convert_int_minutes_to_militar_time_format([[540, 600], [720, 780]]) [['9:00', '10:00'], ['12:00', '13:00']] """ result = [] for i in list: hours = int(i[0] / 60) minutes = int(i[0] % 60) hours2 = int(i[1] / 60) minutes2 = int(i[1] % 60) if minutes == 0: minutes = '00' elif minutes < 10: minutes = '0' + str(minutes) if minutes2 == 0: minutes2 = '00' elif (minutes2 < 10): minutes2 = '0' + str(minutes2) result.append([str(hours) + ':' + str(minutes), str(hours2) + ':' + str(minutes2)]) return result
def esc_seq(n, s): """Escape sequence. Call sys.stdout.write() to apply.""" return f'\033]{n};{s}\007'
def _context_license_spdx(context, value): """convert a given known spdx license to another one""" # more values can be taken from from https://github.com/hughsie/\ # appstream-glib/blob/master/libappstream-builder/asb-package-rpm.c#L76 mapping = { "Apache-1.1": "ASL 1.1", "Apache-2.0": "ASL 2.0", "BSD-3-Clause": "BSD", "GPL-1.0+": "GPL+", "GPL-2.0": "GPLv2", "GPL-2.0+": "GPLv2+", "GPL-3.0": "GPLv3", "GPL-3.0+": "GPLv3+", "LGPL-2.1": "LGPLv2.1", "LGPL-2.1+": "LGPLv2+", "LGPL-2.0": "LGPLv2 with exceptions", "LGPL-2.0+": "LGPLv2+ with exceptions", "LGPL-3.0": "LGPLv3", "LGPL-3.0+": "LGPLv3+", "MIT": "MIT with advertising", "MPL-1.0": "MPLv1.0", "MPL-1.1": "MPLv1.1", "MPL-2.0": "MPLv2.0", "OFL-1.1": "OFL", "Python-2.0": "Python", } if context['spec_style'] == 'fedora': return mapping[value] else: # just use the spdx license name return value
def decode(search_input: str, post: str) -> int: """ Binary space partitioning. """ elem_length = 2 ** len(search_input) elem = 0 for char in search_input: elem_length //= 2 if char == post: elem += elem_length return elem
def _twos_complement(value: int, bits: int) -> int: """ This does twos complement so we can convert hex strings to signed integers. Why is this not built-in to python int? """ if value & (1 << (bits - 1)): value -= 1 << bits return value
def find_seq(template, query): """find sequence in another. Input string template and tuple of queries. Output list of matches. """ matches = [] for seq in query: if seq in template: matches.append(seq) # print('find_seq', matches) return matches
def f2suff(forfile, opath, suff): """ Construct outputfile in opath with new suffix. Definition ---------- def f2suff(forfile, opath, suff): Input ----- forfile Fortran90 file name opath relative output path Script assumes output path: dirname(forfile)/opath suff Input file sufix will be replaced by suff Output ------ Name of output file in opath and new suffix History ------- Written, Matthias Cuntz, Mar 2016 """ import os idir = os.path.dirname(forfile) ifile = os.path.basename(forfile) odir = idir +'/' + opath ofile = ifile[0:ifile.rfind('.')] + '.' + suff return odir + '/' + ofile
def white(message): """ white color :return: str """ return f"\x1b[37;1m{message}\x1b[0m"
def readattr(_obj, _name, _default=None, _error_on_none=None): """ Reads an attribute value from an object :param _obj: The object :param _name: The name of the attribute :param _default: If set, the value to return if the attribute is missing or the value is None :param _error_on_none: If set, the message of an exception that is raised if the attribute is missing or the value is None :return: The value of the attribute """ try: _value = getattr(_obj, _name) except AttributeError: if _error_on_none: raise Exception(_error_on_none) else: return _default if _value is None: if _error_on_none: raise Exception(_error_on_none) else: return _default else: return _value
def check_output(*popenargs, **kwargs): """ Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) 'ls: non_existent_file: No such file or directory\n' """ # Note: This function has been part of the python standard library since # python27. I included it here because I commonly find myself wanting it # on the cluster, which runs python26. from subprocess import Popen, PIPE, CalledProcessError if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) return output
def check_status(checksite): """Return true only if wiki is public and open""" return ((checksite.get('closed') is None) and (checksite.get('private') is None) and (checksite.get('fishbowl') is None))
def make_safe_star_id(star_id): """ Make a star id that is safe to include in a URL. :param star_id: star id that may contain spaces or plus signs [string]. :return: star_id safe to include in a URL [string]. """ return star_id.replace("+", "%2B").replace(" ", "+")
def _round_point_no_nearest(point, epsilon): """ :param point: list of coordinates """ return [round(x / epsilon) * epsilon for x in point]
def formatnumber(n): """Format a number with beautiful commas.""" parts = list(str(n)) for i in range((len(parts) - 3), 0, -3): parts.insert(i, ',') return ''.join(parts)
def generate_hostname(ip_address): """ :param IPv4Address ip_address: :rtype: unicode :return: """ numeric_ip = int(ip_address) return "x{:02x}{:02x}{:02x}{:02x}".format((numeric_ip >> 0x18) & 0xFF, (numeric_ip >> 0x10) & 0xFF, (numeric_ip >> 0x08) & 0xFF, (numeric_ip >> 0x00) & 0xFF)
def distance_from_speed_and_time(movement_speed, movement_time): """Returns distance from speed and time""" return movement_time * movement_speed * 1000 / 3600
def get_masters(ppgraph): """From a protein-peptide graph dictionary (keys proteins, values peptides), return master proteins aka those which have no proteins whose peptides are supersets of them. If shared master proteins are found, report only the first, we will sort the whole proteingroup later anyway. In that case, the master reported here may be temporary.""" masters = {} for protein, peps in ppgraph.items(): ismaster = True multimaster = set() for subprotein, subpeps in ppgraph.items(): if protein == subprotein: continue if peps.issubset(subpeps): if peps.union(subpeps) > peps: ismaster = False break elif peps.intersection(subpeps) == peps: multimaster.update({protein, subprotein}) if not ismaster: continue elif multimaster: premaster = sorted(list(multimaster))[0] else: premaster = protein for pep in peps: try: masters[pep].add(premaster) except KeyError: masters[pep] = {premaster} return masters
def get_r_squared(t, dof): """ Get the r-squared value for effective size measure. Parameters ---------- > t: the t-statistic for the distribution > dof: the degrees of freedom of the sample Returns ------- The r_squared value for effective size measure """ t_squared = t * t return t_squared / (t_squared + dof)
def _ns_join(name, ns): """Dumb version of name resolution to mimic ROS behaviour.""" if name.startswith("~") or name.startswith("/"): return name if ns == "~": return "~" + name if not ns: return name if ns[-1] == "/": return ns + name return ns + "/" + name
def QuickSort(A, l, r): """ Arguments: A -- total number list l -- left index of input list r -- right index of input list Returns: ASorted -- sorted list cpNum -- Number of comparisons """ # Number of comparisons cpNum = r - l # Base case if cpNum == 0: return [A[l]], 0 elif cpNum < 0: return [], 0 # Preprocessing of median-of-three # ------Way 1------ # n = r - l + 1 # c1 = A[l] > A[(l+r)//2] # c2 = A[l] > A[r] # c3 = A[(l+r)//2] > A[r] # if (c1 and c2 and c3) or (not (c1 or c2 or c3)): # A[l], A[(l+r)//2] = A[(l+r)//2], A[l] # elif (c1 and c2 and (not c3)) or (not (c1 or c2 or (not c3))): # A[l], A[r] = A[r], A[l] # ------Way 2------ # middelNum = sorted([A[l], A[(l+r)//2], A[r]])[1] # if A[(l+r)//2] == middelNum: # A[l], A[(l+r)//2] = A[(l+r)//2], A[l] # elif A[r] == middelNum: # A[l], A[r] = A[r], A[l] # ------Way 3------ middelNum = sum([A[l], A[(l+r)//2], A[r]]) - max([A[l], A[(l+r)//2], A[r]]) - min([A[l], A[(l+r)//2], A[r]]) if A[(l+r)//2] == middelNum: A[l], A[(l+r)//2] = A[(l+r)//2], A[l] elif A[r] == middelNum: A[l], A[r] = A[r], A[l] # Partition part p = A[l] i = l + 1 for j in range(l + 1, r + 1): if A[j] < p: A[j], A[i] = A[i], A[j] i += 1 A[l], A[i-1] = A[i-1], A[l] # print("middel:", A) # Recursion call ALeft, cpNumLeft = QuickSort(A, l, i-2) ARight, cpNumRight = QuickSort(A, i, r) ASorted = ALeft + [p] + ARight cpNum = cpNum + cpNumLeft + cpNumRight return ASorted, cpNum
def _parse_licenses(output): """Parse the licenses information. It will return a dictionary of products and their license status. """ licenses = {} # We are starting from 2, since the first line is the # list of fields and the second one is a separator. # We can't use csv to parse this, unfortunately. for line in output.strip().splitlines()[2:]: product, _, status = line.rpartition(" ") product = product.strip() licenses[product] = status return licenses
def tof2ev(d, t0, E0, t): """ d/(t-t0) expression of the time-of-flight to electron volt conversion formula. **Parameters**\n d: float Drift distance t0: float time offset E0: float Energy offset. t: numeric array Drift time of electron. **Return**\n E: numeric array Converted energy """ # m_e/2 [eV] bin width [s] E = 2.84281e-12*(d/((t-t0)*0.00823e-9))**2 + E0 return E