content
stringlengths
42
6.51k
def render_operation_failures(failures): """ Renders the provided operation failures. :param failures: failures to render :return: rendered string """ result = '\n|\t'.join(failures) return '\n|\t{}'.format(result) if result else '-'
def _normalize_location(loc): """ Return a dictionary that represents the given location. If it's already a dictionary it's returned as-is but if not we try different attributes to get the latitude (``latitude`` or ``lat``) and longitude (``longitude``, ``lng``, or ``lon``). """ if isinstanc...
def get_human_readable_time(seconds: float) -> str: """Convert seconds into a human-readable string. Args: seconds: number of seconds Returns: String that displays time in Days Hours, Minutes, Seconds format """ prefix = "-" if seconds < 0 else "" seconds = abs(seconds) int...
def calc_pid(seq1, seq2): """ Calculates the percentage ID (still as a decimal) between two sequences. Parameters ---------- seq1: str seq2: str Returns ------- pid: float """ alnlen = len(seq1) identical = 0 for i in range(0, len(seq1)): if seq1[i].isal...
def is_transmitter(metric): """Is interface ``metric`` a transmitter? :param dict metric: The metric. :rtype: :py:class:`bool` """ return metric.get("name", "").endswith("tx")
def add_extension_if_needed(filepath, ext): """Add the extension ext to fpath if it doesn't have it. Parameters ---------- filepath: str File name or path ext: str File extension Returns ------- filepath: str File name or path with extension added, if needed. ...
def label_match(l1, l2): """ for two sequences with different length, return whether the short one matches the long one(is a substring) """ l1, l2 = list(l1), list(l2) if len(l1) > len(l2): l1, l2 = l2, l1 now = -1 for k in l1: try: now = l2.index(k, now + 1) ...
def normalize_slots(slots): """Slot manipulation library This function "normalizes" a list of slots by merging all consecutive or overlapping slots into non-overlapping ones. IMPORTANT: the input slots array has to be sorted by initial datetime of the slot, this is, for a given slot at position 'i',...
def isTernary(string): """ check if given compound is a ternary """ str1 = string.split('_')[0] nonumber='' for s in str1: if s=='.': return False if s.isdigit(): nonumber=nonumber+' ' else: nonumber=nonumber+s if len(nonumber.spli...
def histogram(s): """to check s in string""" d={} for c in s: d[c]=1+d.get(c,0) return d
def _check_available_port(port, ipv6=True): """ True -- it's possible to listen on this port for TCP/IPv4 or TCP/IPv6 connections. False -- otherwise. """ import socket # noinspection PyBroadException try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('127....
def _remove_illegal_chars(x) -> str: """ Remove illegal quote characters Parameters ---------- x: str Returns ------- str """ return x.replace("\\\\", "").replace('"', "")
def update_markup(markup, field_id, new_name=None): """Helper function to find and rename or delete value from markup""" if isinstance(markup, list): # this is a sequence item so we look at the 'sub_rules' if they exist for row in markup: if 'sub_rules' in row: return...
def _level_parse(level): """Parse levels as integers, or the string 'surface'""" if level == "surface": return str(level) else: return int(level)
def ddmmss_to_deg(position): """ Converts positions in deg:min:sec format to fractional degrees. input: ------ position: str Position in deg:min:sec format. output: ------- position_deg: float Position in fractional degrees. """ split_position = position.split(...
def consecutive_seconds(rel_seconds, window_size_sec, stride_sec=1): """ Function: return a list of all the possible [window_start, window_end] pairs containing consecutive seconds of length window_size_sec inside. Args: rel_seconds: a list of qualified seconds window_size_sec: int ...
def url_add_api_key(url_dict: dict, api_key: str) -> str: """Attaches the api key to a given url Args: url_dict: Dict with the request url and it's relevant metadata. api_key: User's API key provided by US Census. Returns: URL with attached API key infor...
def get_coverage_per_file(target_cov): """Returns the coverage per file within |target_cov|.""" return target_cov['data'][0]['files']
def all_of_type(objects, type): """Return all objects that are instances of a given type. """ return [o for o in objects if isinstance(o, type)]
def navigate_indexed_path(source, path_): """ """ parts = path_.split("[") p_ = parts[0] index = int(parts[1][:-1]) value = source.get(p_, None) if value is None: return value try: return value[index] except IndexError: return None
def lower(text): """Returns text that has been lower. Args: text (str): input text to process. Output: result (str): corresponding text which has been lower. """ return text.lower()
def as_list(val): """return a list with val if val is not already a list, val otherwise""" if isinstance(val, list): return val else: return [val]
def ode(x,r,xc): """ Compute the slope of a coordinate in an circle Params: x = the coordinate of desire slop r = radius of the slope xc = x coordinate of the center return: slop of at the coordinate provided """ return -(r**2 - (x - ...
def format_tqdm_metric(value: float, best_value: float, fmt: str) -> str: """Formats a value to display in tqdm.""" if value == best_value: return (fmt + '*').format(value) return (fmt + ' (' + fmt + '*)').format(value, best_value)
def move_names_to_the_end(names, names_to_move_to_the_end): """ Remove the items of ``names_to_move_to_the_end`` from ``names`` and append to the right of names >>> names = ['a','c','d','e'] >>> names_to_move_to_the_end = ['c','e'] >>> move_names_to_the_end(names, names_to_move_to_the_end) ...
def time_to_text(seconds): """ This function converts a time in seconds into a reasonable format. Parameters ---------- seconds : float Time in seconds. Returns ------- time_as_text: str Time in s, min, h, d, weeks or years depending on input. """ if seconds > ...
def _get_usb_hub_map(device_info_list): """Creates a map of usb hub addresses to device_infos by port. Args: device_info_list (list): list of known usb_connections dicts. Returns: dict: map of usb hub addresses to device_infos by port """ map_usb_hub_ports = {} for device_info in device_info_li...
def _decode_config(c, num_variables): """inverse of _serialize_config, always converts to spin.""" def bits(c): n = 1 << (num_variables - 1) for __ in range(num_variables): yield 1 if c & n else -1 n >>= 1 return tuple(bits(c))
def isprime(number): """ Check if a number is a prime number :type number: integer :param number: The number to check """ if number == 1: return False for i in range(2, int(number**0.5) + 1): if number % i == 0: return False return True
def primary_beam_shape_tag_from_primary_beam_shape_2d(primary_beam_shape_2d): """Generate an image psf shape tag, to customize phase names based on size of the image PSF that the original PSF \ is trimmed to for faster run times. This changes the phase name 'phase_name' as follows: image_psf_shape = 1...
def _check_filepath(filepath): """ Validate if the filepath attr/arg is a str :param str filepath: object to validate :return str: validated filepath :raise TypeError: if the filepath is not a string """ # might be useful if we want to have multiple locked paths in the future # def _che...
def hamming_distance(s1, s2): """Returns the Hamming distance between two equal-length sequences""" if len(s1) != len(s2): raise ValueError("Sequences of unequal length") return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
def log(message, *values): """ log :param message: :param values: :return: """ if not values: print(message) else: values_str = ', '.join(str(x) for x in values) print('{0}: {1}'.format(message, values_str)) return True
def format_ip_int(data: dict): """Collapse napalm ip_interface output to: { {{ Interface }}: ipv4_address: {{ IP }}, ipv6_address: {{ IP }} } """ output = {} for k, v in data.items(): ip_dict = {} for i in range(4, 7, 2): ip = v.get(f"...
def first_sentence(str): """ Return the first sentence of a string - everything up to the period, or the whole text if there is no period. >>> first_sentence('') '' >>> first_sentence('Incomplete') '' >>> first_sentence('The first sentence. This is ignored.') 'The first sentence.' ...
def read_any_text_file(file_name): """ This function trys to read and text file and return its contents. :param file_name: The file to read. If the file isn't in the same directory as this program, you'll need to enter the full path, i.e. /home/username/path/to/file or drive_letter:\\full\\path\\to\\fi...
def page_not_found(e): """Return a custom 404 error.""" return 'Sorry, nothing at this URL.', 404
def undistort_halcon_polynomial(u_tilde, v_tilde, k1, k2, k3, p1, p2): """ From the HALCON Docs: The polynomial model uses three parameters () to model the radial distortions and two parameters () to model the decentering distortions. The following equations transform the distorted image pl...
def __heuristic(a, b): """ The heuristic for A* Grid search """ return sum(abs(ai - bi) for ai, bi in zip(a, b))
def make_rule_key(prefix, rule, group_id, cidr_ip): """Creates a unique key for an individual group rule""" if isinstance(rule, dict): proto, from_port, to_port = [rule.get(x, None) for x in ('proto', 'from_port', 'to_port')] # fix for 11177 if proto not in ['icmp', 'tcp', 'udp'] and fro...
def tupilate(source, val): """Broadcasts val to be a tuple of same size as source""" if isinstance(val, tuple): assert(len(val) == len(source)) return val else: return (val,)*len(source)
def safe_string(o): """This will make string out of ANYTHING without having to worry about the stupid Unicode errors This function tries to make str/unicode out of ``o`` unless it already is one of those and then it processes it so in the end there is a harmless ascii string. Args: o: Anything...
def get_logs_url(build_id, project_id='oss-fuzz-base'): """Returns url that displays the build logs.""" url_format = ('https://console.developers.google.com/logs/viewer?' 'resource=build%2Fbuild_id%2F{0}&project={1}') return url_format.format(build_id, project_id)
def gradients_for_var_group(var_groups, gradients, name): """Returns a slice of `gradients` belonging to the var group `name`.""" start = 0 for group_name in sorted(var_groups.keys()): n = len(var_groups[group_name]) if group_name == name: return gradients[start:start+n] start += n return []
def versionStrToTuple(versionStr): """ Converts a version string to tuple E.g. 'x.y.z' to (x, y, x) """ versionInfo = [] for elem in versionStr.split('.'): try: versionInfo.append(int(elem)) except: versionInfo.append(elem) return tuple(versionInfo)
def unit_sort(text): """ A function to sort files when timepoints are encoded within the filename using common abbreviations. Parameters: text (str): filename e.g. (proteinX_100ns) Returns: Tuple(int, text): for sorting files """ if text.startswith("-"): return 0, t...
def remove_smallest(nums): """Remove smallest integer from list of integers. input = integers, in list output = integers, in list, missing the smallest value ex. [1,2,3,4,5] = [2,3,4,5] ex. [5,3,2,1,4] = [5,3,2,4] ex. [2,2,1,2,1] = [2,2,2,1] """ if not nums: return [] output...
def target_glucose_value( percent_effect_duration, min_value, max_value ): """ Computes a target glucose value for a correction, at a given time during the insulin effect duration Arguments: percent_effect_duration -- percent of time elapsed of the insulin ...
def get_risk(rising, rel_level): """Determines the threat level from relative level and whether it is rising or falling""" if rel_level >= 1 and rising or rel_level >= 1.5: threat = "Severe" elif rel_level >= 0.75 and rising or rel_level >=1 and not rising: threat = "High" elif rel_level...
def irm(target, interference): """Compute ideal ratio mask (IRM)""" mask = target / (target + interference) return mask
def remove_every_other(lst): """Return a new list of other item. >>> lst = [1, 2, 3, 4, 5] >>> remove_every_other(lst) [1, 3, 5] This should return a list, not mutate the original: >>> lst [1, 2, 3, 4, 5] """ return lst[::2]
def convert_bytes(bytes): """Returns given bytes as prettified string.""" bytes = float(bytes) if bytes >= 1099511627776: terabytes = bytes / 1099511627776 size = '%.2fT' % terabytes elif bytes >= 1073741824: gigabytes = bytes / 1073741824 size = '%.2fG' % gigabytes ...
def rk4(y, x, dx, f): """computes 4th order Runge-Kutta for dy/dx. y is the initial value for y x is the initial value for x dx is the difference in x (e.g. the time step) f is a callable function (y, x) that you supply to compute dy/dx for the specified values. """ k1 = dx * f(y...
def escape(s): """ Replace potential special characters with escaped version. For example, newline => \\n and tab => \\t """ return s.replace('\n', '\\n').replace('\t', '\\t').replace('\r', '\\r')
def format_dtype(form_data, key, dtype): """ """ if key not in form_data: return None try: res = dtype(form_data[key]) except: return None return res
def generate_jmespath(text: str, name_contains_array: str) -> str: """ Helper function to generate a bit of jmespath.org code. Example: ```python reference = "contains(labels, 'hi') && contains(labels, 'there')" assert generate_jmespath("hi, there", 'labels') == reference assert generate_...
def make_sid_cookie(sid, uri): """Given a sid (from a set-cookie) figure out how to send it back""" # sometime near 0.92, port got dropped... # uritype, uribody = urllib.splittype(uri) # host, path = urllib.splithost(uribody) # host, port = urllib.splitnport(host) # if port == -1: # port...
def interval_to_milliseconds(interval): """Convert a Binance interval string to milliseconds :param interval: Binance interval string, e.g.: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w :type interval: str :return: int value of interval in milliseconds None if interval pre...
def CORMSE(X,Y): """ caculate the RMSE of X and Y """ import math num=len(X) if len(X)!=len(Y) or len(X)==0: print ("list X and list Y have different length!") RMSE=9999.0 return RMSE else: wucha=0.0 for i in range(num): wucha=wucha+ math.pow((X[...
def add_timestamps(configs, timestamps_dict): """For each config, set its timestamp_format field based on its timestamp_format_key field.""" for config in configs: config["timestamp_format"] = timestamps_dict[config["timestamp_format_key"]] return configs
def BitmaskBool(bitmask, value): """Returns True or False depending on whether a particular bit has been set. Microsoft uses bitmasks as a compact way of denoting a number of boolean settings. The second bit, for example, might be the ADS_UF_ACCOUNTDISABLE bit, so if the second bit is a 1, then the account is...
def _detect_replacing_tx_low_gas_price_parity(message): """source: https://github.com/paritytech/parity/blob/1cd93e4cebeeb7b14e02b4e82bc0d4f73ed713d9/rpc/src/v1/helpers/errors.rs#L316 """ return message.startswith("Transaction gas price is too low")
def four_digit_range(s, lo, hi): """Return True if s is a 4 digit number string in range of lo-hi (inclusive)""" if len(s) != 4: return False return int(s) in range(lo, hi + 1)
def oscar_calculator(wins: int) -> float: """ Helper function to modify rating based on the number of Oscars won. """ if 1 <= wins <= 2: return 0.3 if 3 <= wins <= 5: return 0.5 if 6 <= wins <= 10: return 1.0 if wins > 10: return 1.5 return 0
def egcd(a, b): """ Extended Euclidean Algorithum """ if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y)
def type_check(obj: object, type_name: str) -> bool: """ circulation dependency problems can be resolved by TYPE_CHECKING, but this can not resolve NO type linting problems. eg: if isinstance(msg, Contact): pass in this problem, program don't import Contact at running time. So, it wi...
def mac_from_ip(ip_address): """Create a MAC address based on the provided IP. Algorithm: - the first 2 bytes are fixed to 06:00 - the next 4 bytes are the IP address Example of function call: mac_from_ip("192.168.241.2") -> 06:00:C0:A8:F1:02 C0 = 192, A8 = 168, F1 = 241 and 02 = 2 :p...
def nvl(value, default): """ Evaluates if value es empty or None, if so returns default Parameters: value: the evalue to evaluate default: the default value Returns: value or default """ if value: return value return default
def bool_flag(s): """Helper function to make argparse work with the input True and False. Otherwise it reads it as a string and is always set to True. :param s: string input :return: the boolean equivalent of the string s """ if s == '1' or s == 'True': return True elif s == '0' or s ...
def prepare_data(text): """ Prepare data """ labels = [t.split()[0] for t in text] labels = [l.split(':')[0] for l in labels] X = [t.split()[1:] for t in text] X = [' '.join(t) for t in X] return X, labels
def get_relative_name(task_list, bug_id, current_name): """Convert a name to a relative name.""" for task in task_list: if current_name.endswith("!"): new_current_name = "%sbug_%i" % (current_name, task.bug_id) else: new_current_name = "%s.bug_%i" % (current_name, task.bu...
def row_multiply(matrix, row, factor): """ Multiplies a row by a factor :param matrix: List of lists of equal length containing numbers :param row: index of a row :param factor: multiplying factor :return: List of lists of equal length containing numbers """ matrix[row] = [i*factor for i...
def std(vals): """Computes the standard deviation from a list of values.""" n = len(vals) if n == 0: return 0.0 mu = sum(vals) / n if mu == 1e500: return NotImplemented var = 0.0 for val in vals: var = var + (val - mu)**2 return (var / n)**0.5
def clean_url_fragment(f): """ Args: - f: (str) Returns: (str) """ return f.strip('/')
def problem48(limit): """Problem 48 - Self powers""" # Lazy result = 0 for x in range(1, limit + 1): result += x ** x return int(str(result)[-10:])
def build_iterator(obj_x, obj_y): """Build a cross-tabulated iterator""" l = [] for x in obj_x: for y in obj_y: l.append((x, y)) return l
def afill(start, end, ntries): """A function that fill evenly spaced values between two numbers""" step = (end-start)/float(ntries+1) if ntries > 0 else 0 final_list = [float(start) + (i+1)*step for i in range(ntries)] return(final_list)
def count_genes(person, one_gene, two_genes): """ Subfunction within joint_probability and update to count the number of copies of the gene of interest that a given person carries. """ if person in one_gene: return 1 elif person in two_genes: return 2 else: return 0
def _is_null_msg(dialect, msg, field_name): """ easier unit testing this way """ if dialect == 'mssql': if 'Cannot insert the value NULL into column \'%s\'' % field_name in msg: return True elif dialect == 'sqlite': if '.%s may not be NULL' % field_name in msg: ...
def smart_truncate(text, max_length=100, suffix='...'): """ Returns a string of at most `max_length` characters, cutting only at word-boundaries. If the string was truncated, `suffix` will be appended. """ if text is None: return '' # Return the string itself if length is...
def string_dist(s1, s2, wildcard = "N", letters = ["A","T","C","G"]): """ compute the hamming distance between two aligned strings with wildcards Arguments ---------- s1: the first string s2: the second string wildcard: the letter of the wildcard s1 and s2 should be of the same length and their positions s...
def memoize(n): """ :type n: int :rtype: int """ cache = {0: 0, 1: 1} for i in range(2, n+1): cache[i] = cache[i-1] + cache[i-2] return cache[n]
def _equalsIgnoreCase(a, b): """ Return true iff a and b have the same lowercase representation. >>> _equalsIgnoreCase('dog', 'Dog') True >>> _equalsIgnoreCase('dOg', 'DOG') True """ return a == b or a.lower() == b.lower()
def find_insertion_point(list_, i): """ Return the index where list_[i] belongs in list_[:i + 1]. @param list list_: list to find insertion point in @param int i: index of element to insert @rtype: int >>> find_insertion_point([1, 3, 2], 2 ) 1 """ v = list_[i] while i > 0 and l...
def apply_velocities(pos, vels): """applies velocities by adding velocity to the position for each moon in each dimension """ for i, moon_position in enumerate(pos): for dimmension, _ in enumerate(moon_position): moon_position[dimmension] += vels[i][dimmension] return pos
def payables_turnover(purchases, average_trade_payables): """Computes payables turnover. Parameters ---------- purchases : int or float Purchases average_trade_payables : int or float Average trade payables Returns ------- out : int or float Purchases turnover ...
def mcd(a: int, b: int) -> int: """This function returns the greatest common divisor from a and b. Args: a (int): dividend. b (int): divider. Returns: int: the GCD from a and b. """ if a % b == 0: return b return mcd(b, a % b)
def font_stretch(keyword): """``font-stretch`` descriptor validation.""" return keyword in ( 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded')
def farenheit(ctemp): """ Convert celcius to farenheit.""" return round(9.0/5.0 * ctemp + 32)
def calc_RMM_phase(RMM1, RMM2, amp_thresh=0): """ Given RMM1 and RMM2 indices, calculate MJO phase. Provided by Zane K. Martin (CSU). Args: RMM1: EOF for MJO phase space diagram. RMM2: EOF for MJO phase space diagram. amp_thresh (int): MJO amplitude threshold. Defaults to 0....
def get_current_categories(request, object): """Returns all current categories based on given request. Current categories are the current selected category and all parent categories of it. """ if object and object.content_type == "category": parents = object.get_parents() current_cat...
def substitute_params(sql, sql_params): """ Substitute SQL dict of parameter values Args: sql : sql statement sql_params : dict of parameters to substitute Returns: string containing SQL with parameters substituted in """ for param_name in sql_params...
def squash_whitespace(text): """Squash all single or repeating whitespace characters in `text` to one space character. >>> squash_whitespace('my name \t\t is \\n zach.') 'my name is zach.' """ words = text.split() return ' '.join(words)
def add2possible_rinex(possible_rinex_dct, mark_name_dso, remote_fn, local_fn): """ Update possible_rinex_dct for key=mark_name_dso with the tuple: (remote_fn, local_fn) """ if mark_name_dso not in possible_rinex_dct: possible_rinex_dct[mark_name_dso] = [(remote_fn, local_fn)] else: ...
def inherits_from(obj, parent): """ Takes an object and tries to determine if it inherits at *any* distance from parent. Args: obj (any): Object to analyze. This may be either an instance or a class. parent (any): Can be either instance, class or python path to class. R...
def minAddToMakeValid(S): """ Idea 1: - count up number of '(' chars - do the same for ')' - return the difference O(n) - time, O(1) space Idea #2 - expected indices - init count of min_needed = 0 - iterate over the string - if '(' and count cuurently 0: - count up...
def _upper(val): """ Returns *val*, uppercased. >>> _upper('a') 'A' """ return val.upper()
def str_to_utf8(x): """ #Before writing/output to printer put in utf-8 """ try: return x.encode("utf-8") except: return x
def _DamerauLevenshtein(a, b): """Damerau-Levenshtein edit distance from a to b.""" memo = {} def Distance(x, y): """Recursively defined string distance with memoization.""" if (x, y) in memo: return memo[x, y] if not x: d = len(y) elif not y: d = len(x) else: d = min(...
def apply_ema(y, alpha=0.99): """ EMA for an 1D array :param y: :return: """ st = y[0] y_ = [y[0]] for i in range(1, len(y)): st = alpha * st + (1 - alpha) * y[i] y_.append(st) return y_