content
stringlengths
42
6.51k
def map_labels(usecase,label): """This method returns the entire name of a label""" if usecase == 'colon': if label == 'cancer': return "Cancer" if label == 'hgd': return "Adenomatous polyp - high grade dysplasia" if label == 'lgd': return "Adenomato...
def is_valid_fit(fit): """ Checks fit parameter """ values = ['none', 'rot+trans', 'rotxy+transxy', 'translation', 'transxy', 'progressive'] return fit in values
def _lcp(lst): """Returns the longest common prefix from a list.""" if not lst: return "" cleanlst = list(map(lambda x: x.replace("[", "").replace("]", ""), lst)) s1 = min(cleanlst) s2 = max(cleanlst) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return ...
def position_from_instructions(instructions, path=None): """ Find out what position we're at after following a set of instructions. """ x = y = 0 heading = 0 # 0 = N, 1 = E, 2 = S, 3 = W instructions = instructions.split(', ') for instruction in instructions: turn = instruction[:1]...
def dictaddentry(idict,key,direction,newkey,nvalue): """ Converts a sexigesmal number to a decimal Input Parameters ---------------- idict : dict a dictionary key : str ocation in `dict` to insert the new values direction : {'before','after'} insertion direction...
def find_ingredients_graph_leaves(product): """ Recursive function to search the ingredients graph and find its leaves. Args: product (dict): Dict corresponding to a product or a compound ingredient. Returns: list: List containing the ingredients graph leaves. """ if 'ingredie...
def txt2html(text): """ Convert text to html compatible text Add html tag <br /> to a text @param: text ( string ) @return: text (string ) With """ lines = text.splitlines() txt = "" for line in lines: txt = "".join([txt, line, ' <br />\n']) return txt
def prettify_subpages(subpages): """ Replaces blank subpage (indicative of index) with "Homepage" """ output = subpages.copy() for index, page in enumerate(subpages): if page == '': output[index] = 'Homepage' return output
def merge_args_kwargs_dict(args, kwargs): """Takes a tuple of args and dict of kwargs. Returns a dict that is the result of merging the first item of args (if that item is a dict) and the kwargs dict.""" init_dict = {} if len(args) > 0 and isinstance(args[0], dict): init_dict = args[0] ...
def makelabel(label, suffix): #============================ """ Helper function to generate a meaningful label for sub-properties of resources. :param label: The label of some resource. :param suffix: A suffix to append to the label. :return: A string consisting of the label, a '_', and the suffix. """ r...
def find_index_from_str(delimited_string: str, fnd: str, split: str = ","): """Finds the rank of the string fnd in the passed delimited string This function takes in a raw string with a known delimiter and locates the index position of the fnd value, identifying the rank of the item. Args: del...
def tuple_next(xs): """Next tuple.""" return xs[0], xs[1:]
def keeponly(s, keep): """ py2 table = string.maketrans('','') not_bits = table.translate(table, ) return txt.translate(table, not_bits) """ return ''.join([x for x in s if x in keep])
def make_float_list(val): """Check if the item is a string, and if so, apply str.split() to make a list of floats. If it's a list of floats, return as is. Used as a conversion function for apply_conversions above. Inputs: val: value, either string or list of floats O...
def original(string: str) -> str: """Get either the original of a `ReplaceString` or a string.""" return getattr(string, 'original', string)
def convert_to_list(value): """Convert value to list if not""" if isinstance(value, list): return value else: return [value]
def sum_tree(root): """Sums the nodes of a tree. Arguments: root (binary tree): The root of a binary tree. A binary tree is either a 3-tuple ``(data, left, right)`` where ``data`` is the value of the root node and ``left`` and ``right`` are the left and right subtree...
def is_collision(line_seg1, line_seg2): """ Checks for a collision between line segments p1(x1, y1) -> q1(x2, y2) and p2(x3, y3) -> q2(x4, y4) """ def on_segment(p1, p2, p3): if (p2[0] <= max(p1[0], p3[0])) & (p2[0] >= min(p1[0], p3[0])) & (p2[1] <= max(p1[1], p3[1])) & (p2[1] >= min(p1[1],...
def kelvin2rankine(K): """ Convert Kelvin Temperature to Rankine :param K: Temperature in Kelvin :return: Temperature in R Rankine """ return 9.0 / 5.0 * K
def get_win_target(best_of): """ Gets the number of wins needed to win a match with the given best-of. Arguments: best_of {number} -- the max number of (non-tie) games in a match Returns: number -- the number of game wins needed to win the match """ return (best_of // 2) + 1
def _rangify(start, count, n, name='items'): """ Interpret start as an index into n objects; interpret count as a number of objects starting at start. If start is negative, correct it to be relative to n. If count is negative, adjust it to be relative to n. """ if start < 0: start ...
def ignore_words(txt): """ The results from google search have redundant words in them (happens when a crawler is extracting info). We found this while testing and went to search online and found it. One reference: https://productforums.google.com/forum/#!topic/webmasters/u2qsnn9TFiA The parameter t...
def get_endpoint(server): """Get the endpoint to sign the file, either the full or prelim one.""" if not server: # Setting is empty, signing isn't enabled. return return u'{server}/1.0/sign_addon'.format(server=server)
def word2id(words, vocab, UNK_ID=3): """Summary Parameters ---------- words : TYPE Description vocab : TYPE Description UNK_ID : int, optional Description Returns ------- TYPE Description """ unked = [] for s in words: this_senten...
def fmt_repr(fmt: str, val): """Append repr to a format string.""" return fmt.format(repr(val))
def check_is_valid_ds_name(value, raise_exception=True): """ Check if the value is a valid Dataset name :param value: value to check :param raise_exception: Indicate if an exception shall be raised (True, default) or not (False) :type value: str :type raise_exception: bool :returns: the s...
def get_nb_articles(bib): """Description of get_nb_articles Count the number of articles in the database """ print("There are", len(bib), "articles referenced.") return len(bib)
def reduce_to_unit(divider): """ Reduce a repeating divider to the smallest repeating unit possible. This function is used by :meth:`make_div`. :param divider: The divider. :type divider: str :return: Smallest repeating unit possible. :rtype: str :Example: 'XxXxXxX' -> 'Xx' """ ...
def bool_as_int(val: object) -> str: """Convert a True/False value into '1' or '0'. Valve uses these strings for True/False in editoritems and other config files. """ if val: return '1' else: return '0'
def index(string, substr): """ Convenience method for getting substring index without exception. Returns index if substring is found, -1 otherwise """ try: n = string.index(substr) except ValueError: n = -1 return n
def get_2D_bounding_box(observations): """ Gets the maximum and minimum x and y in order to construct the bounding box. """ x = [] y = [] # slow but elegant! :P for o in observations: x.append(o[0]) y.append(o[1]) return (min(x),min(y)),(max(x),max(y))
def get_list_of_block_numbers(item): """ Creates a list of block numbers of the given list/single event""" if isinstance(item, list): return [element["blockNumber"] for element in item] if isinstance(item, dict): block_number = item["blockNumber"] return [block_number] return l...
def RescaleValue(val, tup_lims_data, tup_lims_rescaled): """ Rescale numeric data value Useful for "rescaling" data for plotting. Example: tup_lims_data = (0, 100) tup_lims_rescaled = (-10, 0) value will be rescaled such that 0 --> -10 and 100 --> 0 Args: val (Float) - value to be res...
def list_to_mask(values, base=0x0): """Converts the specified list of integer values into a bit mask for those values. Optinally, the list can be applied to an existing mask.""" for v in values: base |= (1 << v) return base
def addReading( sensore, readingid, origin, deviceName, resourceName, profileName, valueType, value ): """ sensore is a dict ,origin is int number, else all string. """ reading = { "id": readingid, "origin": origin, "deviceName": deviceName, "resourceName": ...
def nearest_x(num, x): """ Returns the number rounded down to the nearest 'x'. example: nearest_x(25, 20) returns 20. """ for i in range(x): if not (num - i) % x: return num - i
def unify_projection(dic): """Unifies names of projections. Some projections are referred using different names like 'Universal Transverse Mercator' and 'Universe Transverse Mercator'. This function replaces synonyms by a unified name. Example of common typo in UTM replaced by correct spelling:: ...
def transcribe(seq: str) -> str: """ transcribes DNA to RNA by generating the complement sequence with T -> U replacement """ # replacement function def replace_all(text, dictionary): for key, val in dictionary.items(): text = text.replace(key, val) return text # ...
def _format_error(error: list) -> dict: """ Convert the error type list to a dict. Args: error (list): a two element list with the error type and description Returns: dict: explicit names for the list elements """ return {'error_type': error[0], 'description': error[1]}
def build_database_url(ensembl_database): """ Build the correct URL based on the database required GRCh37 databases are on port 3337, all other databases are on port 3306 """ port = 3337 if str(ensembl_database).endswith('37') else 3306 return 'mysql+mysqldb://anonymous@ensembldb.ensembl.org:{}/{}'\...
def generate_labels(seq, mods=None, zeroindex=1): """generate a list of len(seq), with position labels, possibly modified""" i = zeroindex if not mods: return [str(x) for x in range(i, len(seq) + i)] else: if isinstance(mods, list): mods = dict(mods) pos_labels = [] ...
def multiply(value, arg): """Multiplies the value by argument.""" try: return float(value) * float(arg) except (ValueError, TypeError): return ''
def match_state(exp_state, states): """ Matches state values. - exp_state: A dictionary of expected state values, where the key is the state name, the value the expected state. - states: The state content of the state change event. Returns either True or F...
def getMacAddr(macRaw): """ Get mac address via parameter mac raw """ byte_str = map('{:02x}'.format, macRaw) mac_addr = ':'.join(byte_str).upper() return mac_addr
def _get_dimensionality(column): """This function determines the dimensionality of a variable, to see if it contains scalar, 1D, or 2D data. Current version fails on strings.""" try: _=column[0] try: _=column[0][0] return 2 except: return 1 except: ...
def recall(tp, fn, eps=1e-5): """ Calculates recall (a.k.a. true positive rate) for binary classification and segmentation Args: tp: number of true positives fn: number of false negatives Returns: recall value (0-1) """ return tp / (tp + fn + eps)
def atoi(v): """Convert v to an integer, or return 0 on error, like C's atoi().""" try: return int(v or 0) except ValueError: return 0
def compress_column(col): """takes a dense matrix column and puts it into OP4 format""" packs = [] n = 0 i = 0 packi = [] while i < len(col): #print("i=%s n=%s col[i]=%s" % (i, n, col[i])) if col[i] == n + 1: #print("i=n=%s" % i) packi.append(i) ...
def _radix_sort(L, i=0): """ Most significant char radix sort """ if len(L) <= 1: return L done_bucket = [] buckets = [ [] for x in range(255) ] for s in L: if i >= len(s): done_bucket.append(s) else: buckets[ ord(s[i]) ].append(s) buckets = [ _radix_sort(b, i + 1) for b in buck...
def capitalize(text): """ Capitalize first non-whitespace character folling each period in string :param str text: text to capitalize :return: capitalized text :rtype: str """ ret = list(text) # Make sure first word is capitalized... i = 0 while i < (len(text) - 1) and text[i]...
def parse_statement_forwarder_id(json): """ Extract the statement forwarder id from the post response. :param json: JSON from the post response from LearningLocker. :type json: dict(str, dict(str, str)) :return: The extracted statement forwarder id. :rtype: str """ return json['_id']
def _round_to_base(x, base=5): """Round to nearest multiple of `base`.""" return int(base * round(float(x) / base))
def _create_agent_type_id(identifier_type, identifier_value): """Create a key-pair string for the linking_type_value in the db. """ return "{}-{}".format(identifier_type, identifier_value)
def isdistinct(seq): """ All values in sequence are distinct >>> isdistinct([1, 2, 3]) True >>> isdistinct([1, 2, 1]) False >>> isdistinct("Hello") False >>> isdistinct("World") True """ return len(seq) == len(set(seq))
def ArrayOfUTF16StreamCopyToStringTable(byte_stream, byte_stream_size=None): """Copies an array of UTF-16 formatted byte streams to a string table. The string table is a dict of strings with the byte offset as their key. The UTF-16 formatted byte stream should be terminated by an end-of-string character (\x00\...
def make_icon_state_dict(message_icons, icon_names): """Extract the icon state for icon_names from message.""" def binary_sensor_value(icon_flag): return False if icon_flag is None else bool(icon_flag) return {k: binary_sensor_value(message_icons[k]) for k in icon_names}
def Alg_improved_Euclid( a, b ): """ Simple recursive implementation (for gcd) """ if a < b: a, b = b, a if a % b == 0: return b #print a, b if b == 0: return a else: return Alg_improved_Euclid( b, a % b )
def transform_entry(entry): """ Turn the given neo4j Node into a dictionary based on the Node's type. The raw neo4j Node doesn't serialize to JSON so this converts it into something that will. @param entry: the neo4j Node to transform. """ # This transform is used for just nodes as well so first ...
def about_view(request): """View for the about page.""" return {'title': 'about'}
def email_lowercase(backend,details, user=None,*args, **kwargs): """ A pipeline to turn the email address to lowercase """ email = details.get("email") details['email'] = email.strip().lower() if email else None return {"details":details}
def convert_class_functions(line): """Convert class initializer functions to the corresponding variable.""" first_paren = line.find('(') if first_paren == -1: return line line = "unidentified function: " + line return line
def string_escape(string): """ Returns an escaped string for use in Dehacked patch writing. """ string = string.replace('\\', '\\\\') string = string.replace('\n', '\\n') string = string.replace('\r', '\\r') string = string.replace('\t', '\\t') string = string.replace('\"', '\\"') ...
def tiles(width, height, tWidth, tHeight): """Calculates how many tiles does one need for given area @param width: area's width @param height: area's height @param tWidth: tile's width @param tHeight: tiles's height""" area = width * height tile = tWidth * tHeight return area / tile
def process_host(x): """ :return: host, gender, age """ #Homo sapiens; male; age 65 #Homo sapiens; female; age 49 Homo sapiens; male; age 41 #Homo sapiens; female; age 52 Homo sapiens; male; age 61 #Homo sapiens; male Homo sapiens; hospitalized patient raw = x...
def is_additional_rdr_table(table_id): """ Return True if specified table is an additional table submitted by RDR. Currently includes pid_rid_mapping :param table_id: identifies the table :return: True if specified table is an additional table submitted by RDR """ return...
def nested_pairs2dict(pairs): """Create a dict using nested pairs >>> nested_pairs2dict([["foo",[["bar","baz"]]]]) {'foo': {'bar': 'baz'}} :param pairs: pairs [key, value] :type pairs: list :returns: created dict :rtype: dict """ d = {} try: for k, v in pairs: ...
def _find_indicies(array, value): """ Finds the indicies of the array elements that are the closest to `value`. If value is present in `array` then the two indicies are the same. Parameters ---------- value : scalar Value of which the index is to be found. array : list/numpy.ndarray...
def solution(a: list) -> int: """ >>> solution([1, 4, 1]) 0 >>> solution([-1, -2, -3, -2]) 1 >>> solution([4, 2, 2, 5, 1, 5, 8]) 1 """ start = 0 min_ = 10001 for i in range(len(a) - 1): avg = (a[i] + a[i + 1]) / 2 if min_ > avg: min_, start = avg, ...
def perdidas (n_r,n_inv,n_x,**kwargs): """Calcula las perdidas por equipos""" n_t=n_r*n_inv*n_x for kwargs in kwargs: n_t=n_t*kwargs return n_t
def get_correct_message(hidden_word: str) -> str: """Return a output line. Use this method when the user was correct. :param hidden_word: str :return: """ return f"Hit!\n\n" \ f"The word: {hidden_word}\n"
def _get_separator(num, sep_title, sep_character, sep_length): """Get a row separator for row *num*.""" left_divider_length = right_divider_length = sep_length if isinstance(sep_length, tuple): left_divider_length, right_divider_length = sep_length left_divider = sep_character * left_divider_len...
def authorized_groups_text(authorized_groups, default_text='All') -> str: """ Helper function that returns a string for display purposes. """ res = default_text if authorized_groups: res = ', '.join(authorized_groups) return res
def inner_product(koyo, kuwi): """ Inner product between koyo kuwi. """ inner = sum(koyo[key] * kuwi.get(key, 0.0) for key in koyo) return inner
def get_audit(info): """ Prints output in a format that can be parsed from a log file. Spec: <available_peak>, <per_day_peak_remaining>, <today_peak_usage>, <peak_usage_percentage>, <available_off_peak>, <today_off_peak_usage> """ return "{0},{1},{2}...
def format_seconds(seconds): """ convert a number of seconds into a custom string representation """ d, seconds = divmod(seconds, (60 * 60 * 24)) h, seconds = divmod(seconds, (60 * 60)) m, seconds = divmod(seconds, 60) time_string = ("%im %0.2fs" % (m, seconds)) if h or d: time_s...
def equal_sign(num1, num2): """ returns True if the signs of two numbers are equal """ if num1 * num2 > 0: return True else: return False
def sort_high_scores(scores, highest_possible_score): """Returns the high scores sorted from highest to lowest""" if type(scores) != list: raise TypeError( "The first argument of sort_high_scores must be a list.") if type(highest_possible_score) != int: raise TypeError( ...
def remove_digits(s): """ Remove digits in the given string :param s: input string :return: digits removed string """ return ''.join([c for c in s if not c.isdigit()])
def in_reduce(reduce_logic_func, sequence, inclusion_list) -> bool: """Using `reduce_logic_func` check if each element of `sequence` is in `inclusion_list`""" return reduce_logic_func(elmn in inclusion_list for elmn in sequence)
def get_instrument(program): """Return the instrument inferred from the program number.""" if 0 <= program < 8: return "Piano" if 24 <= program < 32: return "Guitar" if 32 <= program < 40: return "Bass" if 40 <= program < 46 or 48 <= program < 52: return "Strings" ...
def get_resample(name: str) -> str: """retrieves code for resampling method Args: name (:obj:`string`): name of resampling method Returns: method :obj:`string`: code of resample method """ methods = { "first": """ import numpy as np def first(in_ar, out_ar, xoff, ...
def polynomial5(x): """Polynomial function with 5 roots in the [-1, 1] range.""" return 63 * x**5 - 70 * x**3 + 15 * x + 2
def fetchall(cursor): """ Fetch all rows from the given cursor Params: cursor (Cursor) : Cursor of previously executed statement Returns: list(dict) : List of dict representing the records selected indexed by column name """ if cursor: cursor_def = [d.name for d in cursor...
def mythdate2dbdate(mythdate): """Turn 20080102 -> 2008-01-02""" return mythdate[0:4] + '-' + mythdate[4:6] + '-' + mythdate[6:8]
def booleanize_list(vals, null_vals=['no', 'none', 'na', 'n/a', '']): """Return a list of true/false from values.""" out = [] for val in vals: val = val.strip().lower() out.append(val and val not in null_vals) return out
def strip_bot_tag(text, bot_tag): """Helper to strip the bot tag out of the message""" # split on bot tag, strip trailing whitespace, join non-empty with space return " ".join([t.strip() for t in text.split(bot_tag) if t])
def vsipGetType(v): """ Returns a tuple with True if a vsip type is found, plus a string indicating the type. For instance for a = vsip_vcreate_f(10,VSIP_MEM_NONE) will return for the call getType(a) (True,'vview_f') also returns types of scalars derived from structure. for i...
def fiboRecursive(n): """ Fibonacci numbers solved with binary recursion """ if n == 0 or n == 1: return 1 else: return fiboRecursive(n - 1) + fiboRecursive(n - 2)
def get_gb_person_id(acc_id, vehicle_index, person_index): """ Returns global person id for GB, year and index of accident. The id is constructed as <Acc_id><Person_index> where Vehicle_index is two digits max. """ person_id = acc_id * 1000 person_id += vehicle_index * 100 person_id +=...
def toLookup(object_list): """A helper function that take a list of two element objects and returns a dictionary that uses the second element as the key. The returned dictionary can be used find the id of an object based on the key passed in. Reduces the number of database queries to one. the items...
def compress_gray(x): """Extract the gray part of a Colay code or cocode word The function returns the 'gray' part of a Golay code or cocode as a 6-bit number. It drops the 'colored' part of the word. A 12-bit Golay code or cocode word can be expressed as a sum of a 6-bit 'gray' and a 6-bit 'color...
def get_provenance_record(caption, ancestor_files, **kwargs): """Create a provenance record describing the diagnostic data and plot.""" record = { 'caption': caption, 'authors': ['schlund_manuel'], 'references': ['acknow_project'], 'ancestors': ancestor_files, } record.up...
def is_word_end(s): """ Checks if a sign finishes a word :param s: the sign to check :return: true if the sign finishes the word """ if s[-1] in "-.": return False return True
def _is_single_bit(value): """ True if only one bit set in value (should be an int) """ if value == 0: return False value &= value - 1 return value == 0
def linestrings_intersect(line1, line2): """ To valid whether linestrings from geojson are intersected with each other. reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js Keyword arguments: line1 -- first line geojson object line2 -- second line geojson object if(lin...
def is_sequence_of_uint(items): """Verify that the sequence contains only unsigned :obj:`int`. Parameters ---------- items : iterable The sequence of items. Returns ------- bool """ return all(isinstance(item, int) and item >= 0 for item in items)
def int_parse(s): """ Parse an integer string in a log file. This is a simple variant on int() that returns None in the case of a single dash being passed to s. :param str s: The string containing the integer number to parse :returns: An int value """ return int(s) if s != '-' else Non...
def clear_bit(target, bit): """ Returns target but with the given bit set to 0 """ return target & ~(1 << bit)
def show_num_bins(autoValue, slider_value): """ Display the number of bins. """ if "Auto" in autoValue: return "# of Bins: Auto" return "# of Bins: " + str(int(slider_value))
def parse_map_line(line, *args): """Parse a line in a simple mapping file. Parameters ---------- line : str Line to parse. args : list, optional Placeholder for caller compatibility. Returns ------- tuple of (str, str) Query and subject. Notes ----- ...