content
stringlengths
42
6.51k
def utm_zone_to_epsg(zone): """ Convert UTM zone string to EPSG code. 56S -> 32756 55N -> 32655 """ if len(zone) < 2: raise ValueError(f'Not a valid zone: "{zone}", expect <int: 1-60><str:S|N>') offset = dict(S=32700, N=32600).get(zone[-1].upper()) if offset is None: raise ValueError(f'Not a valid zone: "{zone}", expect <int: 1-60><str:S|N>') try: i = int(zone[:-1]) except ValueError: i = None if i is not None and (i < 0 or i > 60): i = None if i is None: raise ValueError(f'Not a valid zone: "{zone}", expect <int: 1-60><str:S|N>') return offset + i
def _patsplit(pattern, default): """Split a string into the optional pattern kind prefix and the actual pattern.""" if ':' in pattern: kind, pat = pattern.split(':', 1) if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre', 'listfile', 'listfile0', 'set', 'include', 'subinclude'): return kind, pat return default, pattern
def disease_descriptors(civic_did2, civic_did15, civic_did2950): """Create test fixture for disease descriptors.""" return [civic_did2, civic_did15, civic_did2950]
def quote_item(item, pre='', post=''): """Format an string item with quotes. """ post = post or pre return f'{pre}{item}{post}'
def add_numbers(file: list, tel_numbers: set) -> set: """ Given a file adds all available numbers into a set :param file: file containing telephone numbers :param tel_numbers: variable used to contain the telephone numbers :return: tel_numbers with file numbers extracted """ for column in [0, 1]: temp_numbers = [data[column] for data in file] tel_numbers.update(temp_numbers) return tel_numbers
def NX(lengths, fraction): """ Calculates the N50 for a given set of lengths """ lengths = sorted(lengths, reverse=True) tot_length = sum(lengths) cum_length = 0 for length in lengths: cum_length += length if cum_length >= fraction*tot_length: return length
def is_valid_output(ext): """ Checks if output file format is compatible with Open Babel """ formats = ["ent", "fa", "fasta", "gro", "inp", "mcif", "mdl", "mmcif", "mol", "mol2", "pdb", "pdbqt", "png", "sdf", "smi", "smiles", "txt"] return ext in formats
def friend_second_besties(individual, bestie_dict): """generate the set of (strictly) second-order friends for `individual`, based on the contents of `bestie_dict`""" # extract out friends of friends for each individual in # `individual_list`, by finding friends of each individual, # and friends of those friends, making sure that # degree of separation is strictly 2 second_besties = set() if individual in bestie_dict: for bestie in bestie_dict[individual]: if bestie in bestie_dict: second_besties = second_besties.union(bestie_dict[bestie]) # remove anyone who is a direct friend or the individual themself second_besties = second_besties.difference( bestie_dict[individual].union(set([individual]))) return sorted(second_besties)
def xor_list(prim_list, sec_list): """ Returns the XOR of bits from the primary and secondary lists. """ ret_list = [] for (x_val, y_val) in zip(prim_list, sec_list): ret_list.append(x_val ^ y_val) return ret_list
def flatten_dic(dic): """ Flatten dictionnary with nested keys into a single level : usable in a dataframe Args: dic -- a dictionnary Returns: out -- the flatenned dictionnary (df(out) is a Series) """ out = {} def flatten(x, name=""): """ Recursive axuiliary function Args: x -- an element (a dict, a list, or a value) name -- The inherited parent naming """ if type(x) is dict: for a in x: flatten(x[a], name + a + "_") elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + "_") i += 1 else: out[name[:-1]] = x flatten(dic) return out
def fib2(n): """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # see below a, b = b, a+b return result
def parse_flags(raw_flags): """Return a list of flags. Concatenated flags will be split into individual flags (eg. '-la' -> '-l', '-a'), but the concatenated flag will also be returned, as some command use single dash names (e.g `clang` has flags like "-nostdinc") and some even mix both. """ flags = set() for flag in raw_flags: # Filter out non-flags if not flag.startswith("-"): continue flags.add(flag) # Split and sperately add potential single-letter flags if not flag.startswith("--"): flags.update("-" + char for char in flag[1:]) return list(flags)
def factorial(n): """ Computes the factorial using recursion """ if n == 1: return 1 else: return n * factorial(n-1)
def house_url(path): """ Joins relative house url paths with stem or returns url if stem present. :param path: String path to format. :return: Full house URL. """ stem = "https://house.mo.gov" # Replace insecure with secure if "http://" in path: path = path.replace("http://", "https://") # If the path is a full URL, just return it. if stem in path: return path # Reformat with or without slashes as necessary. if path[0] == "/": return "{}{}".format(stem, path) return "{}/{}".format(stem, path)
def calcsurface_f(c1, c2): """ Helperfunction that calculates the desired surface for two xy-coordinates """ # step 1: calculate intersection (xs, ys) of straight line through coordinates with identity line (if slope (a) = 1, there is no intersection and surface of this parrellogram is equal to deltaY * deltaX) x1, y1 = c1 x2, y2 = c2 a = (y2 - y1) / (x2 - x1) if a == 1: # dan xs equals +/- Infinite en is er there is no intersection with the identity line # since condition 1 holds the product below is always positive surface = (y2 - y1) * (x2 - x1) elif (a < 0): raise ValueError(f"slope is negative; impossible for PAV-transform. Coordinates are {c1} and {c2}. Calculated slope is {a}") else: # than xs is finite: b = y1 - a * x1 xs = b / (1 - a) # xs # step 2: check if intersection is located within line segment c1 and c2. if x1 < xs and x2 >= xs: # then intersection is within # (situation 1 of 2) if y1 <= x1 than surface is: if y1 <= x1: surface = 0.5 * (xs - y1) * (xs - x1) - 0.5 * (xs - x1) * (xs - x1) + 0.5 * (y2 - xs) * (x2 - xs) - 0.5 * ( x2 - xs) * (x2 - xs) else: # (situation 2 of 2) than y1 > x1, and surface is: surface = 0.5 * (xs - x1) ** 2 - 0.5 * (xs - y1) * (xs - x1) + 0.5 * (x2 - xs) ** 2 - 0.5 * (x2 - xs) * ( y2 - xs) # dit is the same as 0.5 * (xs - x1) * (xs - y1) - 0.5 * (xs - y1) * (xs - y1) + 0.5 * (y2 - xs) * (x2 - xs) - 0.5 * (y2 - xs) * (y2 - xs) + 0.5 * (y1 - x1) * (y1 - x1) + 0.5 * (x2 - y2) * (x2 -y2) else: # then intersection is not within line segment # if (situation 1 of 4) y1 <= x1 AND y2 <= x1, and surface is if y1 <= x1 and y2 <= x1: surface = 0.5 * (y2 - y1) * (x2 - x1) + (x1 - y2) * (x2 - x1) + 0.5 * (x2 - x1) * (x2 - x1) elif y1 > x1: # (situation 2 of 4) then y1 > x1, and surface is surface = 0.5 * (x2 - x1) * (x2 - x1) + (y1 - x2) * (x2 - x1) + 0.5 * (y2 - y1) * (x2 - x1) elif y1 <= x1 and y2 > x1: # (situation 3 of 4). This should be the last possibility. surface = 0.5 * (y2 - y1) * (x2 - x1) - 0.5 * (y2 - x1) * (y2 - x1) + 0.5 * (x2 - y2) * (x2 - y2) else: # situation 4 of 4 : this situation should never appear. There is a fourth sibution as situation 3, but than above the identity line. However, this is impossible by definition of a PAV-transform (y2 > x1). raise ValueError(f"unexpected coordinate combination: ({x1}, {y1}) and ({x2}, {y2})") return surface
def get_ether_vendor(mac, lookup_path='nmap-mac-prefixes.txt'): """ Takes a MAC address and looks up and returns the vendor for it. """ mac = ''.join(mac.split(':'))[:6].upper() try: with open(lookup_path, 'r') as f: for line in f: if line.startswith(mac): return line.split()[1].strip() except Exception as e: # pragma: no cover return 'Unknown'
def _copy_params(request, params=None): """ Return a copy of the given request's params. If the request contains an empty 'q' param then it is omitted from the returned copy of the params, to avoid redirecting the browser to a URL with an empty trailing ?q= """ if params is None: params = request.params.copy() if "q" in params and not params["q"].strip(): del params["q"] return params
def decode_time(milliseconds): """Converts a time in milliseconds into a string with hours:minutes,""" mins = int(milliseconds / (1000 * 60) % 60) hrs = int(milliseconds / (1000 * 60 * 60) % 24) return "{h:0>2}:{m:0>2}".format(h=hrs, m=mins)
def clean_strings(lst): """Helper function to clean a list of string values for adding to NWB. Parameters ---------- lst : list A list of (mostly) strings to be prepped for adding to NWB. Returns ------- list of str Cleaned list. Notes ----- Each element is checked: - str types and made lower case and kept - any other type is replaced with 'none' (as a string) - the goal is to replace Python nan or None types for empty cells """ return [val.lower() if isinstance(val, str) else 'none' for val in lst]
def rpm(count, _, nb_read): """ Return rpm value """ return (count / nb_read) * 10**6
def checkDebugOption(debugOptions): """ function to set the default value for debugOptions and turn it from a string into a boolean value Args: debugOptions: string representation of boolean value for debug flag Returns: boolean value for debug flag """ if debugOptions is None: return False elif debugOptions == "True": return True else: return False
def unbundleSizeAndRest(sizeAndRestBundle: int): """ Get the size and the rest of the cipher base from a bundled integer :param sizeAndRestBundle: a bundled number containing the size and the rest of the cipher :return: the size and the rest as a tuple """ if sizeAndRestBundle > 0xffffffff: raise ValueError("The bundled number is too big.") # get the size from the 2nb byte size = (sizeAndRestBundle & 0x0000ff00) >> 8 # get the swap byte from the topmost byte swapValue = (sizeAndRestBundle & 0xff000000) >> 16 # set the swap byte at the 2ns byte and clear the topmost byte rest = (sizeAndRestBundle & 0x00ff00ff) | swapValue return size, rest
def get_range(value, start): """ Filter - returns a list containing range made from given value Usage (in template): <ul>{% for i in 3|get_range %} <li>{{ i }}. Do something</li> {% endfor %}</ul> Results with the HTML: <ul> <li>0. Do something</li> <li>1. Do something</li> <li>2. Do something</li> </ul> Instead of 3 one may use the variable set in the views """ return range(start, value+1, 1)
def n2es(x): """None/Null to Empty String """ if not x: return "" return x
def extract_key_values(array_value, separators=(';', ',', ':'), **kwargs): """Serialize array of objects with simple key-values """ items_sep, fields_sep, keys_sep = separators return items_sep.join(fields_sep.join(keys_sep.join(x) for x in sorted(it.items())) for it in array_value)
def canUnlockAll(boxes): """ canUnlockAll: figures out if all boxes can be opened """ b_len = len(boxes) checked = [False for i in range(b_len)] checked[0] = True stack = [0] while len(stack): bx = stack.pop(0) for b in boxes[bx]: if isinstance(b, int) and b >= 0 and b < b_len and not checked[b]: checked[b] = True stack.append(b) return all(checked)
def hex_to_tcp_state(hex): """ For converting tcp state hex codes to human readable strings. :param hex: TCP status hex code (as a string) :return: String containing the human readable state """ states = { '01': 'TCP_ESTABLISHED', '02': 'TCP_SYN_SENT', '03': 'TCP_SYN_RECV', '04': 'TCP_FIN_WAIT1', '05': 'TCP_FIN_WAIT2', '06': 'TCP_TIME_WAIT', '07': 'TCP_CLOSE', '08': 'TCP_CLOSE_WAIT', '09': 'TCP_LAST_ACK', '0A': 'TCP_LISTEN', '0B': 'TCP_CLOSING' } return states[hex]
def format_time_interval(seconds): """Format a time interval given in seconds to a readable value, e.g. \"5 minutes, 37 seconds\".""" periods = ( ('year', 60*60*24*365), ('month', 60*60*24*30), ('day', 60*60*24), ('hour', 60*60), ('minute', 60), ('second', 1),) result = [] for period_name, period_seconds in periods: if seconds > period_seconds or period_name == 'second': period_value, seconds = divmod(seconds, period_seconds) if period_value > 0 or period_name == 'second': if period_value == 1: result.append("%d %s" % (period_value, period_name)) else: result.append("%d %ss" % (period_value, period_name)) return ", ".join(result)
def dbytes_to_int(h): """ converts bytes represenation of hash to int, without conversion """ return int.from_bytes(h,"big")
def modifyExecutedFiles(executed_files): """ Modifying ansible playbook names to make them uniform across all SDK's """ exe = [] for executed_file in executed_files: executed_file = executed_file.replace('.yml', '').replace('oneview_', '').replace('_facts', '') executed_file = executed_file + 's' exe.append(executed_file) return list(set(exe))
def sqrt(number): """Returns the square root of the specified number as an int, rounded down""" assert number >= 0 offset = 1 while offset ** 2 <= number: offset *= 2 count = 0 while offset > 0: if (count + offset) ** 2 <= number: count += offset offset //= 2 return count
def _parse_arguments(argstring): """ Parses argstring from nginx -V :param argstring: configure string :return: {} of parsed string """ arguments = {} current_key = None current_value = None for part in argstring.split(' --'): if '=' in part: # next part of compound if current_key and current_value: current_value += part if part.endswith("'"): arguments[current_key] = current_value current_key = None current_value = None else: k, v = part.split('=', 1) # compound argument if v.startswith("'") and v.endswith("'"): arguments[k] = v elif v.startswith("'"): current_key = k current_value = v # simple argument else: arguments[k] = v else: # boolean if part: arguments[part] = True return arguments
def string_str_to_str(string_str_rep): """ Return string from given string representation of string Parameters ---------- string_str_rep : str "'str'" Examples -------- >>> string_str_to_str("") '' >>> string_str_to_str('test') 'test' >>> string_str_to_str("'test'") 'test' >>> string_str_to_str('"test"') 'test' Returns ------- str_ : str """ if not isinstance(string_str_rep, str): raise TypeError("Argument must be str ...") str_ = string_str_rep.strip("'\"") return str_
def _get_range_tuples(data): """Split the ranges field from a comma separated list of start-end to a real list of (start, end) tuples. """ ranges = [] for r in data['ranges'].split(',') or []: start, end = r.split('-') ranges.append((start, end)) return ranges
def generateName(nodeName: str, instId: int): """ Create and return the name for a replica using its nodeName and instanceId. Ex: Alpha:1 """ if isinstance(nodeName, str): # Because sometimes it is bytes (why?) if ":" in nodeName: # Because in some cases (for requested messages) it # already has ':'. This should be fixed. return nodeName return "{}:{}".format(nodeName, instId)
def watch_url(video_id): """Construct a sanitized YouTube watch url, given a video id. :param str video_id: A YouTube video identifier. :rtype: str :returns: Sanitized YouTube watch url. """ return 'https://youtube.com/watch?v=' + video_id
def histogram(values, mode=0, bin_function=None): """Return a list of (value, count) pairs, summarizing the input values. Sorted by increasing value, or if mode=1, by decreasing count. If bin_function is given, map it over values first.""" if bin_function: values = map(bin_function, values) bins = {} for val in values: bins[val] = bins.get(val, 0) + 1 if mode: return sorted(bins.items(), key=lambda x: (x[1],x[0]), reverse=True) else: return sorted(bins.items())
def get_stat_name(stat): """Returns the stat name from an integer""" if stat == 1: return "armor" elif stat == 2: return "attackdamage" elif stat == 3: return "movespeed" elif stat == 4: return "magicresist" elif stat == 5: return "movespeed" elif stat == 6: return "critchance" elif stat == 7: return "critdamage" elif stat == 10: return "maximumhealth" elif stat == 23: return "lethality" elif stat == 25: return "attackrange" else: return stat
def rae(*args): """ :param args: [actual, predicted] :return: MRE """ return abs(args[0] - args[1]) / args[0]
def remove_value_from_dict(dictionary:dict,value): """ takes a dict and removes a value """ a = dict(dictionary) for val in dictionary: if val == value: del a[val] return a
def make_bbh(hp,hc,fs,ra,dec,psi,det,ifos,event_time): """ Turns hplus and hcross into a detector output applies antenna response and and applies correct time delays to each detector Parameters ---------- hp: h-plus version of GW waveform hc: h-cross version of GW waveform fs: sampling frequency ra: right ascension dec: declination psi: polarization angle det: detector Returns ------- ht: combined h-plus and h-cross version of waveform hp: h-plus version of GW waveform hc: h-cross version of GW waveform """ # compute antenna response and apply #Fp=ifos.antenna_response(ra,dec,float(event_time),psi,'plus') #Fc=ifos.antenna_response(ra,dec,float(event_time),psi,'cross') #Fp,Fc,_,_ = antenna.response(float(event_time), ra, dec, 0, psi, 'radians', det ) ht = hp + hc # overwrite the timeseries vector to reuse it return ht, hp, hc
def lambda_foo(itr, start_itrs, warmup_itrs, mul_lr=1): """ :param itr: itr >= start_itrs :param start_itrs: :param warmup_itrs: :param mul_lr: :return: """ if itr < start_itrs: return mul_lr else: if itr < start_itrs + warmup_itrs: return (itr - start_itrs) / warmup_itrs * mul_lr else: return mul_lr
def wrapTheta(theta): """ Wrap an angle from the real line onto (-180, 180]. Parameters ---------- theta : float Angle, in degrees. Returns ------- theta_wrapped : float The input, projected into (-180, 180]. """ return (theta + 90) % 360 - 90
def is_relative_path(s): """ Return whether the path given in argument is relative or not. """ tmp = s.replace(u"\\", u"/") return tmp.startswith(u"../") or tmp.startswith(u"~/") or tmp.startswith(u"./")
def lr5(step: int, base_lr: float) -> float: """LR5.""" lr = base_lr _lr = lr * 0.9 ** (step // 100) return max(_lr, 1e-6)
def calc_incidence(cases, pop): """Calculates the incidence value with the population and cases specified.""" return cases / pop * 100000
def _Join(array, delim=''): """ func join(items Array[Str]) Str ... """ # default is not ' '? return delim.join(array)
def indent_length(line_str): """Returns the indent length of a given string as an integer.""" return len(line_str) - len(line_str.lstrip())
def _twos_comp(val, bits): """ Convert an unsigned integer in 2's compliment form of the specified bit length to its signed integer value and return it. """ if val & (1 << (bits -1)) != 0: return val -(1 << bits) return val
def check_not_finished_board(board: list): """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Return True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5',\ '*?????*', '*?????*', '*2*1***']) False >>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215',\ '*35214*', '*41532*', '*2*1***']) True >>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215',\ '*35214*', '*41532*', '*2*1***']) False """ result = True for line in board : if "?" in line : result = False return result
def fact_rec(n): """Assumes n an int > 0 Returns n!""" if n == 1: return n else: return n*fact_rec(n - 1)
def inBytes(gb): """Convert bytes to gigabytes""" return gb * 1024. ** 3
def levelize_strength_or_aggregation(to_levelize, max_levels, max_coarse): """Turn parameter into a list per level. Helper function to preprocess the strength and aggregation parameters passed to smoothed_aggregation_solver and rootnode_solver. Parameters ---------- to_levelize : {string, tuple, list} Parameter to preprocess, i.e., levelize and convert to a level-by-level list such that entry i specifies the parameter at level i max_levels : int Defines the maximum number of levels considered max_coarse : int Defines the maximum coarse grid size allowed Returns ------- (max_levels, max_coarse, to_levelize) : tuple New max_levels and max_coarse values and then the parameter list to_levelize, such that entry i specifies the parameter choice at level i. max_levels and max_coarse are returned, because they may be updated if strength or aggregation set a predefined coarsening and possibly change these values. Notes -------- This routine is needed because the user will pass in a parameter option such as smooth='jacobi', or smooth=['jacobi', None], and this option must be "levelized", or converted to a list of length max_levels such that entry [i] in that list is the parameter choice for level i. The parameter choice in to_levelize can be a string, tuple or list. If it is a string or tuple, then that option is assumed to be the parameter setting at every level. If to_levelize is inititally a list, if the length of the list is less than max_levels, the last entry in the list defines that parameter for all subsequent levels. Examples -------- >>> from pyamg.util.utils import levelize_strength_or_aggregation >>> strength = ['evolution', 'classical'] >>> levelize_strength_or_aggregation(strength, 4, 10) (4, 10, ['evolution', 'classical', 'classical']) """ if isinstance(to_levelize, tuple): if to_levelize[0] == 'predefined': to_levelize = [to_levelize] max_levels = 2 max_coarse = 0 else: to_levelize = [to_levelize for i in range(max_levels-1)] elif isinstance(to_levelize, str): if to_levelize == 'predefined': raise ValueError('predefined to_levelize requires a user-provided ' 'CSR matrix representing strength or aggregation ' 'i.e., (\'predefined\', {\'C\' : CSR_MAT}).') to_levelize = [to_levelize for i in range(max_levels-1)] elif isinstance(to_levelize, list): if isinstance(to_levelize[-1], tuple) and\ (to_levelize[-1][0] == 'predefined'): # to_levelize is a list that ends with a predefined operator max_levels = len(to_levelize) + 1 max_coarse = 0 else: # to_levelize a list that __doesn't__ end with 'predefined' if len(to_levelize) < max_levels-1: mlz = max_levels - 1 - len(to_levelize) toext = [to_levelize[-1] for i in range(mlz)] to_levelize.extend(toext) elif to_levelize is None: to_levelize = [(None, {}) for i in range(max_levels-1)] else: raise ValueError('invalid to_levelize') return max_levels, max_coarse, to_levelize
def num_same_elements(arr_1, arr_2): """Counts the number of same elements in a given lists Args: arr_1(list): first array arr_2(list): second array Returns: same elements(int): number of same elements """ result = set(arr_1).intersection(set(arr_2)) return len(result)
def is_str_float(i): """Check if a string can be converted into a float""" try: float(i); return True except ValueError: return False
def arnonA_mono_to_string(mono, latex=False, p=2): """ String representation of element of Arnon's A basis. This is used by the _repr_ and _latex_ methods. INPUT: - ``mono`` - tuple of pairs of non-negative integers (m,k) with `m >= k` - ``latex`` - boolean (optional, default False), if true, output LaTeX string OUTPUT: ``string`` - concatenation of strings of the form ``X^{m}_{k}`` for each pair (m,k) EXAMPLES:: sage: from sage.algebras.steenrod.steenrod_algebra_misc import arnonA_mono_to_string sage: arnonA_mono_to_string(((1,2),(3,0))) 'X^{1}_{2} X^{3}_{0}' sage: arnonA_mono_to_string(((1,2),(3,0)),latex=True) 'X^{1}_{2} X^{3}_{0}' The empty tuple represents the unit element:: sage: arnonA_mono_to_string(()) '1' """ if len(mono) == 0: return "1" else: string = "" for (m,k) in mono: string = string + "X^{" + str(m) + "}_{" \ + str(k) + "} " return string.strip(" ")
def formsetsort(formset, arg): """ Takes a list of formset dicts, returns that list sorted by the sortable field. """ if arg: sorted_list = [] for item in formset: position = item.form[arg].data if position and position != "-1": sorted_list.append((int(position), item)) sorted_list.sort() sorted_list = [item[1] for item in sorted_list] for item in formset: position = item.form[arg].data if not position or position == "-1": sorted_list.append(item) else: sorted_list = formset return sorted_list
def find_max(nums): """ >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums) == max(nums) True True True True """ max_num = nums[0] for x in nums: if x > max_num: max_num = x return max_num
def get_decimal(f, aprox=2): """Gets the decimal part of a float Args: f (float): Real number to get the decimal part from aprox (int)(optional): Number of decimal digits, default is 2. Returns: float: Decimal part of f """ f = round((f - int(f)), aprox) return f
def parse_int_list(range_string, delim=',', range_delim='-'): """ Returns a sorted list of positive integers based on *range_string*. Reverse of :func:`format_int_list`. Args: range_string (str): String of comma separated positive integers or ranges (e.g. '1,2,4-6,8'). Typical of a custom page range string used in printer dialogs. delim (char): Defaults to ','. Separates integers and contiguous ranges of integers. range_delim (char): Defaults to '-'. Indicates a contiguous range of integers. >>> parse_int_list('1,3,5-8,10-11,15') [1, 3, 5, 6, 7, 8, 10, 11, 15] """ output = [] for element in range_string.strip().split(delim): # Range if range_delim in element: range_limits = list(map(int, element.split(range_delim))) output += list(range(min(range_limits), max(range_limits)+1)) # Empty String elif not element: continue # Integer else: output.append(int(element)) return sorted(output)
def get_preview_html(template, interactive=False): """get_preview_html Parameters ---------- template : {{_type_}} Returns ------- Example ------- """ text = template['text'] if interactive: html = '<span style="background-color:#c8f442" class="cursor-pointer">{}</span>' else: html = '<span style="background-color:#c8f442">{}</span>' l_offset = len(html.format('')) offset = 0 tokenmap = sorted(template['tokenmap'], key=lambda x: x['idx']) for token in tokenmap: start = token['idx'] + offset end = start + len(token['text']) prefix = text[:start] suffix = text[end:] text = prefix + html.format(token['text']) + suffix offset += l_offset return text
def str2mdown(text): """ Converts the given text string to Markdown . :param text: The string to be converted. :return: The Markdown converted text. """ if text is None: return None else: return text.replace("-", "\\-") \ .replace("!", "\\!") \ .replace(".", "\\.") \ .replace(">", "\\>") \ .replace("_", "\\_")
def RPL_AWAY(sender, receipient, message): """ Reply Code 301 """ return "<" + sender + ">: " + message
def _step(dim, ref, radius): """ Helper: returns range object of axis indices for a search window. :param int dim: Total length of the grid dimension :param int ref: The desired number of steps :param int radius: The number of cells from the centre of the chip eg. (chipsize / 2) :return: range object of axis indices :rtype: range """ # if ref == 1: # # centre a single search step # return xrange(dim // 2, dim, dim) # fake step to ensure single xrange value # if ref == 2: # handle 2 search windows, method below doesn't cover the case # return [radius, dim-radius-1] # max_dim = dim - (2*radius) # max possible number for refn(x|y) # step = max_dim // (ref-1) step_size = dim // ref return range(radius, dim-radius, step_size)
def is_even(number=0): """ Checks if a given number is even or not """ print('Number = ', number) return (number % 2 == 0)
def wrap_space_around(text): """Wrap one additional space around text if it is not already present. Args: text (str): Text Returns: str: Text with extra spaces around it. """ if text[0] != " " and text[-1] != " ": return " " + text + " " elif text[0] != " ": return " " + text elif text[-1] != " ": return text + " " else: return text
def list_search(to_search, key, value): """ Given a list of dictionaries, returns the dictionary that matches the given key value pair """ result = [element for element in to_search if element[key] == value] if result: return result[0] else: raise KeyError
def _val_subtract(val1, val2, dict_subtractor, list_subtractor): """ Find the difference between two container types Returns: The difference between the values as defined by list_subtractor() and dict_subtractor() if both values are the same container type. None if val1 == val2 val1 if type(val1) != type(val1) Otherwise - the difference between the values """ if val1 == val2: # if the values are the same, return a degenerate type # this case is not used by list_subtract or dict_subtract return type(val1)() if isinstance(val1, dict) and isinstance(val2, dict): val_diff = dict_subtractor(val1, val2) elif isinstance(val1, (list, tuple)) and isinstance(val2, (list, tuple)): val_diff = list_subtractor(val1, val2) else: val_diff = val1 return val_diff
def dict_select(d, keys): """ Return a dict only with keys in the list of keys. example: clust_kw = 'min_density min_size haircut penalty'.split() clust_kwargs = ut.dict_select(kwargs, clust_kw) """ return dict([(k,d[k]) for k in keys if k in d])
def _safe_restore(data, rep): """ Safely restore pickled data, resorting to representation on fail """ import pickle try: return pickle.loads(data) except Exception: return rep
def webstring(value): """ Convert a Python dictionary to a web string where the values are in the format of 'foo=bar&up=down'. This is necessary when processing needs to be done on a dictionary but the values need to be passed to urllib2 as POST data. """ data = "" for key in value: newstring = key + "=" + value[key] + "&" data += newstring return(data.rstrip("&"))
def Problem_f(name, input, output): """ :param name: The "name" of this Problem :param input: The "input" of this Problem :param output: The "output" of this Problem """ res = '\\begin{example}\n' if name: res += '[' + name + ']\n' res += 'Input: ' + input + '\n' res += 'Output: ' + output + '\n' res += '\\end{example}\n' return res
def _op_seq_str_suffix(line_labels, occurrence_id): """ The suffix (after the first "@") of a circuit's string rep""" if occurrence_id is None: return "" if line_labels is None or line_labels == ('*',) else \ "@(" + ','.join(map(str, line_labels)) + ")" else: return "@()@" + str(occurrence_id) if (line_labels is None or line_labels == ('*',)) \ else "@(" + ','.join(map(str, line_labels)) + ")@" + str(occurrence_id)
def revcomp_str(seq): """ Returns the reverse complement of a `str` nucleotide sequence. Parameters ---------- + seq `str` nucleotide sequence """ comp = str.maketrans('ACGTRYMKWSBDHV', 'TGCAYRKMWSVHDB') anti = seq.translate(comp)[::-1] return anti
def is_float(value): """ Returns whether given values is float """ try: float(value) return True except Exception: return False
def keyfilter_json(json_object, filter_func, recurse=True): """ Filter arbitrary JSON structure by filter_func, recursing into the structure if necessary :param json_object: :param filter_func: a function to apply to each key found in json_object :param recurse: True to look recurse into lists and dicts inside json_object :return: a filtered copy of json_object with identical types at each level """ filtered_object = json_object if isinstance(json_object, list) and recurse: filtered_object = list() for item in json_object: filtered_object.append(keyfilter_json(item, filter_func)) elif isinstance(json_object, dict): filtered_object = dict() for k, v in json_object.items(): if filter_func(k): filtered_object[k] = keyfilter_json(v, filter_func) if recurse else v return filtered_object
def _find_year(year, year_list): """ Internal helper function, not exported. Returns the first year in the list greater or equal to the year :param year: year of interest :param year_list:list: list of years, likely from a yaml census list :return: first year greater than or equal to "year" in "year_list" """ year_list.sort() # Should be sorted, but just in case for i in year_list: if i >= year: return i
def validation_errors_to_error_messages(validation_errors): """ Simple function that turns the WTForms validation errors into a simple list """ errorMessages = [] for field in validation_errors: for error in validation_errors[field]: errorMessages.append(f"{error}") return errorMessages
def ipv4_cidr_to_netmask(bits): """Convert CIDR bits to netmask """ netmask = '' for i in range(4): if i: netmask += '.' if bits >= 8: netmask += '%d' % (2**8-1) bits -= 8 else: netmask += '%d' % (256-2**(8-bits)) bits = 0 return netmask
def attributes(attrs): """Returns an attribute list, constructed from the dictionary attrs. """ attrs = attrs or {} ident = attrs.get("id","") classes = attrs.get("classes",[]) keyvals = [[x,attrs[x]] for x in attrs if (x != "classes" and x != "id")] return [ident, classes, keyvals]
def is_palindrome_v2(s): """ (str) -> bool Return True if and only if s is a palindrome. >>> is_palindrome_v1('noon') True >>> is_palindrome_v1('racecar') True >>> is_palindrome_v1('dented') False """ n = len(s) return s[:n//2] == s[n-1:n-n//2-1:-1]
def bit(value, position, length=1): """ Return bit of number value at position Position starts from 0 (LSB) :param value: :param position: :param length: :return: """ binary = bin(value)[2:] size = len(binary) - 1 if position > size: return 0 else: return int(binary[size - position: size - position + length], 2)
def word_tokenizer(text): """ Dataset is already tokenized """ return text.split(" ")
def get_artist_tags(connect, artist_mbid, maxtags=20): """ Get the musicbrainz tags and tag count given a musicbrainz artist. Returns two list of length max 'maxtags' Always return two lists, eventually empty """ if artist_mbid is None or artist_mbid == '': return [],[] # find all tags q = "SELECT tag.name,artist_tag.count FROM artist" q += " INNER JOIN artist_tag ON artist.id=artist_tag.artist" q += " INNER JOIN tag ON tag.id=artist_tag.tag" q += " WHERE artist.gid='"+artist_mbid+"'" q += " ORDER BY count DESC LIMIT "+str(maxtags) res = connect.query(q) if len(res.getresult()) == 0: return [],[] return map(lambda x: x[0],res.getresult()),map(lambda x: x[1],res.getresult())
def get_geocoord(coord, min_coord, max_coord, size): """Transform abscissa from pixel to geographical coordinate For horizontal operations, 'min_coord', 'max_coord' and 'size' refer respectively to west and east coordinates and image width. For vertical operations, 'min_coord', 'max_coord' and 'size' refer respectively to north and south coordinates and image height. Parameters ---------- coord : list Coordinates to transform min_coord : float Minimal coordinates of the image, as a pixel reference max_coord : float Maximal coordinates of the image, as a pixel reference size : int Image size, in pixels Returns ------- list Transformed coordinates, expressed in the accurate coordinate system """ if isinstance(coord, list): return [min_coord + c * (max_coord - min_coord) / size for c in coord] elif isinstance(coord, int): return min_coord + coord * (max_coord - min_coord) / size else: raise TypeError( "Unknown type (%s), pass a 'list' or a 'int'", type(coord) )
def validate_password(password): """A simple password validator """ length = len(password) > 7 lower_case = any(c.islower() for c in password) upper_case = any(c.isupper() for c in password) digit = any(c.isdigit() for c in password) return length and lower_case and upper_case and digit
def n_tuple_name(n): """Return the proper name of an n-tuple for given n.""" names = {1: 'single', 2: 'pair', 3: 'triple', 4: 'quad'} return names.get(n, '%d-tuple' % n)
def _OsStatus(status, diagnose): """Beautifier function for OS status. @type status: boolean @param status: is the OS valid @type diagnose: string @param diagnose: the error message for invalid OSes @rtype: string @return: a formatted status """ if status: return "valid" else: return "invalid - %s" % diagnose
def calc_point_squre_dist(point_a, point_b): """Calculate distance between two marking points.""" distx = point_a[0] - point_b[0] disty = point_a[1] - point_b[1] return distx ** 2 + disty ** 2
def FVIF(i,n,m=1): """ interest years payments per year """ FVIF = (1 + i/m)**(m*n) return FVIF
def buildranges(amin, amax, rangeval): """Retunrs a list of tuples, with the string-range first and then the numbers in a tuple: [('990-1020', (990, 1020)), ('1020-1050', (1020, 1050))] """ r = [] allvalues = range(amin, amax, rangeval) for index, item in enumerate(allvalues): if (index + 1) < len(allvalues): a = "%d-%d" % (item, allvalues[index + 1]) r.append((a, (item, allvalues[index + 1]))) return r
def track_path(actions, path=None): """ <Purpose> Given a list of actions, it tracks all the activity on files. If a path is given, only the activity on that path will be tracked. Otherwise the activity on all paths will be tracked. <Arguments> actions: A list of actions from a parsed trace path: The path to track <Returns> tracked_actions: A list with the tracked actions """ # this list will contain nested lists inside it with each nested list being a # tracked activity for a file tracked_actions = {} # maps fd to the file. fd_to_file = {} for action in actions: # get the name of the syscall and remove the "_syscall" part at the end. action_name = action[0][:action[0].find("_syscall")] if action_name == "open": # int open(const char *pathname, int flags, mode_t mode); # # ('open_syscall', ('syscalls2.txt', ['O_RDWR', 'O_CREAT', 'O_APPEND'], # ['S_IWUSR', 'S_IRUSR', 'S_IWGRP']), # (4, None)) # get the pathname from the action pathname = action[1][0] # if we are tracking a specific path, only proceed if the pathname is the # one we want to track if path != None and pathname != path: continue # if open failed do not proceed if action[2][0] == -1: continue # get the fd and add it to the list of fds to track fd = action[2][0] # create a new entry in tracked ections tracked_actions[pathname] = [] fd_to_file[fd] = pathname # track this action flags = action[1][1] tracked_actions[pathname].append("OPEN \"" + pathname + "\" flags: " + "|".join(flags)) elif action_name == "close": # int close(int fd); # # ('close_syscall', (3,), (0, None)) # ('close_syscall', (3,), (-1, 'EBADF')) fd = action[1][0] if fd not in fd_to_file: continue # if close was unsuccessful do not proceed if action[2][0] == -1: continue # track this action tracked_actions[fd_to_file[fd]].append("CLOSE FILE") del fd_to_file[fd] elif action_name in ['creat', 'statfs', 'access', 'stat', 'link', 'unlink', 'chdir', 'rmdir', 'mkdir', 'symlink']: path1 = action[1][0] item = '' dangerous = ["chmod", "link", "symlink", "unlink"] if action_name in dangerous: item = "**" action_name = action_name.upper() # track this action item += action_name + "\n arguments: " + \ str(action[1]).strip("()") + "\n return: " + \ str(action[2][0]) + ", " + str(action[2][1]).strip("(),") if path1 not in tracked_actions: tracked_actions[path1] = [] tracked_actions[path1].append(item) elif action_name in ["fstatfs", "fstat", "lseek", "read", "write", "dup", "dup2", "dup3", "getdents", "fcntl"]: fd = action[1][0] if fd not in fd_to_file: continue if action_name == "read": action_name = "**READ" # track this action item = action_name + "\n arguments: " + \ str(action[1]).strip("()") + "\n return: " + \ str(action[2][0]) + ", " + str(action[2][1]).strip("(),") tracked_actions[fd_to_file[fd]].append(item) return tracked_actions
def mac_hex(number): """Convert integer to hexadecimal for incrementing MAC addresses. :param number: Integer number less than 100. :type number: int :returns: 2-digit hexadecimal representation of the input number. :rtype: str """ temp = hex(number)[2:] if number < 16: temp = "0{0}".format(temp) elif number > 99: raise NotImplementedError( "Incrementing MAC addresses only implemented up to 99.") else: pass return temp
def near(n: int, *args) -> str: """ Build the filter to find articles containing words that occur within `n` words of each other. eg. near(5, "airline", "climate") finds articles containing both "airline" and "climate" within 5 words. """ if len(args) < 2: raise ValueError("At least two words must be provided") return f"near{str(n)}:" + '"' + " ".join([a for a in args]) + '"'
def create_matrix(length, height): """ Creates a matrix to store data in using a certain length and height. """ matrix = [[0 for x in range(length)] for y in range(height)] return matrix
def sanitize(string): """ Turns '-' into '_' for accumulo table names """ return string.replace('-', '_')
def build_type_flag(compiler, build_type): """ returns flags specific to the build type (Debug, Release, etc.) (-s, -g, /Zi, etc.) """ if not compiler or not build_type: return "" if str(compiler) == 'Visual Studio': if build_type == 'Debug': return '-Zi' else: if build_type == 'Debug': return '-g' elif build_type == 'Release' and str(compiler) == 'gcc': return '-s' return ""
def fv_annuity(n,c,r): """ Objective: estimate future value of an annuity n : number of payments c : payment amount r : discount formula : c/r*((1+r)**n-1) e.g., >>>fv_annuity(2,100,0.1) 210.0000000000002 """ return c/r*((1+r)**n-1)
def nott(n): """Negative One To The n, where n is an integer.""" return 1 - 2*(n & 1)
def jaccard(ground, found): """Cardinality of set intersection / cardinality of set union.""" ground = set(ground) return len(ground.intersection(found))/float(len(ground.union(found)))