content
stringlengths
42
6.51k
def get_radosgw_username(r_id): """Generate a username based on a relation id""" gw_user = 'juju-' + r_id.replace(":", "-") return gw_user
def replay(i): """ Input: { } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ return {'return':1, 'error':'TBD: need support in CLBla...
def resolver_kind_validator(x): """ Property: Resolver.Kind """ valid_types = ["UNIT", "PIPELINE"] if x not in valid_types: raise ValueError("Kind must be one of: %s" % ", ".join(valid_types)) return x
def is_iterator(obj): """ >>> assert is_iterator(list()) is True >>> assert is_iterator(int) is False """ if isinstance(obj, (list, tuple)): return True try: iter(obj) return True except TypeError: return False
def format_time(t): """Format seconds into a human readable form. >>> format_time(10.4) '10.4s' >>> format_time(1000.4) '16min 40.4s' """ m, s = divmod(t, 60) h, m = divmod(m, 60) if h: return f"{h:2.0f}hr {m:2.0f}min {s:4.1f}s" elif m: return f"{m:2.0f}min {s:4....
def is_residue(a: int, p: int): """ a ^ (p - 1) / 2 = x_o ^ (p - 1) / 2 therefore: x_o ^ (p - 1) = 1 (mod p) """ symbol = pow(a, (p - 1) // 2, p) if symbol == 1: return pow(a, (p + 1) // 4, p)
def format_universe_repo_content_type(universe_version): """ Formats a universe repo content-type of version `universe-version` :param universe_version: Universe content type version: "v3" or "v4" :type universe_version: str :return: content-type of the universe repo version `universe_version` :rty...
def validate_eyr(value: str) -> bool: """Expiration must be between 2020 and 2030, inclusive""" try: return int(value) in range(2020, 2031) except (TypeError, ValueError): return False
def _get_base_dataset_metadata(ds_identifier): """Return base metadata as dict for a given ds_identifier """ meta = { "@context": { "@vocab": "http://schema.org/", "doap": "http://usefulinc.com/ns/doap#", }, # increment when changes to meta data representatio...
def format_string(string, data): """Format a string for notification, based on all content data.""" return string.format( refresh_time=data.get("refresh_time", ""), playtime=data.get("playtime", ""), timestamp=data.get("timestamp", ""), artist=data.get("artist", ""), titl...
def _describe_zones_response(response): """ Generates a response for a describe zones request. @param response: Response from Cloudstack. @return: Response. """ return { 'template_name_or_list': 'zones.xml', 'response_type': 'DescribeAvailabilityZonesResponse', 'response...
def human_readable_time(seconds): """ Returns human readable time :param seconds: Amount of seconds to parse. :type seconds: string. """ seconds = int(seconds) hours = seconds / 3600 seconds = seconds % 3600 minutes = seconds / 60 seconds = seconds % 60 return "{:02...
def lerp(min, max, rat): """ Interpolate between `min` and `max` with the 0-1 ratio `rat`. """ return min+(max-min)*rat
def convert_boolean_for_praat(b): """ Convert Python boolean for use in Praat Praat uses "yes"/"no" or 1/0 values instead of True/False. Convert True to "yes", False to "no" """ if b == True: return "yes" elif b == False: return "no" else: raise ValueError('Input mus...
def find_keywords(args, key_filter=lambda x: not x.startswith("$")): """ This splits up strings like name=value, foo=bar into a dict. Does NOT deal with quotes in value (e.g. key="value with space" will not work By default, note that it takes OUT any key which starts with $ (i.e. a single dollar si...
def days_to_seconds(x: float) -> float: """Convert time in days to seconds. Args: x (float): Time in days. Returns: float: Time in seconds. """ return x * 60 * 60 * 24
def cross(a, b) -> float: """Returns the cross product of a and b.""" return (float(a[0]) * b[1]) - (float(a[1]) * b[0])
def parse_int(value, allow_non_zero=False): """ Parses the given value and returns it as an integer. Args: value (str): The string to be parsed. allow_non_zero (bool): If False, all values below 1 will be set to 1. Returns: int: The parsed value. """ if n...
def pixformat(val=None): """ Set or get pixformat """ global _pixformat if val is not None: _pixformat = val return _pixformat
def operator_not(validator): """Another form of 'not' operator in 'permissions._require_operator'. Warning: While 'permissions.operator_or' accepts multiple arguments, this operator accepts only one validator """ return 'not', validator
def compile_word(word): """Compile a word of uppercase letters as numeric digits. E.g., compile_word('YOU') => '(1*U+10*O+100*Y)' Non-uppercase words unchanged: compile_word('+') => '+'""" if word.isupper(): terms = [str(10**i) + '*' + c for i, c in enumerate(word[::-1])] return '(' + '+...
def scale_bbox(bbox_list, width, height): """ Normalize a bounding box give max_x and max_y. :param bbox_list: list of list of coodinates in format: [xmin, ymin, xmax, ymax] :param width: image max width. :param height: image max height :return: list of list of normalized coordinates. """ ...
def request_example_keys(endpoint, method): """ Returns list with keys for accessing request examples in oas dictionary """ return [ "paths", endpoint, method, "requestBody", "content", "application/fhir+json", "examples", ]
def prepend_blanks(string, length): """Prepend ``length`` blank characters to each line of a ``string`` Here parameter ``string`` is a string that may consist of several lines. """ def prepend_blank_line(line, length): return " " * length + line if len(line.strip()) else line l = [prepe...
def same(x,y): """Are two Python objects considered the same?""" try: if x == y: return True except: pass try: from numpy import isnan if isnan(x) and isnan(y): return True except: pass ## try: ## from numpy import allclose ## if allclose(x,y): return True ##...
def calculate_loop_size(public_key): """ >>> calculate_loop_size(5764801) 8 >>> calculate_loop_size(17807724) 11 """ subject_number = 7 value = 1 loop_size = 0 while value != public_key: value *= subject_number value %= 20201227 loop_size += 1 retur...
def typestr(tc): """ typestr :: Int -> String Return a string of the Typeclass' name to be used in reporting """ return ["Int","Num","Real","Ord","Enum","Fold","String","Func","Any"][tc]
def model(x,param): """Modelo polinomial. `param` contiene los coeficientes. """ n_param = len(param) y = 0 for i in range(n_param): y += param[i] * x**i return y
def get_new_coordinates(coordinates, direction): """ Returns the coordinates of direction applied to the provided coordinates. Args: coordinates: tuple of (x, y) direction: a direction string (like "northeast") Returns: tuple: tuple of (x, y) coordinates """ x, y = coor...
def convert_to_float(number_string): """Convert comma-delimited real numberts in string format to a float >>> convert_to_float("-79,1") -79.1 """ return(float(number_string.replace(',', '.')))
def get_ranks(keywords, script): """Return ranks of queried keyword in a given script. Parameters ---------- keywords : str[] Array of keywords to search in the script. script : dict[] JSON object containing ranks of different keywords. Returns ------- ranks : int[]...
def longest_palindrome(s): """.""" n = len(s) table = [[0 for x in range(n)] for y in range(n)] max_length = 1 for i in range(n): table[i][i] = True # max_length = 2 start = 0 i = 0 while i < n - 1: if s[i] == s[i + 1]: table[i][i + 1] = True ...
def field_to_int(field): """ Return an integer representation. If a "-" was provided return zero. """ if field == "-": return 0 return int(field)
def _parseLocalVariables(line): """Accepts a single line in Emacs local variable declaration format and returns a dict of all the variables {name: value}. Raises ValueError if 'line' is in the wrong format. See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html """ paren = '...
def _ensure_options(given_options=None): """ Ensures dict contains all formatting options. Defaults are: with_attrs (bool): if True, generate module attribute from imports (Default: True) with_mods (bool): if True, generate module imports (Default: True) with...
def strip_list(input_list): """ Strips whitespace for all individual strings in a list Parameters: input_list, a list of strings Returns: output_list, a list of strings """ output_list = [] for item in input_list: output_list.append(item.strip()) return output_l...
def _linear_to_rgb(c: float) -> float: """Converts linear sRGB to RGB :param c: (float) linear sRGB value :return: (float) RGB value """ if c > 0.0031308: return pow(c, 1.0 / 2.4) * 1.055 - 0.055 return abs(c * 12.92)
def _combine_column_lists(user_entries, all_entries): """Combine multiple lists.""" if isinstance(user_entries, bool) and user_entries: res = all_entries elif isinstance(user_entries, list): res = [e for e in user_entries if e in all_entries] elif isinstance(user_entries, str): r...
def StringFill(_string, _len, fill_front = False, fill_spaces = False): """Function to fill the string _string up to length _len with dots. If len(_string) > _len, the string is cropped. **kwargs: fill_front = True to fill in front of the input string. (Preset fill_front = False) Examples: Strin...
def split_role(r): """ Given a string R that may be suffixed with a number, returns a tuple (ROLE, NUM) where ROLE+NUM == R and NUM is the maximal suffix of R consisting only of digits. """ i = len(r) while i > 1 and r[i - 1].isdigit(): i -= 1 return r[:i], r[i:]
def paramToPercent(current: int, min: int, max: int) -> int: """Convert a raw parameter value to a percentage given the current, minimum and maximum raw values. @param current: The current value. @type current: int @param min: The minimum value. @type current: int @param max: The maximum value. @type max:...
def get_cookie_name(state): """Generate the cookie name for the OAuth2.0 state.""" return f"oauth.{state}"
def do_decomposition(gene_trail, selection): """Given a list of lists gene_trail and indexes for every item to be selected in every list in gene_trail, returns a list representing the corresponding decomposition. For example, if gene_trail is [['a', 'b'], ['c'], ['d','e']] and the index for the fir...
def chartoi(c): """ convert a single character to an integer :param str c: :return int: """ if len(c) == 1 and c.isdigit(): return int(c) return 0
def reduce_docs(docs, max_budget, offset, sort_docs=False): """Reduces the number of `docs` (subwords) to fit maximum budget by optionally sorting them by length, and then removing the shortest ones until `max_budget` is exceeded. Otherwise, will go left-to-right to preserve documents. Args: ...
def check_zones(domain, zones): """ Check if the provided domain exists within the zone """ for zone in zones: if domain == zone or domain.startswith(zone + "."): return zone return None
def classify_list_f(a_list, *filters): """Classfy a list like object. Multiple filters in one loop. - collection: list like object - filters: the filter functions to return True/False Return multiple filter results. Example: data = [1, 2, 3] m1 = lambda x: x > 1 m2 = lambda x: x > 2 ...
def is_int(value): """ Tests to see whether a value can be cast to an int Args: value: The value to be tested Returns: True if it can be cast, False if it can't """ try: int(value) return True except ValueError: return False
def merge(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z
def str_to_other(mystr): """ a callable type for my argparse See: https://docs.python.org/2/library/argparse.html?highlight=argparse#type """ f1, f2, f3 = map(float, mystr.split(' ')) return [f1, f2, int(f3)]
def isCombinationValid(combination): """ Checks if a combination (a tuple of 9 digits) is a valid product equation. >>> isCombinationValid(('3', '9', '1', '8', '6', '7', '2', '5', '4')) True >>> isCombinationValid(('1', '2', '3', '4', '5', '6', '7', '8', '9')) False """ return ( ...
def applyFtoEachElemList2 (L, f): """ argument: List L and function f apply function to each element inside of list mutates L by replacing each element of L by f(elem) return mutated L """ for index in range(len(L)): L[index] = f(L[index]) return L
def formatHex(n): """ Format 32-bit integer as hexidecimal """ n = n if (n >= 0) else (-n) + (1 << 31) return "0x" + '{:08X}'.format(n)
def canFinish(numCourses, prerequisites): """ :type numCourse: int :type prerequirements: List[List[int]] :rtype:bool """ ''' if not prerequisites: return True L = [] from collections import defaultdict in_degrees = defaultdict(int) graph = defaultdict(list) #...
def make_figdata(x_data, y_data, labels, dataset_name): """Returns a figure.data list to pass to dcc.Graph""" return [ { 'x': x_data, 'y': y_data[i], 'name': f"{l} ({dataset_name})", # 'mode': 'markers', # 'marker': {'size': 10} 'm...
def action_list_to_string(action_list): """Util function for turning an action list into pretty string""" action_list_string = "" for idx, action in enumerate(action_list): action_list_string += "{} ({})".format( action["name"], action["action"]["class_name"] ) if idx == ...
def diff_between_angles(a, b): """Calculates the difference between two angles a and b Args: a (float): angle in degree b (float): angle in degree Returns: float: difference between the two angles in degree. """ c = (b - a) % 360 if c > 180: c -= 360 return c
def split_path(dp): """Split a path in basedir path and end part for HDF5 purposes""" idx = dp.rfind('/') where = dp[:idx] if idx > 0 else '/' name = dp[idx+1:] return where, name
def next_greater_element(number: int) -> int: """https://leetcode.com/problems/next-greater-element-iii/""" digits = [int(n_char) for n_char in str(number)] n = len(digits) swap_index = -1 for index in range(n - 2, -1, -1): if digits[index] < digits[index + 1]: swap_index = ind...
def lcs(s1, s2): """ Longest common subsequence of two iterables. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. :param s1: first iterable :param s2: second iterable :return: (list) the lcs """ matrix = [[[] for _ in range(len(s2))] f...
def bq_convert_hour_to_index(hour, time_span, remainder): """Convert hour to index according to the SQL.""" return int((hour - remainder) / time_span)
def remove_duplicates(nums) -> int: """ remove_duplicates :param nums: :return: """ # print(list(set(nums))) return len(set(nums))
def lcs(s1: str, s2: str) -> int: """Return the longest common substing of two strings.""" table = [[0] * (len(s2) + 1) for _ in range(2)] for x in s1: for j, y in enumerate(s2, start=1): if x == y: table[1][j] = table[0][j - 1] + 1 elif table[1][j - 1] > tabl...
def floatConverter(num): """assumes num is an int, float, or string representing a number returns a float, representing num""" if isinstance(num, float) or isinstance(num, int) or isinstance(num, str): return float(num) else: raise TypeError("not a valid input")
def format_memory(nbytes): """Returns a formatted memory size string in torch profiler Event """ KB = 1024 MB = 1024 * KB GB = 1024 * MB if (abs(nbytes) >= GB): return '{:.2f} Gb'.format(nbytes * 1.0 / GB) elif (abs(nbytes) >= MB): return '{:.2f} Mb'.format(nbytes * 1.0 / MB)...
def _convert_access(access: str) -> str: """Converts access string to a value accepted by wandb.""" access = access.upper() assert ( access == "PROJECT" or access == "USER" ), "Queue access must be either project or user" return access
def electronicBasis(chain): """Return the basis for the electronic states of a polyene of length chain. The basis states are tight-binding orbitals, one for each CH unit, each with the capacity to hold two electrons. They are represented as integers corresponding to the CH unit number.""" ret...
def check_size(d1: int, d2: int) -> bool: """ Check if dataset size is the same after dataset cleaning :param d1: Original Dataset Size :param d2: Cleaned Dataset Size :return: Return boolean. True """ return True if d1 == d2 else False
def intlist_to_alpha(intlist): """ Convert a list of integers [0, 0, 1, 1, 5, ...] to a list of letters [A, A, B, B, F, ...]. Useful for converting monomer types to compartment names (which can then be used as atom names). Parameters ---------- intlist : list of int list to be conve...
def find_boyer_moore(T,P): """Return the lowestindex of T at which substring P begins (or else -1)""" n,m = len(T), len(P) # introduce convenient notations if m == 0: return 0 # trivial search for empty string last = {} # build last dictionary for k in range(m): last[P[k]] = k # later occurence ov...
def with_suffix(number, base=1000): """Convert number to string with SI suffix, e.g.: 14226 -> 14.2k, 5395984 -> 5.39M""" mapping = {base**3: "G", base**2: "M", base: "k"} for bucket, suffix in mapping.items(): if number > 0.999 * bucket: return "{:.3g}{}".format(number / bucket, suffix)...
def format_message(msg): """Format the given message. """ if not any(msg.endswith(c) for c in ('.', '?', '!')) and len(msg) > 30: msg = msg + ' ...' return msg
def qa(country, uv): """ Do qa on uv-index value: Rule: 0 <= uv < 12 --> pass (P) 12 <= uv < 17 --> doubtful (D) >= 17 --> error (E) all else --> not applicable (NA) """ if not isinstance(uv, float): return 'NA' if 0 <= uv < 12: ...
def remove_old(handle, read_start): """ The remove old function removes the basepairs that do not have sofclips to save memory. :param softclip_data: A dictionary with positions and the number of "normal" bases and softclip bases. :param read_start: An integer representing the place where the read start. ...
def remove_tags(s): """ Removes tags that should be ignored when computing similarites :param s: Sentence as a list of words :return: Same sentence without the tags """ # tags = set(['<START>', '<END>', '<UNK>', 0, 1, 2, 3]) tags = set(['<START>', '<END>', '<UNK>']) filtered_words = [] ...
def parse_summary(summary): """Parse a string from the format 'open / 41' into both its params""" summary = summary.split("/") summary[0] = summary[0].strip() if "?" in summary[0]: summary[0] = "nodata" try: summary[1] = int(summary[1]) except ValueError: summary[1] =...
def pubkey_compressed_to_uncompressed(compressed_pubkey: bytes) -> bytes: """ Converts compressed pubkey to uncompressed format """ assert len(compressed_pubkey) == 33 # modulo p which is defined by secp256k1's spec p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F x = int.from_...
def run_unhovered(var): """ Calls the unhovered method on the variable, if it exists. """ if var is None: return None if isinstance(var, (list, tuple)): for i in var: run_unhovered(i) return f = getattr(var, "unhovered", None) if f is not None: ...
def event_stream_name(high_seq: int) -> str: """ Construct the basename of the event stream object containing the given highest sequence number. """ return f"event-stream-{high_seq}"
def _convert_grad_position_type(grad_position): """Check and convert the type and size of grad position index.""" if isinstance(grad_position, tuple): for gp in grad_position: if not isinstance(gp, int): raise TypeError(f"For 'F.grad', the element in 'grad_position' should be...
def lower(value): """ returns the lowercase copy of input string. :param str value: string to make lowercase. :rtype: str """ return value.lower()
def positiveaxis(axis, ndim): """Positive axis Args: axis(num): dimension index ndim(num): number of dimensions Returns: num """ if axis < 0: axis += ndim if axis < 0 or axis >= ndim: raise IndexError("axis out of range") return axis
def encode_query(query, vocabulary): """Takes a textual query and a vocabulary (mapping from words to integers), returns the encoded query in a list. If a word is not in the dictionary, the function returns False. Args: query (list): A textual query vocabulary (dict): Mapping from all wo...
def get_color_map_list(num_classes): """ Args: num_classes (int): number of class Returns: color_map (list): RGB color list """ color_map = num_classes * [0, 0, 0] for i in range(0, num_classes): j = 0 lab = i while lab: color_map[i * 3] |= (((...
def undiff(usbp, usbn): """Convert P/N diff pair bits into J/K encoding. >>> from cocotb_usb.usb.pp_packet import pp_packet >>> undiff( ... #EJK_ ... '1100', # p ... '1010', # n ... ) 'EJK_' >>> print(pp_packet(undiff( ... #KJKJKJKKJJKJJKKK__J - ACK handshake packet ...
def edge_overlap(low1, high1, low2, high2): """ Returns true if two lines have >0 overlap >>> edge_overlap(0, 1, 1, 2) False >>> edge_overlap(0, 2, 1, 2) True >>> edge_overlap(1, 2, 1, 2) True >>> edge_overlap(1, 2, 0, 1) False >>> edge_overlap(1, 2, 0, 2) True >>> edge_...
def check_all_matching_tags(tag_arg_dict, target_tag_dict): """ Return True if all tag sets in `tag_arg_dict` is a subset of the matching categories in `target_tag_dict`. """ return all( [ tags_set.issubset(target_tag_dict.get(tag_name, set())) for tag_name, tags_set ...
def size_table_name(model_selector): """ Returns canonical name of injected destination desired_size table Parameters ---------- model_selector : str e.g. school or workplace Returns ------- table_name : str """ return "%s_destination_size" % model_selector
def isfloat(x): """ >>> isfloat(12) True >>> isfloat(12) True >>> isfloat('a') False >>> isfloat(float('nan')) True >>> isfloat(float('inf')) True """ try: float(x) except: return False return True
def reverse_dict(d): """ Flip keys and values """ r_d = {} for k, v in d.items(): if v not in r_d: r_d[v] = [k] else: r_d[v].append(k) return r_d
def find(haystack, needle): """Return the index at which the sequence needle appears in the sequence haystack, or -1 if it is not found, using the Boyer- Moore-Horspool algorithm. The elements of needle and haystack must be hashable. >>> find([1, 1, 2], [1, 2]) 1 """ h = len(haystack)...
def camel_case(string): """Returns the CamelCased form of the specified string. """ components = string.split('_') return "".join(x.title() for x in components)
def g(n): """Return the value of G(n), computed recursively. >>> g(1) 1 >>> g(2) 2 >>> g(3) 3 >>> g(4) 10 >>> g(5) 22 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'g', ['While', 'For']) True """ "*** YOUR CODE HERE ***" if n <= 3: ...
def quick_sort(nums: list) -> list: """ Selects an element as pivot and partitions the given array around this pivot. The sub-arrays are then sorted recursively. :param nums: list of n elements to sort :return: sorted list (in ascending order) """ if type(nums) is not list: raise TypeE...
def is_one_of(obj, types): """Return true iff obj is an instance of one of the types.""" for type_ in types: if isinstance(obj, type_): return True return False
def dict_to_list(dict): """Transform a dictionary into a list of values.""" calc_moments_list = list() [calc_moments_list.append(func) for func in dict.values()] return calc_moments_list
def bresenham(x1, y1, x2, y2): """ Return a list of points in a bresenham line. Implementation hastily copied from RogueBasin. Returns: List[Tuple[int, int]]: A list of (x, y) points, including both the start and end-points. """ points = [] issteep = abs(y2-y1) > abs(x2...
def unpound(input: str) -> str: """ Removes '0x' or '#' prefix from a given string :param input: A hexadecimal value. :return: str """ return input.replace('#', '').replace('0x', '')
def search(tokens, section): """Searches the given token list for the given block of information..""" for t in tokens: if t[0] == section: return t[1:] return []
def ne(s,t): """Semantically equivalent to python's !=""" return (s != t)