content
stringlengths
42
6.51k
def _extract_args(cmd_line, args): """ Extract specified arguments and sorts them. Also removes them from the command line. :param cmd_line: Array of command line arguments. :param args: List of arguments to extract. :returns: A tuple. The first element is a list of key, value tuples representing each arguments. The second element is the cmd_line list without the arguments that were extracted. """ # Find all instances of each argument in the command line found_args = [] for cmd_line_token in cmd_line: for arg in args: if cmd_line_token.startswith("--%s=" % arg): found_args.append(cmd_line_token) # Strip all these arguments from the command line. new_cmd_line = [ argument for argument in cmd_line if argument not in found_args ] arguments = [] # Create a list of tuples for each argument we found. for arg in found_args: pos = arg.find("=") # Take everything after the -- up to but not including the = arg_name = arg[2:pos] arg_value = arg[pos + 1:] arguments.append((arg_name, arg_value)) return arguments, new_cmd_line
def sec_to_time(s): """ Returns the hours, minutes and seconds of a given time in secs """ return (int(s//3600), int((s//60)%60), (s%60))
def get_ids_to_values_map(values): """ Turns a list of values into a dictionary {value index: value} :param values: list :return: dictionary """ return {id: category for id, category in enumerate(values)}
def add_ul(text, ul): """Adds an unordered list to the readme""" text += "\n" for li in ul: text += "- " + li + "\n" text += "\n" return text
def get_names_in_waveform_list(waveform_list) -> list: """Gets the names of all Waveform objects in a list of Waveforms Parameters ---------- waveform_list : list A list of Waveform objects Returns ------- list A list of the names of the Waveform objects in waveform_list """ names = [] for w in waveform_list: names.append(w.get_name()) return names
def prod(iterable, start=1): """Multiplies ``start`` and the items of an ``iterable``. :param iterable: An iterable over elements on which multiplication may be applied. They are processed from left to right. :param start: An element on which multiplication may be applied, defaults to ``1``. :return: The result of multiplication. """ for i in iterable: start *= i return start
def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = -n if n < 0 else n res = 0 while n > 0: res += n % 10 n = n // 10 return res
def exporigin(mode, db): """Return the expected origins for a given db/mode combo.""" if mode == 'local' and not db: return 'file' elif mode == 'local' and db: return 'db' elif mode == 'remote' and not db: return 'api' elif mode == 'remote' and db: return 'api' elif mode == 'auto' and db: return 'db' elif mode == 'auto' and not db: return 'file'
def conf_primary(class_result, ordinal): """ Identify the confidence of the primary cover class for the given ordinal day. The days between and around segments identified through the classification process comprise valid segments for this. They also receive differing values based on if they occur at the beginning/end or if they are between classified segments. <- .... |--seg 1--| ...... |--seg 2--| .... -> 0 val 100 val 0 Args: class_result: ordered list of dicts return from pyclass classification ordinal: ordinal day to calculate from Returns: int """ ret = 0 if ordinal > 0: prev_end = 0 for segment in class_result: if segment['start_day'] <= ordinal <= segment['end_day']: ret = int(max(segment['class_probs'][0]) * 100) break elif prev_end < ordinal < segment['start_day']: ret = 100 break prev_end = segment['end_day'] return ret
def MakeDeclarationString(params): """Return a C-style parameter declaration string.""" string = [] for p in params: sep = "" if p[1].endswith("*") else " " string.append("%s%s%s" % (p[1], sep, p[0])) if not string: return "void" return ", ".join(string)
def is_iterable(x): """Returhs True if `x` is iterable. Note: This won't work in Python 3 since strings have __iter__ there. """ return hasattr(x, "__iter__")
def make_str_from_column(board, column_index): """ (list of list of str, int) -> str Return the characters from the column of the board with index column_index as a single string. >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1) 'NS' >>> make_str_from_column([['r', 's', 't', 'u'], ['g', 'a', 'd'], ['x', 'y', 'f', 'b']], 3) 'u b' """ single_string = '' for row in range(len(board)): if column_index < len(board[row]): single_string += board[row][column_index] else: single_string += ' ' return single_string
def get_lang(filename): """ get language from filename """ filename = filename.replace("_cn", '.zh').replace("_ch", '.zh').replace("_", ".") if filename.endswith(".sgm") or filename.endswith(".txt"): return filename.split('.')[-2] else: return filename.split('.')[-1]
def num_bytes(byte_tmpl): """Given a list of raw bytes and template strings, calculate the total number of bytes that the final output will have. Assumes all template strings are replaced by 8 bytes. >>> num_bytes([0x127, "prog_bytes"]) 9 """ total = 0 for b in byte_tmpl: if isinstance(b, int): total += 1 elif isinstance(b, list) and b: tmpl_key = b[0] if tmpl_key == "string_lit": total += 8 elif tmpl_key == "fun_offset": total += 4 else: assert False, "tmpl key: {!r}".format(tmpl_key) elif b in ("prog_entry", "prog_length"): total += 8 else: assert False, "tmpl: {!r}".format(b) return total
def str2float(string: str) -> float: """Converts a string to a float.""" try: if "/" not in string: return float(string) else: return float(string.split("/")[0]) / float(string.split("/")[1]) except: return 1.0
def human2bytes(size, unit, *, precision=2, base=1024): """ Convert size from human to bytes. Arguments: size (int): number unit (str): converts from this unit to bytes 'KB', 'MB', 'GB', 'TB', 'PB', 'EB' Keyword arguments (opt): precision (int): number of digits after the decimal point default is 2 base (int): 1000 - for decimal base 1024 - for binary base (it is the default) Returns: (int) number in bytes Example: >>> human2bytes(10, 'GB') '10737418240.00' >>> human2bytes(10, 'GB', precision=0) '10737418240' >>> human2bytes(10, 'PB') '11258999068426240.00' """ dic_power = { "KB": base, "MB": base ** 2, "GB": base ** 3, "TB": base ** 4, "PB": base ** 5, "EB": base ** 6, "ZB": base ** 7, } if unit not in dic_power: raise ValueError( "invalid unit. It must be {}".format(", ".join(dic_power.keys())) ) try: num_bytes = float(size) * int(dic_power[unit]) except ValueError: raise ValueError("value is not a number") return "{0:.{prec}f}".format(num_bytes, prec=precision)
def split_url_path(url): """Split url into chunks""" #Ensure trailing slash to get parts correct if url =='' or url[-1] != '/': url = url + '/' parts = url.split('/') try: #Final part is now blank return parts[0:-1] except: return parts
def _vector_to_list(vectors): """ Convenience function to convert string to list to preserve iterables. """ if isinstance(vectors, str): vectors = [vectors] return vectors
def _add_char(num, char=' '): """Creates a string value give a number and character. args: num (int): Amount to repeat character kwargs: char (str): Character value to lopp Returns (str): Iterated string value for given character """ string = '' for i in range(num): string += char return string
def indentation(level, word): """ Returns a string formed by word repeated n times. """ return ''.join([level * word])
def bootstrap_dirname(suite, arch): """From the suite/arch calculate the directory name to extract debootstrap into""" return "./" + suite + "-" + arch
def solve(task): """ :param task: string of the task to be evaluated :return: if solved returns solution, else returns None """ try: solution = eval(task) return solution except SyntaxError: return None
def organization_id(data: list, organization_ids: list) -> list: """ Select only features that contain the specific organization_id :param data: The data to be filtered :type data: dict :param organization_ids: The oragnization id(s) to filter through :type organization_ids: list :return: A feature list :rtype: dict """ return [ # Feature only if feature # through the feature in the data for feature in data # if the found org_id is in the list of organization_ids if "organization_id" in feature["properties"] and feature["properties"]["organization_id"] in organization_ids ]
def count_bases(seq): """"THis function is for counting the number of A's in the sequence""" # Counter for the As count_a = 0 count_c = 0 count_g = 0 count_t = 0 for b in seq: if b == "A": count_a += 1 elif b == "C": count_c += 1 elif b == "G": count_g += 1 elif b == "T": count_t += 1 # Return the result return count_a, count_c, count_g, count_t
def first(iterable): """ Return the first object in an iterable, if any. """ return next(iterable, None)
def linear_rampup(current, rampup_length): """Linear rampup""" assert current >= 0 and rampup_length >= 0 if current >= rampup_length: lr = 1.0 else: lr = current / rampup_length #print (lr) return lr
def rle_subseg( rle, start, end ): """Return a sub segment of an rle list.""" l = [] x = 0 for a, run in rle: if start: if start >= run: start -= run x += run continue x += start run -= start start = 0 if x >= end: break if x+run > end: run = end-x x += run l.append( (a, run) ) return l
def intbase(dlist, b=10): """convert list of digits in base b to integer""" y = 0 for d in dlist: y = y * b + d return y
def search_global_list(id, list): """[summary] Args: id ([type]): [description] list ([type]): [description] Returns: [type]: [description] """ for object in list: if object._id == id: return True return False
def sub_time_remaining_fmt(value): """ Finds the difference between the datetime value given and now() and returns appropriate humanize form """ if not value: return "EXPIRED" days = int(value/24) hours = value - days * 24 return "{} days {} hrs".format(days,hours)
def convert_to_celsius(fahrenheit: float) -> float: """ :param fahrenheit: float :return: float """ return (fahrenheit - 32.0) * 5.0 / 9.0
def numbits(num_values: int) -> int: """ Gets the minimum number of bits required to encode given number of different values. This method implements zserio built-in operator numBits. :param num_values: The number of different values from which to calculate number of bits. :returns: Number of bits required to encode num_values different values. """ if num_values == 0: return 0 if num_values == 1: return 1 return (num_values - 1).bit_length()
def _common_interval_domain(dom1, dom2): """ Determine the interval domain that is common to two interval domains Args: dom1: First interval domain dom2: Second interval domain Returns: Common domain """ return (max(dom1[0], dom2[0]), min(dom1[1], dom2[1]))
def aidstr(aid, ibs=None, notes=False): """ Helper to make a string from an aid """ if not notes: return 'aid%d' % (aid,) else: assert ibs is not None notes = ibs.get_annot_notes(aid) name = ibs.get_annot_names(aid) return 'aid%d-%r-%r' % (aid, str(name), str(notes))
def parse_distance(line): """Parse line to tuple with source, target and distance.""" cities, distance = line.split(' = ') source, target = cities.split(' to ') return source, target, int(distance)
def get_box_delta(halfwidth): """ Transform from halfwidth (arcsec) to the box_delta value which gets added to failure probability (in probit space). :param halfwidth: scalar or ndarray of box sizes (halfwidth, arcsec) :returns: box deltas """ # Coefficents for dependence of probability on search box size (halfwidth). From: # https://github.com/sot/skanb/blob/master/pea-test-set/fit_box_size_acq_prob.ipynb B1 = 0.96 B2 = -0.30 box120 = (halfwidth - 120) / 120 # normalized version of box, equal to 0.0 at nominal default box_delta = B1 * box120 + B2 * box120 ** 2 return box_delta
def form_array_from_string_line(line): """Begins the inversion count process by reading in the stdin file. Args: line: A string of input line (usually from a text file) with integers contained within, separated by spaces. Returns: array: List object (Python's standard 'array' type) featuring each of the integers as a separate item in the list.""" array = [int(n) for n in line.split()] return array
def Garbage(length, uppercase=True, lowercase=True, numbers=True, punctuation=False): """\ Return string containing garbage. """ import random uppercaseparts = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lowercaseparts = "abcdefghijklmnopqrstuvwxyz" numberparts = "0123456789" punctuationparts = ".-_" pool = "" if uppercase: pool += uppercaseparts if lowercase: pool += lowercaseparts if numbers: pool += numberparts if punctuation: pool += punctuationparts if not pool: pool = lowercaseparts garbage = "" while len(garbage) < length: garbage += random.choice(pool) return garbage
def __compare(x, y): """ Parameters ---------- x : comparable y : comparable Returns ------- result : int Returns 1 if x is larger than y, -1 if x is smaller then y, 0 if x equals y. """ if x > y: return 1 elif x < y: return -1 else: return 0
def _most_specific(a, b, default = None): """ If a and b are from the same hierarcy, return the more specific of [type(a), type(b)], or the default type if they are from different hierarchies. If default is None, return type(a), or type(b) if a does not have a type_cls """ if (hasattr(a, 'type_cls') and hasattr(a, 'type_cls')): if issubclass(b.type_cls, a.type_cls): return type(b) elif issubclass(a.type_cls, b.type_cls): return type(a) elif default is None: if hasattr(a, 'type_cls'): return type(a) elif hasattr(b, 'type_cls'): return type(b) return default
def replace_version(content, from_version, to_version): """ Replaces the value of the version specification value in the contents of ``contents`` from ``from_version`` to ``to_version``. :param content: The string containing version specification :param to_version: The new version to be set :return: (result_content, number of occurrences) """ frm_str = str(from_version) to_str = str(to_version) count = content.count(frm_str) result_setup_py = content.replace(frm_str, to_str, count) return result_setup_py, count
def __get_base_name(input_path): """ /foo/bar/test/folder/image_label.ext --> test/folder/image_label.ext """ return '/'.join(input_path.split('/')[-3:])
def row_has_lists(row: list) -> bool: """ Returns if the dataset has list or not. """ for item in row: if isinstance(item, list): return True return False
def format_resp(number, digits=4): """ Formats a number according to the RESP format. """ format_string = "%%-10.%dE" % digits return format_string % (number)
def face_is_edge(face): """Simple check to test whether given (temp, working) data is an edge, and not a real face.""" face_vert_loc_indices = face[0] face_vert_nor_indices = face[1] return len(face_vert_nor_indices) == 1 or len(face_vert_loc_indices) == 2
def unescape(string): """Return unescaped string.""" return bytes(string, 'ascii').decode('unicode_escape')
def test(name, age): """ Description: Function description information Args: name: name information age: age information Returns: Returned information Raises: IOError: An error occurred accessing the bigtable.Table object. """ name = 'tom' age = 11 return name, age
def firstDateIsEarlier(d1, d2): """ Given dates in the form {"year":1970, "month": 01, "day": 01}, return True if the first date is the earlier of the two """ yyyymmdd1 = str(d1["year"]) + str(d1["month"]) + str(d1["day"]) yyyymmdd2 = str(d2["year"]) + str(d2["month"]) + str(d2["day"]) return int(yyyymmdd1) < int(yyyymmdd2)
def schedule_url(year, semester, subject, kind="all"): """ kind: All, UGRD, or GRAD semester: Fall, Spring, or Summer subject: an int; a key from constants.SUBJECTS """ return ( "http://registrar-prod.unet.brandeis.edu/registrar/schedule/classes" f"/{year}/{semester}/{subject}/{kind}" )
def add_inverse(a, b): """Adds two values as a parallel connection. Parameters ---------- a: float, ndarray b: float, ndarray Returns ------- out: float the inverse of the sum of their inverses """ if a and b: return (a**(-1) + b**(-1))**(-1) else: return 0
def maxSeq(arr): """ A function to extract the sub-sequence of maximum length which is in ascending order. Parameters: arr (list); the sequence from which the sub-sequence of maximum length should be extracted Returns: maximumSeq (list); the sub-sequence of maximum length in ascending order Raises: TypeError: If user enters an invalid sequence such as dictionaries. """ try: if not(isinstance(arr,list)): #Checking if sequence is invalid or not raise TypeError maximumSeq = [] tempSeq = [] if len(arr) == 0 or len(arr) == 1: #if user provides empty or 1 element sequences return arr for i in range(len(arr)-1): tempSeq.append(arr[i]) #add each element to temporary sequence if arr[i+1]<arr[i]: #When the sequence breaks if len(maximumSeq) < len(tempSeq): maximumSeq = tempSeq tempSeq = [] #Reset the temporary sequence tempSeq.append(arr[-1]) #Adding the last element in arr, because loop stops at second last element if len(maximumSeq) < len(tempSeq): maximumSeq = tempSeq return maximumSeq except TypeError: print("Error: Please provide a sequence of type 'list' and try again.")
def order_verts(v1, v2): """ get order of vert inds for dihedral calculation. """ common_verts = set(v1).intersection(set(v2)) ordered_verts = [list(set(v1).difference(common_verts))[0], list(common_verts)[0], list(common_verts)[1], list(set(v2).difference(common_verts))[0]] return ordered_verts
def get_all_python_expression(content_trees, namespaces): """Return all the python expressions found in the whole document """ xpath_expr = ( "//text:a[starts-with(@xlink:href, 'py3o://')] | " "//text:user-field-get[starts-with(@text:name, 'py3o.')] | " "//table:table-cell/text:p[regexp:match(text(), '\${[^\${}]*}')] | " "//table:table-cell[regexp:match(@table:formula, '\${[^\${}]*}')]" ) res = [] for content_tree in content_trees: res.extend( content_tree.xpath( xpath_expr, namespaces=namespaces, ) ) return res
def _sanitize_numbers(uncleaned_numbers): """ Convert strings to integers if possible """ cleaned_numbers = [] for x in uncleaned_numbers: try: cleaned_numbers.append(int(x)) except ValueError: cleaned_numbers.append(x) return cleaned_numbers
def filter_empty_tracks(score): """ Filters out empty tracks and returns new score """ return list(filter( lambda score_track: score_track, score))
def region_states(pl, pr, region1, region3, region4, region5): """ :return: dictionary (region no.: p, rho, u), except for rarefaction region where the value is a string, obviously """ if pl > pr: return {'Region 1': region1, 'Region 2': 'RAREFACTION', 'Region 3': region3, 'Region 4': region4, 'Region 5': region5} else: return {'Region 1': region5, 'Region 2': region4, 'Region 3': region3, 'Region 4': 'RAREFACTION', 'Region 5': region1}
def find_all_indexes(input_str, search_str): """ Searches for substring/character in input_str :param input_str: String in which to search substring :param search_str: Substring to be searched :return: Indexes of all substring matching position """ l1 = [] length = len(input_str) index = 0 while index < length: i = input_str.find(search_str, index) if i == -1: return l1 l1.append(i) index = i + 1 return l1
def abs_distance(temp_vals): """Takes a list of numbers and returns the idex of the number in the list that has the smallest distance to 20. Args: temp_vals ([temp_vals]): List of numbers Returns: [Int]: Index of the number in the list that is closest to 20 Note: If multiple numbers in the list have the same distance to 20. The first value that is reached during iteration is kept. """ smallest_dist = float('inf') index_of_smallest = -1 for i in range(0, len(temp_vals)): val = temp_vals[i] try: value = float(val) except: value = float(val[:-3]) if abs(value - 20) < smallest_dist: smallest_dist = abs(value - 20) index_of_smallest = i return index_of_smallest
def extract_qa_bits(band_data, bit_location): """Get bit information from given position. Args: band_data (numpy.ma.masked_array) - The QA Raster Data bit_location (int) - The band bit value """ return band_data & (1 << bit_location)
def no_float_zeros(v): """ if a float that is equiv to integer - return int instead """ if v % 1 == 0: return int(v) else: return v
def dmp_copy(f, u): """ Create a new copy of a polynomial ``f`` in ``K[X]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.densebasic import dmp_copy >>> f = ZZ.map([[1], [1, 2]]) >>> dmp_copy(f, 1) [[1], [1, 2]] """ if not u: return list(f) v = u - 1 return [ dmp_copy(c, v) for c in f ]
def _NameValueListToDict(name_value_list): """Converts Name-Value list to dictionary. Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary of the pairs. If a string is simply NAME, then the value in the dictionary is set to True. If VALUE can be converted to an integer, it is. """ result = {} for item in name_value_list: tokens = item.split('=', 1) if len(tokens) == 2: # If we can make it an int, use that, otherwise, use the string. try: token_value = int(tokens[1]) except ValueError: token_value = tokens[1] # Set the variable to the supplied value. result[tokens[0]] = token_value else: # No value supplied, treat it as a boolean and set it. result[tokens[0]] = True return result
def semeval_Acc(y_true, y_pred, score, classes=4): """ Calculate "Acc" of sentiment classification task of SemEval-2014. """ assert classes in [2, 3, 4], "classes must be 2 or 3 or 4." if classes == 4: total=0 total_right=0 for i in range(len(y_true)): if y_true[i]==4:continue total+=1 tmp=y_pred[i] if tmp==4: if score[i][0]>=score[i][1] and score[i][0]>=score[i][2] and score[i][0]>=score[i][3]: tmp=0 elif score[i][1]>=score[i][0] and score[i][1]>=score[i][2] and score[i][1]>=score[i][3]: tmp=1 elif score[i][2]>=score[i][0] and score[i][2]>=score[i][1] and score[i][2]>=score[i][3]: tmp=2 else: tmp=3 if y_true[i]==tmp: total_right+=1 sentiment_Acc = total_right/total elif classes == 3: total=0 total_right=0 for i in range(len(y_true)): if y_true[i]>=3:continue total+=1 tmp=y_pred[i] if tmp>=3: if score[i][0]>=score[i][1] and score[i][0]>=score[i][2]: tmp=0 elif score[i][1]>=score[i][0] and score[i][1]>=score[i][2]: tmp=1 else: tmp=2 if y_true[i]==tmp: total_right+=1 sentiment_Acc = total_right/total else: total=0 total_right=0 for i in range(len(y_true)): if y_true[i]>=2:continue #or y_true[i]==1:continue total+=1 tmp=y_pred[i] if tmp>=2: #or tmp==1: if score[i][0]>=score[i][1]: tmp=0 else: tmp=1 if y_true[i]==tmp: total_right+=1 sentiment_Acc = total_right/total return sentiment_Acc
def has_file_allowed_extension(filename, extensions): """Checks if a file is an allowed extension. Args: filename (string): path to a file extensions (iterable of strings): extensions to consider (lowercase) Returns: bool: True if the filename ends with one of given extensions """ filename_lower = filename.lower() return any(filename_lower.endswith(ext) for ext in extensions)
def form_binary_patterns(k: int) -> list: """ Return a list of strings containing all binary numbers of length not exceeding 'k' (with leading zeroes) """ result = [] format_string = '{{:0{}b}}'.format(k) for n in range(2 ** k): result.append(format_string.format(n)) return result
def sqlize_list(l): """ magic """ return ', '.join(map(lambda x: "(\"{}\")".format(x), l))
def alternative_string_arrange(first_str: str, second_str: str) -> str: """ Return the alternative arrangements of the two strings. :param first_str: :param second_str: :return: String >>> alternative_string_arrange("ABCD", "XY") 'AXBYCD' >>> alternative_string_arrange("XY", "ABCD") 'XAYBCD' >>> alternative_string_arrange("AB", "XYZ") 'AXBYZ' >>> alternative_string_arrange("ABC", "") 'ABC' """ first_str_length: int = len(first_str) second_str_length: int = len(second_str) abs_length: int = ( first_str_length if first_str_length > second_str_length else second_str_length ) output_list: list = [] for char_count in range(abs_length): if char_count < first_str_length: output_list.append(first_str[char_count]) if char_count < second_str_length: output_list.append(second_str[char_count]) return "".join(output_list)
def cohens_d(xbar, mu, s): """ Get the Cohen's d for a sample. Parameters ---------- > xbar: mean of the sample > mu: mean of the population > s: standard distribution of the sample Returns ------- Cohen's d, or the number of standard deviations the sample mean is away from the population mean """ return (xbar - mu) / s
def camelcase(string): """Convert a snake_cased string to camelCase.""" if '_' not in string or string.startswith('_'): return string return ''.join([ x.capitalize() if i > 0 else x for i, x in enumerate(string.split('_')) ])
def wrap_text(text, line_length): """Wrap a string of text based on the given line length. Words that are longer than the line length will be split with a dash. Arguments: text (Str): the text that will be wrapped line_length (Int): the max length of a line Returns: List [Str] """ words = text.split() lines = [] while len(words) > 0: line = "" while len(line) < line_length and len(words) > 0: characters_left = line_length - len(line) if characters_left >= len(words[0]): word = words.pop(0) else: if len(line) == 0: # Word is too long for line, split word across lines length = line_length - 1 # Give room for the dash word, words[0] = (words[0][:length], words[0][length:]) word += "-" else: break line = " ".join((line, word)).strip() lines.append(line) return lines
def ordinal(num: int) -> str: """ Returns the ordinal representation of a number Examples: 11: 11th 13: 13th 14: 14th 3: 3rd 5: 5th :param num: :return: """ return ( f"{num}th" if 11 <= (num % 100) <= 13 else f"{num}{['th', 'st', 'nd', 'rd', 'th'][min(num % 10, 4)]}" )
def only_one_image(supdata, max): """Place have one image""" return max == 1 or isinstance(supdata['photo_ref'], str)
def pad_range_1d(low, high, amount): """Pad range by `amount`, keeping the range centered.""" pad = amount / 2 return low - pad, high + pad
def resolve_insee_sqlfile(tablename): """Retrieve the name of the SQL file according to the name of the table """ name = "_".join(tablename.split("_")[:-1]) return "create_infra_" + name + ".sql"
def get_identitypool_id(identitypools, name): """ Get identity pool id based on the name provided. """ for identitypool in identitypools: if identitypool["Name"] == name: return identitypool["Id"]
def reverse(A): """ reverse an array: [3,6,7,9] = [9,7,6,3]~ """ A_len = len(A) for i in range(A_len // 2): print("-----------------------") print("Renge: %s" % i) k = A_len - i - 1 print("k = %s" % k) print("Before Change A[i] = %s, A[k] = %s " % (A[i], A[k])) A[i], A[k] = A[k], A[i] print("After Change A[i] = %s, A[k] = %s " % (A[i], A[k])) print("Array at time: %s" % A) print("------------------------") return A
def get_html_subsection(name): """ Return a subsection as HTML, with the given name :param name: subsection name :type name: str :rtype: str """ return "<h2>{}</h2>".format(name)
def chrom_header(sample_name: str) -> str: """Create final header line. Single sample only""" s = "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t{0}".format( sample_name ) return s
def ine(x): """convert "" to None""" if not x: return None return x
def parse_imslp_date(year, month, day): """Return a date from imslp. Only return if all 3 components exist, and are integers This prevents parsing items that only have some components (e.g. yyyy-mm), or approximate values (e.g. c 1600)""" if year and month and day: try: year = int(year) month = int(month) day = int(day) return f"{year:d}-{month:02d}-{day:02d}" except ValueError: return None
def nl(h, q): """ h is a public key for NTRU Cryptosystem. The private key [f, g] is in NTRU Lattice [[I, H], [O, qI]], where H = cyclic permutations of the coefficients of h. >>> h = [1, 2, 3] >>> nl(h, 32) [[ 1, 0, 0, 1, 2, 3], [ 0, 1, 0, 3, 1, 2], [ 0, 0, 1, 2, 3, 1], [ 0, 0, 0, 32, 0, 0], [ 0, 0, 0, 0, 32, 0], [ 0, 0, 0, 0, 0, 32]] """ lh = len(h) out = [[h[(-i+j)%lh] for j in range(lh)] for i in range(lh)] for i in range(lh): I, I[i] = lh*[0], 1 out[i] = I + out[i] for i in range(lh): Q, Q[i] = lh*[0], q out = out + [lh*[0] + Q] return out
def _transpose(list_): """ Transposes a list of lists. """ transposed_ = [[row[col] for row in list_] for col in range(len(list_[0]))] transposed = [col for col in transposed_ if col] return transposed
def pi(dest, E): """Return ``s`` in ``(s, d, w)`` with ``d`` == `dest` and `w` minimized. :param dest: destination vertex :type dest: int :param E: a set of edges :type E: [(int, int, float), ...] :return: vertex with cheapest edge connected to `dest` :rtype: int or None """ src, weight = None, 0 for (s, d, w) in E: if d == dest: if src is None or w < weight: src = s weight = w return src
def dictlist_lookup(dictlist, key, value): """ From a list of dicts, retrieve those elements for which <key> is <value>. """ return [el for el in dictlist if el.get(key)==value]
def three_points_to_rectangle_params(a, b, c): """Takes three corners of a rectangle and returns rectangle parameters for matplotlib (xy, width, height)""" x_low = min([a[0], b[0], c[0]]) y_low = min([a[1], b[1], c[1]]) x_high = max([a[0], b[0], c[0]]) y_high = max([a[1], b[1], c[1]]) xy = (x_low, y_low) width = x_high - x_low height = y_high - y_low return xy, width, height
def sum_of_multiples(limit, multiples): """ Find the sum of all the unique multiples of particular numbers up to but not including that number. :param limit int - The highest resulting product of multiples. :param multiples list - The multiples to multiply and sum. :return int - The total or sum of multiples that meet the criteria. """ total = 0 if len(multiples) == 0: return total factor = 1 products = {} limit_reached = False last_change_counter = 0 while not limit_reached: last_total = total for index, number in enumerate(multiples): result = number * factor # skip results we already stored if products.get(result) is not None: continue products[result] = number if result < limit: total += result elif index == 0: # Cancle out if the smallest (index 0) multiple exceeds limit limit_reached = True factor += 1 # cancel out if not increasing over time if last_change_counter > 10: break if last_total == total: last_change_counter += 1 else: last_change_counter = 0 return total
def removeByTypesFromNested(l, typesRemove : tuple): """Remove items in the input iterable l which are of one of the types in typesRemove Args: l : Input iterable typesRemove (tuple): Input types to be removed Returns: Iteratable with all nested items of the types removed """ # remove all the bytes l = filter(lambda i : not isinstance(i, typesRemove), l) # recurse into the sublist l = [ removeByTypesFromNested(i, typesRemove) if isinstance(i, (list, tuple)) else i for i in l ] # clean up the empty sublists l = [ i for i in l if not isinstance(i, (list, tuple)) or len(i) > 0 ] return l
def grid_enc_inv (w,l,k): """ Note: i, j, and c all start at 1 """ i = ((k-1) % w)+1 j = (((k - i) % (w*l)))/w + 1 c = (k - i - ((j - 1) * w))/(w*l) + 1 return (i,j,c)
def check_is_left(name): """ Checks if the name belongs to a 'left' sequence (/1). Returns True or False. Handles both Casava formats: seq/1 and 'seq::... 1::...' """ if ' ' in name: # handle '@name 1:rst' name, rest = name.split(' ', 1) if rest.startswith('1:'): return True elif name.endswith('/1'): # handle name/1 return True return False
def text_get_line(text, predicate): """Returns the first line that matches the given predicate.""" for line in text.split("\n"): if predicate(line): return line return ""
def _fetch_first_result(fget, fset, fdel, apply_func, value_not_found=None): """Fetch first non-none/empty result of applying ``apply_func``.""" for f in filter(None, (fget, fset, fdel)): result = apply_func(f) if result: return result return value_not_found
def median(seq): """Returns the median of *seq* - the numeric value separating the higher half of a sample from the lower half. If there is an even number of elements in *seq*, it returns the mean of the two middle values. """ sseq = sorted(seq) length = len(seq) if length % 2 == 1: return sseq[int((length - 1) / 2)] else: return (sseq[int((length - 1) / 2)] + sseq[int(length / 2)]) / 2
def _stringify_performance_states(state_dict): """ Stringifies performance states across multiple gpus Args: state_dict (dict(str)): a dictionary of gpu_id performance state values Returns: str: a stringified version of the dictionary with gpu_id::performance state|gpu_id2::performance_state2 format """ return "|".join("::".join(map(lambda x: str(x), z)) for z in state_dict.items())
def _tagshortcuts(event, type, id): """given type=conv, type=convuser, id=here expands to event.conv_id""" if id == "here": if type not in ["conv", "convuser"]: raise TypeError("here cannot be used for type {}".format(type)) id = event.conv_id if type == "convuser": id += "|*" return type, id
def parse_lambda_arn(function_arn): """Extract info on the current environment from the lambda function ARN Parses the invoked_function_arn from the given context object to get the name of the currently running alias (either production or development) and the name of the function. Example: arn:aws:lambda:aws-region:acct-id:function:stream_alert:production Args: function_arn (str): The AWS Lambda function ARN Returns: dict: { 'region': 'region_name', 'account_id': 'account_id', 'function_name': 'function_name', 'qualifier': 'qualifier' } """ split_arn = function_arn.split(':') return { 'region': split_arn[3], 'account_id': split_arn[4], 'function_name': split_arn[6], 'qualifier': split_arn[7] if len(split_arn) == 8 else None # optional qualifier }
def giftcertificate_order_summary(order): """Output a formatted block giving attached gift certifificate details.""" return {'order' : order}
def _hex_to_triplet(h): """Convert an hexadecimal color to a triplet of int8 integers.""" if h.startswith('#'): h = h[1:] return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
def myFilter(f, L): """puts a function on each element of list""" def filterHelp(f, L, lst): if(L == []): return lst if(f(L[0])==True): return filterHelp(f, L[1:], lst + [L[0]]) else: return filterHelp(f, L[1:], lst) return filterHelp(f, L, [])
def initialize_beliefs(grid): """ Fill grid with intializ beliefs (continious distribution) """ height = len(grid) width = len(grid[0]) area = height * width belief_per_cell = 1.0 / area beliefs = [] for i in range(height): row = [] for j in range(width): row.append(belief_per_cell) beliefs.append(row) return beliefs
def get_mpi_env(envs): """get the slurm command for setting the environment """ cmd = '' for k, v in envs.items(): cmd += '%s=%s ' % (k, str(v)) return cmd