content
stringlengths
42
6.51k
def read_str(data, start, length): """Extract a string from a position in a sequence.""" return data[start:start+length].decode('utf-8')
def label(language='en', value=''): """Create and return a label (dict)""" return {language: {'language': language, 'value': value}}
def drude(x, x0=4.59, gamma=0.90, **extras): """Drude profile for the 2175AA bump. :param x: Inverse wavelength (inverse microns) at which values for the drude profile are requested. :param gamma: Width of the Drude profile (inverse microns). :param x0: Center of the Drude profile (inverse microns). :returns k_lambda: The value of the Drude profile at x, normalized such that the peak is 1. """ #return (w * gamma)**2 / ((w**2 - w0**2)**2 + (w * gamma)**2) return (x*gamma)**2 / ((x**2 - x0**2)**2 + (x * gamma)**2)
def bindigits(n:int, bits:int)->str: """Convierte a binario un numero de complemento A2 en caso de negativo, normal en caso de ser positivo Args: n (int): E.g 7 bits (int): eg 3 Returns: str: E.g '001' """ s = bin(n & int("1"*bits, 2))[2:] return ("{0:0>%s}" % (bits)).format(s)
def get_center(x_min: int,y_min: int,x_max:int,y_max:int): """Get center of bounding box. Args: x_min (int): Minimum x value in pixels. y_min (int): Minimum y value in pixels. x_max (int): Maximum x value in pixels. y_max (int): Maximum y value in pixels. Returns: tuple: Center (x,y) in pixels. """ x = (x_min+x_max)/2 y = (y_min+y_max)/2 return x,y
def is_stored(self): """ Checks if the given model is stored in a previously defined secondary storage system. For the base model it's always considered (by default) to be not stored (transient). :rtype: bool :return: If the current model is stored in the hypothetical secondary storage system, considered always false (no persistence layer present). """ # in case the is persisted method is present, it should # be used to check if the model is stored in a secondary # storage systems otherwise it's always considered to be # a transient model (default case) if hasattr(self, "is_persisted"): return self.is_persisted() return False
def dict_update(fields_list, d, value): """ :param fields_list: list of hierarchically sorted dictionary fields leading to value to be modified :type fields_list: list of str :param d: dictionary to be modified :type d: dict :param value: new value :type value: any type :return: updated dictionary :rtype: dict """ if len(fields_list) > 1: l1 = fields_list[1:] k = fields_list[0] if k not in list(d.keys()): d[k] = dict() d[k] = dict_update(l1, d[k], value) else: k = fields_list[0] d[k] = value return d return d
def count_if(iterable, pred, first=0, last=None): """ Count the number of elements in an iterable that satisfy a condition Parameters ---------- iterable: an iterable object with __get_item__ pred: a unary predicate function first: first element to check last: one past last element to check. None will check until end of iterable Returns ------- count: the number of elements in iterable range that satisfy pred """ assert hasattr(iterable, '__getitem__') # Only slice for sub-ranges, slight performance improvement iterable = iterable if first == 0 and last is None else iterable[first:last] return sum(1 for x in iterable if pred(x))
def is_tool(name): """Check whether `name` is on PATH and marked as executable.""" from shutil import which return which(name) is not None
def str_to_bool(s): """Convert string boolean values to bool. The conversion is case insensitive. :param val: input string :return: True if val is 'true' otherwise False """ return str(s).lower() == 'true'
def _parse_ipv4(ip): """ Parse an ipv4 address and port number. """ addr, port = ip.split(':') return addr, port
def to_field_name(mp_name): """Get the field name for the Materialized Property named `mp_name` """ return '_' + mp_name
def get_post_data(start_year, _ID_BenefitSurtax_Switches=True, quick_calc=False): """ Convenience function for posting GUI data """ data = {'has_errors': ['False'], 'start_year': str(start_year), 'data_source': 'PUF', 'csrfmiddlewaretoken':'abc123'} if _ID_BenefitSurtax_Switches: switches = {'ID_BenefitSurtax_Switch_0': ['True'], 'ID_BenefitSurtax_Switch_1': ['True'], 'ID_BenefitSurtax_Switch_2': ['True'], 'ID_BenefitSurtax_Switch_3': ['True'], 'ID_BenefitSurtax_Switch_4': ['True'], 'ID_BenefitSurtax_Switch_5': ['True'], 'ID_BenefitSurtax_Switch_6': ['True']} data.update(switches) if quick_calc: data['quick_calc'] = 'Quick Calculation!' return data
def row_button_width(row_buttons): """ returns the width of the row buttons """ if not row_buttons: return 0 n = len(row_buttons) return n * 25 + (n - 1) * 5
def delete_behavior_validator(value): """ Property: SchemaChangePolicy.DeleteBehavior """ valid_values = [ "LOG", "DELETE_FROM_DATABASE", "DEPRECATE_IN_DATABASE", ] if value not in valid_values: raise ValueError("% is not a valid value for DeleteBehavior" % value) return value
def get_moment(at): """Get moment value from one at type value: >>> get_moment('minute.1') 1 :param at: One at type value. """ return int(at[at.find('.') + 1:])
def int2bin6(num): """ Converts the given integer to a 6-bit binary representation """ return "".join(num & (1 << i) and '1' or '0' for i in range(5, -1, -1))
def unlistify(x): """ Converts 1-element list to x. """ # The isinstance() built-in function is recommended over the type() built-in function for testing the type of an object if isinstance(x, list): if len(x)==1: return x[0] else: return x else: return x
def load_token(token_name): """ Read supplementary text file for Scopus API key Args: token_name: the name of your Scopus API key file """ try: with open(token_name, 'r') as file: return str(file.readline()).strip() except EnvironmentError: print(f'Error loading {token_name} from file')
def get_middle(s): """This will find the middle character(s).""" i = (len(s) - 1) // 2 return s[i:-i] or s
def get_status( object ): """ Gets the lower Status information Args: object: The object containing Status Returns: The state within Status (None if not found) The health within Status (None if not found) """ state = None health = None if "Status" in object: state = object["Status"].get( "State", None ) health = object["Status"].get( "Health", None ) return state, health
def args_idx(x): """Get the idx of "?" in the string""" return x.rfind('?') if '?' in x else None
def infant_action_valuation(signals): """ Parameters ---------- signals : dict """ count = 0 for signal in signals: if signals[signal] == "still": count += 1 return max(count / float(4), 0.1)
def extract_transcript_annotations_from_GTF(tab_fields): """ Extracts key-value annotations from the GTF description field """ attributes = {} description = tab_fields[-1].strip() # Parse description for pair in [x.strip() for x in description.split(";")]: if pair == "": continue pair = pair.replace('"', '') key, val = pair.split() attributes[key] = val # Put in placeholders for important attributes (such as gene_id) if they # are absent if "gene_id" not in attributes: attributes["gene_id"] = "NULL" attributes["source"] = tab_fields[1] return attributes
def get_syst ( syst , *index ) : """Helper function to decode the systematic uncertainties Systematic could be - just a string - an object with index: obj [ibin] - a kind of function: func (ibin) """ if isinstance ( syst , str ) : return syst elif syst and hasattr ( syst , '__getitem__' ) : return str ( syst [ index ] ) elif syst and callable ( syst ) : return str ( syst ( *index ) ) elif syst : raise AttributeError("Invalid systematic %s/%s" % ( syst , type( syst ) ) ) return ''
def collect_doc(ori_doc): """ mysql> describe document; original documents (should not be changed in the whole process); +----------+----------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+----------------+------+-----+---------+-------+ | doc_id | varchar(300) | NO | PRI | NULL | | | doc_body | varchar(15000) | YES | | NULL | | +----------+----------------+------+-----+---------+-------+ :param ori_doc: list of tuples, [(doc_id, doc_body)] :return: doc_name2txt: a dictionary of txt, key is the name of the documents (from multiple datasets), value is the corresponding documentation text. """ print('collecting original documents from DB list.') print(len(ori_doc), ' total documents are collected.') doc_name2txt = dict() for (doc_id, doc_body) in ori_doc: # repeated documentation is not allowed assert doc_id not in doc_name2txt doc_name2txt[doc_id] = doc_body return doc_name2txt
def _intenum_converter(value, enum_klass): """Convert a numeric family value to an IntEnum member. If it's not a known member, return the numeric value itself. """ try: return enum_klass(value) except ValueError: return value
def get_init_partition(nodes): """ Parameters ---------- nodes : arr_like. Vertices of the netlist's graph. Returns ------- list, list Nodes in partition 1 and 2. """ return list(nodes[:len(nodes)//2]), list(nodes[len(nodes)//2:])
def ifb(bites): """ ifb is a wrapper for int.from_bytes """ return int.from_bytes(bites, byteorder="big")
def linear_oversample_list(alist, factor=2): """Linearly oversample a list: Calculate intermediate values between the list entries using the given oversampling factor. The default factor of two fills the medians into the list. Parameters ---------- alist : list Input list that should be oversampled. factor : int Oversampling factor. Default: 2 Returns ------- list Oversampled list. """ import numpy as np newlist = [] for i1,i2 in zip(alist[:-1],alist[1:]): newlist.append(i1) for n in np.arange(factor-1): newlist.append( i1+(n+1)/factor*(i2-i1) ) newlist.append(alist[-1]) return newlist
def find_missing_integer(lst): """Returns the first missing integer in an ordered list. If not found, returns the next integer. """ try: return sorted(set(range(lst[0], lst[-1])) - set(lst))[0] except: return max(lst) + 1
def endian_swap(value): """"Given a 32-bit integer value, swap it to the opposite endianness""" return (((value >> 24) & 0xff) | ((value >> 8) & 0xff00) | ((value << 8) & 0xff0000) | (value << 24))
def replace_key(dictionary, new_key, old_key): """ This method is used for replace key in dictionary. :param dictionary: dictionary object on which we wan to replace key. :param new_key: key which will replace in dictionary :param old_key: existing key in dictionary :return: dict object """ dictionary[new_key] = dictionary.pop(old_key) return dictionary
def _get_ftype_from_filename(fn, ext_unit_dict=None): """ Returns the boundary flowtype and filetype for a given ModflowFlwob package filename. Parameters ---------- fn : str The filename to be parsed. ext_unit_dict : dictionary, optional If the arrays in the file are specified using EXTERNAL, or older style array control records, then `f` should be a file handle. In this case ext_unit_dict is required, which can be constructed using the function :class:`flopy.utils.mfreadnam.parsenamefile`. Returns ------- flowtype : str Corresponds to the type of the head-dependent boundary package for which observations are desired (e.g. "CHD", "GHB", "DRN", or "RIV"). ftype : str Corresponds to the observation file type (e.g. "CHOB", "GBOB", "DROB", or "RVOB"). """ ftype = None # determine filetype from filename using ext_unit_dict if ext_unit_dict is not None: for key, value in ext_unit_dict.items(): if value.filename == fn: ftype = value.filetype break # else, try to infer filetype from filename extension else: ext = fn.split(".")[-1].lower() if "ch" in ext.lower(): ftype = "CHOB" elif "gb" in ext.lower(): ftype = "GBOB" elif "dr" in ext.lower(): ftype = "DROB" elif "rv" in ext.lower(): ftype = "RVOB" msg = f"ModflowFlwob: filetype cannot be inferred from file name {fn}" if ftype is None: raise AssertionError(msg) flowtype_dict = { "CHOB": "CHD", "GOBO": "GHB", "DROB": "DRN", "RVOB": "RIV", } flowtype = flowtype_dict[ftype] return flowtype, ftype
def bolditalics(msg: str): """Format to bold italics markdown text""" return f'***{msg}***'
def haskeys(d, *keys): """Returns True if all keys are present in a nested dict `d`.""" if len(keys) == 1: return keys[0] in d first = keys[0] if first in d and isinstance(d[first], dict): return haskeys(d[first], *keys[1:]) return False
def uintToXaya (value): """ Converts a hex literal for an uint256 from Ethereum format (with 0x prefix) to the Xaya format without. """ assert value[:2] == "0x" return value[2:]
def filter_invalid_unicode(text): """Return an empty string and True if 'text' is in invalid unicode.""" return ("", True) if isinstance(text, bytes) else (text, False)
def extract_object(input_object): """Chunk of code to extract the inner JSON from objects. Required to reduce unneccessary lines in HUG script & improve maintainability.""" temp_dict = {} for item in input_object: temp_dict[str(item)] = input_object[item] return temp_dict
def bits(num, width): """Convert number into a list of bits.""" return [int(k) for k in f'{num:0{width}b}']
def _ComputeEditDistance(hs, rs): """Compute edit distance between two list of strings. Args: hs: the list of words in the hypothesis sentence rs: the list of words in the reference sentence Returns: edit distance as an integer """ dr, dh = len(rs) + 1, len(hs) + 1 dists = [[]] * dr # initialization for dynamic programming for i in range(dr): dists[i] = [0] * dh for j in range(dh): if i == 0: dists[0][j] = j elif j == 0: dists[i][0] = i # do dynamic programming for i in range(1, dr): for j in range(1, dh): if rs[i - 1] == hs[j - 1]: dists[i][j] = dists[i - 1][j - 1] else: tmp0 = dists[i - 1][j - 1] + 1 tmp1 = dists[i][j - 1] + 1 tmp2 = dists[i - 1][j] + 1 dists[i][j] = min(tmp0, tmp1, tmp2) return dists[-1][-1]
def find_magic_number_brute_force(numbers): """Find magic number using brute force O(n) :param numbers array of sorted unique integers :param magic magic number to be searched for :return index of magic number, else -1 """ for index in range(len(numbers)): if numbers[index] == index: return index return -1
def DiscTag(data): """Extracts the disc number and formats it according to the number of discs in the set, ie, 2 digits if there are 10 or more discs and 1 digit if there are fewer than 10 discs. Input parameter ``data`` is expected to be a ``mutagen.flac.FLAC`` or ``mutagen.flac.VCFLACDict``, however any ``dict``-like interface should work. The values returned from this interface should be a ``list[str]``, or compatible, with the actual data stored at index 0. If the keys "DISCTOTAL" or "DISCNUMBER" are not both present, the empty string is returned.""" if any(x not in data for x in ["DISCTOTAL", "DISCNUMBER"]): return "" if int(data["DISCTOTAL"][0]) < 2: raise RuntimeError("Needs multiple discs") # str(int(y)) such that if y == "01", str(int(y)) == "1", for 2-9 disc sets # str(int(y)) such that if y == "1", str(int(y)) == "01" for 10-99 disc sets def get(key): return str(int(data[key][0])) disclen = len(get("DISCTOTAL")) return f"{get('DISCNUMBER').rjust(disclen, '0')}."
def create_compile_command(file_name): """ Creates the bash command for compiling a JUnit test. Params: file_name (str): The file name of the test to compile. Return: str: The bash command for compiling. """ return f"javac -d classes -cp classes/:junit-jupiter-api-5.7.0.jar:apiguardian-api-1.1.1.jar {file_name}"
def distill_links(F1, F2): """ Obtains the distilled fidelity of two links assuming Werner states :param F1: type float Fidelity of link 1 :param F2: type float Fidelity of link 2 :return: type float Fidelity of the distilled link """ a = F1 * F2 b = (1 - F1) / 3 c = (1 - F2) / 3 return (a + b * c) / (a + F1 * c + F2 * b + 5 * b * c)
def cb_bands(ctx, param, value): """ Click callback for parsing and validating `--bands`. Parameters ---------- ctx : click.Context Ignored. param : click.Parameter Ignored. value : str See the decorator for `--bands`. Returns ------- tuple Band indexes to process. """ if value is None: return value else: return sorted([int(i) for i in value.split(',')])
def pack_variable_length(value, limit=True): """ Encode a positive integer as a variable-length number used in Standard MIDI files. ValueError rasied if value is over 0x0FFFFFFF (=would require >4 bytes). Set limit=False to override this. """ if value < 0: raise ValueError(f"Value is negative: {value}") if limit and value > 0x0FFFFFFF: raise ValueError(f"Value too large: {value}") dest = bytearray() dest.append(value & 0x7F) value >>= 7 while value: dest.append((value & 0x7F) | 0x80) value >>= 7 return bytes(reversed(dest))
def flatten_errors(error): """ Django's ValidationError contains nested ValidationErrors, which each have a list of errors, so we need to flatten them. """ return {k: [item for items in v for item in items] for k, v in error.items()}
def degToRad(deg): """ Convert deg to rad. 5 decimal places output :param: deg(float): degrees :output: rad(float): radians """ # Convert to float if int if type(deg) == int: deg = float(deg) assert type(deg) == float return round(deg * 3.14159265359 / 180, 5)
def search(strings, chars): """Given a sequence of strings and an iterator of chars, return True if any of the strings would be a prefix of ''.join(chars); but only consume chars up to the end of the match.""" if not all(strings): return True tails = strings for ch in chars: tails = [tail[1:] for tail in tails if tail[0] == ch] if not all(tails): return True return False
def list_to_table(list): """Convert a list to a tabulated string""" list_to_table = "" for row in range(len(list)): list_to_table += str(row+2) + "\t" + str(list[row]) + "\n" return list_to_table
def _make_clean_col_info(col_info, col_id=None): """ Fills in missing fields in a col_info object of AddColumn or AddTable user actions. """ is_formula = col_info.get('isFormula', True) ret = { 'isFormula': is_formula, # A formula column should default to type 'Any'. 'type': col_info.get('type', 'Any' if is_formula else 'Text'), 'formula': col_info.get('formula', '') } if col_id: ret['id'] = col_id return ret
def vis_params_rgb(bands=['R', 'G', 'B'], minVal=0, maxVal=3000, gamma=1.4, opacity=None): """ Returns visual parameters for a RGB visualization :param bands: list of RGB bandnames, defaults to ['R', 'G', 'B'] :param minVal: value to map to RGB value 0, defaults to 0 :param maxVal: value to map to RGB8 value 255, defaults to 3000 :param gamma: gamma value, defaults to 1.4 :param opacity: opacity value, defaults to None :return: dictionary containing the parameters for visualization """ params = { 'bands': bands, 'min': minVal, 'max': maxVal, 'gamma': gamma, 'opacity': opacity } return params
def sort(seq): """ Takes a list of integers and sorts them in ascending order. This sorted list is then returned. :param seq: A list of integers :rtype: A list of integers """ for n in range(1, len(seq)): item = seq[n] hole = n while hole > 0 and seq[hole - 1] > item: seq[hole] = seq[hole - 1] hole = hole - 1 seq[hole] = item return seq
def reduce_shape(shape): """ Reduce dimension in shape to 3 if possible """ try: return shape[:3] except TypeError: return shape
def compute_log_pdf_ratio(potential_function, parameter_tm1, parameter_t, x_tm1, x_t): """ return log( \gamma_{t}(x_t) / \gamma_{tm1}(x_{tm1})) arguments potential_function : function potential function (takes args x and parameters) parameter_tm1 : jnp.array() second argument of potential that parameterizes the potential (at previous iteration) parameter_t : jnp.array() second argument of the potential that parameterizes the potential (at the current iteration) x_tm1 : jnp.array(N) positions (or latent variables) at previous iteration x_t : jnp.array(N) positions (or latent variables) at the current iteration returns out : float log( \gamma_{t}(x_t) / \gamma_{tm1}(x_{tm1})) """ return potential_function(x_tm1, parameter_tm1) - potential_function(x_t, parameter_t)
def format_direction(direction): """ Examples -------- >>> format_direction('ra') 'ra' >>> format_direction('el') 'alat' >>> format_direction('az') 'alon' """ lowerdir = direction.lower() if lowerdir == 'el': return 'alat' elif lowerdir == 'az': return 'alon' return direction
def IsUnique(s): """ checks if the characters in the string are unique :param s: string to be compared :type s: str :return: true if the string has unique chars else false :rtype: bool """ s = sorted(s) for i in range(len(s)): if i<len(s)-1 and s[i] == s[i+1]: return False return True
def formatBold(t: str = "", close: bool = True) -> str: """ Applies IRC bold formatting to the provided text (t), optionally resetting formatting at the end of it (True by default). """ reset = '\x0f' return f"\x02{t}{reset if close else ''}"
def show_tags(context, tags): """Show tags""" splits = tags.split(',') for index, tag in enumerate(splits): splits[index] = tag.lstrip() return { 'tags': splits, }
def frequency(variant_obj): """Returns a judgement on the overall frequency of the variant. Combines multiple metrics into a single call. """ most_common_frequency = max(variant_obj.get('thousand_genomes_frequency') or 0, variant_obj.get('exac_frequency') or 0) if most_common_frequency > .05: return 'common' elif most_common_frequency > .01: return 'uncommon' else: return 'rare'
def RGB_TO_HSB(col): """ Converts a 3-tuple with RGB values (in range 0..255) into a 3-tuple with HSB color values in range [0..1]. """ r, g, b = col cmax = float(max(r, g, b)) cmin = float(min(r, g, b)) delta = cmax - cmin brightness = cmax / 255.0 saturation = (delta / cmax) if cmax > 0 else 0 hue = 0 if saturation > 0: redc = (cmax - r) / delta greenc = (cmax - g) / delta bluec = (cmax - b) / delta if r == cmax: hue = bluec - greenc elif g == cmax: hue = 2.0 + redc - bluec else: hue = 4.0 + greenc - redc hue /= 6.0 if hue < 0: hue += 1.0 return (hue, saturation, brightness)
def GetGOFrequencies(gene2go, genes): """count number of each go category in gene list. return a tuple containing: * the total number of GO categories found. * dictionary of counts per GO category * dictionary of genes found with GO categories """ counts = {} total = 0 found_genes = {} for gene_id in genes: if gene_id not in gene2go: continue found_genes[gene_id] = 1 for go in gene2go[gene_id]: if go.mGOId not in counts: counts[go.mGOId] = 0 counts[go.mGOId] += 1 total += 1 return total, counts, found_genes
def ffloat(string): """ In case of fortran digits overflowing and returing ********* this fuction will replace such values with 1e9 """ if 'nan' in string.lower(): return 1e9 try: new_float = float(string) except ValueError: if '*******' in string: new_float = 1e9 else: return None return new_float
def write_lines(file_name, lines): """ Inverse of :read_lines, just do the opposite True if written, False otherwise """ try: with open(file_name, "w") as f: f.writelines("\n".join([line.strip().replace("\n","") for line in lines if line.strip().replace("\n","") != ""])) except Exception: return False return True
def highlight_term(term, s, pattern='<strong>%s</strong>'): """Highlight ``term`` in ``s`` by replacing it using the given ``pattern``. """ term = term.lower() term_len = len(term) i = 0 highlighted = '' while i < len(s): window = s[i:i + term_len] if window.lower() == term: highlighted += pattern % window i += term_len else: highlighted += s[i] i += 1 return highlighted
def rpr(s): """Create a representation of a Unicode string that can be used in both Python 2 and Python 3k, allowing for use of the u() function""" if s is None: return 'None' seen_unicode = False results = [] for cc in s: ccn = ord(cc) if ccn >= 32 and ccn < 127: if cc == "'": # escape single quote results.append('\\') results.append(cc) elif cc == "\\": # escape backslash results.append('\\') results.append(cc) else: results.append(cc) else: seen_unicode = True if ccn <= 0xFFFF: results.append('\\u') results.append("%04x" % ccn) else: # pragma no cover results.append('\\U') results.append("%08x" % ccn) result = "'" + "".join(results) + "'" if seen_unicode: return "u(" + result + ")" else: return result
def escape(text: str, *, mass_mentions: bool = False, formatting: bool = False) -> str: """Get text with all mass mentions or markdown escaped. Parameters ---------- text : str The text to be escaped. mass_mentions : `bool`, optional Set to :code:`True` to escape mass mentions in the text. formatting : `bool`, optional Set to :code:`True` to escpae any markdown formatting in the text. Returns ------- str The escaped text. """ if mass_mentions: text = text.replace("@everyone", "@\u200beveryone") text = text.replace("@here", "@\u200bhere") if formatting: text = ( text.replace("`", "\\`") .replace("*", "\\*") .replace("_", "\\_") .replace("~", "\\~") ) return text
def get_points(result): """get respective points win = 3, lose = 0, draw = 1 point""" if result == 'W': return 3 elif result == 'D': return 1 else: return 0
def initial_policy(observation): """A policy that sticks if the player score is >= 20 and his otherwise Parameters: ----------- observation: Returns: -------- action: 0 or 1 0: STICK 1: HIT """ return 0 if observation[0] >= 20 else 1
def expand(sequence): """ Permute the string """ string = str(sequence) string_length = len(string) return " ".join( [string[idx:string_length] for idx in range(0, string_length)] )
def insert_pad(text, pad_left=True, pad_right=True, pad_symbol=' '): """ Inserts pads to the given text (at the start and at the end) :rtype : string :param text: Text to insert pads to :param pad_left: Whether to insert or not a pad to the left :param pad_right: Whether to insert or not a pad to the left :param pad_symbol: The symbol to insert as pad :return: The text with the corresponding pads """ # validating 'pad_symbol' if pad_symbol is None or len(pad_symbol) != 1: raise Exception('The pad symbol must be a single character') # computing pad_left text pad_left_str = pad_symbol if pad_left else '' # computing pad_right text pad_right_str = pad_symbol if pad_right else '' # returning the string with pads return "%s%s%s" % (pad_left_str, text, pad_right_str)
def pretty_str(label, arr): """ Generates a pretty printed NumPy array with an assignment. Optionally transposes column vectors so they are drawn on one line. Strictly speaking arr can be any time convertible by `str(arr)`, but the output may not be what you want if the type of the variable is not a scalar or an ndarray. Examples -------- >>> pprint('cov', np.array([[4., .1], [.1, 5]])) cov = [[4. 0.1] [0.1 5. ]] >>> print(pretty_str('x', np.array([[1], [2], [3]]))) x = [[1 2 3]].T """ def is_col(a): """ return true if a is a column vector""" try: return a.shape[0] > 1 and a.shape[1] == 1 except (AttributeError, IndexError): return False if label is None: label = '' if label: label += ' = ' if is_col(arr): return label + str(arr.T).replace('\n', '') + '.T' rows = str(arr).split('\n') if not rows: return '' s = label + rows[0] pad = ' ' * len(label) for line in rows[1:]: s = s + '\n' + pad + line return s
def rle(input): """ Format a list as run-length encoding JSON. """ output = [input[0]] for item in input[1:]: if isinstance(output[-1], list) and output[-1][1] == item: output[-1][0] += 1 elif output[-1] == item: output[-1] = [2, item] else: output.append(item) return output
def remove_padding(sentence, pad_idx): """Removes the paddings from a sentence""" try: return sentence[: sentence.index(pad_idx)] except ValueError: return sentence
def opv(d, func, *args): """ Apply func to all values of a dictionary. :param d: A dictionary. :param func: Callable accepting a value of `d` as first parameter. :param args: Additional positional arguments to be passed to `func`. :return: `dict` mapping the keys of `d` to the return value of the function call. """ return {i: func(v, *args) for i, v in d.items()}
def auto_category(name): """ this function helps to choose a category of file automatically :param name: :return: """ name = name.lower() DOCUMENT = ('pdf','doc','docx','ppt','pptx','xls','xlsx','csv','mobi','epub','azw3','txt') ARCHIVE = ('zip','bz2','gzip','tar','gz','7z','rar') MEDIA = ('mp4','gif','jpg','jpeg','png','webp','webm','mov','rmvb','mkv','mp3','flac') EXE = ('sh','exe','dmg','app','appimage','msi','java','js','py','go','html','css','bat') if len(name.split('.')) <= 1: return 'default' else: ext = name.split('.')[-1] if ext in DOCUMENT: return 'document' elif ext in ARCHIVE: return 'archive' elif ext in MEDIA: return 'media' elif ext in EXE: return 'exe/code' else: return 'default'
def normalise_bytes(buffer_object): """Cast the input into array of bytes.""" return memoryview(buffer_object).cast("B")
def get_size_str(grid_width, grid_height, book_size='digest'): """ Get a string that matches the size of a component/composite :param grid_width: :type grid_width: :param grid_height: :type grid_height: :param book_size: :type book_size: :return: :rtype: """ return f"{book_size}_{grid_width}x{grid_height}"
def get_file_name(path): """ :param path: :return: """ parts = path.split("/") return parts[len(parts) - 1]
def i(n,pv,fv,pmt): """Calculate the interest rate of an annuity""" i=0.0000001 a=0 while a <= fv: a = pv*((1+i)**n) + pmt*((1+i)**n-1)/i if a<fv: pass i=i+0.0000001 else: return i # prevent next iteration break
def create_keypair(session, KeyName, DryRun=False): """ Returns dict with SHA-1 digest of the DER encoded private key An unencrypted PEM encoded RSA private key and the name of the key pair. Args: session(Session): boto3.session.Session object KeyName (str): Desired name of the keypair Returns: (dict): """ if session is None: return None client = session.client('ec2') response = client.create_key_pair( KeyName = KeyName, DryRun = DryRun ) return response
def drop_edge_punct(word): """ Remove edge punctuation. :param word: a single string >>> drop_edge_punct("'fieri") 'fieri' >>> drop_edge_punct('sedes.') 'sedes' """ if not word: return word try: if not word[0].isalpha(): word = word[1:] if not word[-1].isalpha(): word = word[:-1] except: pass return word
def _setmovepointer(cells, offset): """Adds given offset to every elements in cells, except for None (normally represents "one or more other cells").""" result = [i + offset for i in cells if i is not None] if None in cells: result.append(None) return set(result)
def all_is_None (phrase): """Returns TRUE if all elements in <phrase> is null""" phrase = [x for x in phrase if not x is None] return phrase == []
def StrReverse(s): """Reverse a string""" lst = list(str(s)) lst.reverse() return "".join(lst)
def _IsDigest(url): """Return true if the given image url is by-digest.""" return '@sha256:' in url
def str_to_bool(value): """ Convert a human readable string into a boolean. """ valuestr = str(value).lower() if valuestr in ['1', 'yes', 'enable', 'true']: return True elif valuestr in ['0', 'no', 'disable', 'false']: return False else: raise Exception("Unable to convert '%s' to boolean" % (repr(value)))
def contains(wordlist, letter): """Return a list of words that contain the correct letter.""" result = [] for word in wordlist: if letter in word: result.append(word) return result
def validate_user_input_to_int(user_input): """ validates user input against type integer & automatically converts and returns the value : user_input --> value entered by user """ try: return int(user_input) except Exception: return "error"
def calc_BMI(w,h): """calculates the BMI Arguments: w {[float]} -- [weight] h {[float]} -- [height] Returns: [float] -- [calculated BMI = w / (h*h)] """ return (w / (h*h))
def get_md5sum(config_file): """ Get MD5SUM_HEADER from config file .aos """ ret = None with open(config_file, "r") as f: for line in f.readlines(): line = line.strip() if "MD5SUM_HEADER" in line: ret = line.replace("MD5SUM_HEADER=", "") return ret
def strictly_decreasing(L): """Return True if list L is strictly decreasing.""" return all(x > y for x, y in zip(L, L[1:]))
def asset_image_aoi(gee_dir): """return the aoi for the reclassify tests available in our test account""" return f"{gee_dir}/reclassify_image_aoi"
def normalize_protocol(raw_protocol): """ A function to normalize protocol names between IOS and NXOS. For example, IOS uses 'C' and NXOS uses 'direct" for connected routes. This function will return 'connected' in both cases. :param raw_protocol: <str> The protocol value found in the route table output :return: A normalized name for that type of route. """ if raw_protocol[0] == 'S' or "static" in raw_protocol: return 'static' elif raw_protocol[0] == 'C' or 'direct' in raw_protocol: return 'connected' elif raw_protocol[0] == 'L' or 'local' in raw_protocol: return 'local' elif raw_protocol[0] == 'D': return 'eigrp' elif raw_protocol[0] == 'O': return 'ospf' elif raw_protocol[0] == 'B': return 'bgp' elif raw_protocol[0] == 'i': return 'isis' elif raw_protocol[0] == 'R': return 'rip' else: return raw_protocol
def is_raid_valid_combination( disks, raid ): """ Should return True if combination is valid and False otherwise. Test row that is passed here can be incomplete. To prevent search for unnecessary items filtering function is executed with found subset of data to validate it. """ # check raid level compatibility with number of drives # [ "raid0", "raid1", "raid5", "raid6", "raid00", "raid10", "raid50", "raid60" ] if raid == "raid0": return True elif raid == "raid1": return disks in ["2", "4", "6", "8"] elif raid == "raid5": return disks in ["3", "4", "5", "6", "7", "8"] elif raid == "raid6": return disks in ["3", "4", "5", "6", "7", "8"] elif raid == "raid00": return disks in ["2", "4", "6", "8"] elif raid == "raid10": return disks in ["4", "8"] elif raid == "raid50": return disks in ["6", "8"] elif raid == "raid60": return disks in ["6", "8"] return True
def b2d(n): """ binary to decimal conversion""" num = 0 nn = list(n) nn.reverse() for j in range(len(nn)): if nn[j]==0: continue num = num+2**j return num
def checkTupleAlmostEqualIn(tup, tupList, place): """ check if a tuple in a list of tuples in which float items only need to be almost equal :type tup: tuple :param tup: tuple to be checked :type tupList: list of tuples :para tupList: list of tuples that tup need to be check with :place: decimal places to round the values to compare """ for T in tupList: length = len(tup) if length != len(T): continue for i in range(length): if type(tup[i]) is float: if round(tup[i], place) != round(T[i], place): break else: if tup[i] != T[i]: break if i == length - 1: return True return False
def update_egress_req_count_metric(mp_endpoint_names): """Update the metrics of the "Egress Request Count (sum)" dashboard widget""" results = [] for mp_name in mp_endpoint_names: endpoints = mp_endpoint_names[mp_name] for endpoint in endpoints: entry = ["AWS/MediaPackage", "EgressRequestCount", "Channel", mp_name, "OriginEndpoint", endpoint] results.append(entry) return results
def checkdeplaid(incidence): """ Given an incidence angle, select the appropriate deplaid method. Parameters ---------- incidence : float incidence angle extracted from the campt results. """ if incidence >= 95 and incidence <= 180: return 'night' elif incidence >=90 and incidence < 95: return 'night' elif incidence >= 85 and incidence < 90: return 'day' elif incidence >= 0 and incidence < 85: return 'day' else: return False