content
stringlengths
42
6.51k
def brl_converter(string): """Convert a BRL price (R$ XXX.XXX,XX) to a float.""" return float(string.strip("R$ ").replace('.', '').replace(',', '.'))
def clicked_watchtime_reward(responses): """Calculates the total clicked watchtime from a list of responses. Args: responses: A list of IEvResponse objects Returns: reward: A float representing the total watch time from the responses """ reward = 0.0 for response in responses: if response.clic...
def rgb_hex(color): """this function converts a color in rgb to hex format and vice versa""" color_conversions = { '#4286f4': 'rgb(66, 134, 244)', '#5905c6': 'rgb(89, 5, 198)', '#fce702': 'rgb(252, 231, 2)', '#ffffff': 'rgb(255, 255, 255)', '#000000': 'rgb(0, 0, 0)', '#0ac913': 'rgb(10, 201, 19)', '#65c672': ...
def lower(text: str, *args, **kwargs) -> str: """Return text in lowercase style. This is a convenience function wrapping inbuilt lower(). It features the same signature as other conversion functions. Note: Acronyms are not being honored. Args: text (str): Input string to be converted ...
def fhir_field_value_serializer(value): """ """ if value: value = value.as_json() else: value = None return value
def flatten(v, attr=None): """ Flattens value """ if attr is not None: if isinstance(v,dict) and attr in v: v[attr] = flatten(v[attr]) return if isinstance(v, (list, tuple, set)) and len(v) == 1: return list(v)[0] else: return v
def split_pages(pattern, data): """ This test splits the data by the <page> tag. """ return len(pattern.split(data))
def _sanity_check_margs(margs): """ Sanity check for the margs, returns number of entries in margs as n_dim """ try: _ = iter(margs) except: err_msg = "margs must be an iterable with each entry " err_msg += "corresponding a marginal distribution of an " err_msg += "in...
def mat_idx_to_triu_fast(row, col, n): """mat_idx_to_triu_fast(row, col, n) Convert two-dimensional index to linear index of upper triangle. This is the fast implementation, which does not check the order of row and col. :param int row: Matrix row index. :param int col: Matrix column index. Must be greater tha...
def float_sum(iterable): """ Sum the elements of the iterable, and return the result as a float. """ return float(sum(iterable))
def format_header_line(key, value, as_strings=False): """ Format key, value pair as an 80 character RAW header line. Parameters ---------- key : str Header key value : str or int or float Header value as_strings : bool If values are already formatted strings, pas...
def cdf(weights): """ Cummulative density function. Used to convert topic weights into probabilities. Args: weights (list): An array of floats corresponding to weights """ total = sum(weights) result = [] cumsum = 0 for w in weights: cumsum += w result.append(cumsum / total) return result
def normalize_strides( strides ): """Normalize strides of the same format. Args: strides: An integer or pair of integers. Returns: A pair of integers. Raises: ValueError: Input strides is neither an integer nor a pair of integers. """ if isinstance(strides, (list, tuple)) and len(strides)...
def validipport(port): """ Returns True if `port` is a valid IPv4 port. >>> validipport('9000') True >>> validipport('foo') False >>> validipport('1000000') False """ try: if not (0 <= int(port) <= 65535): return False except Value...
def __convert_frequency_dict_to_rates(freq_dict): """ Converts a Frequency Dictionary to a Probability Dictionary :param dict freq_dict: Dictionary of Frequencies of Occurrence :return: Dictionary of Probabilities/Rates of Occurrence :rtype: dict """ n_tot = sum(freq_dict.values()) for k ...
def _create_mix_addr_query( address_names, node_max_num, level=0, node_name="a", param_name="biggestword", is_show_tabs=False): """Create a part of the query for finding address objects. """ if (not any(address_names) or (node_max_num - level) > le...
def check_board(board): """ This function is to check whether whole board is checked :param board:(dict) a dictionary to store boggle information :return :(bool) if all elements in board are checked """ for key in board: if not board[key]['checked']: return False return True
def _filetype_cor(file_types): """ This functions changes the file types needed for glob: ['**/*.md'] to ['*.md'] """ new_type = [] for filetype in file_types: new_type.append(filetype.replace('**/', '')) return new_type
def prep_condiments(condiments): """Here the caller passes a mutable object, so we mess with it directly.""" try: del condiments["steak sauce"] except KeyError: pass condiments["spam sauce"] = 42 return "Now this is what I call a condiments tray!"
def num_to_emoji(num:int): """ Retrieve emoji related to a number Parameters ---------- num: int number Returns ------- str emoji that represent a number """ number = { 0: ':zero:', 1: ':one:', 2: ':two:', ...
def funcparser_callable_space(*args, **kwarg): """ Usage: $space(43) Insert a length of space. """ if not args: return '' try: width = int(args[0]) except TypeError: width = 1 return " " * width
def intersection(list1, list2): """ Compute and return the elements common to list1 and list2. `list1` and `list2` can be sets, lists, or pandas.Series. """ return list(set(list1).intersection(set(list2)))
def sum_sector_ids(rooms): """Sum sector IDs.""" return sum(id for id, name, checksum in rooms)
def layer_type_qa(flags): """ Returns the quality flag for the layer type, as identified from the feature classification flag """ return (flags & 24) >> 3
def bag_of_words(text): """Returns bag-of-words representation of the input text. Args: text: A string containing the text. Returns: A dictionary of strings to integers. """ bag = {} for word in text.lower().split(): bag[word] = bag.get(word, 0) + 1 return bag
def _bits_to_float(bits, lower=-90.0, middle=0.0, upper=90.0): """Convert GeoHash bits to a float.""" for i in bits: if i: lower = middle else: upper = middle middle = (upper + lower) / 2 return middle
def startswith(value, term): """returns value.startswith(term) result""" return value.startswith(term)
def dbspl_to_pa(dbspl, ref=20e-6): """ Convert dBSPL to Pascals (rms). By default, the reference pressure is 20 uPa. """ return ref * 10**(dbspl / 20.0)
def quote(s): """Surround with quotes for YAML.""" return f'"{s}"'
def feincms_page_title(context, request, path_fragment, is_current_page): """ Set the crumb name to the title of the current FeinCMS page, if one is available in the current context. """ # We only want to set the crumb title for the current page if not is_current_page: return None # ...
def factory_decorated_function(specific_arg, specific_kwarg=True): """I should see this factory docstring""" # do stuff return 'computed value'
def remove_suffix(files, suffix): """Remove suffix from files.""" return [f[:-len(suffix)] for f in files]
def bubble_sort(array): """My bubble sort implementation""" swapped = True while swapped: swapped = False for idx in range(len(array) - 1): if array[idx] > array[idx + 1]: swapped = True array[idx + 1], array[idx] = array[idx], array[idx + 1] r...
def get_where_column(conds): """ [ [where_column, where_operator, where_value], [where_column, where_operator, where_value], ... ] """ where_column = [] for cond in conds: where_column.append(cond[0]) return where_column
def _sanitize(header_tuple): """Sanitize request headers. Remove authentication `Bearer` token. """ header, value = header_tuple if (header.lower().strip() == "Authorization".lower().strip() and "Bearer".lower().strip() in value.lower().strip()): return header, "Bearer <redacte...
def roman_numeral(n: int) -> str: """Returns the Roman numeral representation of an integer. >>> roman_numeral(476) 'CDLXXVI' >>> roman_numeral(778) 'DCCLXXVIII' >>> roman_numeral(1229) 'MCCXXIX' >>> roman_numeral(1453) 'MCDLIII' >>> roman_numeral(1492) 'MCDXCII' >>> rom...
def build_person(first_name, last_name, age=None): """Return a dictionary, including the information of one person""" person = {'first': first_name, 'last': last_name} if age: person['age'] = age return person
def total_zones(endpoints: list) -> int: """ Returns the true unique number of zones, taking into account that multiple endpoints can have the same zone name. - us-west-1 - us-west-1 == 2 zones - us-east-1 - us-west-1 - us-west-2 == 3 zones - us-east-2 """ zones = {e['l...
def to_bytes(text, encoding=None, errors='strict'): """Return the binary representation of `text`. If `text` is already a bytes object, return it as-is.""" if isinstance(text, bytes): return text if not isinstance(text, str): raise TypeError('to_bytes must receive a unicode, str or bytes...
def getIndexPositions(listOfElements, item): """ Returns the indexes of all occurrences of give element in the list- listOfElements """ indexPosList = [] for index in range(0, len(listOfElements)): if listOfElements[index] == item: indexPosList.insert(len(indexPosList), index) re...
def __filename_to_index(filename, dictionary): """ Checks whether any dictionary key is in filename, and if so, returns the key. Raises an error if not exactly 1 key is present in filename. :param filename: String to check presence of keys. :param dictionary: Dict mapping strings to integer values. :return index...
def _idFromHeaderInfo(headerInfo, isDecoy, decoyTag): """Generates a protein id from headerInfo. If "isDecoy" is True, the "decoyTag" is added to beginning of the generated protein id. :param headerInfo: dict, must contain a key "id" :param isDecoy: bool, determines if the "decoyTag" is added or not. ...
def contfrac_rat(numer, denom): """ Returns the continued fraction of the rational number numer/denom. Input: numer -- an integer denom -- a positive integer coprime to num Output list -- the continued fraction [a0, a1, ..., am] of the rational number num/den...
def build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None): """build menu with given buttons""" menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)] if header_buttons: menu.insert(0, header_buttons) if footer_buttons: menu.append(footer_buttons) retur...
def get_frame_durations(sentences, timestamps): """Given a list of sentences and timestamps of all words, return timestamps of each sentence Args: sentences (list): List of sentences timestamps (list): [ [<word_string>, <start_time_float>, <end_time_float>], ... ...
def _split(f, s, a_p='', a_s='', b_p='', b_s='', reverse=False): """Split string on a symbol and return two string, first possible empty""" splitted = f.split(s) if len(splitted) == 1: a, b = '', splitted[0] if reverse: b, a = a, b else: a, b = splitted if a: ...
def hill_eq(hill_constants, x): """ Four parameter sigmoidal Hill equation. y = upper + (lower-upper)/(1+(x/EC50)**-hillslope) Parameters ---------- hill_constants : tuple Tuple of the four parameters : upper, lower, EC50 and hillslope x : float x-value for use in the equation ...
def uniqueify(items): """Return a list of the unique items in the given iterable. Order is NOT preserved. """ return list(set(items))
def create_dict_sim_artists_top_tracks_duration(sa_list, t_tracks, dur_list): """ Create a dictionary of similar artists, top tracks and track duration """ master = {} for i in range(len(sa_list)): if sa_list[i] in master: master[sa_list[i]].extend([t_tracks[i], dur_list[i]]) e...
def quantize(x): """Quantizes a byte into one of 8 equally-spaced values. """ top = x & (7 << 5) return top | top >> 3 | top >> 6
def nested_sort(obj): """ Sort a dict/list and all it's values recursively """ if isinstance(obj, dict): return sorted((k, nested_sort(v)) for k, v in obj.items()) if isinstance(obj, list): return sorted(nested_sort(x) for x in obj) else: return obj
def gen_arg_name(name: str) -> str: """ adds double dashes as prefix name -> --name -name -> --name """ return "--" + "-".join(i for i in name.split('-') if i)
def _get_item(dic: dict, keys: list) -> dict: """Get a value from a dict given the path of keys.""" for key in keys: dic = dic[key] return dic
def format_tweet_msg(section, title, url, description): """Format a tweet combining the title, description and URL. It ensures the total size does not exceed the tweet max characters limit. And it also replaces common words in the description to use hashtags. """ # First let's introduce hashtags to...
def scale_unit_to_bounds(seq, bounds): """ Scales all elements in seq (unit hypercube) to the box constraints in bounds. :param seq: the sequence in the unit hypercube to scale :type seq: iterable :param bounds: bounds to scale to :type seq: iterable of [lb, ub] pairs :returns: a list of sc...
def _min_max(a, b): """Helper for @range_for_expression.""" return (min(a[0], b[0]), max(a[1], b[1]))
def role(value): """Display publisher role/capacity""" return { 'E ': 'Original Publisher', 'AM': 'Administrator', 'SE': 'Sub-publisher' }.get(value, 'Unknown publisher role')
def shuf_key(shuf): """ return an index to sort shuffles in this order. """ return ["none", "edge", "be04", "be08", "be16", "smsh", "dist", "agno", ].index(shuf)
def wrap_functional_unit(dct): """Transform functional units for effective logging. Turns ``Activity`` objects into their keys.""" data = [] for key, amount in dct.items(): if isinstance(key, int): data.append({"id": key, "amount": amount}) else: try: ...
def manhattan_distance(pts): """ distance between two points measured along axes at right angles return manhattan distance between two lists """ if len(pts) <= 1: return 0 return sum(abs(a-b) for a,b in pts)
def has_balanced_parens(exp: str) -> bool: """ Checks if the parentheses in the given expression `exp` are balanced, that is, if each opening parenthesis is matched by a corresponding closing parenthesis. **Example:** :: >>> has_balanced_parens("(((a * b) + c)") False :par...
def get_header(headers, name, default=None): """Return the value of header *name*. The *headers* argument must be a list of ``(name, value)`` tuples. If the header is found its associated value is returned, otherwise *default* is returned. Header names are matched case insensitively. """ name =...
def check_isinstance(item, clazzes, msg=None): """ >>> check_isinstance(1, int) True >>> check_isinstance(1.1, (int, float)) True >>> check_isinstance(1.1, [int, float]) Traceback (most recent call last): ... TypeError: isinstance() arg 2 must be a type or tuple of types >>> ...
def cross(a, b): """Cross Product function Given vectors a and b, calculate the cross product. Parameters ---------- a : list First 3D vector. b : list Second 3D vector. Returns ------- c : list The cross product of vector a and vector b. ...
def birch_murnaghan(V, E0, B0, B1, V0): """BirchMurnaghan equation from PRB 70, 224107""" eta = (V/V0)**(1./3.) E = E0 + 9.*B0*V0/16.*(eta**2-1)**2*(6 + B1*(eta**2-1.) - 4.*eta**2) return E
def is_valid_arch(target_arch, os_desc): """ Check that the image's architecture is consistent with the target binary. """ return not (target_arch == 'x86_64' and os_desc['arch'] != 'x86_64')
def restarttime_to_minutes(time): """ converts a restart time from the human readable output to minutes after midnight. -1 means never """ if time == "never" : return -1 minutes = 0 tokens = time.split() if tokens[1] == "pm" : minutes = 12*60 hours, min = tokens[...
def _close_to(values, v_ref): """ returns the index of the value which is close to the v_ref. """ ind = 0 good=values[ind] for i, vv in enumerate(values): if abs(vv - v_ref) < good: good = vv ind = i return ind
def region_observation_probability(state, observation): """ Measurement model for a single Region element for the WestAfrica simulator. Returns a probability of the combination (state, observation). """ measure_correct = 0.85 measure_wrong = 0.5*(1-measure_correct) if state != observation: ...
def xstr(s): """ Replace None with an empty string (for CSV export) """ return '' if s is None else str(s)
def decay_fn(epoch, learning_rate): """ Jorgensen decays to 0.96*lr every 100,000 batches, which is approx every 28 epochs """ if (epoch % 70) == 0: return 0.96 * learning_rate else: return learning_rate
def convertSptype(spT): """ Converts a spectral type into its numerical equivalent, based on Alice Perez's conversion table. INPUT spT: The spectral type. Examples include 'A4', 'F3.5', and 'M2.1'. Must be a string. OUTPUT spT_float: The spectral type as a float value. See the README file at ...
def _extract_aligned_cdrs(aligned_protseqs, cdr_columns): """ from db use the aligned_protseq and cdr_column to return the aligned cdrs with gaps preserved Parameters ---------- aligned_protseqs : string example: 'GQGVEQ.P.AKLMSVEGTFARVNCTYSTSG......FNGLSWYQQREGQAPVFLSYVVL....DGLKDS.....G...
def get_pod_by_uid(uid, podlist): """ Searches for a pod uid in the podlist and returns the pod if found :param uid: pod uid :param podlist: podlist dict object :return: pod dict object if found, None if not found """ for pod in podlist.get("items", []): try: if pod["meta...
def normalize_auth_header(header): """ Normalize a header name into WSGI-compatible format. >>> normalize_auth_header('X-NSoT-Email') 'HTTP_X_NSOT_EMAIL' :param header: Header name """ return 'HTTP_' + header.upper().replace('-', '_')
def _while_loop_python(cond_fun, body_fun, init_val, maxiter): """Python based implementation (no jit, reverse-mode autodiff ok).""" val = init_val for _ in range(maxiter): cond = cond_fun(val) if not cond: # When condition is met, break (not jittable). break val = body_fun(val) return v...
def solution(strr): """check if all brackets closed properly""" closerof = {'{':'}', '[':']','(':')'} Start = ('[','{','(') Closer = (']','}',')') stack = [] for i in strr: # push into stack, if new bracket found if i in Start: stack.append(i) # pop ...
def find(iteratee, seq): """ Iterates over elements of `seq`, returning the first element that the iteratee returns truthy for. Examples: >>> find(lambda x: x >= 3, [1, 2, 3, 4]) 3 >>> find(lambda x: x >= 5, [1, 2, 3, 4]) is None True >>> find({'a': 1}, [{'a': 1}...
def postpend_list(base_word: str, postpend: list, separator: str='') -> list: """Appends list:postpend to end of str:base_word with default str:separator='', returns a list. """ return [f'{base_word}{separator}{post}' for post in postpend]
def NearZero(z): """Determines whether a scalar is small enough to be treated as zero :param z: A scalar input to check :return: True if z is close to zero, false otherwise Example Input: z = -1e-7 Output: True """ return abs(z) < 1e-6
def is_short_option(argument): """ Check if a command line argument is a short option. :param argument: The command line argument (a string). :returns: :data:`True` if the argument is a short option, :data:`False` otherwise. """ return len(argument) >= 2 and argument[0] == '-' and argument[1] !...
def convert_bool_value_to_status_string(value): """Convert a boolean value, e.g. the value returned by is_message_pair_in_logfile(), into a meaningful string representation. Parameters ---------- value: Boolean value: True, None or False Returns ------- String "Passed Successfully", "...
def check_yellow_positions(curword: str, yllw: list) -> bool: """ Checks the positions of present letters to eliminate words that have previously guessed yellow letter positions :param curword: The currently word from the wordpool :param yllw: List of present words :return: Bool -False if word d...
def createJSONPackage(data): """ Returns a JSON package. Args: data (dict) : A dictionary consisting of the data to JSONify. """ import json return json.dumps(data)
def dig(your_dict, *keys): """digs into an dict, if anything along the way is None, then simply return None """ end_of_chain = your_dict key_present = True for key in keys: if (isinstance(end_of_chain, dict) and (key in end_of_chain)) or ( isinstance(end_of_chain, (list, tupl...
def parse_number(string): """ Retrieve a number from the string. Parameters ---------- string : str the string to parse Returns ------- number : float the number contained in the string """ num_str = string.split(None, 1)[0] number = float(num_str) retur...
def to_string(value: int, ghs_dict: dict) -> str: """Get status key by value from dictionary.""" for string_val, return_val in ghs_dict.items(): if value == return_val: return string_val if ghs_dict == "GHSChannelType": return "Invalid" return "Reserved"
def problem_9_1(arr1, arr2): """ You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. """ m = len(arr2) - 1 p = len(arr1) - 1 n = len(arr1) - len(arr2) - 1 while n >= 0 and m >= 0: if ar...
def create_mapping(dict_times): """ If times are not integers transform each one of them to a unique integer of its own. """ keys = list(dict_times.keys()) mapping = {} for i in range(len(keys)): mapping.update({keys[i]: i}) return mapping
def match(line=None, contains=[]): """ Return true if line contains all of a set of specified strings between '/' characters. """ if line is None: raise RuntimeError('[-] no line to search') if type(contains) is not list: raise RuntimeError('[-] kwarg "contains" must be a list') ...
def divide(array): """Divides an array into a list of two lists where the input is cut in half""" a = array[:len(array)//2] b = array[len(array)//2:] return [a, b]
def generate_polling_readable_message(resource_type_name: str, resource_name: str) -> str: """ Generate appropriate markdown message for polling commands. Args: resource_type_name (str): The name type of the updated resource. For example: Policy, Firewall, IP-Group, etc. resource_name (str):...
def nearest_power_of_two(x): """ Return a number which is nearest to `x` and is the integral power of two. Parameters ---------- x : int, float Returns ------- x_nearest : int Number closest to `x` and is the integral power of two. """ x = int(x) x_lower = 1 if x =...
def rotate_matrix(matrix): """ https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/ """ n = len(matrix[0]) for x in range(0, int(n / 2)): for y in range(x, n - 1 - x): temp = matrix[x][y] matrix[x][y] = matrix[y][n - 1 - x] matrix[y][n...
def children(letter, x, y): """Gives the indices of the "children" of the variables describing the neighbours of a cell, according to the scheme described by Knuth""" assert letter in ["a", "b", "c", "d", "e", "f", "g"], "Letter does not have children in Knuth's scheme" if letter == "a": return ("b"...
def _field_ids(extent_map, field_names): """Convert a (field-name, ...) tuple to a (field-id, ...) tuple for the given extent map.""" field_name_id = extent_map['field_name_id'] return tuple(field_name_id[name] for name in field_names)
def valid_key(key: str): """Checks if the user-key is valid, otherwise returns True Raises: TypeError, Warning Returns: True >>> from vigenere import valid_key >>> valid_key('qwerty') True >>> valid_key(420) Traceback (most recent call last): ... TypeError: The...
def match_pattern(resource: bytes, pattern: bytes, mask: bytes, ignored: bytes): """ Implementation of algorithm in:x https://mimesniff.spec.whatwg.org/#matching-a-mime-type-pattern True if pattern matches the resource. False otherwise. """ resource = bytearray(resource) pattern = bytearray(...
def parseReplacements(config): """Parses the replacements of the program.""" replacements = {} for key, val in config.items(): if isinstance(val, str): # Escape string so that it is not divided into multiple command arguments replacements[key] = "\"{}\"".format(val) e...
def entropy_order(linko_enum): """Key function to sort by graph shannon entropy. Adds another dimention to the linko_enum that is the count of the number of links. With this added dimension, this function will cause the sort routine to sort first on linograph size, then on the number of links, and ...