content
stringlengths
42
6.51k
def GetTestName(test, sep='#'): """Gets the name of the given test. Note that this may return the same name for more than one test, e.g. if a test is being run multiple times with different parameters. Args: test: the instrumentation test dict. sep: the character(s) that should join the class name and...
def is_anagram(word1, word2): """Takes 2 strings, returns True if words are anagrams, otherwise False""" w1 = list(word1) w2 = list(word2) w1.sort() w2.sort() return w1 == w2
def extract_app_version(lines): """ Extracts version string from array of lines (content of version.txt file) :param lines: :return: version string """ for line in lines: parts = [elem.strip() for elem in line.split('=')] if len(parts) == 2 and parts[0].lower() == 'version_str': ...
def _check_supported(label, support_dict): """ See if we can handle it. """ if label in support_dict: return True else: return False
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. Taken from https://stackoverflow.com/a/26853961/6326903 """ result = {} for dictionary in dict_args: result.update(dictionary) r...
def is_in_strs(src): """ Return a list with an element for each boundary in `src`, where each element is `True` if it's "inside a string" and `False` otherwise. The beginning of a string section in `src` should be marked with `(` and the end marked with `)`. However, note th...
def find_upper_bound(x): """ find_upper_bound returns an integer n with n >= len(x), without using the len() function. The complexity is O(log(len(x)). """ n = 1 while True: try: v = x[n] except IndexError: return n n *= 2
def get_product_position(x, y): """Find the product's position in the recall announcment based on the label. Otherwise return 0,0, '' to signify that the product does not exist.""" if str(y) in str(x): result_start = x.index(y) result_end = result_start + len(y) return result_start, ...
def check_structure(struct): """ Return True if the monophyly structure represented by struct is considered "meaningful", i.e. encodes something other than an unstructured polytomy. """ # First, transform e.g. [['foo'], [['bar']], [[[['baz']]]]], into simply # ['foo','bar','baz']. def d...
def pred_seq_max_conf(detector_output_images_entries): """ Surface the max_detection_conf field, include detections of all classes. """ return max([entry['max_detection_conf'] for entry in detector_output_images_entries])
def pos_to_linecol(text, pos): """Return a tuple of line and column for offset pos in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why. """ line_start = text.rfind("\n", 0, pos) + 1 line = text.count("\n", 0, line_start) + 1 col = pos - line_start...
def assign_flag(pred: float, t_rouge: float, t_orange: float) -> str: """Turns a prediction score pred into an alert level. Args: pred: A predicted risk score between 0 and 1 t_rouge: A threshold, between 0 and 1, used for selecting "high risk" records. t_orange: A threshold, between 0 ...
def solve_me_first(a: int, b: int) -> int: """ >>> solve_me_first(2, 3) 5 """ ret = a + b return ret
def intersection(list1, list2): """ Returns the intersection and then the items in list2 that are not in list 1. """ int_dict = {} not_int_dict = {} list1_dict = {} for e in list1: list1_dict[e] = 1 for e in list2: if e in list1_dict: int_dict[e] = 1 else: not_int_dict[e] = 1 return [list(i...
def dblp_doi_page_filter(url): #http://dx.doi.org/10.1109/SP.2015.9 """ This function is used to filter doi_page links Input is: value (url) Output is: True (match result), False(not match) """ if 'http://dx.doi.org' in url: return True return False
def guess_format(text): """Guess YANG/YIN format If the first non-whitespace character is '<' then it is XML. Return 'yang' or 'yin'""" format = 'yang' i = 0 while i < len(text) and text[i].isspace(): i += 1 if i < len(text): if text[i] == '<': format = 'yin' ...
def climb_stairs_optimized(steps): """ :type steps: int :rtype: int """ a_steps = b_steps = 1 for _ in range(steps): a_steps, b_steps = b_steps, a_steps + b_steps return a_steps
def max_subarray1(sequence): """ Find sub-sequence in sequence having maximum sum """ # this is the version before the final version for testing purposes max_sum, max_sub = 0, [] for i in range(len(sequence)): for j in range(i+1, len(sequence)): sub_seq = sequence[i:j+1] ...
def sort(_list): """ quick_sort algorithm :param _list: list of integers to sort :return: sorted list """ if len(_list) <= 1: return list(_list) pivot = _list[len(_list) // 2] left = [x for x in _list if x < pivot] middle = [x for x in _list if x == pivot] right = [x for ...
def bits_to_dec(arr): """ [False, True, True] --> 3 [1, 0, 1, 0] --> 6 "0111" --> 7 [1, '0', 0, False, '1', True] --> 35 """ return int("".join([str(int(x)) for x in arr]), 2)
def BasinOrderToBasinRenameList(basin_order_list): """When we take data from the basins they will be numbered accoring to their junction rank, which is controlled by flow routing. The result is often numbered basins that have something that appears random to human eyes. We have developed a routine to renum...
def wind_format(speed, direction): """Converts a wind speed and direction into a string formatted for user display. Args: speed: wind speed direction: window direction (in degrees: 0 is north, 90 is east, etc.) Returns: A string containing the speed and direction, such as "25 N...
def __filter_vertices(k, coreness, *args, **kwargs): """ .. function filter_vertices(k, coreness) Filters coreness mapping for vertex ids in k-core >= k. :param k: minimum k-core :param list coreness: vertex -> k-core mapping :return: vertices in k-core """ return list(filter(lambda i:...
def parse_other_violated_policy(raw_other_violated_policy_list: list) -> list: """ Parses a list of policies to context paths :param raw_other_violated_policy_list: the raw policies list :return: the parsed policies list """ other_violated_policy_list: list = [] for raw_other_violated_policy...
def fullname(_o): """return fqn of this module""" # _o.__module__ + "." + _o.__class__.__qualname__ is an example in # this context of H.L. Mencken's "neat, plausible, and wrong." # Python makes no guarantees as to whether the __module__ special # attribute is defined, so we take a more circumspect...
def _board_to_cartesian(x, y, z): """Translate from logical board coordinates (x, y, z) into cartesian coordinates for printing hexagons. Example coordinates:: ___ ___ /-15\___/1 5\___ \___/0 4\___/3 4\ /-13\___/1 3\___/ \___/0 2\___/2 2\___ \___/1 ...
def interpolate_tuple( startcolor, goalcolor, percentage ): """ Take two RGB color sets and mix them at a specific percentage """ # white R = startcolor[0] G = startcolor[1] B = startcolor[2] targetR = goalcolor[0] targetG = goalcolor[1] targetB = goalcolor[2] DiffR = targ...
def tokenize(string): """ Split the input into the constituent elements that comprise it for example convert the string '2 3 +' into a list [2, 3, '+'] """ tokens = string.split(' ') # Create a list to hold the results to return # A list is a bit like a growable array of things resu...
def add_spaces_to_lines(count, string): """Adds a number of spaces to the start of each line""" all_lines = string.splitlines(True) new_string = all_lines[0] for i in range(1, len(all_lines)): new_string += ' ' * count + all_lines[i] return new_string
def warmup_lr(init_lr, step, iter_num): """ Warm up learning rate """ return step/iter_num*init_lr
def octagonalNum(n): """Returns the nth octagonal number.""" return int(n * (3*n - 2))
def isglobalelement(domains): """ Check whether all domains are negations.""" for domain in domains.split(","): if domain and not domain.startswith("~"): return False return True
def ipv4(address): """ Check if valid IPv4 address `Required` :param str address: string to check Returns True if input is valid IPv4 address, otherwise False """ import socket try: if socket.inet_aton(str(address)): return True except: return False
def miller_rabin_base_2(n): """Perform the Miller Rabin primality test base 2""" d, s = n - 1, 0 while not d & 1: d, s = d >> 1, s + 1 x = pow(2, d, n) if (x == 1) or (x == n - 1): return True for i in range(s - 1): x = pow(x, 2, n) if x == 1: return...
def get_file_id(fp): """ Split string to get wave id in DNS challenge dataset.""" return fp.split("_")[-1].split(".")[0]
def Legendre( x, n ): """ Function used to compute the Legendre polynomials. Args: x (any): variable. n (int): polynomials order Returns: any: returns the value of the polynomials at a given order for a given variable value. Testing: Already te...
def get_name_for_predict_column(columns): """ Get a unique name for predicted column. """ # As of now, the predicted column will take the form # constant string + number # The constant string is fixed as '_predicted' k = '_predicted' i = 0 # Try attribute name of the form "_id", "_i...
def confopt_list(confstr, list=[], default=None): """Return an element from list or default.""" ret = default for elem in list: if confstr.lower() == elem.lower(): ret = elem break return ret
def check_name(name, name_list): """ Check the validity of name. :param name: test name :type name: str :param name_list: players names :type name_list: list :return: validity as bool """ if len(name) != 0 and name not in name_list: return True return False
def convolution_math(in_channels, filter_size, out_channels): """ Convolution math: Implement how parameters scale as a function of feature maps and filter size in convolution vs depthwise separable convolution. Args: in_channels : number of input channels filter_size : size of the filter out_chann...
def normalizeGlyphTopMargin(value): """ Normalizes glyph top margin. * **value** must be a :ref:`type-int-float` or `None`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)) and value is not None: raise TypeError("Glyph top margin must be a...
def verify_error(error: Exception, v_error: Exception): """error verifier""" return isinstance(error, v_error.__class__)\ and error.__dict__ == v_error.__dict__
def xgcd(a, b): """ Extended Euclidean Distance return (g, x, y) such that a*x + b*y = g = gcd(x, y) """ x0, x1, y0, y1 = 0, 1, 1, 0 while a != 0: q, b, a = b // a, a, b % a y0, y1 = y1, y0 - q * y1 x0, x1 = x1, x0 - q * x1 return b, x0, y0
def calculate_same_padding(kernel_size, dilation, stride): """Calculates the amount of padding to use to get the "SAME" functionality in Tensorflow.""" return ((stride - 1) + dilation * (kernel_size - 1)) // 2
def is_branch(v): """ Check wether a variable is branch length or weight parameter :param v: variable :return: True/False """ return str(v)[0] == 't'
def user_display_name(user): """ Returns the preferred display name for the given user object: the result of user.get_full_name() if implemented and non-empty, or user.get_username() otherwise. """ try: full_name = user.get_full_name().strip() if full_name: return full_na...
def _get_dict_elements(npk, hu, ele_a, ele_b): """Return the appropriate hookup elements for node_info.""" e_ret = {ele_a.lower(): '', ele_b.lower(): ''} try: e_hookup = hu[npk].hookup['@<middle'] except KeyError: return e_ret for element in e_hookup: if element.upstream_part...
def hamming(first, second): """ hamming distance between two strings """ return len(list(filter(lambda x : ord(x[0])^ord(x[1]), zip(first, second))))
def num_to_chrom(chrom): """Return a chromsome in the format chr# even if is number.""" chrom = str(chrom) return chrom if chrom.startswith('chr') else 'chr' + chrom
def filter_function(file_name): """ Internal function to check if the file_name contains 'scisweeper.h5' Args: file_name (str): name of the current file Returns: bool: [True/ False] """ return "scisweeper.h5" in file_name
def diff(df): """ Assuming col1 and col2 are lists, return set difference between list1 & list2 """ return list(set(df[0]) - set(df[1]))
def remove_duplicados(lista_a, lista_b): """Remove itens duplicados""" primeira_lista = set(lista_a) segunda_lista = set(lista_b) return primeira_lista | segunda_lista
def set_pos(x,y, printing=True): """x,y: int, <printng>: Boolean (True)""" if printing: print(f"\033[{x};{y}H", end="") else: return f"\033[{x};{y}H"
def quote_string(arg: str) -> str: """Quote a string""" if '"' in arg: quote = "'" else: quote = '"' return quote + arg + quote
def calc_mean_score(movies): """Helper method to calculate mean of list of Movie namedtuples, round the mean to 1 decimal place""" ratings = [m.score for m in movies] mean = sum(ratings) / max(1, len(ratings)) return round(mean, 1)
def permutation_rank(p): """Given a permutation of {0,..,n-1} find its rank according to lexicographical order :param p: list of length n containing all integers from 0 to n-1 :returns: rank between 0 and n! -1 :beware: computation with big numbers :complexity: `O(n^2)` """ n = ...
def range_truncate(s, max_len=8) : """Truncate a string to assist debug traces.""" if len(s) > max_len : return s[0:2] + "..." + s[-2:] return s
def errno_from_exception(e): """Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instatiates an Exception without any args you will get a tuple error. So this function abstracts all that behavior to...
def getLineNumber(lines, phrases, debug=False): """Returns the line numbers containing the provided phrases after searching for the previous phrases sequentially. Search starts with the first phrase, once it is found, search starts with the 2nd phrase from that line, until the last phrase is found. Igno...
def prime_factors(no)->list: """ Return the list of prime factors of the number. """ prime=[i for i in range(no+1)] factors=[] for i in range(2,no+1): if prime[i]==i: for j in range(i*i,no+1,i): prime[j]=i while(no>=2): factors.append(prime[no]) no=no//prime[no] return factors
def get_multiplexer(num): """ Get max decimal multiplexer. """ m = 1 while num % 10 == 0: num = num / 10 m *= 10 return m
def is_exist_protected_branch_exclude_master(repo_name, repos): """ check there exist other protected branches exclude master """ for repo in repos: if repo_name == repo['name']: if len(repo['branches']) == 1: return False return True return False
def _func_annotation_for(func): """Retrieve the function annotation for a given function or create it""" current = getattr(func,'__annotations__',None) if current is None: current = func.__annotations__ = {} return current
def calc_conformance(results): """Returns a tuple with the number of total and failed testcase variations and the conformance as percentage.""" total = len(results) failed = sum(1 for status, _ in results.values() if status != 'PASS') conformance = (total - failed) * 100 / total return total, failed...
def download_sequences(): """Downloads the requested sequences from the VOT dataset. :param list subsets: An optional list of subsets of VOT to download. If this is ``None``, all subsets will be downloaded. :param str root_directory: The root directory into which to download the sequences. ...
def encode_chrom(chrom): """Encodes the chromosome.""" if str(chrom) == "23": return "X" if str(chrom) == "24": return "Y" if str(chrom) == "26": return "M" return str(chrom)
def time_duration_formatter(x): """Format time duration in seconds """ mm, ss = divmod(x, 60) hh, mm = divmod(mm, 60) dd, hh = divmod(hh, 24) res = '' if dd: res += '%dd ' % dd if dd or hh: res += '%dh ' % hh if dd or hh or mm: res += '%dm ' % mm res += '...
def check_saturation(vol1: int, vol2: int) -> bool: """Check if percentage of orders received is acceptable""" acceptance = 0.95 try: if vol2/vol1 >= acceptance: return True else: return False except ZeroDivisionError: return False
def _hex64(n: int) -> str: """Formats a 64-bit unsigned integer.""" return f'0x{n:016x}'
def choose(n, r): """The number of ways of choosing r items from n All calculations done as integer. Parameters ---------- n number of items to choose from r number of items to choose Returns ------- combin The number if ways of making the choice """ if n < 0 or r < 0: ...
def reverse_one_hot(y_): """ Function to reverse one-hot coding E.g.: [[0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]] --> [[5], [0], [3]] """ flat_y = [] for index, entry in enumerate(y_, start=0): # print("--- y_ [", index, "]:", entry) for bit, code in enumerate(e...
def format_macrofunction(function): """Format the fully qualified name of a macro function, for error messages.""" # Catch broken bindings due to erroneous imports in user code # (e.g. accidentally to a module object instead of to a function object) if not (hasattr(function, "__module__") and hasattr(fu...
def solution(xs): """ Boring case analysis. In this problem the pain is just to not miss any case. """ if len(xs)==1: return str(xs[0]) count_neg = 0 count_pos = 0 count_zero = 0 prod_pos = 1 prod_neg = 1 max_neg = -float("inf") for x in xs: if x ==0: ...
def add_to_inventory(inventory, items): """sorts items argument so that they become a dictionary with values depending on the number of repetitions of a given item in the items argument. Then the newly created dictionary is merged to the inventory argument.""" new_items = (dict((item, items.count(...
def ranks(x, reverse=False): """ Returns a tuple containing the rank of each element of the iterable `x`. The ranks start at `0`. If `reverse` is `False`, the elements of `x` are ranked in ascending order, and in descending order otherwise. Equal elements will all be assigned the same (lowest-poss...
def pretty_stacktrace(stacktrace): """Prettifies stacktrace""" if not stacktrace: return "<No stacktrace>" return stacktrace
def get_histogram_units(histogram_data): """ Function takes dictionary of histogram data. Checks for units key which indicates it is newer format or older and return unit. """ units = None units_present = False units_absent = False for k1, v1 in histogram_data.items(): if not v...
def _unpad(padded): """ Remove the padding applied by _pad() """ return padded[:-ord(padded[len(padded) - 1:])]
def _format_dataset_name(name, term): """Returns name with colour codes and length w/o them for datasets.""" return (name, len(name))
def pysolr_formatter(credentials): """ Returns formatted Solr credentials for a pysolr-Solr connection. Args: credentials (dict): The credentials dictionary from the relationships. Returns: (string) A formatted pysolr credential. """ return "http://{0}:{1}/{2}".fo...
def _collect_lines(data): """ Split lines from data into an array, trimming them """ matches = [] for line in data.splitlines(): match = line.strip() matches.append(match) return matches
def _get_range_squared(range_instru): """Returns range (m), squared and converted to km.""" m2km = 0.001 return (range_instru*m2km)**2
def adjust_probabilities(p_list): """ Adjust a list of probabilties to ensure that they sum to 1 """ if p_list is None or len(p_list) == 0: out = None else: total = sum(p_list) if total == 1: out = p_list elif total == 0: raise ValueError('Pro...
def max_and_min_product_subarray(arr): """ Assumption: Output is always greater than or equal to 1. :param arr: :return: """ curr_max = curr_min = global_max = global_min = 1 for elt in arr: # If this element is positive, update curr_max. # Update curr_min only if curr_min i...
def get_file_name(path): """Get the file name without .csv postfix. Args: path: A string for the absolute path to the file. Returns: A string for the path without .csv postfix """ filename = path.strip('\n').strip('.csv') return filename
def is_image(filename): """ Check if filename has valid extension :param filename: :return: boolean indicating whether filename is a valid image filename """ filename = filename.lower() return filename.endswith(".jpg") \ or filename.endswith(".png") \ or filename.endsw...
def calc_c02_emission(n_persons=0, emission_rate=0, internal_source=0, time=0): """ :param n_persons: # number of persons in the zone :param emission_rate: # CO2 emission rate per person [mg/h] :param internal_source: # emission rate of interal sources [mg/h] :param time: ...
def determine_atts(desc, targ, miss): """ Determine the entire list of attributes. """ atts = list(set(desc).union(targ).union(miss)) atts.sort() return atts
def best_model_compare_fn(best_eval_result, current_eval_result, key): """Compares two evaluation results and returns true if the second one is greater. Both evaluation results should have the value for key, used for comparison. Args: best_eval_result: best eval metrics. current_eval_result: curre...
def match(text, pattern, limit = -1): """ Matches all or first "limit" number of occurrences of the specified pattern in the provided text :param text: A String of characters. This is the text in which we want to find the pattern. :param pattern: The pattern to look for. Expected to be a regular express...
def null_group_membership(username, group): """Default group membership test. Gives HOST permission to all users and MOD permission to those with dpauth.moderator Django permission. Custom implementations can delegate to this one if group is blank. Parameters: username -- the Username instance...
def html_escape(s, quote=False, crlf=False): """html.escape but also newlines""" s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") if quote: s = s.replace('"', "&quot;").replace("'", "&#x27;") if crlf: s = s.replace("\r", "&#13;").replace("\n", "&#10;") return s
def sls(container) -> list: """ sorted list set """ return sorted(list(set(container)))
def search_clip_threshold(qs, la, lb, rc, rd): """ assume qs is sorted, rc,la>=0 return inf{M: Pr(q(X)<= la/M+lb) <= M*rc+rd } """ n = len(qs) lo, hi = 0, n while lo<hi: mid = (lo+hi)//2 cur_M = la/(qs[mid]-lb) if mid/n < cur_M*rc+rd: lo = mid+1 el...
def qualitative_pcs_value(pcs_value): """Convert PCS value into qualitative description""" if pcs_value < 369: output = "Very good" elif pcs_value < 1088: output = "Good" elif pcs_value < 1700: output = "Standard" elif pcs_value < 4622: output = "Bad" elif pcs_val...
def find_smallest_angle(angle1, angle2, absolute_value=False): """Find the smallest angle between two provided azimuth angles. @param: - angle1 - first angle in degrees between 0 and 360 degrees @param: - angle2 - first angle in degrees between 0 and 360 degrees @param: - absolute_value - if true, retur...
def reportMissingGenes(geneSet, gafDict, indicator): """ Finds and reports Uniprot AC's in the provided background/interest gene sets which are not present in the gene association file (most likely obsolete entries). Also returns a new set where these missing genes are removed. Parameters -----...
def last_8chars(x): """Function that aids at list sorting. Args: x: String name of files. Returns: A string of the last 8 characters of x. """ return (x[-8:])
def dict_to_nice_str(d, max_line_length=80): """Returns dictionary [d] as as nicely formatted string.""" s, last_line_length = "", 0 for k in sorted(d.keys()): item_len = len(f"{k}: {d[k]}, ") if last_line_length + item_len > max_line_length: s += f"\n{k}: {d[k]}, " l...
def getNumPlaces(x): """ getNumPlaces() | gets the number of decimal places in a float/integer x | (float) (int) returns (int) """ if int(x) == x: return 0 return len(str(x)) - len(str(int(x))) - 1