content
stringlengths
42
6.51k
def bx_encode(n, alphabet): """ Encodes an integer :attr:`n` in base ``len(alphabet)`` with digits in :attr:`alphabet`. :: # 'ba' bx_encode(3, 'abc') :param n: a positive integer. :param alphabet: a 0-based iterable. """ if not isinstance(n, int): raise TypeError("an integer is required") base = len(alphabet) if n == 0: return alphabet[0] digits = [] while n > 0: digits.append(alphabet[n % base]) n = n // base digits.reverse() return "".join(digits)
def largest_product(arr): """ Returns the largest_product inside an array incased inside a matrix. input <--- Array of array with 2 value inside each output <--- Largest Product of pair inside Matrix """ largest_product = 0 for container in arr: x, y = container if x * y > largest_product: largest_product = x * y return largest_product
def get_health_multiple(obj): """ get individual scores for 4 repo components. """ branch_count = 0 branch_age = 0 issues = 0 pull_requests = 0 denom = len(obj["repo"]) assert all(isinstance(obj[x], list) for x in obj) assert all(len(obj[x]) == denom for x in obj) for brc in obj["branch count"]: if brc >= 3: branch_count += 1 for mba in obj["min branch age (days)"]: if mba >= 90: branch_age += 1 for i in obj["issues"]: if i > 0: issues += 1 for prq in obj["pull requests"]: if prq > 0: pull_requests += 1 return denom, branch_count, branch_age, issues, pull_requests
def as_string(raw_data): """Converts the given raw bytes to a string (removes NULL)""" return bytearray(raw_data[:-1])
def unsignedIntegerToBytes(integer, numbytes): """Converts an unsigned integer into a sequence of bytes, LSB first. integer -- the number to be converted numbytes -- the number of bytes to be used in representing the integer """ bytes = list(range(numbytes)) for i in bytes: bytes[i] = int(integer%256) integer -= integer%256 integer = int(integer//256) if integer>0: raise IndexError('Overflow in conversion between uint and byte list.') else: return bytes
def scale(vertex, scale_factor): """Move a coordinate closer / further from origin. If done for all vertices in a 2d shape, it has the effect of changing the size of the whole shape.""" [vertex_x, vertex_y] = vertex return [vertex_x * scale_factor, vertex_y * scale_factor]
def nb_arcs_from_density(n: int, d: int) -> int: """ Determines how many arcs in a directed graph of n and density d. Using a function I derived that had the follow characteristics m(d=0) = n, m(d=0.5) = (n)n-1/2 + 1, m(d=1) = n(n-1) """ assert n > 1 assert 0 <= d <= 1 return round((2 * n - 4) * d ** 2 + d * (n - 2) ** 2 + n)
def get_path_to_h1_dir(name: str, data_directory: str) -> str: """Get the path to the directory where the star formation data should be stored Args: name (str): Name of the galaxy data_directory (str): dr2 data directory Returns: str: Path to h1 dir """ return f"{data_directory}/h1/{name}"
def sizeof_fmt(num, suffix='B'): """ Print in human friendly format """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def dictify(nl_tups): """ Return dict if all keys unique, otherwise dont modify """ as_dict = dict(nl_tups) if len(as_dict) == len(nl_tups): return as_dict return nl_tups
def find_span_linear(degree, knot_vector, num_ctrlpts, knot, **kwargs): """ Finds the span of a single knot over the knot vector using linear search. Alternative implementation for the Algorithm A2.1 from The NURBS Book by Piegl & Tiller. :param degree: degree :type degree: int :param knot_vector: knot vector :type knot_vector: list, tuple :param num_ctrlpts: number of control points :type num_ctrlpts: int :param knot: knot :type knot: float :return: span of the knot over the knot vector :rtype: int """ span = 0 # Knot span index starts from zero while span < num_ctrlpts and knot_vector[span] <= knot: span += 1 return span - 1
def calculatePixel(posMN, overlap, targetSize, shape): """Get the corresponding pixel start end x/y values to the tile defined by row/column in posMN. Args: posMN ([type]): tile as in row/column overlap ([type]): overlap between tiles as defined by getTilePositions targetSize ([type]): Size of the tiles shape ([type]): shape of the tiled image Returns: [type]: tuple of start/end x/y pixels of the tile """ posXY = ( int(posMN[0] * (targetSize - overlap)), int(posMN[1] * (targetSize - overlap)), int(posMN[0] * (targetSize - overlap) + targetSize), int(posMN[1] * (targetSize - overlap) + targetSize), ) # shift the last one if it goes over the edge of the image if posMN[1] * (targetSize - overlap) + targetSize > shape[1]: shift = int(posMN[1] * (targetSize - overlap) + targetSize) - shape[1] posXY = (posXY[0], posXY[1] - shift, posXY[2], posXY[3] - shift) # print('Shifted vert for ', shift, 'pixel') if posMN[0] * (targetSize - overlap) + targetSize > shape[0]: shift = int(posMN[0] * (targetSize - overlap) + targetSize) - shape[0] posXY = (posXY[0] - shift, posXY[1], posXY[2] - shift, posXY[3]) # print('Shifted hor for ', shift, 'pixel') return posXY
def reverse_captcha(string: str) -> int: """ Solves the AOC first puzzle, part two. """ summation = 0 half = len(string) / 2 for i, char in enumerate(string): if char == string[int((i + half) % len(string))]: summation += int(char) return summation
def get_bitstream_type(field, db_object): """Retrieves the bitstream type from the device image object""" device_image = getattr(db_object, 'image', None) if device_image: return device_image.bitstream_type return None
def retrieve_team_abbreviation(team_name: str) -> str: """Retrieves the team abbreviation from the team name. Args: team_name (str): The full team name or team's home city. Raises: ValueError: If team name is not found in the team_abbreviation_mapping dict. Returns: str: The team abbreviation. """ team_abbreviation_mapping = { ("Arizona", "Arizona Cardinals"): "ARI", ("Atlanta", "Atlanta Falcons"): "ATL", ("Buffalo", "Buffalo Bills"): "BUF", ("Baltimore", "Baltimore Ravens"): "BAL", ("Carolina", "Carolina Panthers"): "CAR", ("Chicago", "Chicago Bears"): "CHI", ("Cincinnati", "Cincinnati Bengals"): "CIN", ("Cleveland", "Cleveland Browns"): "CLE", ("Dallas", "Dallas Cowboys"): "DAL", ("Denver", "Denver Broncos"): "DEN", ("Detroit", "Detroit Lions"): "DET", ("GreenBay", "Green Bay Packers"): "GNB", ("Houston", "Houston Texans"): "HOU", ("Indianapolis", "Indianapolis Colts"): "IND", ("Jacksonville", "Jacksonville Jaguars"): "JAX", ("KansasCity", "Kansas City Chiefs", "KCChiefs", "Kansas"): "KAN", ("LAChargers", "Los Angeles Chargers", "LosAngeles"): "LAC", ("Oakland", "Oakland Raiders"): "OAK", ("LARams", "Los Angeles Rams"): "LAR", ("LasVegas", "Las Vegas Raiders", "LVRaiders"): "LVR", ("Miami", "Miami Dolphins"): "MIA", ("Minnesota", "Minnesota Vikings"): "MIN", ("NewEngland", "New England Patriots"): "NWE", ("NewOrleans", "New Orleans Saints"): "NOR", ("NYGiants", "New York Giants"): "NYG", ("NYJets", "New York Jets"): "NYJ", ("Philadelphia", "Philadelphia Eagles"): "PHI", ("Pittsburgh", "Pittsburgh Steelers"): "PIT", ("San Diego", "San Diego Chargers", "SanDiego"): "SDG", ("SanFrancisco", "San Francisco 49ers"): "SFO", ("St Louis", "St. Louis Rams", "St.Louis"): "STL", ("Seattle", "Seattle Seahawks"): "SEA", ("TampaBay", "Tampa Bay Buccaneers", "Tampa"): "TAM", ("Tennessee", "Tennessee Titans"): "TEN", ( "Washington", "Washingtom", "Washington Football Team", "Washington Redskins", ): "WAS", } for k, v in team_abbreviation_mapping.items(): if team_name in k: return v raise ValueError(f"Team name {team_name} not found in team_abbreviation_mapping")
def zpad(x, l): """ Left zero pad value `x` at least to length `l`. """ return b"\x00" * max(0, l - len(x)) + x
def value(x): """Returns 0 if x is 'sufficiently close' to zero, +/- 1E-9""" epsilon = pow(1, -9) if x >= 0 and x <= epsilon: return 0 if x < 0 and -x <= epsilon: return 0 return x
def return_failure(message, error_code=500): """ Generates JSON for a failed API request """ return {"success": False, "error": message, "error_code": error_code}
def is_aws_domain(domain): """ Is the provided domain within the amazonaws.com zone? """ return domain.endswith(".amazonaws.com")
def get_output_video_length(timestamps: list): """ Calculates the output video length from the timestamps, each portion length would be end - start Parameters ---------- timestamps : list timestamps for the video to edit Returns ------- int final video length References ---------- timestamps has list of start and end like : [[start, end], [start, end]] to get a length of each portion end - start to get final length finalLength += end[i] - start[i] ; i: 0 -> len(timestamps) """ video_length = 0 if len(timestamps) < 0: return 0 for start, end in timestamps: video_length += abs(end - start) return video_length
def unwrapText(text): """Unwrap text to display in message boxes. This just removes all newlines. If you want to insert newlines, use \\r.""" # Removes newlines text = text.replace("\n", "") # Remove double/triple/etc spaces text = text.lstrip() for i in range(10): text = text.replace(" ", " ") # Convert \\r newlines text = text.replace("\r", "\n") # Remove spaces after newlines text = text.replace("\n ", "\n") return text
def titlefirst(value): """Put the first letter into uppercase. """ if len(value) < 1: return value.upper() else: return value[0].upper() + value[1:]
def allowed_file(filename, checklist): """ checks if a file extension is one of the allowed extensions """ return '.' and filename.rsplit(".", 1)[1].lower() in checklist
def unpack_vlq(data): """Return the first VLQ number and byte offset from a list of bytes.""" offset = 0 value = 0 while True: tmp = data[offset] value = (value << 7) | (tmp & 0x7f) offset += 1 if tmp & 0x80 == 0: break return value, offset
def ScalarAverageRamanActivityTensor(ramanTensor): """ Average a Raman-activity tensor to obtain a scalar intensity. """ # This formula came from D. Porezag and M. R. Pederson, Phys. Rev. B: Condens. Matter Mater. Phys., 1996, 54, 7830. alpha = (ramanTensor[0][0] + ramanTensor[1][1] + ramanTensor[2][2]) / 3.0; betaSquared = 0.5 * ( (ramanTensor[0][0] - ramanTensor[1][1]) ** 2 + (ramanTensor[0][0] - ramanTensor[2][2]) ** 2 + (ramanTensor[1][1] - ramanTensor[2][2]) ** 2 + 6.0 * (ramanTensor[0][1] ** 2 + ramanTensor[0][2] ** 2 + ramanTensor[1][2] ** 2) ); return 45.0 * alpha ** 2 + 7.0 * betaSquared;
def _check_filesys_for_sadpt(savefs_dct, es_keyword_dct): """ See if a sadpt exists """ # Find the TS cnf_save_fs, cnf_save_locs = savefs_dct['runlvl_cnf_fs'] overwrite = es_keyword_dct['overwrite'] if not cnf_save_locs: print('No transition state found in filesys', 'at {} level...'.format(es_keyword_dct['runlvl']), 'Proceeding to find it...') _run = True elif overwrite: print('User specified to overwrite energy with new run...') _run = True else: print('TS found and saved previously in ', cnf_save_fs[-1].path(cnf_save_locs)) _run = False return _run
def assert_positive_int(name: str, value: str) -> int: """ Makes sure the value is a positive integer, otherwise raises AssertionError :param name: Argument name :param value: Value :return: Value as integer """ try: int_value = int(value) except ValueError: raise AssertionError( "Expected a positive integer for {}, but got `{}`".format(name, value)) if int_value < 1: AssertionError( "Expected a positive integer for {}, but got `{}`".format(name, value)) return int_value
def get_digest_msid(digest_object): """given a digest object try to get the msid from the doi""" try: doi = getattr(digest_object, "doi") return doi.split(".")[-1] except AttributeError: return None return None
def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ cleaned_data = [] """ Now lets loop through predictions, ages, and net_worths to find the largest residual errors, from the description, we know that this is the difference between the prediction and the net worth which is : prediction - net_worths. """ for pred, a, net_w in zip(predictions, ages, net_worths): cleaned_data.append((a, net_w, pred - net_w)) cleaned_data.sort(key=lambda i: i[2]) # Sort the data by the 2nd index (third element, which is the error) return cleaned_data[:81]
def _is_large_prime(num): """Inefficient primality test, but we can get away with this simple implementation because we don't expect users to be running print_fizzbuzz(n) for Fib(n) > 514229""" if not num % 2 or not num % 5: return False test = 5 while test*test <= num: if not num % test or not num % (test+2): return False test += 6 return True
def distance(x1, y1, x2, y2): """ Distance between two points (x1, y1), (x2, y2). """ return pow((pow(x1 - x2, 2) + pow(y1 - y2, 2)), 0.5)
def everyone(seq,method=bool): """Returns last that is true or first that is false""" if not seq: return False for s in seq: if not method(s): return s if not s else None return seq[-1]
def is_unique(digit: str) -> bool: """Returns if a digit can be deduced solely by the length of its representation""" return len(digit) in {2, 3, 4, 7}
def is_leximin_better(x: list, y: list): """ >>> is_leximin_better([6,2,4],[7,3,1]) True >>> is_leximin_better([6,2,4],[3,3,3]) False """ return sorted(x) > sorted(y)
def rgb8_to_hsl(rgb): """Takes a rgb8 tuple, returns a hsl tuple.""" HUE_MAX = 6 r = rgb[0] / 255.0 g = rgb[1] / 255.0 b = rgb[2] / 255.0 cmin = min(r, g, b) cmax = max(r, g, b) delta = cmax - cmin h = 0 s = 0 l = (cmax + cmin) if delta != 0: if l < 0.5: s = delta / l else: s = delta / (2 - l) if r == cmax: h = (g - b) / delta elif g == cmax: h = 2 + (b - r) / delta elif b == cmax: h = 4 + (r - g) / delta return h, s, l
def google_form_likert(x): """ clean google_form_likert as numeric float value. """ try: output = float(x[0]) return output except: return x
def get_duplicate_indices1(words): """Given a list of words, loop through the words and check for each word if it occurs more than once. If so return the index of its first ocurrence. For example in the following list 'is' and 'it' occurr more than once, and they are at indices 0 and 1 so you would return [0, 1]: ['is', 'it', 'true', 'or', 'is', 'it', 'not?'] => [0, 1] Make sure the returning list is unique and sorted in ascending order.""" duplicate_words = {word for word in words if words.count(word) > 1} return sorted([words.index(word) for word in duplicate_words])
def cscan_branch1(coo_names): """ scan branch 1 directory name """ return '_'.join(sorted(coo_names))
def type_name(t) -> str: """ Gets a string naming the type :param t: value to get type if :return: the type name """ if not isinstance(t, type): t = type(t) # if isinstance(t, type): # raise TypeError('T is "type"') return getattr(t, '__name__', repr(t))
def rcumode2antset_eu(rcumode): """ Map rcumode to antenna set for EU stations. Antenna set is only meaningful in Dutch stations. But it is required in beamctl arguments. Parameters ---------- rcumode: int The RCU mode. Returns ------- antset: str Antenna set name. """ rcumode = int(rcumode) if rcumode == 3 or rcumode == 4: antset = 'LBA_INNER' elif rcumode == 5 or rcumode == 6 or rcumode == 7: antset = 'HBA_JOINED' else: raise ValueError("Undefined rcumode: {}.".format(rcumode)) return antset
def select_span(cropped_length, original_length, center_point): """ Given a span of original_length pixels, choose a starting point for a new span of cropped_length with center_point as close to the center as possible. In this example we have an original span of 50 and want to crop that to 40: Original: |-----------------------------------X------------| Crop with ideal center point: |-------------------X------------------| Clamped to actual leeway: |-------------------------X------------| If the original center point is 37/50 and the center point of the new span is 21/40, a crop with the ideal center would start at 37 - 21 = 16. However, the crop is just 10 smaller than the original, so that's our positioning leeway. Original: |------X-----------------------------------------| Crop with ideal center point: |-------------------X------------------| Clamped to actual leeway: |------X-------------------------------| If the original center point is 8/50 and the center point of the new span is 21/40, a crop with the ideal center would start at 8 - 21 = -13. This gets clamped to zero. """ original_center_point = original_length * center_point # center_point is a float 0..1 ideal_center_point = cropped_length / 2 leeway = original_length - cropped_length ideal_crop_origin = original_center_point - ideal_center_point clamped = min(max(ideal_crop_origin, 0), leeway) return round(clamped)
def dic_remove_entries(in_dic, filter_dic): """ Remove entries from in_dic dictionary, given key values from filter_dic. >>> in_dic = {'id1': 10, 'id2': 15, 'id3':20} >>> filter_dic = {'id2' : 1} >>> dic_remove_entries(in_dic, filter_dic) {'id1': 10, 'id3': 20} """ # Checks. assert in_dic, "given dictionary in_dic empty" assert filter_dic, "given dictionary filter_dic empty" # Filter. for filter_id in filter_dic: if filter_id in in_dic: del in_dic[filter_id] return in_dic
def qname_encode(name): """Encode QNAME without using labels.""" def _enc_word(word): return bytes([len(word) & 0xFF]) + word.encode("ascii") return b"".join([_enc_word(x) for x in name.split(".")]) + b"\x00"
def bar(value, minimum, maximum, size=20): """Print a bar from minimum to value""" sections = int(size * (value - minimum) / (maximum - minimum)) return '|' * sections
def rotacionar_1(lista: list, k: int) -> list: """ >>> lista = [1, 2, 3, 4, 5, 6, 7] >>> rotacionar_1(lista, 3) [5, 6, 7, 1, 2, 3, 4] >>> rotacionar_1(lista, 5) [3, 4, 5, 6, 7, 1, 2] """ tamanho = len(lista) parte_1 = lista[tamanho-k:] parte_2 = lista[:tamanho-k] return parte_1 + parte_2
def sort(x): """Sorts list, if input is a list Parameters ---------- x : List Outputs ------- Sorted list """ if isinstance(x,list): return sorted(x) else: return x
def find_or_create_node(branch, key): """ Given a list, look for dictionary with a key matching key and return it's value. If it doesn't exist, create it with the value of an empty list and return that. """ for node in branch: if not isinstance(node, dict): continue if key in node: return node[key] new_branch = [] node = {key: new_branch} branch.append(node) return new_branch
def dedupe(iterable): """Returns a list of elements in ``iterable`` with all dupes removed. The order of the elements is preserved. """ result = [] seen = {} for item in iterable: if item in seen: continue seen[item] = 1 result.append(item) return result
def comp_dice_score(tp, fp, tn, fn): """ Binary dice score. """ if tp + fp + fn == 0: return 1 else: return (2*tp) / (2*tp + fp + fn)
def is_str(txt): """test if a value's type is string Parameters ---------- txt: value to test Returns ------- bool: True if txt is str, False otherwise """ return type(txt) == str
def computeLastHitValues(blocks): """ given the query length and 'blacks' sting from a last hit return the: match length the blocks string looks something like this: "73,0:1,15,0:1,13,0:1,9" where integer elements indicate lenghts of matches and colon separated elements indicate lengths of gaps """ matchLen = 0 for segment in blocks.split(','): try: matchLen += int(segment) except ValueError: (hml, qml) = segment.split(":") mml = max(int(hml), int(qml)) matchLen += mml return matchLen
def get_ks001_extension(filename: str, pipe: str = "|") -> str: """ get extension of filename filename extension is the string going from the end till the last dictionary separator. For example |a=5_b=2|.csv will return "csv" For example |a=5_b=2|.original.csv will return "original.csv" For example |a=5_b=2|csv will lead to UB :param filename: the filename to check. Implicitly under KS001 format :param pipe: the character used by KS001 to divide dictionaries :return: the extension. May contain multiple "." """ return filename[filename.rfind(pipe)+2:]
def compare(x, y): """Write a compare function that returns 1 if x > y, 0 if x == y, and -1 if x < y""" if x > y: return 1 elif x < y: return -1 else: return 0
def get_recursively(search_dict: dict, field: str) -> list: """Take a dict with nested lists and dicts, and searche all dicts for a key of the field provided. https://stackoverflow.com/a/20254842 Args: search_dict (dict): Dictionary to search field (str): Field to search for Returns: list: List of values of field """ fields_found = [] for key, value in search_dict.items(): if key == field: fields_found.append(value) elif isinstance(value, dict): results = get_recursively(value, field) for result in results: fields_found.append(result) elif isinstance(value, list): for item in value: if isinstance(item, dict): more_results = get_recursively(item, field) for another_result in more_results: fields_found.append(another_result) return fields_found
def get_unique_name(new_name, name_list, addendum='_new'): """Utility function for returning a name not contained in a list""" while new_name in name_list: new_name += addendum return new_name
def _chargrams(s,n): """Generate character n-grams. """ return [s[i:i+n] for i in range(len(s)-n+1)]
def relation_from_expr(expr): """ get relation from a tvm expression """ relation_lst = [] return relation_lst
def is_single_bool(val): """ Checks whether a variable is a boolean. Parameters ---------- val The variable to check. Returns ------- bool True if the variable is a boolean. Otherwise False. """ return type(val) == type(True)
def _gen_neighbor_keys(result_prefix="") -> tuple: """Generate neighbor keys for other functions to store/access info in adata. Parameters ---------- result_prefix : str, optional generate keys based on this prefix, by default "" Returns ------- tuple: A tuple consisting of (conn_key, dist_key, neighbor_key) """ if result_prefix: result_prefix = result_prefix if result_prefix.endswith("_") else result_prefix + "_" if result_prefix is None: result_prefix = "" conn_key, dist_key, neighbor_key = ( result_prefix + "connectivities", result_prefix + "distances", result_prefix + "neighbors", ) return conn_key, dist_key, neighbor_key
def all_same(items): """Determine if all items of a list are the same item. Args: items: List to verify Returns: result: Result """ # Do test and return result = all(item == items[0] for item in items) return result
def interval(seconds): """ gives back interval as tuple @return: (weeks, days, hours, minutes, seconds) formats string for fermtime_remaining returns the formatted string for text-field """ WEEK = 60 * 60 * 24 * 7 DAY = 60 * 60 * 24 HOUR = 60 * 60 MINUTE = 60 weeks = seconds // WEEK seconds = seconds % WEEK days = seconds // DAY seconds = seconds % DAY hours = seconds // HOUR seconds = seconds % HOUR minutes = seconds // MINUTE seconds = seconds % MINUTE if weeks >= 1: remaining_time = ("Week:%d Days:%d Hours:%02d:%02d" % (int(weeks), int(days), int(hours), int(minutes))) return remaining_time elif weeks == 0 and days >= 1: remaining_time = ("Days:%d Hours:%02d:%02d:%02d" % (int(days), int(hours), int(minutes), int(seconds))) return remaining_time elif weeks == 0 and days == 0: remaining_time = ("Hours:%02d:%02d:%02d" % (int(hours), int(minutes), int(seconds))) return remaining_time else: pass pass
def get_deleted_row(curr_records, prev_records): """ Returns ------- row_num : int Index of the deleted row. Notes ----- Assumes a row was in fact deleted. """ records = zip(curr_records, prev_records) for i, (curr_record, prev_record) in enumerate(records): if curr_record != prev_record: return i # last row was deleted return len(curr_records)
def read_bool(value): """converts a value to boolean""" if hasattr(value, 'lower'): if value.lower() in ['false', 'no', '0', 'off']: return False return bool(value)
def byte_to_int16(lsb, msb): """ Converts two bytes (lsb, msb) to an int16 :param lsb: Least significant bit :param msb: Most significant bit :return: the 16 bit integer from the two bytes """ return (msb << 8) | lsb
def is_url(str_): """ heuristic check if str is url formatted """ return any([ str_.startswith('http://'), str_.startswith('https://'), str_.startswith('www.'), '.org/' in str_, '.com/' in str_, ])
def sort_dict_by_value(dic, reverse=False): """ sort a dict by value Args: dic: the dict to be sorted reverse: reverse order or not Returns: sorted dict """ return dict(sorted(dic.items(), key=lambda x: x[1], reverse=reverse))
def is_error_start(line): """Returns true if line marks a new error.""" return line.startswith("==") and "ERROR" in line
def pointInRect(x, y, left, top, width, height): """Returns ``True`` if the ``(x, y)`` point is within the box described by ``(left, top, width, height)``.""" return left < x < left + width and top < y < top + height
def __GetAuthorizationTokenUsingResourceTokens(resource_tokens, path, resource_id_or_fullname): """Get the authorization token using `resource_tokens`. :Parameters: - `resource_tokens`: dict - `path`: str - `resource_id_or_fullname`: str :Returns: dict """ if resource_tokens.get(resource_id_or_fullname): return resource_tokens[resource_id_or_fullname] else: path_parts = path.split('/') resource_types = ['dbs', 'colls', 'docs', 'sprocs', 'udfs', 'triggers', 'users', 'permissions', 'attachments', 'media', 'conflicts', 'offers'] for one_part in reversed(path_parts): if not one_part in resource_types and one_part in resource_tokens: return resource_tokens[one_part] return None
def genus_species_subprefix_subspecies(tokens): """ Input: Brassica oleracea var. capitata Output: <taxon genus="Brassica" species="oleracea" sub-prefix="var" sub-species="capitata"><sp>Brassica</sp> <sp>oleracea</sp> var <sp>capitata</sp></taxon> """ (genus, species, subprefix, subspecies) = (tokens[0], tokens[1], tokens[2], tokens[3]) return f'''<taxon genus="{genus}" species="{species}" sub-prefix="{subprefix}" sub-species="{subspecies}"><sp>{genus}</sp> <sp>{species}</sp> {subprefix} <sp>{subspecies}</sp></taxon>'''
def print_project_policies_rejection(policy_dict): """ Prints the the policy and corresponding rejected resources from projects""" output = '' for policy in policy_dict: # policy output += "Rejected by Policy " + '"' + policy + '":\n' for node in policy_dict[policy]: # name output += "\t* " + node.resource.displayName # licenses licenses = node.resource.licenses if licenses is not None: license_output = " (" for lice in licenses: license_output += lice + ", " output += license_output[:-2] + ") \n" return output
def c(ixs): """The sum of a range of integers Parameters ---------- ixs : list data list Returns ---------- sum : int values """ return sum(range(1, sum((i > 0 for i in ixs)) + 1))
def _merge(left, right): """Merge two lists and return the merged result """ result = [] while len(left) or len(right): if len(left) and len(right): if left[0] <= right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) elif len(left): result.extend(left) left = [] elif len(right): result.extend(right) right = [] return result
def read_file(filename): """Reads a file. """ try: with open(filename, 'r') as f: data = f.read() except IOError as e: return (False, u'I/O error "{}" while opening or reading {}'.format(e.strerror, filename)) except: return (False, u'Unknown error opening or reading {}'.format(filename)) return (True, data)
def f1d5p(f, h): """ A highly accurate five-point finite difference stencil for computing derivatives of a function. It works on both scalar and vector functions (i.e. functions that return arrays). Since the function does four computations, it's costly but recommended if we really need an accurate reference value. The function is evaluated at points -2h, -h, +h and +2h and these values are combined to make the derivative according to: http://www.holoborodko.com/pavel/numerical-methods/numerical-derivative/central-differences/ How to use: use fdwrap or something similar to generate a one-variable function from the (usually) much more complicated function that we wish to differentate. Then pass it to this function. Inputs: f = The one-variable function f(x) that we're differentiating h = The finite difference step size, usually a small number Outputs: fp = The finite difference derivative of the function f(x) around x=0. """ fm2, fm1, f1, f2 = [f(i*h) for i in [-2, -1, 1, 2]] fp = (-1*f2+8*f1-8*fm1+1*fm2)/(12*h) return fp
def uncapitalize_name(name): """ >>> uncapitalize_name("Href") 'href' >>> uncapitalize_name("HttpEquiv") 'http-equiv' """ buf = [] for c in name: if 'A' <= c <= 'Z' and len(buf): buf.append('-') buf.append(c) return ''.join(buf).lower()
def _validate_str_with_equals(input_string): """ make sure an input string is of the format {0}={1} {2}={3} {4}={5} ... Some software programs put spaces after the equals sign and that's not cool. So we make the string into a readable format :param input_string: input string from an edi file :type input_string: string :returns line_list: list of lines as ['key_00=value_00', 'key_01=value_01'] :rtype line_list: list """ input_string = input_string.strip() # remove the first >XXXXX if ">" in input_string: input_string = input_string[input_string.find(" ") :] # check if there is a // at the end of the line if input_string.find("//") > 0: input_string = input_string[0 : input_string.find("//")] # split the line by = l_list = input_string.strip().split("=") # split the remaining strings str_list = [] for line in l_list: s_list = line.strip().split() for l_str in s_list: str_list.append(l_str.strip()) # probably not a good return if len(str_list) % 2 != 0: # _logger.info( # 'The number of entries in {0} is not even'.format(str_list)) return str_list line_list = [ "{0}={1}".format(str_list[ii], str_list[ii + 1]) for ii in range(0, len(str_list), 2) ] return line_list
def get_tags(sync_config): """ return a list of tags with, there name, and displayName """ tags = [] for tag in sync_config['tags']: tags.append({'name': tag['name'], 'displayName': tag['displayName']}) return tags
def to_locale(language): """ Simplified copy of `django.utils.translation.to_locale`, but we need it while the `settings` module is being loaded, i.e. we cannot yet import django.utils.translation. Also we don't need the to_lower argument. """ p = language.find('-') if p >= 0: # Get correct locale for sr-latn if len(language[p + 1:]) > 2: return language[:p].lower() + '_' + language[p + 1].upper() + language[p + 2:].lower() return language[:p].lower() + '_' + language[p + 1:].upper() else: return language.lower()
def validate_str_length(value, min_length=None, max_length=None): """Validation value is a string and its length is between [min_size:max_size] as long those are defined. :param value: A string value :type value: string | NoneType :param min_length: The minimum amount of characters the value can have :type min_length: integer :param max_length: The maximum amount of characters the value can have :type max_length: integer :return: True if values is a string with length within boundaries or None. Otherwise returns False :rtype: bool """ if value is None: return True if not isinstance(value, str): return False gte_min = True if not min_length else min_length <= len(value) lte_max = True if not max_length else max_length >= len(value) return gte_min and lte_max
def invert_momenta(p): """ fortran/C-python do not order table in the same order""" new_p = [] for i in range(len(p[0])): new_p.append([0]*len(p)) for i, onep in enumerate(p): for j, x in enumerate(onep): new_p[j][i] = x return new_p
def __validate_currency_name_and_amount(currency_name, amount): """ Returns true if currency_name and amount contain values. These values are already empty at the point this function is called if they are invalid, so return false if they do not contain values :param currency_name: :param amount: :return: """ if currency_name is None or len(currency_name) == 0 or amount is None or len(amount) == 0: return False else: return True
def make_repr(type_str, *args, **kwargs): """ Creates a string suitable for use with ``__repr__`` for a given type with the provided arguments. Skips keyword arguments that are set to ``None``. For example, ``make_repr("Example", None, "string", w=None, x=2)`` would return a string: ``"Example(None, 'string', x=2)"`` Args: type_str (str): The name of the type to create a representation for. Returns: Tuple[str, bool]: A tuple including the ``__repr__`` string and a boolean indicating whether all the arguments were default (i.e. None). """ all_args = list(map(repr, args)) for key, val in filter(lambda t: t[1] is not None, kwargs.items()): all_args.append("{:}={:}".format(key, repr(val))) repr_str = "{:}({:})".format(type_str, ", ".join(all_args)) return repr_str, all(arg == repr(None) for arg in all_args)
def split_host_port(host_port, default_port): """ Split host:port into host and port, using the default port in case it's not given. """ host_port = host_port.split(':') if len(host_port) == 2: host, port = host_port return host, port else: return host_port[0], default_port
def maximum_digital_sum(a: int, b: int) -> int: """ Considering natural numbers of the form, a**b, where a, b < 100, what is the maximum digital sum? :param a: :param b: :return: >>> maximum_digital_sum(10,10) 45 >>> maximum_digital_sum(100,100) 972 >>> maximum_digital_sum(100,200) 1872 """ # RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of # BASE raised to the POWER return max( [ sum([int(x) for x in str(base ** power)]) for base in range(a) for power in range(b) ] )
def mmval(mx, val, mn=0): """Return the value if within maxi or mini, otherwise return the boundary (mini if less than mini, maxi if greater than maxi). mx {number} Upper bound. val {number} Value to boundary check. [mn=0] {number} Lower bound, assumes zero. return {number} val or associated boundary. """ return max(mn, min(val, mx))
def get_contents(nmeaStr): """Return the AIS msg string. AIS goo""" return nmeaStr.split(',')[5]
def divisors_concise(integer: int): """ Same as above, except I used a list comprehension """ output = [i for i in range(2, integer) if integer % i == 0] return output if len(output) else f"{str(integer)} is prime"
def shift_pos(pos, label_shift): """shift a pos by (sx, xy) pixels""" shiftx = label_shift[0] shifty = label_shift[1] pos2 = pos.copy() for key, position in pos2.items(): pos2[key] = ( position[0] + shiftx, position[1] + shifty) return pos2
def check_uniqueness_in_rows(board: list) -> bool: """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', \ '*35214*', '*41532*', '*2*1***']) True >>> check_uniqueness_in_rows(['***21**', '452453*', '423145*', '*543215', \ '*35214*', '*41532*', '*2*1***']) False >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*553215', \ '*35214*', '*41532*', '*2*1***']) False """ unique = True num = len(board) - 2 board_c = list(map(lambda x: x[1: -1], board[1:-1])) possible_val = set(map(str, range(1, num+1))) for line in board_c: line_val = set() for val in line: if val in possible_val and val not in line_val: line_val.add(val) else: unique = False break if not unique: break return unique
def property_uses_get_resource(resource, property_name): """ returns true if a port's network property uses the get_resource function """ if not isinstance(resource, dict): return False if "properties" not in resource: return False for k1, v1 in resource["properties"].items(): if k1 != property_name: continue if isinstance(v1, dict) and "get_resource" in v1: return True return False
def minimumTotal(triangle): """ :type triangle: List[List[int]] :rtype: int """ if not triangle: return 0 n = len(triangle) current_cache = triangle[-1] for i in range(n-2, -1, -1): for j in range(i+1): current_cache[j] = triangle[i][j] + min(current_cache[j], current_cache[j+1]) return current_cache[0]
def ask_custom_question(question, choice_one, choice_two, not_done): """Method to ask the user a customized True or False question""" while not_done: answer = input( "\n[?] {} ['{}' or '{}']: ".format(question, choice_one, choice_two) ) if answer[0].lower() == choice_one[0].lower(): break if answer[0].lower() == choice_two[0].lower(): not_done = False break print("\n[!] ERROR - your response", answer, " is invalid!\n") print("[-] Please type either '{}' or '{}'!\n".format(choice_one, choice_two)) return not_done
def _addPrj(grpnum,pos,currentFltCat,nextFltCat,prevFltCat): """Almost always insures that that two or more of the same flight category exists""" # # Beginning hour of TAF is always added, regardless of any impending flight category # change # if grpnum == 0 and pos == 0: return True elif pos: return currentFltCat in [nextFltCat,prevFltCat] else: return currentFltCat == nextFltCat
def custom_attention_masks(input_ids): """Creates attention mask for the given inputs""" attention_masks = [] # For each sentence... for sent in input_ids: # Create the attention mask. # - If a token ID is 0, then it's padding, set the mask to 0. # - If a token ID is > 0, then it's a real token, set the mask to 1. att_mask = [int(token_id > 0) for token_id in sent] # Store the attention mask for this sentence. attention_masks.append(att_mask) return attention_masks
def bit_length(num): """Number of bits required to represent an integer in binary.""" s = bin(num) s = s.lstrip('-0b') return len(s)
def get_depth(root): """ return 0 if unbalanced else depth + 1 """ if not root: return 0 left = get_depth(root.left) right = get_depth(root.right) if abs(left-right) > 1 or left == -1 or right == -1: return -1 return 1 + max(left, right)
def get_vid_name(file): """Creates the new video name. Args: file: String name of the original image name. Returns: A string name defined by the Subject and Session numbers. """ return file.split("_")[0] + "_" + file.split("_")[1]
def ensure_is_listlike(thing): """ Check if THING is list or tuple and, if neither, convert to list. """ if not isinstance(thing, (list, tuple)): thing = [thing,] return thing
def dew_point(air_temperature): """Rough calculation for dew point in specific humidity (kg moisture per kg air). Based on doubling of dew point per 10 degrees celsius, and a dew point of 0.051kg at 40 degrees celsius.""" return 0.051 * 2 ** ((air_temperature - 40.0) / 10.0)