content
stringlengths
42
6.51k
def remove_empty_line(content: str) -> str: """ Remove all full empty line """ lines = content.split("\n") lines_new = list() for line in lines: if line.strip(): lines_new.append(line) new_content = "\n".join(lines_new) return new_content
def unflatten_dict(dictionary: dict, sep: str = ".") -> dict: """ Unflattens a dict, where keys and the keys from their subdirs are separated by :param:`sep` Parameters ---------- dictionary : dict the dictionary to unflatten sep : str the separation string Returns ------- """ return_dict = {} for key, value in dictionary.items(): parts = key.split(sep) d = return_dict for part in parts[:-1]: if part not in d: d[part] = dict() d = d[part] d[parts[-1]] = value return return_dict
def warning_prettyprint(message, category, filename, lineno, line=None) -> str: """ Monkeypatch the default warning message printing so it's prettier. """ result = ( f'\nWARNING\n-------\n{message}\n\n' ) return result
def wrap_border(x, y, grid): """ Detects border collision and adjusts x and/or y to wrap to the other side """ rows = len(grid) cols = len(grid[0]) if x >= cols: x = x - cols elif x < 0: x = cols + x if y >= rows: y = y - rows elif y < 0: y = rows + y return (x, y)
def choose_string(g1, g2): """Function used by merge_similar_guesses to choose between 2 possible properties when they are strings. If the 2 strings are similar, or one is contained in the other, the latter is returned with an increased confidence. If the 2 strings are dissimilar, the one with the higher confidence is returned, with a weaker confidence. Note that here, 'similar' means that 2 strings are either equal, or that they differ very little, such as one string being the other one with the 'the' word prepended to it. >>> s(choose_string(('Hello', 0.75), ('World', 0.5))) ('Hello', 0.25) >>> s(choose_string(('Hello', 0.5), ('hello', 0.5))) ('Hello', 0.75) >>> s(choose_string(('Hello', 0.4), ('Hello World', 0.4))) ('Hello', 0.64) >>> s(choose_string(('simpsons', 0.5), ('The Simpsons', 0.5))) ('The Simpsons', 0.75) """ v1, c1 = g1 # value, confidence v2, c2 = g2 if not v1: return g2 elif not v2: return g1 v1, v2 = v1.strip(), v2.strip() v1l, v2l = v1.lower(), v2.lower() combined_prob = 1 - (1 - c1) * (1 - c2) if v1l == v2l: return (v1, combined_prob) # check for common patterns elif v1l == 'the ' + v2l: return (v1, combined_prob) elif v2l == 'the ' + v1l: return (v2, combined_prob) # if one string is contained in the other, return the shortest one elif v2l in v1l: return (v2, combined_prob) elif v1l in v2l: return (v1, combined_prob) # in case of conflict, return the one with highest confidence else: if c1 > c2: return (v1, c1 - c2) else: return (v2, c2 - c1)
def insertion_sort(array): """insertion sort""" #list = [8,4,23,42,16,15] for i in range (1 , len(array)): # we consider the first element as sorted temp = array[i] # pointer is the current element # now we start comparing the anchor to the elements before it j = i - 1 while j >= 0 and array[j] > temp: array[j+1] = array[j] j = j - 1 array[j+1] = temp return array
def append_arguments(params_a, params_b): """ Concatenates two argument strings. """ if len(params_a) == 0: return params_b elif len(params_b) == 0: return params_a else: return params_a + ',' + params_b
def update(cur_aggregate, new_value): """For a new value new_value, compute the new count, new mean, the new m_2. * mean accumulates the mean of the entire dataset. * m_2 aggregates the squared distance from the mean. * count aggregates the number of samples seen so far. """ (count, mean, m_2) = cur_aggregate count = count + 1 delta = new_value - mean mean = mean + delta / count delta2 = new_value - mean m_2 = m_2 + delta * delta2 return (count, mean, m_2)
def get_fontext_synonyms(fontext): """ Return a list of file extensions extensions that are synonyms for the given file extension *fileext*. """ return {'ttf': ('ttf', 'otf'), 'otf': ('ttf', 'otf'), 'afm': ('afm',)}[fontext]
def as_word(number): """Convert a number in a word. If this gets complex we will add the inflect module instead. """ ordinal = { 1: 'First', 2: 'Second', 3: 'Third'} return ordinal.get(number, '{}th'.format(number))
def get_indexes(lst, sub_lst, compare_function=None): """Return the indexes of a sub list in a list. :param lst: the list to search in :param sub_lst: the list to match :param compare_function: the comparaison function used :type lst: list :type sub_lst: list :type compare_function: function, takes 2 list as argument :return: the list of indexes of sub_lst in lst. :rtype: list of int """ indexes = [] ln = len(sub_lst) for i in range(len(lst)): if compare_function: if compare_function(lst[i:i + ln], sub_lst): indexes.append(i) else: if lst[i:i + ln] == sub_lst: indexes.append(i) return indexes
def linear_search_recursive(array, item, index=0): """O(1) beacuse we are recursing here""" # implement linear search recursively here if item is not None: if item == array[index]: return index else: return linear_search_recursive(array, item, index+1) # once implemented, change linear_search to call linear_search_recursive # to verify that your recursive implementation passes all tests
def pad_trunc(data, maxlen): """ For a given dataset pad with zero vectors or truncate to maxlen """ new_data = [] # Create a vector of 0's the length of our word vectors zero_vector = [] for _ in range(len(data[0][0])): zero_vector.append(0.0) for sample in data: if len(sample) > maxlen: temp = sample[:maxlen] elif len(sample) < maxlen: temp = sample additional_elems = maxlen - len(sample) for _ in range(additional_elems): temp.append(zero_vector) else: temp = sample new_data.append(temp) return new_data
def isVertical(start, end): """ Given a line decide if it is vertical """ return start[0] == end[0]
def create_dict(breadcrumbs, value=None): """ Created a dict out of the breadcrumbs in a recursive manner. each entry in the breadcrumb should be a valid dictionary key. If value is None, the last string within' the breadcrumbs becomes the final value. :param breadcrumbs: :param value: :return: """ if value is not None: if not breadcrumbs: return value elif len(breadcrumbs) == 1: return breadcrumbs[0] return {breadcrumbs[0]: create_dict(breadcrumbs[1:], value)}
def optimizeAngle(angle): """ Because any rotation can be expressed within 360 degrees of any given number, and since negative angles sometimes are one character longer than corresponding positive angle, we shorten the number to one in the range to [-90, 270[. """ # First, we put the new angle in the range ]-360, 360[. # The modulo operator yields results with the sign of the # divisor, so for negative dividends, we preserve the sign # of the angle. if angle < 0: angle %= -360 else: angle %= 360 # 720 degrees is unnecessary, as 360 covers all angles. # As "-x" is shorter than "35x" and "-xxx" one character # longer than positive angles <= 260, we constrain angle # range to [-90, 270[ (or, equally valid: ]-100, 260]). if angle >= 270: angle -= 360 elif angle < -90: angle += 360 return angle
def check_threshold(service, config_high_threshold, config_low_threshold, curr_util): """ Checks whether Utilization crossed discrete threshold Args: service: Name of the micro/macroservice config_high_threshold: Upper limit threshold to utilization set in config file config_low_threshold: Lower limit threshold to utilization set in config file curr_util: value of the current utilization Returns: String "High" if upper limit crossed String "Low" if lower limit crossed String "Normal" if none crossed """ if float(curr_util) > float(config_high_threshold): return "High" elif float(curr_util) < float(config_low_threshold): return "Low" else: return "Normal"
def registra_aluno(nome, ano_entrada, ano_nascimento, **misc): """Cria a entrada do registro de um aluno.""" registro = {'nome': nome, 'ano_entrada': ano_entrada, 'ano_nascimento': ano_nascimento} for key in misc: registro[key] = misc[key] return registro
def tuple2str(t, n): """ Returns string representation of product state. Parameters ---------- t : tuple Product state. n : int Total number of spin-orbitals in the system. """ s = "" for i in range(n): if i in t: s += "1" else: s+= "0" return s
def get_hashtag_spans(tokens): """ Finds the spans (start, end) of subtokes in a list of tokens Args: tokens: list[str] Returns: spans: list[tuple[int]] """ is_part = ["##" in t for t in tokens] spans = [] pos_end = -1 for pos_start, t in enumerate(is_part): if pos_start <= pos_end: continue if t: last_pos = len(is_part[pos_start:]) - 1 for j, t_end in enumerate(is_part[pos_start:]): if not t_end: pos_end = pos_start + j break if j == last_pos: pos_end = pos_start + j + 1 spans.append((pos_start, pos_end)) return spans
def parameter_key_function(parameter): """ returns a key for sorting parameters """ value = {'RFC_IMPORT':1, 'RFC_CHANGING':2, 'RFC_TABLES':3, 'RFC_EXPORT':4} return value[parameter['direction']]
def version_tuple(version): """Get version tuple""" parts = version.split('.') return tuple(int(x) if x.isnumeric() else x for x in parts)
def containsAny(seq, aset): """ Check whether sequence seq contains ANY of the items in aset. """ for c in seq: if c in aset: return True return False
def isbn_check (isbn): """ (string)-->(True or False) Determines whether a 10 digit string is a valid ISBN. Isolates last number in input string, and computes/compares this value to the correct 10th digit obtained from a string with the first 9 digits of the input string. Returns true if true, false if not. ('097522980X')--> True ('5678901231')--> Flase """ isbn_numStr = isbn[0:-1] isbncheck_math = sum([(int(isbn_numStr[i])*(i+1)) for i in range(0,9)]) isbncheck_mathremainder = (isbncheck_math % 11) if isbncheck_mathremainder == 10: isbncheck_mathremainder = str('X') print (isbncheck_mathremainder == isbn[-1]) == True return (isbncheck_mathremainder == isbn[-1]) else: print (int(isbncheck_mathremainder) == int(isbn[-1])) return (isbncheck_mathremainder == isbn[-1])
def boyer_moore_voting_algorithm(arr: list) -> int: """ :param arr: list :return: int """ res = arr[0] # Initialization counter = 0 # Counter for i in range(len(arr)): if counter == 0: res = arr[i] counter = 1 elif res == arr[i]: counter += 1 else: counter -= 1 return res
def set_file_name(site, dates): """ Create the file name for the echogram based on the mooring site name, and the date range plotted. :param site: mooring site name :param dates: date range shown in the plot :return file_name: file name as a string created from the inputs """ file_name = site + '_Bioacoustic_Echogram_' + dates[0] + '-' + dates[1] + '_Calibrated_Sv' return file_name
def gcd(a, b): """Compute gcd(a,b) :param a: first number :param b: second number :returns: the gcd """ pos_a, _a = (a >= 0), abs(a) pos_b, _b = (b >= 0), abs(b) gcd_sgn = (-1 + 2*(pos_a or pos_b)) if _a > _b: c = _a % _b else: c = _b % _a if c == 0: return gcd_sgn * min(_a,_b) elif _a == 1: return gcd_sgn * _b elif _b == 1: return gcd_sgn * _a else: return gcd_sgn * gcd(min(_a,_b), c)
def round_grade(grade: int) -> int: """ Round the grade according to policy. Parameters ---------- grade: int Raw grade. Returns ------- rounded_grade: int Rounded grade. """ if grade < 38: rounded_grade = grade else: closest_multiple_5 = (grade // 5 + 1) * 5 if (closest_multiple_5 - grade) >= 3: rounded_grade = grade else: rounded_grade = closest_multiple_5 return rounded_grade
def Msg (TYPE, **kw): """ Craft a message """ m = kw m['TYPE'] = TYPE return m
def check_if_duplicates(lst_img): """ Check if given list contains any duplicates """ set_of_elems = set() for elem in lst_img: if elem in set_of_elems: return True else: set_of_elems.add(elem) return False
def real_space_shape_2d_tag_from_real_space_shape_2d(real_space_shape_2d): """Generate a sub-grid tag, to customize phase names based on the sub-grid size used. This changes the phase name 'phase_name' as follows: real_space_shape_2d = None -> phase_name real_space_shape_2d = 1 -> phase_name_real_space_shape_2d_2 real_space_shape_2d = 4 -> phase_name_real_space_shape_2d_4 """ if real_space_shape_2d is None: return "" y = str(real_space_shape_2d[0]) x = str(real_space_shape_2d[1]) return "__rs_shape_" + y + "x" + x
def constructLimitsOffsets(limit, offset): """ Create a list of limit and offset pairs for partial fetching of maximum 100 apps. Arguments: limit -- the number of apps to fetch offset -- the offset from where to start fetching Returns: A list of limit,offset pairs where limit is no larger than 100 """ limitOffsets = [] while limit > 100: limitOffsets.append(('100', str(offset) if offset > 0 else None)) offset += 100 limit -= 100 limitOffsets.append((str(limit), str(offset) if offset > 0 else None)) return limitOffsets
def same_shape(t1: tuple, t2: tuple) -> bool: """ Returns True if t1 and t2 are the same shape. False, otherwise.""" try: return len(t1) == len(t2) except: return False
def _q_start(query_seq, q_seq): """ returns the starting pytyon string index of query alignment (q_seq) in the query_sequence (query_seq) :param query_seq: string full query sequence :param q_seq: string alignment sequence (may contain gaps as "-") :return: :example: >>_q_start(query_seq = "ATGATG", q_seq = "ATG") 0 >>_q_start(query_seq = "ATGATG", q_seq = "GATG") 2 >>_q_start(query_seq="ATGATG", q_seq="GA-TG") 2 """ q_seq = q_seq.replace("-", "") # remove gaps to get index for original sequence q_start = query_seq.find(q_seq) return(q_start)
def get_time_signature_code(number: int) -> str: """Return a string for a time signature number.""" if number > 10: div, mod = divmod(number, 10) return chr(57472 + div) + chr(57472 + mod) return chr(57472 + number)
def computeFraction( poi_messages, all_messages ): """ compute the fraction of messages to/from a person that are from/to a POI """ fraction = 0 if poi_messages == 'NaN' or all_messages == 'NaN': fraction = 'NaN' else: fraction = float(poi_messages)/all_messages return fraction
def get_file_id(service, file_name, mime_type=None, parent_id=None): """Return the ID of a Google Drive file :param service: A Google Drive API service object :param file_name: A string, the name of the file :param mime_type: A string, optional MIME type of file to search for :param parent_id: A string, optional id of a parent folder to search in :return file_id: A string, file ID of the first found result """ file_id = None query = """name='{}' and trashed=False """.format(file_name) if parent_id: query += "and parents in '{}'".format(parent_id) if mime_type: query += "and mimeType in '{}'".format(mime_type) try: results = service.files().list( q=query, fields='files(name, id)').execute() if len(results['files']) > 1: print('Multiple files found, retrieving first from list') file_id = results['files'][0]['id'] except Exception as e: print('An error occurred: {}'.format(e)) return file_id
def parse_float_gt0(value): """Returns value converted to a float. Raises a ValueError if value cannot be converted to a float that is greater than zero. """ value = float(value) if value <= 0: msg = 'Invalid value [{0}]: require a number greater than zero' raise ValueError(msg.format(value)) else: return value
def hexpad(val: int, size: int = 4): """Compile integer into 4 char padded hex.""" if val > (1 << 8 * size) - 1: raise Exception( f"Cannot pack value larger than {hex((1 << 8 * size) - 1)}") return hex(val)[2:].zfill(size).upper()
def parse_key(key): """Deconstructs a DB key into the timestamp and designator. """ if not isinstance(key, str): key = key.decode() des, ts, = key.split(',') return (des, int(ts),)
def closest_bin(q, bin_edges): """ Find closest bin to a q-value :param float q: q-value :param list bin_edges: list of bin edges """ for i in range(len(bin_edges)): if q > bin_edges[i] and q <= bin_edges[i+1]: return i return None
def stars_and_color_presence_checker(board: list) -> bool: """Checks if color blocks have same numbers and if stars and ziros are in cells, in which they shouldn't be. Returns ture if anything wrong is found. >>> stars_and_color_presence_checker(["**** ****", "***1 ****", "** 3****", "* 4 1****",\ "7 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 9****"]) False """ for i in range(5): color_block = {} for j in range(4 - i, 9 - i): if board[j][i] == '*' or board[j][i] == '0': return True if board[j][i] != ' ': color_block[board[j][i]] = color_block.setdefault( board[j][i], 0) + 1 for j in range(i + 1, i + 5): if board[8 - i][j] == '*' or board[8 - i][j] == '0': return True if board[8 - i][j] != ' ': color_block[board[8 - i][j] ] = color_block.setdefault(board[8 - i][j], 0) + 1 for value in color_block.values(): if value > 1: return True return False
def snake_index_to_coordinates(index, x_dimension, y_dimension): """Obtain the column and row coordinates corresponding to a snake ordering index on a 2-d grid. """ if index > x_dimension * y_dimension - 1: raise ValueError('Index exceeds x_dimension * y_dimension - 1.') row = index // x_dimension if row % 2 == 0: column = index % x_dimension else: column = x_dimension - 1 - index % x_dimension return column, row
def _compute_max_name_width(contracts: dict) -> int: """Return the maximum width needed by the function name column.""" return max( len(function) for contract, functions in contracts.items() for function in functions )
def tags(reserved, request, response): """ :param reserved: Reserved for future use :param request: Original request sent to device :param response: Reply from device for request :return: return a list of strings :rtype: list """ r = [] if len(request) > 0: r = ["scythe", "att&ck", "att&ck-technique:T1057"] return r
def to_iterable(value, allow_none=True): """ Tries to convert the given value to an iterable, if necessary. If the given value is a list, a list is returned; if it is a string, a list containing one string is returned, ... :param value: Any object :param allow_none: If True, the method returns None if value is None, else it returns an empty list :return: A list containing the given string, or the given value """ if value is None: # None given if allow_none: return None else: return [] elif isinstance(value, (list, tuple, set, frozenset)): # Iterable given, return it as-is return value # Return a one-value list return [value]
def is_datetime_string(string: str) -> bool: """ Check if the string is date-like. Parameters ---------- string : str Returns ------- is_date: bool """ from dateutil.parser import parse try: parse(string) return True except ValueError: return False
def brand_penetration_rate(number_of_brand_purchasers, total_purchasers): """Returns the percentage of penetration rate for a brand. Args: number_of_brand_purchasers (int): Total number of unique purchasers of a brand. total_purchasers (int): Total unique purchasers. Returns: Percentage of purchasers who have purchased the brand. """ return (number_of_brand_purchasers / total_purchasers) * 100
def is_metoffice(sheet_cell): """Is this variable produced by the Met Office?""" if not sheet_cell: return False not_producing_values = ['CHECK', 'FALSE'] for value in not_producing_values: if value == sheet_cell.upper(): return False return True
def quicksort(ar:list): """ Sort a list with quicksort algorithm. The quicksort algorithm splits a list into two parts and recursively sorts those parts by making swaps based on the elements value in relation to the pivot value. It is an O(n log(n)) sort. Args: ar: list to sort. Returns: The input list sorted. """ def sort(ar, lo, hi): # if the two ends haven't swapped if lo < hi: # find the partition partition_index = partition(ar, lo, hi) # sort both sides sort(ar, lo, partition_index - 1) sort(ar, partition_index + 1, hi) def partition(ar, lo, hi): # basic partition by using the high value as a pivot pivot = ar[hi] # the value being examined i = lo for j in range(lo, hi): # if ar[j] <= pivot: ar[i], ar[j] = ar[j], ar[i] i += 1 # swap the pivot into place ar[i], ar[hi] = ar[hi], ar[i] return i sort(ar, 0, len(ar)-1) return ar
def significant(n, digits=3): """"Returns a number rounded to some (default 3) significant digits. significant(5882) == '5880' significant(0.40032, 4) == '0.400'""" if digits < 1: raise ValueError('Digits must be >= 1') integer_digits = len(str(int(n))) - (n < 0) if integer_digits >= digits: return str(int(round(n, digits - integer_digits))) else: return ('{' + '0:.{}f'.format(digits - integer_digits) + '}').format(n)
def readable_lines(cmd): """ Goes through and places new lines to split up a command to make it readable. """ result = "" line_length = 0 for section in cmd: if line_length + len(section) + 8 > 80: line_length = 4 result += '\\\n' result += ' ' * line_length result += section + ' ' else: line_length += len(section) result += section + ' ' return result
def check_imo_number(imo): """ do a basic integrity check of an IMO number Args: imo(str): the IMO number as a string Returns: True: if valid IMO number False: invalid IMO number """ if len(imo) > 7: return False try: lastdigit = imo[6] total = 0 multiplyby = 7 for digit in range(0, 6): total += int(imo[digit]) * multiplyby multiplyby -= 1 except IndexError: return False return bool(str(total)[len(str(total)) - 1] == lastdigit)
def MakeUnique (s, in_use): """Return an identifier based on C{s} that is not in the given set. The returned identifier is made unique by appending an underscore and, if necessary, a serial number. The order is : C{x}, C{x_}, C{x_2}, C{x_3}, ... @param in_use: The set of identifiers already in use in the relevant scope. C{in_use} is updated to contain the returned identifier. @rtype: C{str} """ if s in in_use: ctr = 2 s = s.rstrip('_') candidate = '%s_' % (s,) while candidate in in_use: candidate = '%s_%d' % (s, ctr) ctr += 1 s = candidate in_use.add(s) return s
def add_chars(w1, w2): """ Return a string containing the characters you need to add to w1 to get w2. You may assume that w1 is a subsequence of w2. >>> add_chars("owl", "howl") 'h' >>> add_chars("want", "wanton") 'on' >>> add_chars("rat", "radiate") 'diae' >>> add_chars("a", "prepare") 'prepre' >>> add_chars("resin", "recursion") 'curo' >>> add_chars("fin", "effusion") 'efuso' >>> add_chars("coy", "cacophony") 'acphon' >>> from construct_check import check >>> # ban iteration and sets >>> check(LAB_SOURCE_FILE, 'add_chars', ... ['For', 'While', 'Set', 'SetComp']) # Must use recursion True """ "*** YOUR CODE HERE ***" assert len(w1) <= len(w2) if len(w1) == 0: return w2 if w1[0] == w2[0]: return add_chars(w1[1:], w2[1:]) else: return w2[0] + add_chars(w1, w2[1:])
def calc_bandwidth_rbs(bandwidth_mhz: float) -> str: """ Convert bandwidth in mhz to rbs Args: bandwidth_mhz: float, Bandwidth in mhz Returns: Bandwidth in rbs """ bandwidth_rbs = int(5 * bandwidth_mhz) return str(bandwidth_rbs)
def sizeof_fmt(num: int, suffix: str = "B") -> str: """ Human readable version of file size. Supports: - all currently known binary prefixes (https://en.wikipedia.org/wiki/Binary_prefix) - negative and positive numbers - numbers larger than 1,000 Yobibytes - arbitrary units Examples: >>> sizeof_fmt(168963795964) "157.4 GiB" >>> sizeof_fmt(168963795964, suffix="o") "157.4 Gio" Source: https://stackoverflow.com/a/1094933/1117028 """ val = float(num) for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"): if abs(val) < 1024.0: return f"{val:3.1f} {unit}{suffix}" val /= 1024.0 return f"{val:,.1f} Yi{suffix}"
def make_segments(utts, recname, min_utt_len=2.0): """ Make kaldi friendly segments of the format recname-VWXYZ Input: uttlist imported from transcription json, recname """ seglines = [] speakers = [] utt_ids = [] i = 0 for utt in utts: utt_id = '{0}-{1:0=5d}'.format(recname, i) start = float(utt['start']) stop = float(utt['stop']) if float(start) + min_utt_len > float(stop): # Discard too short snippets continue speaker_id = utt['speaker_id'] if not speaker_id.strip(): # Discard empty speaker_ids continue line = '{} {} {} {}\n'.format(utt_id, recname, start, stop) seglines.append(line) speakers.append(speaker_id) utt_ids.append(utt_id) i += 1 return seglines, utt_ids, speakers
def get_descriptors(format=False): """Get DREAM challenge descriptors""" if format: result = [ "Intensity", "Pleasantness", "Bakery", "Sweet", "Fruit", "Fish", "Garlic", "Spices", "Cold", "Sour", "Burnt", "Acid", "Warm", "Musky", "Sweaty", "Ammonia", "Decayed", "Wood", "Grass", "Flower", "Chemical", ] else: result = [ "INTENSITY/STRENGTH", "VALENCE/PLEASANTNESS", "BAKERY", "SWEET", "FRUIT", "FISH", "GARLIC", "SPICES", "COLD", "SOUR", "BURNT", "ACID", "WARM", "MUSKY", "SWEATY", "AMMONIA/URINOUS", "DECAYED", "WOOD", "GRASS", "FLOWER", "CHEMICAL", ] return result
def distance(a, b): """ Calculate distance between coordinates a and b. Params ------ a : tuple b : tuple Returns ------- out : float Squared distance between coordinates a and b. """ return (a[0] - b[0])**2 + (a[1] - b[1])**2
def break_(): """Create a break statement.""" return ['break']
def turn_rightmost_0_bit(n: int) -> int: """ Turn on the rightmost 0-bit. >>> bin(turn_rightmost_0_bit(0b11110001)) '0b11110011' """ return n | (n + 1)
def array_to_string(arr, do_not_flatten_strings=True): """ Converts an array of objects to a comma separated string """ res = "" if arr is None: return None if do_not_flatten_strings and isinstance(arr, str): return arr if hasattr(arr, '__iter__'): for part in arr: if part is not None: res = res + str(part) + ", " if len(res) > 1: return res[:-2] else: return "" else: return str(arr)
def find_all(l: list, sub: list) -> list: """ returns list of indices of all finds """ res = [] for l_i in range(len(l)): match = True for sub_i in range(len(sub)): if l_i+sub_i >= len(l) or l[l_i+sub_i] != sub[sub_i]: match = False break if match: res.append(l_i) return res
def init_global_params(run_settings): """ initialize global parameters :run_settings: run settings dict, must contain - dims - max_iterations - num_centroids - threshold :returns: GlobalParams list """ global_params = [] global_params.append(run_settings['num_points']) global_params.append(run_settings['dims']) global_params.append(run_settings['num_centroids']) global_params.append(run_settings['max_iterations']) global_params.append(run_settings['threshold']) return global_params
def __none_to_zero(string): """ Return '0' if the string is "none" or "null"; return the string itself otherwise. @type string: C{string} @param string: The string to test for values of "none" or "null". @rtype: C{string} @return: '0' if the string is "none" or "null", the string itself otherwise. """ if (string.lower() == "none" or string.lower() == "null"): return '0' else: return string
def AddIdx(idx): """Adds index value to a string for auto name generation.""" return '-%s' % str(idx)
def dummy_get_app(*dummy): """ dummy app """ return ["get"]
def record_optional_paths(database, include_path_candidate, header): """Add optional path set into include path candidates database. Optional include path if the source file location is identical location of included header file location""" if include_path_candidate not in database[header]["include_paths"]: database[header]["include_paths"].append(include_path_candidate) if "optional" not in database[header]["path_types"]: database[header]["path_types"].append("optional") return database
def sd(array): """ Calculates the standard deviation of an array/vector """ import numpy as np array=np.array(array) result= np.std(array) return result
def are_at_least_one_None(list_parameters): """returns list_parameters.at least one.is_None""" for parameter in list_parameters: if parameter is None: return True else: continue return False
def ensure_str(obj): """ Converts bytes to a utf-8 string. """ if obj is None: return None if isinstance(obj, str): return obj if isinstance(obj, bytes): return obj.decode('utf-8') else: raise TypeError("Must be bytes or str")
def clean_numeric(x): """ Convierte cualquier string a numeric limpiando cualquier formato. """ if isinstance(x, str): x = ''.join(e for e in x if e.isnumeric() or e == '.') return x
def _squash_devicegroup(device_group, device_group_hierarchy_children): """Recursive function for determining all of a device group's child device groups""" result = [device_group] if device_group in device_group_hierarchy_children: for child_dg in device_group_hierarchy_children[device_group]: result += _squash_devicegroup(child_dg, device_group_hierarchy_children) return sorted(result)
def blacklist_lookup(ip_address, blacklist_mem_db): """ Queries the in memory DB of blacklisted addresses for an IPv4 address. Returns the blacklist name or `None` of no matching IP was found. :param blacklist_mem_db: Object containing the in memory blacklist db. :param ip_address: String IPv4 Network Address :return: String or None """ for item in blacklist_mem_db: if item['type'] == 'ip_network' and ip_address in item['value']: return item['name'] elif ip_address == item['value']: return item['name']
def rotate(grid): """Rotate grid 90 deg to the right.""" rows = grid.split('\n') return '\n'.join(''.join(chars) for chars in zip(*reversed(rows)))
def get_results_value(results): """ Gets the value in the last column of the first row of the ga results :param results: dict: results from the ga analytics query :return: int: the value from the results """ if results.get('rows', []): return results.get('rows')[0][-1] return None
def strip_left(s, pattern): """ Strips a string left (start) of string if found. Otherwise, returns the original string. :param s: str :param pattern: str :rtype: str """ if s.startswith(pattern): return s[len(pattern):-1] else: return s
def sum_positive_numbers(n): """ :returns sum of positive numbers """ if n == 0: return 0 else: return n + sum_positive_numbers(n - 1)
def get_table_name(element): """ The function will return a fully qualified table name according to the logic applied to the processed element. In this case, input data already provides the table name directly but it can be extended to more complex use cases. """ return 'PROJECT_ID:DATASET.' + element['type']
def guess_input_handler(seqs, add_seq_names=False): """Returns the name of the input handler for seqs.""" if isinstance(seqs, str): if '\n' in seqs: # can't be a filename... return '_input_as_multiline_string' else: # assume it was a filename return '_input_as_string' if isinstance(seqs, list) and len(seqs) and isinstance(seqs[0], tuple): return '_input_as_seq_id_seq_pairs' if add_seq_names: return '_input_as_seqs' return '_input_as_lines'
def make_posix_path(windows_path): """Convert a Windows path to a posix path""" return windows_path.replace('\\', '/').replace('C:', '/c')
def which(executable): """Equivalent of witch(1). Returns the path (if any) of executable.""" import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(executable) if fpath: if is_exe(executable): return executable else: for path in os.environ['PATH'].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, executable) if is_exe(exe_file): return exe_file return(None)
def _prefix_keys(old_dict, prefix): """Adds a prefix to all keys in a dict""" new_dict = {} for key, value in old_dict.items(): new_key = u"{} - {}".format(prefix, key) new_dict[new_key] = old_dict[key] return new_dict
def get_package(package_info: dict) -> str: """Construct the package name and exact version to install.""" package_tag = f"{package_info['name']}=={package_info['version']}" # The package is a local file source = package_info.setdefault("source", {}) if source.get("type") == "file": # Trim off the app root path package_tag = package_info["source"]["url"] package_tag = package_tag[package_tag.find("/") + 1 :] # skipcq: FLK-E203 # The package is from a URL elif source.get("type") == "url": package_tag = package_info["source"]["url"] # The package is from a git repo revision elif source.get("type") == "git": git_hash = package_info["source"]["resolved_reference"] git_repo_archive = package_info["source"]["url"].replace(".git", "/archive") package_tag = f"{git_repo_archive}/{git_hash}.zip" return package_tag
def typedvalue(value): """ Convert value to number whenever possible, return same value otherwise. >>> typedvalue('3') 3 >>> typedvalue('3.0') 3.0 >>> typedvalue('foobar') 'foobar' """ try: return int(value) except ValueError: pass try: return float(value) except ValueError: pass return value
def updateGameReleaseDate(gtitle: str, new_rdate: str) -> str: """Return a query to update the release date of a given game.""" return (f"UPDATE game " f"SET release_date='{new_rdate}' " f"WHERE title='{gtitle}';" )
def check_orientation(orientation): """ Check if orientation is valid input or not. Return True if is 'horizontal', False if 'vertical', raise Error if invalid input :param str orientation: str, allowed values are 'horizontal' and 'vertical' :return: True if is horizontal, False if vertical :rtype: bool :raises ValueError: invalid input """ if orientation.lower().strip()[0] == "h": return True elif orientation.lower().strip()[0] == "v": return False else: raise ValueError("Invalid input orientation: %s." % orientation)
def get_step_lrf(n, decay, period): """ Decays the learning rate by `decay` every `period` epochs. Args: n (int): current epoch decay (float): 0.97 period (int): 1 """ lrf = decay ** (n // period) return lrf
def merge_specializations(data, duplicated_courses, id): """ Merges specializations for the same course """ specializations = [] for course in data["courses"]: if course["id"] == id: for specialization in course["specializations"]: specializations.append(specialization) return specializations
def prettyTime(t): """ prettyTime(t): input t comes in as seconds. Output is a str with units attached (secs, mins, hrs, etc.) """ if t < 120: return '%.2f secs' % (t) t = t / 60.0 if t < 120: return '%.2f mins' % (t) t = t / 60.0 if t < 25: return '%.2f hrs' % (t) t = t / 24.0 if t < 28: return '%.2f days' % (t) t = t / 7.0 return '%.2f weeks' % (t)
def snake_to_camel(name): """Returns the camel case of the given snake cased input""" parts = name.split('_') return parts[0] + "".join(x.title() for x in parts[1:])
def _read_whole_file(file_path): """ Read a text file into a single string. Assumes UTF-8 encoding. """ with open(file_path, "r", encoding="utf-8") as f: return f.read()
def trailing_zeros(number): """ Returns the 1-based index of the first bit set to 1 from the right side of a 32bit integer >>> trailing_zeros(0) 32 >>> trailing_zeros(0b1000) 4 >>> trailing_zeros(0b10000000) 8 """ if not number: return 32 index = 0 while (number >> index) & 1 == 0: index += 1 return index + 1
def all_prefixes(li): """ Returns all prefixes of a list. Args: li: list from which to compute all prefixes Returns: list of all prefixes """ return [tuple(li[:i + 1]) for i in range(len(li))]
def version_is_compatible(imp_version, version): """Determine whether versions are compatible. :param imp_version: The version implemented :param version: The version requested by an incoming message. """ version_parts = version.split('.') imp_version_parts = imp_version.split('.') try: rev = version_parts[2] except IndexError: rev = 0 try: imp_rev = imp_version_parts[2] except IndexError: imp_rev = 0 if int(version_parts[0]) != int(imp_version_parts[0]): # Major return False if int(version_parts[1]) > int(imp_version_parts[1]): # Minor return False if (int(version_parts[1]) == int(imp_version_parts[1]) and int(rev) > int(imp_rev)): # Revision return False return True
def counter_count(string): """String's counter() method is used.""" return {i: string.count(i) for i in string}
def count_local_minmax(A): """ Count local max and min @author Akafael """ n = len(A) # Trivial Solution if n <= 1: return 1 # Calculate the diff B = [] count = 0 isRising = False isFalling = False for i in range(1, n - 1): B.append(A[i + 1] - A[i]) # Count Pikes if B[i] > 0: isRising = True if isFalling == True: count += 1 isFalling == False elif B[i] < 0: isFalling = True if isRising == True: count += 1 isRising == False return count
def distance_weights(pool, labels): """Calculate weights based on distance""" weights = [0 for _ in range(len(labels))] for i in pool: for label in labels: pool_label = i[0] distance = i[1] if pool_label == label: weights[label] += 1 / distance return weights.index(max(weights))
def bitwise_contains(a: int, b: int) -> bool: """Return True if any bit of mask `b` is contained in `a`.""" return bool(a & b)