content
stringlengths
42
6.51k
def accuracy_score(data): """ Given a set of (predictions, truth labels), return the accuracy of the predictions. :param data: [List[Tuple]] -- A list of predictions with truth labels :returns: [Float] -- Accuracy metric of the prediction data """ return 100 * sum([1 if p == t else 0 for p, ...
def handle_pci_dev(line): """Handle if it is pci line""" if "Region" in line and "Memory at" in line: return True if line != '\n': if line.split()[0][2:3] == ':' and line.split()[0][5:6] == '.': return True return False
def rc_to_xy(track, r, c): """ Convert a track (row, col) location to (x, y) (x, y) convention * (0,0) in bottom left * x +ve to the right * y +ve up (row,col) convention: * (0,0) in top left * row +ve down * col +ve to the right Args: track (list): List of strin...
def get_out_direct_default(out_direct): """get default out direct""" outdict = {"console": "1", "monitor": "2", "trapbuffer": "3", "logbuffer": "4", "snmp": "5", "logfile": "6"} channel_id_default = outdict.get(out_direct) return channel_id_default
def only_even(arg1, arg2): """ Get even numbers between arg1 and arg2 :param arg1: Number :param arg2: Number :return: List of the even value between arg1 and arg2 """ def even_filter(num): """ Function fo filter :param num: Number :return: True if even, e...
def duplicate_count(text): """Return duplicate count""" unique = dict() for elem in text.lower(): if elem in unique: unique[elem] = unique[elem]+1 else: unique[elem] = 1 return len([k for k,v in unique.items() if v >= 2])
def command_settings(body_max=102400000, time_max=0): """ Generates dictionary with command settings """ settings = { "body_max": int(body_max), "time_max": int(time_max) } return settings
def isPal(x): """Assumes x is a list Returns True if the list is a palindrome; False otherwise""" temp = x[:] temp.reverse() if temp == x: return True else: return False
def guess(key, values): """ Returns guess values for the parameters of this function class based on the input. Used for fitting using this class. :param key: :param values: :return: """ return [max(values)-min(values), 0.5*(max(key)-min(key)), min(values)]
def _format_binary(num: int, padding: int) -> str: """Format a number in binary.""" return format(num, f'#0{padding + 2}b')[2:]
def check_format(filename): """ check the format of file :param filename: :return: """ allowed_format = [".fa", ".fasta", ".fa.gz", ".fasta.gz"] if any([f for f in allowed_format if filename.endswith(f)]): return 0 else: msg = "file format is not in %s" % allowed_format ...
def get_counter(data, base): """ See setCounters() / getCounters() methods in IJ source, ij/gui/PointRoi.java. """ b0 = data[base] b1 = data[base + 1] b2 = data[base + 2] b3 = data[base + 3] counter = b3 position = (b1 << 8) + b2 return counter, position
def calculate_avg_movie_score(movies): """Calculate average scores for each director""" ratings = [ m.score for m in movies ] # make a list of all the movie scores of the specific director average = sum(ratings) / max( 1, len(ratings) ) # add the list and divide by the number of it...
def py_hash(key, num_buckets): """Generate a number in the range [0, num_buckets). Args: key (int): The key to hash. num_buckets (int): Number of buckets to use. Returns: The bucket number `key` computes to. Raises: ValueError: If `num_buckets` is not a positive number...
def _filter_data_list(data: list, by_key, by_value, ignore_case: bool): """Parameter 'data': - A list of entity dicts """ if data: result = [] for entry in data: entry_value = entry[by_key] value = by_value if ignore_case: entry_value = ...
def is_markdown_cell(cell): """Returns whether a cell is a Markdown cell Args: cell (``nbformat.NotebookNode``): the cell in question Returns: ``bool``: whether a cell is a Markdown cell """ return cell["cell_type"] == "markdown"
def safe_float(string_, default=1.0): """Convert a string into a float. If the conversion fails, return the default value. """ try: ret = float(string_) except ValueError: return default else: return ret
def is_whitespace(char): """Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. import unicodedata if char == " " or char == "\t" or char == "\n" or char == "\r": ...
def find_encryption( public_key, loops ): """ Starting from the given public_key, this function applies the transformation for loops times and returns the value """ value = 1 for _ in range(loops): value *= public_key value = value % 20201227 return value
def parse_iopub_for_reply(msgs, line_number): """Get kernel response from message pool (Async). .. note:: some kernel (iperl) do not discriminate when client asks for `user_expressions`. But still they give a printable output. Parameters ---------- msgs : list List of message...
def make_goal(s): """Generate a goal board with an given size Args: s (int, s>=3): The size of goal board to generate, i.e. the width of the board. Returns: goal (list): A 2D list representing tiles of the goal board, e.g., if the size given is 3, the goal is [[1,...
def binomial_coeff(n, k): """ Math is fun (Thanks Adrien and Eric) """ import functools as ft import operator as op k = min(k, n - k) n = ft.reduce(op.mul, range(n, n - k, -1), 1) d = ft.reduce(op.mul, range(1, k + 1), 1) return n / d
def _pure_cyclotron_freq(q, m, B): """pure cyclotron frequency""" return B * q / m
def scale_to_100(value): """Scale the input value from 0-255 to 0-100.""" return max(0, min(100, ((value * 100.0) / 255.0)))
def fnCalculate_Bistatic_RangeRate(speed_light,tau_u1,tau_d1,tau_u2,tau_d2,tc): """ Calculate the average range rate. eqn 6.37 in Montenbruck 2000. tc = length of integration interval, i.e. length of CPI Created: 04/04/17 """ range_rate = (speed_light/tc)*(tau_u2+tau_d2-tau_u1-tau_d1); # removed 0.5 factor...
def _KeyMissing(side): """One log is missing a key present in the other log.""" return 'Key missing from %s' % side
def prepare_package(date, metainfo=None): """ Prepare metainfo for package """ base = { 'publishedDate': date, 'releases': [], 'publisher': { 'name': '', 'scheme': '', 'uri': '' }, } if metainfo: base.update(metainfo) return...
def separate_file_from_parents(full_filename): """Receives a full filename with parents (separated by dots) Returns a duple, first element is the filename and second element is the list of parents that might be empty""" splitted = full_filename.split('.') file = splitted.pop() parents = splitted...
def stations_by_river(stations): """Find stations which are by the same river Args: stations (list): list of MonitoringStation objects Returns: dictionary: river name as key to a list of station names """ dic_stations_river = {} for station in stations: key = st...
def objsize(obj): """ Returns the size of a deeply nested object (dict/list/set). The size of each leaf (non-dict/list/set) is 1. """ assert isinstance(obj, (dict, list, set)), obj if not obj: return 0 if isinstance(obj, dict): obj = obj.values() elem = next(it...
def concatStrDict(d, order=[]): """Concatenates all entries of a dictionary (assumed to be lists of strings), in optionally specified order.""" retstr = "" if d != {}: if order == []: order = list(d.keys()) for key in order: itemlist = d[key] ...
def line_value(line_split): """ Returns 1 string representing the value for this line None will be returned if theres only 1 word """ length = len(line_split) if length == 1: return None elif length == 2: return line_split[1] elif length > 2: return b' '.join(li...
def restructure_stanford_response(json_doc): """Restructure the JSON output from stanford KP. :param: json_doc: the API response from stanford KP """ # convert from list to dict if isinstance(json_doc, list): json_doc = {'data': json_doc} if 'data' in json_doc: for _doc in json_...
def app(environ, start_response): """A barebones WSGI app. This is a starting point for your own Web framework """ status = "200 OK" response_headers = [("Content-Type", "text/plain")] start_response(status, response_headers) return [b"Hello world from a simple WSGI application\n"]
def split_simple(molname_simple): """split simple molname Args: molname_simple: simple molname Return: atom list number list Example: >>> split_simple("Fe2O3") >>> (['Fe', 'O'], ['2', '3']) """ atom_list=[] num_list=[] tmp=None num="" fo...
def initialize_3d_list(a, b, c): """ :param a: :param b: :param c: :return: """ lst = [[[None for _ in range(c)] for _ in range(b)] for _ in range(a)] return lst
def find_idx_scalar(scalar, value): """ Retrieve indexes of the value in the nested list scalar. The index of the sublist corresponds to a K value. The index of the element corresponds to a kappa value. Parameters: scalar -- list, size 2^n x 2^n value -- float """ # Give sublist index and element index in sc...
def recursive_update(target, update): """Recursively update a dictionary. Taken from jupytext.header """ for key in update: value = update[key] if value is None: # remove if it exists target.pop(key, None) elif isinstance(value, dict): target[key] ...
def _sum_state_financial_outlay(results:dict): """ Aggregate state total financial outlay for FRT Arguments: results {dict} -- Result set from `get_state_frts` Returns: float -- Returns total financial outlay """ if results == None: return 0 total_financial_outlay =...
def _check_maybe_route(variable_name, variable_value, route_to, validator): """ Helper class of ``SlashCommand`` parameter routing. Parameters ---------- variable_name : `str` The name of the respective variable variable_value : `str` The respective value to route maybe. ...
def normalize_url_without_bewit(url, bewit): """Normalizes url by removing bewit parameter.""" bewit_pos = url.find('bewit=') # Chop off the last character before 'bewit=' which is either a ? or a & bewit_pos -= 1 bewit_end = bewit_pos + len("bewit=" + bewit) + 1 o_url = ''.join([url[0:bewit_pos...
def expandBrackets(f, lower, upper, step=1.1, step_mod=1.0, max_iteration=1<<10): """Expand brackets upwards using a geometric series @param f callable (function of form f(x) = 0) @param lower float (initial guess, not varied) @param upper float (initial guess, is expanded) ...
def disp_to_depth(disp, min_depth, max_depth): """Convert network's sigmoid output into depth prediction """ min_disp = 1 / max_depth max_disp = 1 / min_depth scaled_disp = min_disp + (max_disp - min_disp) * disp depth = 1 / scaled_disp return scaled_disp, depth
def rootssq(ll): """Return the root of the sum of the squares of the list of values. If a non-iterable is passed in, just return it.""" try: return sum([ss**2 for ss in ll])**0.5 except TypeError: pass # ll is not iterable return ll
def _CreateLinkColumn(name, label, url): """Returns a column containing markdown link to show on dashboard.""" return {'a_' + name: '[%s](%s)' % (label, url)}
def create_default_config(schema): """Create a configuration dictionary from a schema dictionary. The schema defines the valid configuration keys and their default values. Each element of ``schema`` should be a tuple/list containing (default value,docstring,type) or a dict containing a nested schem...
def replace_string_newline(str_start: str, str_end: str, text: str) -> str: """ re.sub function stops at newline characters, but this function moves past these params: str_start, the start character of the string to be delted str_end, the end character of the string to be deleted te...
def check_password_requirements(password: str) -> str: """Check if password meets requirements.""" if len(password) < 8: return "Password must be at least 8 characters long." if not any(char.isdigit() for char in password): return "Password must contain at least one number." if not any(c...
def reldiff(x,y,floor=None): """ Checks relative (%) difference <floor between x and y floor would be a decimal value, e.g. 0.05 """ d = x-y if not d: return 0 ref = x or y d = float(d)/ref return d if not floor else (0,d)[abs(d)>=floor] #return 0 if x*(1-r)<y<x*(1+r) e...
def html_quote( line ): """Change HTML special characters to their codes. Follows ISO 8859-1 Characters changed: `&`, `<` and `>`. """ result = line if "`" not in result: result = line.replace( "&", "&amp;" ) result = result.replace( "<", "&lt;" ) result = result.replace( ...
def _xor(bs1, bs2, n): """Return exclusive or of two given byte arrays""" bs = bytearray() for (b1, b2) in zip(bs1, bs2): bs.append(b1 ^ b2) return bs
def process_standard_commands(command, game): """Process commands which are common to all rooms. This includes things like following directions, checking inventory, exiting the game, etc. Returns true if the command is recognized and processed. Otherwise, returns false. """ if command == ...
def unitarity_decay(A, B, u, m): """Eq. (8) of Wallman et al. New J. Phys. 2015.""" return A + B*u**m
def get_optimal_knapsack_value(W, items): """ Gets the highest value the knapsack can carry given items of the form [(weight, value)] up to a weight W Complexity: O(n * S) """ n = len(items) knapsacks = dict() for i in range(n, -1, -1): for j in range(W + 1): if i == n: knapsacks[(...
def _check_return_value(ret): """ Helper function to check if the 'result' key of the return value has been properly set. This is to detect unexpected code-paths that would otherwise return a 'success'-y value but not actually be succesful. :param dict ret: The returned value of a state function. ...
def find_item(keys, d, create=False): """Return a possibly deeply buried {key, value} with all parent keys. Given: keys = ['a', 'b'] d = {'a': {'b': 1, 'c': 3}, 'b': 4} returns: {'a': {'b': 1}} """ default = {} if create else None value = d.get(keys[0], default) ...
def sum_numbers_in_list(array: list) -> int: """ BIG-O Notation = O(n) """ result = 0 for i in array: result += i return result
def _include_spefic_ft(graph, ft_type, method, sorted_features, ft_dict): """ Execute features individually """ num_of_feature_type = 0 if ft_type in ft_dict else None if ft_type in sorted_features and ft_type in ft_dict: num_of_feature_type = len(sorted_features[ft_type]) for f in sorted_fe...
def _remove_nulls(managed_clusters): """ Remove some often-empty fields from a list of ManagedClusters, so the JSON representation doesn't contain distracting null fields. This works around a quirk of the SDK for python behavior. These fields are not sent by the server, but get recreated by the CLI...
def ts(nodes, topo_order): # topo must be a list of names """ Orders nodes by their topological order :param nodes: Nodes to be ordered :param topo_order: Order to arrange nodes :return: Ordered nodes (indices) """ node_set = set(nodes) return [n for n in topo_order if n in node_set]
def _normalize_requirement_name(name: str) -> str: """ Normalizes the string: the name is converted to lowercase and all dots and underscores are replaced by hyphens. :param name: name of package :return: normalized name of package """ normalized_name = name.lower() normalized_name = norma...
def list_evolution(list1,list2): """ returns the index evolution of each element of the list 1 compared to the index within list 2 NB: if lists length do not match, place None value at missing index """ # return [list2.index(x) - list1.index(x) for x in list1 if x in list2] evo = [] ...
def check_pid(pid): """ Check For the existence of a unix pid. """ import os try: os.kill(pid, 0) except OSError: return False else: return True
def get_unique_value_from_summary_ext(test_summary, index_key, index_val): """ Gets list of unique target names and return dictionary """ result = {} for test in test_summary: key = test[index_key] val = test[index_val] if key not in result: result[key] = val retu...
def add_modules_to_metadata(modules, metadata): """ modules is dict of otus, metadata is a dictionary of dictionaries where outer dict keys are features, inner dict keys are metadata names and values are metadata values """ for module_, otus in modules.items(): for otu in otus: i...
def perplexity(probability: float, length: int) -> float: """Return the perplexity of a sequence with specified probability and length.""" return probability ** -(1 / length)
def accept_lit(char, buf, pos): """Accept a literal character at the current buffer position.""" if pos >= len(buf) or buf[pos] != char: return None, pos return char, pos+1
def get_pacer_case_id_from_nonce_url(url): """Extract the pacer case ID from the URL. In: https://ecf.almd.uscourts.gov/cgi-bin/DktRpt.pl?56120 Out: 56120 In: https://ecf.azb.uscourts.gov/cgi-bin/iquery.pl?625371913403797-L_9999_1-0-663150 Out: 663150 """ param = url.split("?")[1] if "L...
def condense_multidimensional_zeros(css): """Replace `:0 0 0 0;`, `:0 0 0;` etc. with `:0;`.""" css = css.replace(":0 0 0 0;", ":0;") css = css.replace(":0 0 0;", ":0;") css = css.replace(":0 0;", ":0;") # Revert `background-position:0;` to the valid `background-position:0 0;`. css = c...
def remove_digits(s): """ Returns a string with all digits removed. """ return ''.join(filter(lambda x: not x.isdigit(), s))
def parse_core_proc_tomo_fh_section(root): """ place older function to be developed yet """ core_proc_tomo_fh_obj = None return core_proc_tomo_fh_obj
def persistence_model(series): """DOCSTRING Wrapper for baseline persistence model""" return [x for x in series]
def rep_int(value): """ takes a value and see's if can be converted to an integer Args: value: value to test Returns: True or False """ try: int(value) return True except ValueError: return False
def equal_para(struct): """compares the number of '(' and ')' and makes sure they're equal. Return bool True is ok and False is not a valid structure.""" if struct.count('(') == struct.count(')'): return True else: return False
def build_history_object(metrics): """ Builds history object """ history = { 'batchwise': {}, 'epochwise': {} } for matrix in metrics: history["batchwise"][f"training_{matrix}"] = [] history["batchwise"][f"validation_{matrix}"] = [] history["epochwise...
def Serialize(obj): """Convert a string, integer, bytes, or bool to its file representation. Args: obj: The string, integer, bytes, or bool to serialize. Returns: The bytes representation of the object suitable for dumping into a file. """ if isinstance(obj, bytes): return obj if isinstance(ob...
def init_actions_(service, args): """ this needs to returns an array of actions representing the depencies between actions. Looks at ACTION_DEPS in this module for an example of what is expected """ # some default logic for simple actions return { 'test_all': ['test_list_services', ...
def capital_case(st: str) -> str: """Capitalize the first letter of each word of a string. The remaining characters are untouched. Arguments: st {str} -- string to convert Returns: str -- converted string """ if len(st) >= 1: words = st.split() return ' '.join([f'{s...
def decode(bytedata): """Convert a zerocoded bytestring into a bytestring""" i = 0 l = len(bytedata) while i < l: if bytedata[i] == 0: c = bytedata[i+1] - 1 bytedata = bytedata[:i+1] + (b"\x00"*c) + bytedata[i+2:] i = i + c l = l + c - 1 i ...
def get_headers(sql, prefix=None): """Returns a list of headers in an sql select string""" cols = [] open_parenth = False clean_sql = "" # Remove anything in parentheses, liable to contain commas for i, char in enumerate(sql): if char == "(": open_parenth = True elif ...
def split_NtoM(N, M, rank): """ split N to M pieces see https://stackoverflow.com/a/26554699/9746916 """ chunk = N // M remainder = N % M if rank < remainder: start = rank * (chunk + 1) stop = start + chunk else: start = rank * chunk + remainder ...
def handle_index(l, index): """Handle index. If the index is negative, convert it. If the index is out of range, raise an IndexError. """ # convert negative indices to positive ones if index < 0: # len(l) has always type 'int64' # while index can be an signed/unsigned integer ...
def growing_plant(upSpeed, downSpeed, desiredHeight) -> int: """ Each day a plant is growing by upSpeed meters. Each night that plant's height decreases by downSpeed meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know wh...
def get_definitions_diff(previous_definition_string, new_definition_string): """Returns a triple of lists (definitions_removed, definitions_shared, definitions_added)""" old_definitions = [i for i in previous_definition_string.split('|') if i] new_definitions = [i for i in new_definition_string.split('|...
def knapsack_rec(W, val, weight, n): """recursive knapsac problem where W = max weight knapsack can hold val = array of values weight = array of weights associated with values n = length of the arrays """ # Base case if n == 0 or W == 0: return 0 # if weight of item is more t...
def problem_forms(doc): """ Return non-XFormInstances (duplicates, errors, etc.) """ return doc["doc_type"] != "XFormInstance"
def hyper_replace(text, old: list, new: list): """ Allows you to replace everything you need in one function using two lists. :param text: :param old: :param new: :return: """ msg = str(text) for x, y in zip(old, new): msg = str(msg).replace(x, y) return msg
def confirm(cause): """ Display confirm msg (Green) """ return ("\033[1;32;40m [+] "+cause + " \033[0m ")
def repeating_key_xor(message_bytes, key): """Returns message XOR'd with a key. If the message, is longer than the key, the key will repeat. """ output_bytes = b'' index = 0 for byte in message_bytes: output_bytes += bytes([byte ^ key[index]]) if (index + 1) == len(key): ...
def _getText(nodelist): """ returns collected and stripped text of textnodes among nodes in nodelist """ rc = "" for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc.strip()
def pop_path(path): """Return '/a/b/c' -> ('a', '/b/c').""" if path in ("", "/"): return ("", "") assert path.startswith("/") first, _sep, rest = path.lstrip("/").partition("/") return (first, "/" + rest)
def init_field(height=20, width=20): """Creates a field by filling a nested list with zeros.""" field = [] for y in range(height): row = [] for x in range(width): row.append(0) field.append(row) return field
def getAverageScore(result): """ Get the average score of a set of subscores for a student \n :param result: A dicitonary containing the results of a student \t :type result: {extensions : {http://www.boxinabox.nl/extensions/multiple-results : [{value, ...}], ...}, ...} \n :returns: The average ...
def div_to_int(int_numerator, int_denominator, round_away=False): """Integer division with truncation or rounding away. If round_away evaluates as True, the quotient is rounded away from zero, otherwise the quotient is truncated. """ is_numerator_negative = False if int_numerator < 0: int_numerator =...
def firstTarget(targets): """ Return the first (year, coefficient) tuple in targets with coefficient != 0. """ targets.sort(key=lambda tup: tup[0]) # sort by year for year, coefficient in targets: if coefficient: # ignore zeros return (year, coefficient)
def a2idx(a): """ Tries to convert "a" to an index, returns None on failure. The result of a2idx() (if not None) can be safely used as an index to arrays/matrices. """ if hasattr(a, "__int__"): return int(a) if hasattr(a, "__index__"): return a.__index__()
def unbinary(value): """Converts a string representation of a binary number to its equivalent integer value.""" return int(value, 2)
def arg_name(name): """Get the name an argument should have based on its Python name.""" return name.rstrip('_').replace('_', '-')
def isBin(s): """ Does this string have any non-ASCII characters? """ for i in s: i = ord(i) if i < 9: return True elif i > 13 and i < 32: return True elif i > 126: return True return False
def s_hex_dump(data, addr=0): """ Return the hex dump of the supplied data starting at the offset address specified. :type data: Raw :param data: Data to show hex dump of :type addr: int :param addr: (Optional, def=0) Offset to start displaying hex dump addresses from :rtype: str :r...