content
stringlengths
42
6.51k
def get_matched_tags(tags, confidence): """Return the name and rounded confidence of matched tags.""" return { tag["name"]: tag["confidence"] for tag in tags if tag["confidence"] > confidence }
def get_baseline_probs(baseline_f): """ Read in baseline probabilities from a file that has them listed in the first line non commented line. # lines are ignored as comments Args: baseline_f (str): a file containing a probability array of the form: [ PrA PrC PrG PrT ] Whe...
def get_term(value, level, goal_type, shape): """Get treatment plan utility term value. Parameters ---------- value : float Clinical goal value. level : float Clinical goal AcceptanceLevel. goal_type : str Clinical goal type (e.g., 'MaxDose') shape : {'linear', 'line...
def format_dogstatsd_tags(tags): """ {k: v} => ['k:v'] """ return [f'{k}:{v}' for k, v in tags.items()]
def is_push_enabled(value): """To ensure that value passed is a boolean value, not string (which in appstack.yml is possible) Args: value(bool or str): value from which covert to bool; should be bool or 'true' or 'false' case insensitive """ if isinstance(value, ...
def collect_fields(node, fragments): """Recursively collects fields from the AST Args: node (dict): A node in the AST fragments (dict): Fragment definitions Returns: A dict mapping each field found, along with their sub fields. {'name': {}, 'sentimentsPerLanguage': {...
def recursive_conditional_map(xr, f, condition): """Walks recursively through iterable data structure ``xr``. Applies ``f`` on objects that satisfy ``condition``.""" return tuple(f(x) if condition(x) else recursive_conditional_map(x, f, condition) for x in xr)
def _polynomial_sim(x, y, p=2): """ polynomial/linear kernel compute the similarity between the dicts x and y with terms + their counts p: >1 for polynomial kernel (default = 2) """ # get the words that occur in both x and y (for all others the product is 0 anyways) s = set(x.keys()) & set(y...
def inRange(v1, minVal = 0, maxVal = 1): """ Check if every value in v1 is in the range (minVal, maxVal) """ for v in v1: if v < minVal or v > maxVal: return False return True
def append_list(list_a, list_b): """ Append list of -n- elements in list of -n- lists """ for i, a in enumerate(list_a): list_b[i].append(a) return list_b
def binomial_table(n, k): """ Pascal's triangle: (n, k) = C[n][k] """ C = [[0] * (i + 1) for i in range(n + 1)] for i in range(n + 1): for j in range((min(i, k) + 1)): if j == 0 or j == i: C[i][j] = 1 else: C[i][j] = C[i - 1][j - 1...
def format_correct(row): """ This function help determine if users enter the boggle board in a correct format. :param row: string, Entered row of letters :return: Boolean, return True if the entered row is in correct format """ if len(row) != 7: return False else: for i in ra...
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if len(ints) == 0: return None min_element = ints[0] max_element = ints[len(ints) - 1] for element in ints: ...
def prop_to_dict(p): """convert properties to dictionary""" if len(p) == 0: return {} r_dict = {} for s in p.decode().split("\n"): kv = s.split("=") r_dict[kv[0].strip()] = kv[1].strip() return r_dict # python >= 2.7 is required: # return { # k.strip(): v.stri...
def generate_random_experiment_histories_file_path(experiment_path_prefix, net_number): """ Given an 'experiment_path_prefix', return random-histories-file path with 'net_number'. """ return f"{experiment_path_prefix}-random-histories{net_number}.npz"
def validate_index(n: int, ind: int, command: str): """ Simple function to validate existence of index within in the model repository. Args: n (int): length of indices ind (int): selected index command (str): name of command for "tailored" help message """ # ensure index e...
def int_to_uint16(value_in): """ Convert integer to Unsigned 16 bit little endian integer :param value_in: Integer < 65535 (0xFFFF) :return: """ bin_string = '{:016b}'.format(value_in) big_byte = int(bin_string[0:8], 2) little_byte = int(bin_string[8:16], 2) return [little_byte, big_...
def find_average_record(sen_set, voting_dict): """ Input: a set of last names, a voting dictionary Output: a vector containing the average components of the voting records of the senators in the input set Example: >>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Rav...
def parse_path(path): """Parse the path returned from `dictdiffer`.""" if isinstance(path, str): path = path.split('.') path = [str(x) if isinstance(x, int) else x for x in path] return path[0], '.'.join(path[1::])
def normalize(reading: int, min_reading: int, center_reading: int, max_reading: int) -> float: """ Normalizes a reading between -1.0 and 1.0. Positive and negative values are computed separately, as they can span different intervals initially. :param reading: The reading to normalize. :par...
def get_decoded(dict_like, *attrs): """ Retrieve decoded values from a dict-like object if they exist. If no attrs are passed, all values are retrieved. """ # Filter for existing if len(attrs) == 0: items = dict_like.items() else: items = [ (attr, dict_like[attr]) f...
def sanitize_tf_resource_name(name): """Sanitize concatenated name for terraform resource names""" return name.replace(".", "-").replace("_", "")
def weight_normalize2D(lst, invert, normalize_max): """ Used to normalize 2 dimensional list (binary values) according to their weight (normalize_max) and also takes into inversion into account while returning. :param lst: 2D list of items. :param invert: boolean variable, invert the values or not ...
def asTermVect(doc, useDf=True, addTf=True): """ A simple string to a term vector""" tv = {} terms = doc.lower().split() for term in terms: df = 1.0 if useDf and term in ['a', 'the']: df = 13.0 elif useDf and term in ['dog', 'puppy']: df = 5.0 elif...
def rename( val, rename_di, ): """ only rename the end values of nested dictionary {ignore : {ignore : {ignore : target}, ignore_2 : target}} val = {ignore : {ignore : {ignore : target}, ignore_2 : target}} rename_di = {ignore: 1, target: 2, ignore_2: 3} output {ignore : {ignore : {ignore : ...
def get_small_joker_value(deck): """(list of int) -> int Precondition: deck must be valid (contains all ints up to the highest int in the deck and is not an empty list) Return the second highest value (the small joker) in the deck >>>get_small_joker_value([1, 4, 5, 7, 8, 2]) 7 """ re...
def get_winner(columns): """Check if columns has winner and return one.""" cols_count = len(columns) rows_count = len(columns[0]) def _same(a, b, c, d): return a != None and a == b and b == c and c == d # check vertical for col in range(cols_count): for row in range(rows_count ...
def _find_factors(number: int) -> list: """Get all factors of a given number :param number: The number we're finding the factor of :type number: int :returns: A list of all the factors. :rtype: list""" factors = [] for digit in range(1, number//2 + 1): if number % digit == 0: ...
def format_time(msec): """Converts msec to correct unit. Returns it as formatted string.""" if msec < 10**3: #ms return str(msec)+"ms" else: return str(msec//1000)+"s"
def format_metric(metric): """Format a single metric. Parameters: metric (dict): The metric to format Returns: metric (dict): The new metric in the format needed for the put_metric_data API. """ metric_keys = metric.keys() metric["MetricName"] = metric.pop("met...
def _tdoa_shift(idx, cc_size, fs=None): """convert index in cc to tdoa""" if idx > cc_size / 2: idx = idx - cc_size if fs is None: return idx else: return 1.0 * idx / fs
def comp_div_list(name_list): """ Given stock name, return cash dividends collected Inputs name_list: e.g. ['Dividends/Cash/UOL.txt'] Outputs div_list: e.g. [100] """ div_list = [] for name in name_list: sum = 0 print("name = " + name) try: ...
def find_biggest_frag(frag_mols_obj): """ This will take a frag mol object and return the largest fragment and the index in frag_mols_obj. Inputs: :param tuple frag_mols_obj: A tuple containing all the fragments of an rdkit mol. Returns: :returns: rdkit.Chem.rdchem.Mol frag_mols_ob...
def removesuffix(string: str, suffix: str) -> str: """Remove suffix from string, if present.""" return string[: -len(suffix)] if suffix and string.endswith(suffix) else string
def calc_dist_to_center(img_width, left_fitx, right_fitx): """Calculate the distance to the center of the street.""" center = img_width / 2. left_bottom_x = left_fitx[-1] right_bottom_x = right_fitx[-1] lane_width = right_bottom_x - left_bottom_x center_lane = (lane_width / 2.0) + left_bottom_x...
def screen_to_world(screen_coord, cam_coord): """Convert screen coordinates into world coordinates. Args: screen_coord (list): screen coordinates to convert. cam_coord (list): camera coordinates. Returns: list """ return [screen_coord[0] - cam_coord[0], screen_coord[1] - ca...
def unwrap_appendix_box(json_content): """for use in removing unwanted boxed-content from appendices json""" if json_content.get("content") and len(json_content["content"]) > 0: first_block = json_content["content"][0] if ( first_block.get("type") and first_block.get("typ...
def interleave_lists(num, *lsts): """ Interleave two or more lists by picking ``num`` items from 1, then ``num`` from 2, etc. """ result = [] offset = 0 while offset < len(lsts[0]) - 1: for lst in lsts: result.extend(lst[offset:offset + num]) offset += num ret...
def del_none(dictionary): """ Delete keys with the value ``None`` in a dictionary, recursively. This alters the input so you may wish to ``copy`` the dict first. """ for key, value in list(dictionary.items()): if value is None: del dictionary[key] elif value is []: ...
def array_replace(space, w_arr, args_w): """ Replaces elements from passed arrays into the first array """ for i, w_arr in enumerate(args_w): if w_arr.tp != space.tp_array: space.ec.warn("array_replace_recursive(): Argument #%d " "should be an array" % (i+1)) ...
def ft2m(ft): """ Converts feet to meters. """ if ft == None: return None return ft * 0.3048
def json_object(name="object"): """Returns a json object for general storage""" return "jsonobject" + name + ""
def flatten_json(nested_json, exclude=['']): """Flatten json object with nested keys into a single level. Args: nested_json: A nested json object. exclude: Keys to exclude from output. Returns: The flattened json object if successful, None otherwise. """ o...
def rgba_to_hex(colours): """Convert RGBA array to hex colour.""" return '#{:02x}{:02x}{:02x}{:02x}'.format(*colours)
def calculateperformance(true_annotations, predicted_annotations): """ Calculates common classification evaluation metrics. :param true_annotations: The ground truth annotations in a sequence. Values in [True, False] :param predicted_annotations: The predicted annotations in a sequence. Values in [True,...
def cal_map(predicted_order): """[summary] Args: predicted_order ([type]): [description] Returns: [type]: [description] """ p_at_k = list() p_at_k.append(predicted_order[0]) for i in range(1, len(predicted_order)): p_at_k.append((p_at_k[-1] * i + predicted_order[i])...
def references(name, tag): """Provides suggested references for the specified data set Parameters ---------- name : str Instrument name tag : str Instrument tag Returns ------- refs : str Suggested Instrument reference(s) """ refs = {'tec': ...
def extend_box(top_left, bottom_right, dx): """gets a box from a face in order to crop image to look for face again Args: top_left: point for top left bottom_right: point for bottom_right dx: the new box size Returns: """ top_left = (top_left[0] - dx, top_left[...
def format_task_id(task_id): """Create a human-readable representation of the task_id for log messages etc.""" return "'" + ", ".join(s for s in task_id if s) + "'"
def get_unique_features(pairs): """ Get a list of each feature that is present in any pair. :param pairs: list of tuples :return: list """ unique_features = [] for i in range(len(pairs)): if pairs[i][0] not in unique_features: unique_features.append(pairs[i][0]) if p...
def _fibonacci_memo(n, T): """Fibonacci series by top-down memoization. Time complexity: O(n). Space complexity: O(n). """ if T[n]: return T[n] if n <= 1: T[n] = n else: T[n] = _fibonacci_memo(n - 1, T) + _fibonacci_memo(n - 2, T) return T[n]
def dcs_consensus_tag(tag, ds): """(str, str) -> str Return consensus tag for duplex reads. Strand removed and family size from both SSCS included in order of pos_neg strand. Test cases: >>> dcs_consensus_tag('TTCA_7_55259315_7_55259454_98M_98M_neg:3', 'CATT_7_55259315_7_55259454_98M_98M_pos:6') ...
def getSampleName(x): """ Parses sample name from fastqc path. """ name = x.split("/") name = name[-2] name = name.replace("_R1_001_fastqc", "") name = name.replace("_R1_fastqc", "") return name
def make_n_gram(string: str, n: int) -> list: """ Creates n-grams from the given string :param string: Specify a input String :param n: Specify the n-gram size :return: Returns the Array containing n-grams Example: >>> make_n_gram("Hello world", 2) >>> ['He', 'el', 'll', 'lo', ...
def recursive(array, element, low): """ Perform Linear Search by Recursive Method. :param array: Iterable of elements. :param low: traversing variable of an array. :param element: element to be searched. :return: returns value of index of element (if found) else return None. """ if array...
def dropc(str, args): """drop args from str ie. dropc('abc\t\n\r', ['\t','\n','\r']) --> 'abc' """ if args: return dropc(''.join(str.split(args[-1])), args[:-1]) return str
def remove_allcaps(sent): """ Given a sentence, filter it so that it doesn't contain some words that are ALLcaps :param sent: string, like SOMEONE wheels SOMEONE on, mouthing silent words of earnest prayer. :return: Someone wheels someone on, mouthing silent words of earnest prayer. ...
def get(config, name): """Get value from config with fallback to default""" # We assume the default fallback key in the config is `__default__` return config.get(name, config.get("__default__", None))
def get_sentiment(score: float, thresh=0.05) -> str: """ Engineers sentiment (positive, negative, neutral) based on sentiment score [-1, 1]. Default thresholds: positive: compound score >= 0.05 neutral: 0.05 > compound score > -0.05 negative: compound score <= -0.05 """ asser...
def get_spiral_coords(w, h): """ Determine the sequence of coordinates found by spiraling in on an image of given size clockwise from the top-left corner to the centre. """ x, y = 0, 0 depth = 0 coords = [] while len(coords) < w * h: # Check for the special case where we are 1 pi...
def remove_odd_whitespaces(text): """Remove multiple and trailing/leading whitespaces.""" return ' '.join(text.split())
def sgn(x: int) -> int: """Return 1 if negative, 2 if positive""" return int(x>=0)+1
def merge_tensors(tensor_objects, non_tensor_objects, tensor_flags): """ Merge two lists (or tuples) of tensors and non-tensors using a mapping of positions in merged list (or tuple). Parameters: tensor_objects (list/tuple): Tensors to merge. non_tensor_objects (list/tuple): Non-tensors to m...
def shorten(s, n=100): """Shorten string s to at most n characters, appending "..." if necessary.""" if s is None: return None if len(s) > n: s = s[:n-3] + '...' return s
def _ms_opatom(op): """ Stringify the operator part of a term. If multiple motional modes are being considered, then the resultant Mathematica object will have `2n+1` arguments for `n` motional modes. """ sy = 1 if op[0] == 'P' else 2 pairs = ','.join(str(x) for pair in op[1:] for x in pair...
def remove_none_attributes(payload): """Assumes dict""" return {k: v for k, v in payload.items() if not v is None}
def __parse_check_p_n_y(p, n, y): """Parses and checks `n`, `y` and `p`, returns (inferred) `n`.""" if p: if p < 0: raise ValueError("Probability value `p` must be larger than 0.") if p > 1: raise ValueError("Probability value `p` must be less than 1.") n = round(...
def vect3_subtract(v1, v2): """ Subtracts one 3d vector from another. v1, v2 (3-tuple): 3d vectors return (3-tuple): 3d vector """ return (v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2])
def word_flipper(our_string): """ Flip the individual words in a sentence Args: our_string(string): String with words to flip Returns: string: String with words flipped """ word = "" new_sentence = "" word_list = our_string.split(" ") print(word_list) # for idx...
def parse_list(data, formatter, index_shift=1): """Parses each element in data using a formatter function. Data is a list of dicts. """ output = "".join([formatter(i + index_shift, item) for i, item in enumerate(data)]) return output
def sort_line_bbox(g, bg): """ Sorted the bbox in the same line(group) compare coord 'x' value, where 'y' value is closed in the same group. :param g: index in the same group :param bg: bbox in the same group :return: """ xs = [bg_item[0] for bg_item in bg] xs_sorted = sorted(xs) ...
def ascetime(sec): """return elapsed time as str. Example: return `"0h33:21"` if `sec == 33*60 + 21`. """ h = sec / 60**2 m = 60 * (h - h // 1) s = 60 * (m - m // 1) return "%dh%02d:%02d" % (h, m, s)
def _intersection(la: list, lb: list): """ Calculates an intersection between two lists of relations. """ tmp = lb[:] cnt_tp, cnt_fn = 0, 0 for a in la: if a in tmp: cnt_tp += 1 tmp.remove(a) else: cnt_fn += 1 return cnt_tp, cnt_fn
def lcm_naive(a, b): """ get native lcm """ for l in range(1, a*b + 1): if (l % a == 0) and (l % b == 0): return l return a*b
def rotation(new_rotation=0): """Set the display rotation. :param new_rotation: Specify the rotation in degrees: 0, 90, 180 or 270""" global _rotation if new_rotation in [0, 90, 180, 270]: _rotation = new_rotation return True else: raise ValueError('Rotation: 0, 90, 180 or ...
def coalesce(*values): """Return the first non-None value or None if all values are None""" return next((v for v in values if v is not None and v != ""), "N/A")
def map_keys(f, dct): """ Calls f with each key of dct, possibly returning a modified key. Values are unchanged :param f: Called with each key and returns the same key or a modified key :param dct: :return: A dct with keys possibly modifed but values unchanged """ f_dict = {} for k, ...
def group_dict_by_var(d: dict) -> dict: """Given a dictionary keyed by 2-length tuples, return a dictionary keyed only by the second element of the tuple. """ return {k: d[(proc, k)] for (proc, k) in d}
def set_value_by_percentile(this, lo, hi): """set `this` below or above percentiles to given values this (float) lo(float) hi(float) """ if this < lo: return lo elif this > hi: return hi else: return this
def sort_set_by_list(s, l, keep_duplicates=True): """ Convert the set `s` into a list ordered by a list `l`. Elements in `s` which are not in `l` are omitted. If ``keep_duplicates==True``, keep duplicate occurrences in `l` in the result; otherwise, only keep the first occurrence. """ if kee...
def boolify(string): """ convert string to boolean type :param string: string :return: bool """ if string == 'True' or string == 'true': return True if string == 'False' or string == 'false': return False raise ValueError("wrong type")
def max_val(t): """ t, tuple or list Each element of t is either an int, a tuple, or a list No tuple or list is empty Returns the maximum int in t or (recursively) in an element of t """ def find_all_int(data): int_list = [] for item in data: if isinstance(item, l...
def cross_prod(a, b): """ Simplified cross product of two 2D vectors. Parameters ---------- a, b : array_like Vectors in a 2D-euclidean space Returns ------- x : float """ x = a[0]*b[1] - a[1]*b[0] return x
def getRegion(rid): """ :param rid: :return: """ try: list=rid.split(":") return list[3] except Exception as e: return None
def build_data(_data, kwds): """ Returns property data dict, regardless of how it was entered. :param _data: Optional property data dict. :type _data: dict :param kwds: Optional property data keyword pairs. :type kwds: dict :rtype: dict """ # Doing this rather than defaulting th...
def cuda_tpb_bpg_2d(x, y, TPBx = 8, TPBy = 8): """ Get the needed blocks per grid for a 2D CUDA grid. Parameters : ------------ x, y : int Total number of threads in first and second dimension TPBx, TPBy : int Threads per block in x and y Returns : ------------ (B...
def clean_key(k): """ Remove search space markup from key. """ return k.split(':')[0].split('__')[-1]
def normalize_job_id(job_id): """Convert the job id into job_id, array_id.""" job_id = job_id.split('.')[0] if '[' in job_id: job_id, array_id = job_id.split('[') job_id = job_id.strip('[]') array_id = array_id.strip('[]') if not array_id: array_id = None else...
def sol_2(ar: list) -> list: """using count (inplace)""" cnt = [0, 0, 0] for i in ar: cnt[i] += 1 for i in range(len(ar)): if cnt[0]: ar[i] = 0 elif cnt[1]: ar[i] = 1 else: ar[i] = 2 cnt[ar[i]] -= 1 return ar
def get_coverage_color(coverage_percent: float) -> str: """ Returns color to represent coverage percent. Args: coverage_percent (float): Coverage percent. Returns: (str): Representing the color """ if coverage_percent <= 50.0: return 'danger' elif coverage_percent < ...
def remove_formatting(formatted_text): """Throw away style info from prompt_toolkit formatted text tuples.""" return ''.join([formatted_tuple[1] for formatted_tuple in formatted_text])
def _box_fit_response(box_size: dict, split_text: list, font_size: int, shift_x: float, shift_y: float) -> list: """ Helper method to build one splits result """ splits, y_value = [], box_size["y"] + shift_y for content in split_text: split = { "content": content, "font_size": f...
def _get_right_parentheses_index_(struct_str): """get the position of the first right parenthese in string""" # assert s[0] == '(' left_paren_count = 0 for index, single_char in enumerate(struct_str): if single_char == '(': left_paren_count += 1 elif single_char == ')': ...
def get_unique_ngrams(string, n): """ Return the set of different tri-grams in a string """ spaces = ' ' # * (n // 2 + n % 2) string = spaces + " ".join(string.lower().split()) + spaces string_list = [string[i:] for i in range(n)] return set(zip(*string_list))
def convert_to_demisto_severity(severity: float) -> int: """Maps Cyberpion severity to Cortex XSOAR severity Converts the Cyberpion alert severity level (1 to 10, float) to Cortex XSOAR incident severity (1 to 4) for mapping. :type severity: ``float`` :param severity: severity as returned from the...
def build_env_file(conf): """ Construct the key=val string from the data structurr. Parameters ---------- conf : dict The key value's Returns ------- str The key=val strings. """ return "\n".join(['{}={}'.format(k, v) for k, v in conf.items()])
def snakecase_to_kebab_case(key: str) -> str: """Convert snake_case to kebab-case.""" return f'--{key.lower().replace("_", "-")}'
def centralmoment(vi, k): """ Converts raw distribution moments to central moments Parameters ---------- vi : array The first four raw distribution moments k : int The central moment (0 to 4) to calculate (i.e., k=2 is the variance) Returns ------- cm : scal...
def filter_select(sel_array, reg): """ Filtra o select dado uma lista de intervalos de bits :param sel_array: :return: lista de dados convertidos para decimal """ strings = [] for item in sel_array: strings.append(int(reg[item[0]:item[1]], 2)) return strings
def calc_canopy_drainage_flux(canopyStore, canopyStore_max, k_can): """ Calculate the canopy drainage flux from canopy interception storage Parameters ---------- canopyStore : int or float Canopy Interception storage [mm] canopyStore_max : int or float Maximum non-drainable ...