content
stringlengths
42
6.51k
def split_number_and_unit(s): """Parse a string that consists of a integer number and an optional unit. @param s a non-empty string that starts with an int and is followed by some letters @return a triple of the number (as int) and the unit """ if not s: raise ValueError("empty value") s...
def all_positive(entrylist): """True iff all values in the list are positive""" for x in entrylist: if x<0: return False return True
def humansize(nbytes): """ Copied from https://stackoverflow.com/questions/14996453/python-libraries-to-calculate-human-readable-filesize-from-bytes#14996816 """ suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] i = 0 while nbytes >= 1024 and i < len(suffixes)-1: nbytes /= 1024. i +...
def bps_mbps(val: float) -> float: """ Converts bits per second (bps) into megabits per second (mbps). Args: val (float): The value in bits per second to convert. Returns: float: Returns val in megabits per second. Examples: >>> bps_mbps(1000000) 1.0 >>> b...
def busca_sequencial(valor, lista, index): """Busca sequencial recursiva. Returns: Retorna o indice do valor na lista. Se nao encontrar retorna -1. """ if len(lista) == 0 or index == len(lista): return -1 if lista[index] == valor: return index return busca_sequencial(val...
def left_to_right_check(input_line: str, pivot: int): """ Check row-wise visibility from left to right. Return True if number of building from the left-most hint is visible looking to the right, False otherwise. input_line - representing board row. pivot - number on the left-most hint of the in...
def bcdtodec(bcd): """Convert binary coded decimal to decimal""" return ((bcd >> 4) * 10) + (bcd & 0x0F)
def words_not_the(sentence): """Words not 'the' Given a sentence, produce a list of the lengths of each word in the sentence, but only if the word is not 'the'. >>> words_not_the('the quick brown fox jumps over the lazy dog') [5, 5, 3, 5, 4, 4, 3] """ words = sentence.split() lst = [...
def shift(register, feedback, output): """GPS Shift Register :param list feedback: which positions to use as feedback (1 indexed) :param list output: which positions are output (1 indexed) :returns output of shift register: """ # calculate output out = [register[i-1] for i in output] ...
def _search(text, font, deleting): """ >>> from fontTools.agl import AGL2UV >>> from defcon import Font >>> font = Font() >>> for glyphName, value in AGL2UV.items(): ... _ = font.newGlyph(glyphName) ... font[glyphName].unicodes = [value] ... _ = font.newGlyph(glyphName + ".al...
def first_rule(board: list) -> bool: """ Function checks whether the colored cells of each line contain numbers from 1 to 9 without repetition. Returns True if this rule of the game is followed. >>> first_rule(["**** ****","***1 ****","** 3****","* 4 1****",\ " 9 5 "," 6 83 *","3 1 **"...
def sizeof_fmt(num): """ Handy formatting for human readable filesize. From http://stackoverflow.com/a/1094933/1657047 """ for x in ["bytes", "KB", "MB", "GB"]: if num < 1024.0 and num > -1024.0: return "%3.1f %s" % (num, x) num /= 1024.0 return "%3.1f %s" % (num, "T...
def auto_none_days(days, points): """Autoincrement don't works days yet with None.""" return points + [None for _ in range(len(days) - len(points))]
def combo_cross_breeding( parent1: list, parent2: list): """ This function cross breeds the two parents by joinining and combining them ... Attributes ---------- parent1:List features in vectorized form parent2:List features in vectori...
def _make_tester_for_previous(var, expr, context, strong): """Return temporal tester for "previous".""" # select operator if context == 'bool': op = '<=>' # strong "previous" operator "--X" ? if strong: init = '(~ {var})'.format(var=var) else: init = v...
def format_dict(input_dict): """Dict string formatter >>> from collections import OrderedDict >>> from pyams_utils.dict import format_dict >>> input = {} >>> format_dict(input) '{}' >>> input = OrderedDict((('key1', 'Value 1'), ('key2', 'Value 2'),)) >>> print(format_dict(input)) { ...
def perfect_unshuffle(seq): """Returns a list containing the perfectly unshuffled supplied sequence SEQ, if previously perfectly shuffled. """ return seq[::2] + seq[1::2]
def check_filters(filters): """Checks that the filters are valid :param filters: A string of filters :returns: Nothing, but can modify ``filters`` in place, and raises ``ValueError``s if the filters are badly formatted. This functions conducts minimal parsing, to make sure that the relationship exist...
def get_text_list(list_, last_word='or'): """ >> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >> get_text_list(['a', 'b'], 'and') 'a and b' >> get_text_list(['a']) 'a' >> get_text_list([]) '' """ if len(list_...
def split_variable_name(name): """Extracts layer name and variable name from the full variable scope.""" parts = name.split('/') return parts[-2], parts[-1]
def get_band_height(element): """ Return height the the specified element. :param element: current jrxml element being processes. :return: """ return float(element['child'][0]['band']['attr']['height'])
def match2(g1, s, guesses_number, ans): """ The second and subsequence letters, user inputted, matched with the answer or not. """ answer1 = "" if g1 in s: print("You are correct!") for k in range(len(s)): ch3 = s[k] ch4 = ans[k] if ch3 == g1: ...
def PatternCount(Text, Pattern): """Count the input patern in the text.""" Text = str(Text) Pattern = str(Pattern) count = 0 for i in range(len(Text) - len(Pattern) + 1): if Text.find(Pattern, i, i + len(Pattern)) != -1: count = count + 1 return count
def lexical_distance(a, b): """ Computes the lexical distance between strings A and B. The "distance" between two strings is given by counting the minimum number of edits needed to transform string A into string B. An edit can be an insertion, deletion, or substitution of a single character, or ...
def scaled(signal, factor): """" scale the signal scaling factor limit 0.2 - 2 """ scaled_signal = signal * factor return scaled_signal
def check_sw_status_admin(supported_nodes, output): """Check if a node is in OPERATIONAL status""" lines = output.splitlines() for line in lines: line = line.strip() if len(line) > 0 and line[0].isdigit(): node = line[0:10].strip() if node in supported_nodes: ...
def convert_bytes(fileSize): """ utility function to convert bytes into higher size units. Arguments: 1. fileSize: Size of the file in bytes Result: Returns size of file in ['bytes', 'KB', 'MB', 'GB', 'TB'] """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if fileSize < 1024...
def frange(a, b, n): """ kind of like a floating point range function :param a: the start point :param b: the end point :param n: the number of intervals you want. :returns: a sequence of floating point nubers, evenly spaced between a and b result[0] == a result[-1] == b len(r...
def selectdeclevel(freq): """ Calculate an appropriate SHD order for the given frequency :param freq: Frequency (in Hz) :return: Decomposition order Note: This is not used since we are looking at frequencies above 2607 Hz only. Hence Nmax=4 is used """ if freq < 652.0: Ndec = 1 ...
def _dictionary_product(dictionary): """Returns a named cartesian product of dictionary's values.""" # Converts {'a': [1, 2], 'b': [3, 4]} into # [{'a': 1, 'b': 3}, {'a': 1, 'b': 4}, {'a': 2, 'b': 3}, {'a': 2, 'b': 4}] product = [[]] for values in dictionary.values(): # Iteratively grow the...
def io_serdes(serial_in_p, serial_in_n, serial_out_p, serial_out_n): """ Vendor specific IO SERDES """ mod_insts = [] return mod_insts
def calc_metric(y_true, y_pred): """ :param y_true: [(tuple), ...] :param y_pred: [(tuple), ...] :return: """ num_proposed = len(y_pred) num_gold = len(y_true) y_true_set = set(y_true) num_correct = 0 for item in y_pred: if item in y_true_set: num_correct += 1...
def check_new_items(db_info, api_info): """ Find the number of new items on the API """ new_items = [] for item in api_info['data']: if not any(d['case_id'] == item['id'] for d in db_info): new_items.append(item) return new_items
def filterResultsByRunsetFolder(runSets, form): """ Filters out results that don't have the specified runsetFolder name """ ret = [] for runset in runSets: if runset.runsetFolder == form['runset'].value: ret.append(runset) return ret
def get_bitcode(edge_array, distinct_edge): """ Return bitcode of distinct_edge """ bitcode = ["0"] * len(edge_array) for i, row in enumerate(edge_array): for item in row: if distinct_edge in item[0]: bitcode[i] = "1" break return ""....
def onefunction(a, b): """ Return the addition of ``a+b``. Second line should be aligned. :param a: first element :param c: second element :return: ``a + b`` :raises TypeError: guess """ if type(a) != type(b): raise TypeError("Different type {0} != {1}".format(a, b)) ret...
def b(u, dfs_data): """The b(u) function used in the paper.""" return dfs_data['b_u_lookup'][u]
def get_abyss_rank_mi18n(rank: int, tier: int) -> str: """Turn the rank returned by the API into the respective rank name displayed in-game.""" if tier == 4: mod = ("1", "2_1", "2_2", "2_3", "3_1", "3_2", "3_3", "4", "5")[rank - 1] else: mod = str(rank) return f"bbs/level{mod}"
def single_char_xor(input_bytes, char_value): """Returns the result of each byte being XOR'd with a single value. """ output_bytes = b'' for byte in input_bytes: output_bytes += bytes([byte ^ char_value]) return output_bytes
def file_text(txt_or_fname: str) -> str: """ Determine whether text_or_fname is a file name or a string and, if a file name, read it :param text_or_fname: :return: """ if len(txt_or_fname) > 4 and '\n' not in txt_or_fname: with open(txt_or_fname) as ef: return ef.read() r...
def _tpu_version(index): """Chooses a GCP TPU version based on the index.""" if index < 100: return 'v2-alpha', 'v2-8' # version, accelerator-type else: return 'v2-alpha', 'v3-8'
def _hashable(x): """ Ensure that an point is hashable by a python dict. """ return tuple(map(float, x))
def cubic_ease_in(p): """Modeled after the cubic y = x^3""" return p * p * p
def prepare_target(x): """ Encode the OS into 3 categories """ if x <= 24: return 0 elif x <= 72: return 1 else: return 2
def _apply_inputs(config, inputs_map): """Update configuration with inputs This method updates the values of the configuration parameters using values from the inputs map. """ config.update(inputs_map) return config
def detect(source): """Detects if source is likely to be eval() packed.""" return source.strip().lower().startswith('eval(function(')
def get_vf_res_scale_down(width: int, height: int, res_limit='FHD', vf: str = '') -> str: """generate 'scale=<w>:<h>' value for ffmpeg `vf` option, to scale down the given resolution return empty str if the given resolution is enough low thus scaling is not needed""" d = {'FHD': (1920, 1080), 'HD': (1280, 7...
def failed(response): """DreamHost does not use HTTP status codes to indicate success or failure, relying instead on a 'result' key in the response.""" try: if response['result'] == u'success': return False except: pass return True
def process_coin(amt, moneyIn): """Returns the amount of each coin""" if moneyIn == 'quarter' or moneyIn == 'quarters': return amt * .25 elif moneyIn == 'dime' or moneyIn == 'dimes': return amt * .10 elif moneyIn == 'nickel' or moneyIn == 'nickels': return amt * .05 elif moneyIn == 'pen...
def getKfactorsFrom(output): """ Read NLLfast output and return the k-factors. """ if not output: return False else: lines = output.split('\n') il = 0 line = lines[il] process = False while not "K_NLO" in line and il < len(lines) - 2: ...
def aggregation(item1, item2): """ For an (airport, counters) item, perform summary aggregations. """ count1, total1, squares1, min1, max1 = item1 count2, total2, squares2, min2, max2 = item2 minimum = min((min1, min2)) maximum = max((max1, max2)) count = count1 + count2 total =...
def template_substitute(text, **kwargs): """ Replace placeholders in text by using the data mapping. Other placeholders that is not represented by data is left untouched. :param text: Text to search and replace placeholders. :param data: Data mapping/dict for placeholder key and values. :re...
def len_selfies(selfies: str) -> int: """Returns the number of symbols in a given SELFIES string. :param selfies: a SELFIES string. :return: the symbol length of the SELFIES string. :Example: >>> import selfies as sf >>> sf.len_selfies("[C][=C][F].[C]") 5 """ return selfies.count...
def update_deviation(player_ratings, deviation_factors=None): """ :param player_ratings: The previous rating period's data. The key must be hashable and uniquely identify a player. The dictionary and its values are not modified by this function. :type player_ratings: dict[Any, Rating] ...
def get_atom_list(line): """ splits the number from the atom a\\a o1 c2 c3 c4 o5 h6 h7 h8 h9 -> [O, C, C, C, O, H, H, H, H] """ line = line.split()[1:] atoms = [] for a in line: atom = '' num = '' for b in a: if b.isdigit(): ...
def strip_special_characters(some_string): """Remove all special characters, punctuation, and spaces from a string""" # Input: "Special $#! characters spaces 888323" # Output: 'Specialcharactersspaces888323' result = ''.join(e for e in some_string if e.isalnum()) return result
def attributify(numeral: str) -> str: """Returns the numeral string argument as a valid attribute name.""" return numeral.replace(" ", "").replace("-", "")
def parseBool(value): """ Parse a boolean, which in FIX is either a single 'Y' or 'N'. :param value: the tag value (should be 1 character) :return: bool """ if value == 'Y': return True elif value == 'N': return False else: raise ValueError('FIX boolean values must be Y or N (got %s)' % value)
def gcd(m, n): """(int, int) -> int Uses Euclid's method to compute the greatest common factor (greatest common divisor) of two integers, <m> and <n> Returns greatest common factor (gcd) of the two integers """ if n == 0: result = m else: result = gcd(n, m % n) ...
def p_to_r(p, d, rtype='EI'): """ Converts an RB decay constant (`p`) to the RB error rate (`r`). Here `p` is (normally) obtained from fitting data to `A + Bp^m`. There are two 'types' of RB error rate corresponding to different rescalings of `1 - p`. These are the entanglement infidelity (EI) typ...
def _InvokeMember(obj, membername, *args, **kwargs): """Retrieves a member of an object, then calls it with the provided arguments. Args: obj: The object to operate on. membername: The name of the member to retrieve from ojb. *args: Positional arguments to pass to the method. **kwargs: Keyword argu...
def dict_to_item_list(table): """Given a Python dictionary, convert to sorted item list. Parameters ---------- table : dict[str, any] a Python dictionary where the keys are strings. Returns ------- assoc_list : list[(str, str)] the sorted item list representation of the giv...
def get_distributive_name() -> str: """Try to obtain distributive name from /etc/lsb-release""" try: with open('/etc/lsb-release', mode='r', encoding='utf-8') as file: for line in file: if line.startswith('DISTRIB_ID'): parts = line.split('=') ...
def next_power_of_two(x): """"Next Largest Power of 2 Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with the same most significant 1 as x, but all 1's below...
def get_num_processes(profileDict): """ Returns the number of processes used in the given profile Args: profileDict (dict): Dictionary of the JSON format of a MAP profile Returns: Number of processes used in the profile passed in """ assert isinstance(profileDict, dict) re...
def reduce_nums(val_1, val_2, val_op): """ Apply arithmetic rules to compute a result :param val1: input parameter :type val1: int or string :param val2: input parameter :type val2: int or string :param val_op: C operator in *+*, */*, *-*, etc :type val_op: string :rtype: int """ #print val_1, val_2, val_op...
def helper(n, best): """ :param n: int, the number we need to find the the biggest digit. :param best: int, currently biggest digit. :return: int, the biggest digit. """ if n < 0: # if the number is negative number, change it to positive. n = -n if n < 10: if best != 0: return best else: return n #...
def squared_error(label, prediction): """Calculates the squared error for a single prediction.""" return float((label - prediction)**2)
def get_latitude_and_longitude_list(all_places): """Return list of dictionaries containing latitude and longitude of all places""" places_list = [] for place in all_places: temp_dict = {} temp_dict['latitude'] = float(place.latitude) temp_dict['longitude'] = float(place.longitude) ...
def vol_cone(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * area_of_base * height >>> vol_cone(10, 3) 10.0 >>> vol_cone(1, 1) 0.3333333333333333 """ return are...
def xss_strip_all_tags(s): """ Strips out all HTML. """ return s def fixup(m): text = m.group(0) if text[:1] == "<": return "" # ignore tags if text[:2] == "&#": try: if text[:3] == "&#x": return unichr(int(text[3:-1...
def calc_tnr(tn: float, fp: float) -> float: """ :param tn: true negative or correct rejection :param fp: false positive or false alarm :return: true negative rate """ try: calc = tn / (tn + fp) except ZeroDivisionError: calc = 0 return calc
def hex_to_rgb(h): """Converts a "#rrbbgg" string to a (red, green, blue) tuple. Args: h: a hex string Returns: an R, G, B tuple """ h = h.lstrip("#") return tuple(int(h[i : i + 2], 16) for i in (0, 2, 4))
def mag_to_flux(mag, mag_zp): """ Returns total flux of the integrated profile, units relative to mag_zp """ return 10 ** (-0.4 * (mag - mag_zp))
def is_eof(data): """check for eof indication in data""" return data[0] == 254
def decode_pdb_address(addr, aliases=[]): """Decodes Ax-By-z or x/y/z into PDB address, bank number, and output number. Raises a ValueError exception if it is not a PDB address, otherwise returns a tuple of (addr, bank, number). """ for alias in aliases: if alias.matches(addr): ...
def comma_formatter(x, pos): """Return tick label for Indian-style comma delimited numbers.""" x = str(int(x)) result = x[-3:] i = len(x) - 3 while i > 0: i -= 2 j = i + 2 if i < 0: i = 0 result = x[i:j] + ',' + result return result
def fibonacci(n): """Find nth fibonacci number using recursive algorithm. input: n (int) n for nth fibonacci number returns: (int) representing value of nth fib number """ if n <= 1: return n else: return fibonacci(n - 1) + fibonacci(n - 2)
def num_atoms_in_shell(shell: int) -> int: """Calculates number of atoms in a magic number NP shell - icosahedron shells - cuboctahedron shells - elongated-pentagonal-bipyramid shells """ if shell == 0: return 1 return 10 * (shell + 1) * (shell - 1) + 12
def _req_input_to_args(req_input): """ Given a list of the required inputs for the build command, create an args string :param list[str] req_input: input names :return str: args string """ return ["--" + x + " <arg_here>" for x in req_input]
def remove_non_class_entries(entries): """ Removes entries that do not end with `.class`. :param entries: dict of zip file entry name to the list of entry names inside that nested zip file :return: entries without files that do not end with `.class` """ new_entries = {} for entry...
def filter_data(lines): """ Filter out lines that are too short or too long. """ return [line for line in lines if len(line) >= 8 and len(line) <= 60]
def find_str(find_exp, where): """find_exp is present in buffer where""" for item in where: if find_exp in str(item): return True return False
def check_parens(str): """ check_parens takes a string and: returns 0 if the number of parentheses is balanced and matched. returns 1 if more left parentheses than right. returns -1 if string has broken (unmatched) parentheses. """ counter = 0 for i in range(len(str)): # if loop...
def check_special_characters(string): """ Check if string has the target special character. Return True if unwanted character is in the string. """ check = ["[", "@", "_", "!", "#", "$", "%", "^", "&", "*", "(", ")", "<", ">", "?", "/", "\\", "|", "}", "{", "~", ":", "]", "'"] retu...
def validateFilenameGmv(value): """ Validate filename. """ if 0 == len(value): raise ValueError("Filename for LaGriT input mesh not specified.") return value
def remove_punctuation(string: str) -> str: """ Removes all non-letter, non-space characters from a string :param string: a string :return: a string containing only letters and spaces """ return ''.join([c for c in string if c.isalpha() or c.isspace()])
def get_primary_registry_uid(service_uid): """Return the primary registry uid of the service with passed service_uid. """ try: root = service_uid.split("-")[0] return "%s-%s" % (root, root) except: return "a0-a0"
def f_to_t(f: float) -> float: """ Convertrs frequency to time. :param f: Frequency in uHz :return: Time in seconds """ return 10 ** 6 / f
def is_empty(value): """ """ if value is None: return True return value in ['', [], {}]
def replace_all(buffer, replacements): """Substitute multiple replacement values into a buffer. Replacements is a list of (start, end, value) triples. """ result = bytearray() prev = 0 offset = 0 for u, v, r in replacements: result.extend(buffer[prev:u]) result.extend(r) ...
def in_bounds(x, y, margin, maxx, maxy): """Returns True if (x,y) is within the rectangle (margin,margin,maxx-margin,maxy-margin).""" return margin <= x < (maxx - margin) and margin <= y < (maxy - margin)
def rotate_inplace(matrix): """Performs the same task as above, in constant space complexity. :type matrix: List[List[int]] :rtype: None """ # useful constants NUM_ROWS, NUM_COLS = len(matrix), len(matrix[0]) # A: Reverse the rows in the Matrix row_index_start, row_index_end = 0, NUM_R...
def OR(condition_1, condition_2): """Evaluates both conditions and returns True or False depending on how both conditions are evaluated. Parameters ---------- condition_1 : condition that evaluates to True or False condition that will return True or False condition_2 : condition that evalu...
def gen_include_exclude_sets(include_filename, exclude_filename): """ generate an include and an exclude set of indicators by reading indicators from a flat, newline-delimited file """ include = set() exclude = set() if include_filename: for indicator in open(include_filename).readl...
def shared_length(a, *args) -> int: """ Returns the shared length between arguments if the length identical. >>> shared_length([1,1,1], [2,2,2], [3,3,3]) 3 >>> shared_length(np.array([1]), np.array([2])) 1 >>> shared_length((1, 1), [2, 2]) 2 >>> shared_length((1, 1), (2, 2)) 2 ...
def find_factors(n): """ Finds a list of factors of a number """ factList = {1, n} for i in range(2, int(n ** 0.5) + 1): if (n % i == 0): factList.add(i) factList.add(n // i) return sorted(factList)
def f2x(x): """function is only used for testing purposes""" return( 2*x )
def canonical_message_builder(content, fmt): """Builds the canonical message to be verified. Sorts the fields as a requirement from AWS Args: content (dict): Parsed body of the response fmt (list): List of the fields that need to go into the message Returns (str): canonical mes...
def any_key_from_list_in_dict(test_list, test_dict): """ Takes a list and a dictionary and checks if any of the keys from the list are present in the dict. Raises a KeyError with the key if found, returns False otherwise. """ for key in test_list: if key in test_dict: raise KeyError(key) return False