content
stringlengths
42
6.51k
def vdowham(eta, vel_entrain, e_eff, r_eff): """ Calculate the velocity parameter of the contact problem according to Dowson-Hamrock. Parameters ---------- eta: ndarray, scalar The dynamic viscosity of the lubricant. vel_entrain: ndarray, scalar The entrainment velocity of the contact problem. e_eff: ndarray, scalar The effective modulus of the contact problem. r_eff: ndarray, scalar The effective radius of the contact problem. Returns ------- param_velocity: ndarray, scalar The velocity parameter of the contact problem. """ param_velocity = eta * vel_entrain / (e_eff * r_eff) return param_velocity
def check_palin(s): """ This is `Open-Palm's` function that checks if elements of a given list of strings `s` is a palindrome or not. The input `inp` is a tuple containing a single element.Therefore only the first (0 th argument) is accessed. The first argument of the tuple i.e `s[0]`. s[0] is a list of strings. Then, elements of `s[0]` is traversed and checked if the element is a palindrome or not. The result is stored in a new list `ls`. This new list is returned in the end. For example: s = ( ['malayalam', 'pop', 'linux'] ) s[0] = ['malayalam', 'pop', 'linux'] """ s = s[0] ls = [] try: for i in s: ls.append(i == i[::-1]) return(ls) except ValueError: print("Wrong Data Type")
def check_tr_id_full_coverage(tr_id, trid2exc_dic, regid2nc_dic, pseudo_counts=False): """ Check if each exon of a given transcript ID is covered by > 0 reads. If so return True, else False. >>> trid2exc_dic = {"t1" : 2, "t2" : 2, "t3" : 1} >>> regid2nc_dic = {"t1_e1": 0.4, "t1_e2": 1.2, "t2_e1": 0.4, "t2_e2": 0.0, "t3_e1": 1.6} >>> check_tr_id_full_coverage("t1", trid2exc_dic, regid2nc_dic) True >>> check_tr_id_full_coverage("t2", trid2exc_dic, regid2nc_dic) False >>> check_tr_id_full_coverage("t3", trid2exc_dic, regid2nc_dic) True """ min_ex_cov = 0 if pseudo_counts: min_ex_cov = 1 for i in range(trid2exc_dic[tr_id]): ex_nr = i + 1 ex_id = tr_id + "_e" + str(ex_nr) ex_cov = regid2nc_dic[ex_id] if ex_cov == min_ex_cov: return False return True
def _get_record_fields(d): """Get field names from a potentially nested record. """ if isinstance(d, dict): if "fields" in d: return d["fields"] else: for v in d.values(): fields = _get_record_fields(v) if fields: return fields
def judge_para(data): """judge whether is valid para""" for _, para_tokens in data["context"].items(): if len(para_tokens) == 1: return False return True
def do_not_do_anything_here_either_3(do_nothing=False): """ do not do anything here either """ if do_nothing: print("I'm sleeping") return do_nothing
def elem_match(values, filter_expr): """ Element match filter function :param values: list - values :param filter_expr: lambda function :return: bool """ for val in values: if filter_expr(val): return True return False
def byte_to_gb(byte_number): """ convert byte to GB :param byte_number: byte number :return: GB """ return byte_number / (1024 ** 3)
def get_dl_url(project, user, version, base='https://github.com', ext='tar.gz'): """Gets the package download url. Args: version (str): A semver valid version. user (str): The username. base (str): The hosting site (default: 'https://github.com'). ext (str): The file extension (default: 'tar.gz'). Returns: str: The download url Examples: >>> get_dl_url('pkutils', 'reubano', '0.3.0') == ( ... 'https://github.com/reubano/pkutils/archive/v0.3.0.tar.gz') True """ return '%s/%s/%s/archive/v%s.%s' % (base, user, project, version, ext)
def interval_union(start, stop): """Compute non-unique union of many intervals""" return [ i for rng in zip(start, stop) for i in range(*rng) ]
def bubble_sort(x): """Implementation of Bubble sort. Takes integer list as input, returns sorted list.""" print("Starting Bubble sort on following list:\n", x) loop = 0 unsorted = True while(unsorted): loop += 1 print("Bubble sort is in iteration: ", loop) changes = 0 for i in range(0, (len(x)-1)): if x[i] > x[i+1]: print("Bubble sort is changing position of: ", x[i], "and", x[i+1]) j = x[i] x[i] = x[i+1] x[i+1] = j changes += 1 if changes == 0: unsorted = False print("Bubble sort is finished. Sorted list is: \n", x) return x
def get_float(fields, key): """Convert a string value to a float, handling blank values.""" value = fields[key] try: value = float(value) except ValueError: value = 0.0 return value
def remove_keys_from_dict(dictionary: dict, excess_keys) -> dict: """Remove `excess_keys` from `dictionary` Parameters ---------- dictionary: dict A dictionary from that you want to filter out keys excess_keys: iterable Any iterable object (e.g list or set) with keys that you want to remove from `dictionary` Returns ------- `dictionary` without keys that were in `excess_keys` """ dictionary = dictionary.copy() for key in excess_keys: dictionary.pop(key, None) return dictionary
def dict_merge(dst, src): """ Merges ``src`` onto ``dst`` in a deep-copied data structure, overriding data in ``dst`` with ``src``. Both ``dst`` and ``src`` are left intact; and also, they will not share objects with the resulting data structure either. This avoids side-effects when the result structure is modified, which would cause the original ``dst`` to receive modifications if deep copy had not been used. """ import copy def rec_merge(dst, src): dst = copy.copy(dst) for key, val in list(src.items()): if (key in dst) and isinstance(val, dict) and isinstance(dst[key], dict): dst[key] = rec_merge(dst[key], val) else: dst[key] = copy.copy(val) return dst return rec_merge(dst, src)
def get_shorter_move(move, size): """ Given one dimension move (x or y), return the shorter move comparing with opposite move. The Board is actually round, ship can move to destination by any direction. Example: Given board size = 5, move = 3, opposite_move = -2, return -2 since abs(-2) < abs(3). """ if move == 0: return 0 elif move > 0: opposite_move = move - size else: opposite_move = move + size return min([move, opposite_move], key=abs)
def nextDay(year, month, day): """ Returns the year, month, day of the next day. Simple version: assume every month has 30 days. """ # if day >= than 30, we reset day and increase month number if day >= 30: day = 1 month += 1 else: day += 1 # we may have a case, that after increasing month, we would have month number 13 # which means, that we should add 1 to a year and reset a month to 1 if month > 12: year += 1 month = 1 return year, month, day
def filter_dict(it, d): """ Filters a dictionary to all elements in a given iterable :param it: iterable containing all keys which should still be in the dictionary :param d: the dictionary to filter :return: dictionary with all elements of d whose keys are also in it """ if d is None: return {} return dict(filter(lambda cf: cf[0] in it, d.items()))
def process_response(correct, allowed, response): """Checks a response and determines if it is correct. :param correct: The correct answer. :param allowed: List of possible answers. :param response: The answer provided by the player. :return: "correct", "incorrect", or "exit" """ try: response = response.casefold() except AttributeError: pass if response not in allowed: return "exit" elif response == correct: print("Congratulations! Your are correct.\n") return "correct" else: print("Incorrect\n") return "incorrect"
def npint2int(npints): """ Changes a list of np.int64 type to plain int type. Because it seems sqlite is changing np.intt64 to byte type?? """ ints = [] for npint in npints: ints.append(int(npint)) return ints
def get_gate_info(gate): """ gate: str, string gate. ie H(0), or "cx(1, 0)". returns: tuple, (gate_name (str), gate_args (tuple)). """ g = gate.strip().lower() i = g.index("(") gate_name, gate_args = g[:i], eval(g[i:]) try: len(gate_args) except TypeError: gate_args = gate_args, if gate_name == "cx": gate_name = "cnot" return gate_name, gate_args
def has_metadata(info): """Checks for metadata in variables. These are separated from the "key" metadata by underscore. Not used anywhere at the moment for anything other than descriptiveness""" param = dict() metadata = info.split('_', 1) try: key = metadata[0] metadata = metadata[1] except IndexError: metadata = False key = info return key if metadata else info
def get_company_name(companies_list, company): """Return company name from companies on companies_list. Args: companies_list (list): [description] company (str): company id or name Returns: str: company name or "" """ company_name = "" for item in companies_list: if company == item.get("id") or company == item.get("name"): company_name = item.get("name") break return company_name
def u64_to_hex16le(val): """! @brief Create 16-digit hexadecimal string from 64-bit register value""" return ''.join("%02x" % (x & 0xFF) for x in ( val, val >> 8, val >> 16, val >> 24, val >> 32, val >> 40, val >> 48, val >> 56, ))
def enabled_disabled(b): """Convert boolean value to 'enabled' or 'disabled'.""" return "enabled" if b else "disabled"
def encode_packet(data, checksum, seqnum, seqmax, compression): """encode_packet Take an already encoded data string and encode it to a BitShuffle data packet. :param data: bytes """ msg = "This is encoded with BitShuffle, which you can download " + \ "from https://github.com/charlesdaniels/bitshuffle" compatlevel = "1" encoding = "base64" data = data.decode(encoding="ascii") fmt = "((<<{}|{}|{}|{}|{}|{}|{}|{}>>))" packet = fmt.format(msg, compatlevel, encoding, compression, seqnum, seqmax, checksum, data) return packet
def str_to_bytes(value, encoding="utf8"): """Converts a string argument to a byte string""" if isinstance(value, bytes): return value if not isinstance(value, str): raise TypeError('%r is not a string' % value) return value.encode(encoding)
def rawgit(handle, repo, commit, *args): """Returns url for a raw file in a github reposotory.""" url_head = 'https://raw.githubusercontent.com' return '/'.join((url_head, handle, repo, commit) + args)
def remove_nan(values): """ Replaces all 'nan' value in a list with '0' """ for i in range(len(values)): for j in range(len(values[i])): if str(values[i][j]) == 'nan': values[i][j] = 0 return values
def find_item_index(py_list, item): """Find the index of an item in a list. Args: py_list (list): A list of elements. item (int or str): The element in the list. n (int): The upper limit of the range to generate, from 0 to `n` - 1. Returns: index (int): the index of the element. Examples: >>> py_list = ["foo", "bar", "baz"] >>> item = "bar" >>> idx = find_item_index(py_list, item) >>> print("Index: %d" % idx) Index: 1 """ return py_list.index(item)
def difference(xs, ys): """Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. Objects and Arrays are compared in terms of value equality, not reference equality""" out = [] for x in xs: if x not in ys and x not in out: out.append(x) return out
def undecorate(string): """Removes all ANSI escape codes from a given string. Args: string: string to 'undecorate'. Returns: Undecorated, plain string. """ import re return re.sub(r'\033\[[^m]+m', '', string)
def f2c(f): """Fahrenheit to Celsius""" return (f - 32)*5/9
def element_exist_in_list(main_list, sub_list): """ Returns true if sub_list is already appended to the main_list. Otherwise returns false""" try: b = main_list.index(sub_list) return True except ValueError: return False
def filename_removed_items(removed_keys, selector=None): """Generate filename for JSON with items removed from original payload.""" filename = "_".join(removed_keys) if selector is None: return "broken_without_attribute_" + filename else: return "broken_without_" + selector + "_attribute_" + filename
def is_min_heap(level_order: list) -> bool: """ in level order traversal of complete binary tree, left = 2*i+1 right = 2*i+2 """ length = len(level_order) for index in range(int(length / 2 - 1), -1, -1): left_index = 2 * index + 1 right_index = left_index + 1 if left_index < length and level_order[left_index] < level_order[index]: return False if right_index < length and level_order[right_index] < level_order[index]: return False return True
def boost_velocity(vel, dvel, lboost=0): """P velocity boost control""" rel_vel = dvel - vel - lboost * 5 if vel < 1400: if dvel < 0: threshold = 800 else: threshold = 250 else: threshold = 30 return rel_vel > threshold
def dummy_sgs(dummies, sym, n): """ Return the strong generators for dummy indices Parameters ========== dummies : list of dummy indices `dummies[2k], dummies[2k+1]` are paired indices sym : symmetry under interchange of contracted dummies:: * None no symmetry * 0 commuting * 1 anticommuting n : number of indices in base form the dummy indices are always in consecutive positions Examples ======== >>> from sympy.combinatorics.tensor_can import dummy_sgs >>> dummy_sgs(range(2, 8), 0, 8) [[0, 1, 3, 2, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 5, 4, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 7, 6, 8, 9], [0, 1, 4, 5, 2, 3, 6, 7, 8, 9], [0, 1, 2, 3, 6, 7, 4, 5, 8, 9]] """ if len(dummies) > n: raise ValueError("List too large") res = [] # exchange of contravariant and covariant indices if sym is not None: for j in dummies[::2]: a = list(range(n + 2)) if sym == 1: a[n] = n + 1 a[n + 1] = n a[j], a[j + 1] = a[j + 1], a[j] res.append(a) # rename dummy indices for j in dummies[:-3:2]: a = list(range(n + 2)) a[j:j + 4] = a[j + 2], a[j + 3], a[j], a[j + 1] res.append(a) return res
def stop_func(x, y): """ stop_func""" c = x * y c_s = x + y return c_s, c
def pack(x: int, y: int, z: int) -> int: """ Pack x, y, and z into fields of an 8-bit unsigned integer. x: bits 4..7 (4 bits) y: bits 2..3 (2 bits) z: bits 0..1 (2 bits) """ word = (x << 4) | (y << 2) | z return word
def is_valid_positive_float(in_val): """Validates the floating point inputs Args: in_val (string): The string to check Returns: bool: True if the string can be converted to a valid float """ try: _ = float(in_val) except: return False if float(in_val) < 0.0: return False return True
def post_to_html(content): """Convert a post to safe HTML, quote any HTML code, convert URLs to live links and spot any @mentions or #tags and turn them into links. Return the HTML string""" content = content.replace("&", "&amp;") content = content.replace("<", "&lt;") content = content.replace(">", "&gt;") #return '<a class="comurl" href="' + url + '" target="_blank" rel="nofollow">' + text + '<img class="imglink" src="/images/linkout.png"></a>' import re r = re.compile(r"(http://[^ ]+)") return r.sub(r'<a href="\1">\1</a>', content) #nearly there replace ' with " and done. #content = content.replace("http://", "<a href='http://") return content
def generic_print(expr): """Returns an R print statement for expr print("expr"); """ return "print(\"{}\");".format(expr)
def non_empty_string(value): """Must be a non-empty non-blank string""" return bool(value) and bool(value.strip())
def roman_to_int(s): """ Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. roman_integer_value = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000} For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer :type s: str :rtype: int """ integer_value = 0 for index, char in enumerate(s): if char == "I": integer_value += 1 elif char == "V": integer_value += 5 elif char == "X": integer_value += 10 elif char == "L": integer_value += 50 elif char == "C": integer_value += 100 elif char == "D": integer_value += 500 elif char == "M": integer_value += 1000 if index >= 1 and (s[index - 1] == "I" and char in ["X", "V"]): # not out of bound check, # and check if previous character is not I and the current current character is neither "X" nor "V", # if so, decrement integer_value by 2. example : "IX" is 9, here we calculated "I"+"X"=11 # after decrementing the integer_value it becomes 9 again integer_value -= 2 if index >= 1 and (s[index - 1] == "X" and char in ["L", "C"]): integer_value -= 20 if index >= 1 and (s[index - 1] == "C" and char in ["M", "D"]): integer_value -= 200 print(integer_value) return integer_value
def escapearg(args): """Escapes characters you don't want in arguments (preventing shell injection)""" special_chars = '#&;`|*?~<>^()[]{}$\\' for char in special_chars: args = args.replace(char, '') return args
def format_long_dict_list(data): """Return a formatted string. :param data: a list of dicts :rtype: a string formatted to {a:b, c:d}, {e:f, g:h} """ newdata = [str({str(key): str(value) for key, value in d.iteritems()}) for d in data] return ',\n'.join(newdata) + '\n'
def tx_is_coinbase( tx ): """ Is a transaction a coinbase transaction? """ for inp in tx['vin']: if 'coinbase' in inp.keys(): return True return False
def filter_markdown(md, **kwargs): """Strip out doctoc Table of Contents for RippleAPI""" DOCTOC_START = "<!-- START doctoc generated TOC please keep comment here to allow auto update -->" DOCTOC_END = "<!-- END doctoc generated TOC please keep comment here to allow auto update -->" doctoc_start_i = md.find(DOCTOC_START) doctoc_end_i = md.find(DOCTOC_END) if doctoc_start_i != -1 and doctoc_end_i != -1: md = md[:doctoc_start_i]+md[doctoc_end_i+len(DOCTOC_END):] return md
def indent(text: str) -> str: """ Indent each line in a string. """ lines = text.replace("\r", "").split("\n") new_lines = [] for line in lines: if len(line.strip()) == 0: new_lines.append("") else: new_lines.append("\t" + line) return "\n".join(new_lines)
def _ignore_quote(pos, text): """Check whether quote is truly end of a sentence. The end of a quotation may not be the end of the sentence. This function does a 'weak' test to find out: if the next non-whitespace character is lower case, then you don't have a full-sentence. As such, the quote does not mark the end of a sentence; set its position to -1. Args: pos (int): Relevant index near where quote detected. text (str): Text being parsed. Returns: -1 (int): if quote is not the end of the sentence. pos (int): if quote is the end of the sentence. """ # Don't want to look at something outside the bounds of text if (pos + 3) < len(text): # The 'weak' criterion... if text[pos + 3].islower(): return -1 # Quote 'may' be end of sentence return pos
def get_sea_attribute_cmd(seaname): """ Get pvid, pvid_adapter, and virt_adapters from the configured SEA device. Also get the state of the SEA. :param seaname: sea device name :returns: A VIOS command to get the sea adapter's attributes. """ return ("ioscli lsdev -dev %(sea)s -attr pvid,pvid_adapter,virt_adapters;" "ioscli lsdev -type sea | grep %(sea)s" % {'sea': seaname})
def check_ticket(ticket, patterns): """ :param ticket: str only contains '(', ')' :param patterns for comparison :return: bool """ stack = [] for c in ticket: if c in patterns: if len(stack) == 0: return False if stack.pop() != patterns[c]: return False else: stack.append(c) return len(stack) == 0
def getcamera_target(minextents, maxextents): """ Compute the center of the DTM in pixel space Parameters ----------- minextents (tuple) (xmin, ymin, zmin) maxextents (tuple) (xmax, ymax, zmax) Returns -------- center (tuple) (xcenter, ycenter, zcenter) """ xcenter = (maxextents[0] - minextents[0]) / 2.0 ycenter = (maxextents[1] - minextents[1]) / 2.0 zcenter = (maxextents[2] - minextents[2]) / 2.0 return xcenter, ycenter, zcenter
def convert_mac_address_format(cisco_mac): """Converts a MAC address from the cisco format xxxx.xxxx.xxxx to the standard format accepted by IPAM xx:xx:xx:xx:xx:xx """ a = cisco_mac.replace('.','') result = ':'.join([a[0:2], a[2:4], a[4:6], a[6:8], a[8:10], a[10:12]]) return result
def calc_multi_element_lens_petzval_sum(ns, rocs): """Calculate Petzval sum of a multi-element lens. Args: ns (sequence): Refractive indices of all media. rocs (sequence): Length is one less than ns. Returns: Petzval sum. """ assert len(ns) == len(rocs) + 1 ps = 0 for n1, n2, roc in zip(ns[:-1], ns[1:], rocs): ps += (n2 - n1)/(roc*n1*n2) return ps
def resolveSpecTypeCombos(t1, t2): """Resolve Quantity and QuantSpec types when combined. QuantSpec <op> QuantSpec -> specType rules: same types -> that type ExpFuncSpec o RHSfuncSpec -> RHSfuncSpec ImpFuncSpec o RHSfuncSpec -> RHSfuncSpec (should this be an error?) ImpFuncSpec o ExpFuncSpec -> ImpFuncSpec""" if t1=='RHSfuncSpec' or t2=='RHSfuncSpec': return 'RHSfuncSpec' elif t1=='ImpFuncSpec' or t2=='ImpFuncSpec': return 'ImpFuncSpec' else: return 'ExpFuncSpec'
def pluralize(count, item_type): """Pluralizes the item_type if the count does not equal one. For example `pluralize(1, 'apple')` returns '1 apple', while `pluralize(0, 'apple') returns '0 apples'. :return The count and inflected item_type together as a string :rtype string """ def pluralize_string(x): if x.endswith('s'): return x + 'es' else: return x + 's' text = '{} {}'.format(count, item_type if count == 1 else pluralize_string(item_type)) return text
def is_isogram(string): """ Determine if the input string is an isogram. param: str to test if it is an isogram return: True or False if the input is an isogram """ # An empty string is an isogram if string == "": return True # Lowercase the string to simplify comparisions input = str.lower(string) # Dictionary to hold the letters we've seen used_letters = {} for letter in input: # Only testing alpha characters, all others are ignored, e.g. hyphen if letter.isalpha(): # If the letter has already been seen, return False if letter in used_letters: return False # Otherwise, add it to the letters we've seen used_letters[letter] = 1 # Did not find a repeat of the alpha characters in the input return True
def isNotTrue (b) : """return True if b is not equal to True, return False otherwise >>> isNotTrue(True) False >>> isNotTrue(False) True >>> isNotTrue("hello world") True """ # take care: not(X or Y) is (not X) and (not Y) if b is not True and b != True : # base case: b not equals to True => return True return True else : # otherwise: solve the problem recursively return isNotTrue(not b) == (False or ...)
def format_array(arr, precision=4): """ Create a string representation of a numpy array with less precision than the default. Parameters ---------- arr : array Array to be converted to a string precision : int Number of significant digit to display each value. Returns ------- str Nice string representation of the array. """ if arr is None: return "" formatting_str = "{0:." + str(precision) + "g}" str_values = [formatting_str.format(float(val)) for val in arr] content = ", ".join(str_values) return "[" + content + "]"
def _database_privileges_sql_limited(database_name): """Return a tuple of statements granting privileges on the database. :param database_name: Database name :type: str :return: a tuple of statements :rtype: tuple(str) """ tmpl = 'grant create on database {db} to {usr}' return (tmpl.format(db=database_name, usr='loading_user')),
def csv_encode(text): """Format text for CSV.""" encode_table = { '"': '""', '\n': '', '\r': '' } return '"%s"' % ''.join( encode_table.get(c, c) for c in text )
def isSubstateOf(parentState, subState): """Determine whether subState is a substate of parentState >>> isSubstateOf('FOO__BAR', 'FOO') False >>> isSubstateOf('FOO__BAR', 'FOO__BAR') True >>> isSubstateOf('FOO__BAR', 'FOO__BAR__BAZ') True >>> isSubstateOf('FOO__BAR', 'FOO__BAZ') False """ if parentState is None or subState is None: return False if parentState == subState: return True if len(subState) <= len(parentState): return False if subState[:len(parentState)+2] == parentState + '__': return True return False
def Lennard_Jones_AB(r, C6, C12, lam): """ Computes the Lennard-Jones potential with C6 and C12 parameters Parameters ---------- C6: float C6 parameter used for LJ equation C12: float C12 parameter used for LJ equation grid.ri: ndarray In the context of rism, ri corresponds to grid points upon which RISM equations are solved lam: float Lambda parameter to switch on potential Returns ------- result: float The result of the LJ computation """ return ((C12 / r ** 12) - (C6 / r ** 6)) * lam
def slugify(s): """ Slugify a string for use in URLs. This mirrors ``nsot.util.slugify()``. :param s: String to slugify """ disallowed_chars = ['/'] replacement = '_' for char in disallowed_chars: s = s.replace(char, replacement) return s
def create_unique_id_for_nodes(input_objs, start_no): """ :param input_objs: :param start_no: :return: """ current_no = start_no if 'nodes' in input_objs: for node in input_objs['nodes']: # if 'id' in node: node['id'] = current_no current_no = current_no + 1 # unique adding return input_objs
def examp01(row, minimum, maximum): """Returns how many numbers between `maximum` and `minimum` in a given `row`""" count = 0 for n in row: if minimum <= n <= maximum: count = count + 1 return count
def cropped_positions_arcface(annotation_type="eyes-center"): """ Returns the 112 x 112 crop used in iResnet based models The crop follows the following rule: - In X --> (112/2)-1 - In Y, leye --> 16+(112/2) --> 72 - In Y, reye --> (112/2)-16 --> 40 This will leave 16 pixels between left eye and left border and right eye and right border For reference, https://github.com/deepinsight/insightface/blob/master/recognition/arcface_mxnet/common/face_align.py contains the cropping code for training the original ArcFace-InsightFace model. Due to this code not being very explicit, we choose to pick our own default cropped positions. They have been tested to provide good evaluation performance on the Mobio dataset. For sensitive applications, you can use custom cropped position that you optimize for your specific dataset, such as is done in https://gitlab.idiap.ch/bob/bob.bio.face/-/blob/master/notebooks/50-shades-of-face.ipynb """ if isinstance(annotation_type, list): return [cropped_positions_arcface(item) for item in annotation_type] if annotation_type == "eyes-center": cropped_positions = { "leye": (55, 72), "reye": (55, 40), } elif annotation_type == "left-profile": cropped_positions = {"leye": (40, 30), "mouth": (85, 30)} elif annotation_type == "right-profile": return {"reye": (40, 82), "mouth": (85, 82)} else: raise ValueError(f"Annotations of the type `{annotation_type}` not supported") return cropped_positions
def stretch(audio, byte_width): """ stretches the samples to cover a range of width 2**bits, so we can convert to ints later. """ return audio * (2**(8*byte_width-1) - 1)
def get_precision(value): """ This is a hacky function for getting the precision to use when comparing the value sent to WF via the proxy with a double value passed to it. Arguments: value - the value to return the precision to use with a %.E format string """ sval = '%.2f' % (float(value)) last_index = len(sval) found_decimal = False for index in range(len(sval) - 1, 0, -1): char = sval[index] last_index = index if char == '.': found_decimal = True if char != '0' and char != '.': break if not found_decimal: return last_index - 1 else: return last_index
def version_check(checked_version, min_version): """ Checks whether checked version is higher or equal to given min version :param checked_version: version being checked :param min_version: minimum allowed version :return: True when checked version is high enough """ def version_transform(ver): version = '' vn = va = '' stage = 0 ver = '.' + (ver or '') for c in ver: if c == '.': if vn or va: version += '{0:0>3}{1: <2}.'.format(vn, va) vn = va = '' stage = 0 continue if c.isdigit(): pass elif c.isalpha(): stage = max(1, stage) else: stage = max(2, stage) if stage == 0: vn += c elif stage == 1: va += c if vn or va: version += '{0:0>3}{1: <2}.'.format(vn, va) return version[:-1] if not checked_version: return False return version_transform(checked_version) >= version_transform(min_version)
def abbr(S, max, ellipsis='...'): # type: (str, int, str) -> str """Abbreviate word.""" if S is None: return '???' if len(S) > max: return ellipsis and (S[:max - len(ellipsis)] + ellipsis) or S[:max] return S
def es_base(caracter): """ (str of len == 1) -> bool Valida si un caracter es una base >>> es_base('t') True >>> es_base('u') False :param caracter: str que representa el caracter complementario :return: bool que representa si es una base valida """ if int == type(caracter): raise TypeError(str(caracter) + ' no es una base') if float == type(caracter): raise TypeError(str(caracter) + ' no es una base') if len(caracter) != 1: raise ValueError(caracter + ' tiene mas de 1 caracter') base = ['A', 'a', 'C', 'c', 'G', 'g', 'T', 't'] if caracter in base: return True if caracter not in base: return False
def string_to_list(string): """ Convert to list from space-separated entry. If input string is empty, return empty list. :param string: Input space-separated list. :return: List of strings. >>> string_to_list("") == [] True >>> string_to_list("one") == ["one"] True >>> string_to_list("one two") == ["one", "two"] True """ # This is because(''.split('') -> ['']) result = [] if len(string) > 0: result = string.split(' ') return result
def HTTP405(environ, start_response): """ HTTP 405 Response """ start_response('405 METHOD NOT ALLOWED', [('Content-Type', 'text/plain')]) return ['']
def remove_diag_specific_models(project_models): """ @brief Remove a number of models from project_info['MODELS'] @param project_models Current models from the project_info['MODELS'] """ project_models = [model for model in project_models if not model.is_diag_specific()] return project_models
def finder(res_tree, nodes): """ Uses recursion to locate a leave resource. :param res_tree: The (sub)resource containing the desired leave resource. :param nodes: A list of nodes leading to the resource. :return: Located resource content. """ if len(nodes) == 1: return res_tree[nodes[0]] else: cur_node = nodes.pop() try: return finder(res_tree[cur_node], nodes) except TypeError: return finder(res_tree[int(cur_node)], nodes)
def fill(instance, index, content): """Filler to list/array. :type instance: list :type index: int :type content: Any :param instance: 'list' instance :param index: Index to be filled :param content: Content of a Index :return: None""" if isinstance(instance, list): instance_len = len(instance) if instance_len == index or instance_len > index: instance[index] = content if instance_len == index-1: instance.append(content) if instance_len < index: _n = index - instance_len for _n_ in range(_n+1): instance.append(None) instance[index] = content return None if isinstance(instance, dict): instance[index] = content return None else: raise TypeError("Instance need to be list")
def parse_hours(hours): """ simple mask >>> parse_hours(0x0b) 11 >>> parse_hours(0x28) 8 """ return int(hours & 0x1f)
def get_masks(tokens, max_seq_length): """Mask for padding""" if len(tokens) > max_seq_length: raise IndexError("Token length more than max seq length!") return [1] * len(tokens) + [0] * (max_seq_length - len(tokens))
def max_sum_naive(arr: list, length: int, index: int, prev_max: int) -> int: """ We can either take or leave the current number depending on previous max number """ if index >= length: return 0 cur_max = 0 if arr[index] > prev_max: cur_max = arr[index] + max_sum_naive(arr, length, index + 1, arr[index]) return max(cur_max, max_sum_naive(arr, length, index + 1, prev_max))
def parse_new_patient(in_data): """To change the input data from string to integer This function will take the input data with keys "patient id" and "patient age" and change them from string to integer. If it contains more than integer it will show an error message. :param in_data: JSON contains keys "patient id" and "patient age" :return: the changed data format (to int) or error message """ if type(in_data) is not dict: return "No dictionary exists" if "patient_id" in in_data.keys(): try: in_data["patient_id"] = int(in_data["patient_id"]) except ValueError: return "Patient ID is not a number or can't convert to integer" else: return "No such key: patient_id" if "patient_age" in in_data.keys(): try: in_data["patient_age"] = int(in_data["patient_age"]) except ValueError: return "Patient age is not a number or can't convert to integer" else: return "No such key: patient_age" return in_data
def LotkaVolterra(y, time, alpha, beta, gamma, delta): """ Definition of the system of ODE for the Lotka-Volterra system.""" r, f = y dydt = [alpha*r - beta*f*r, delta*f*r - gamma*f] return dydt
def print_ident(col): """Adding indents in accordance with the level Args: col (int): level Returns: str: """ ident = ' ' out = '' for i in range(0, col): out += ident return out
def flip_ctrlpts_u(ctrlpts, size_u, size_v): """ Flips a list of 1-dimensional control points in u-row order to v-row order. **u-row order**: each row corresponds to a list of u values (in 2-dimensions, an array of [v][u]) **v-row order**: each row corresponds to a list of v values (in 2-dimensions, an array of [u][v]) :param ctrlpts: control points in u-row order :type ctrlpts: list, tuple :param size_u: size in u-direction :type size_u: int :param size_v: size in v-direction :type size_v: int :return: control points in v-row order :rtype: list """ new_ctrlpts = [] for i in range(0, size_u): for j in range(0, size_v): temp = [float(c) for c in ctrlpts[i + (j * size_u)]] new_ctrlpts.append(temp) return new_ctrlpts
def convertSI(s): """Convert a measurement with a range suffix into a suitably scaled value""" du = s.split() if len(du) != 2: return s units = du[1] # http://physics.nist.gov/cuu/Units/prefixes.html factor = { "Y": "e24", "Z": "e21", "E": "e18", "P": "e15", "T": "e12", "G": "e9", "M": "e6", "k": "e3", " ": "", "m": "e-3", "u": "e-6", "n": "e-9", "p": "e-12", "f": "e-15", "a": "e-18", "z": "e-21", "y": "e-24", }[units[0]] return du[0] + factor
def yesno(value): """Convert 0/1 or True/False to 'yes'/'no' strings. Weka/LibSVM doesn't like labels that are numbers, so this is helpful for that. """ if value == 1 or value == True: return 'yes' return 'no'
def lwrap(s, w=72): """ Wrap a c-prototype like string into a number of lines """ l = [] p = "" while len(s) > w: y = s[:w].rfind(',') if y == -1: y = s[:w].rfind('(') if y == -1: break l.append(p + s[:y + 1]) s = s[y + 1:].lstrip() p = " " if len(s) > 0: l.append(p + s) return l
def attsiz(att: str) -> int: """ Helper function to return attribute size in bytes :param str: attribute type e.g. 'U002' :return size of attribute in bytes :rtype int """ return int(att[1:4])
def create_index_from_sequences(sequences): """ Creates indices from sequences. :param sequences: list of sequences. :return: indices. """ indices = [] for index in range(0, len(sequences)): indices.append(index) return indices
def sort_into_categories(items, categories, fit, unknown_category_name=None): """ Given a list of items and a list of categories and a way to determine if an item fits into a category creates lists of items fitting in each category as well as a list of items that fit in no category. :return: A mapping category (or unknown_category_name) -> sub-list of items in that category """ categorized_sublists = {} for category in categories: sublist = [item for item in items if fit(item, category)] categorized_sublists[category] = sublist if unknown_category_name: # now those that do not fit sublist = [item for item in items if not any(fit(item, category) for category in categories)] categorized_sublists[unknown_category_name] = sublist return categorized_sublists
def check_compatible(numIons, wyckoff): """ check if the number of atoms is compatible with the wyckoff positions needs to improve later """ N_site = [len(x[0]) for x in wyckoff] for numIon in numIons: if numIon % N_site[-1] > 0: return False return True
def xml_escape(input: str) -> str: """Convert an object into its String representation Args: input: The object to be converted Returns: The converted string """ if input is None: return "" from xml.sax.saxutils import escape return escape(input)
def vec_sub(a, b): """ Subtract two vectors or a vector and a scalar element-wise Parameters ---------- a: list[] A vector of scalar values b: list[] A vector of scalar values or a scalar value. Returns ------- list[] A vector difference of a and b """ if type(b) is list: assert len(a) == len(b) # return [a[n] - b[n] for n in range(len(a))] return [*map(lambda ai, bi: ai - bi, a, b)] else: # return [a[n] - b for n in range(len(a))] return [*map(lambda ai: ai - b, a)]
def _numeric_derivative(y0, y1, err, target, x_min, x_max, x0, x1): """Get close to <target> by doing a numeric derivative""" if abs(y1 - y0) < err: # break by passing dx == 0 return 0., x1, x1 x = (target - y0) / (y1 - y0) * (x1 - x0) + x0 x = min(x, x_max) x = max(x, x_min) dx = abs(x - x1) x0 = x1 x1 = x return dx, x0, x1
def get_key_of_max(dict_obj): """Returns the key that maps to the maximal value in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1} >>> print(get_key_of_max(dict_obj)) a """ return max( dict_obj, key=lambda key: dict_obj[key])
def describe_result(result): """ Describe the result from "import-results" """ status = result['status'] suite_name = result['suite-name'] return '%s %s' % (status, suite_name)
def euclidean_distance_square(point1, point2): """! @brief Calculate square Euclidean distance between two vectors. \f[ dist(a, b) = \sum_{i=0}^{N}(a_{i} - b_{i})^{2}; \f] @param[in] point1 (array_like): The first vector. @param[in] point2 (array_like): The second vector. @return (double) Square Euclidean distance between two vectors. @see euclidean_distance, manhattan_distance, chebyshev_distance """ distance = 0.0 for i in range(len(point1)): distance += (point1[i] - point2[i]) ** 2.0 return distance
def test_desc_with_no_default(test_arg): """ this is test for description decoration without default parm value :param test_arg: :return: """ print('this.is decr without any default value') return {}
def minimallyEqualXML(one, two, removeElements=()): """ Strip all the whitespace out of two pieces of XML code, having first converted them to a DOM as a minimal test of equivalence. """ from xml.dom import minidom sf = lambda x: ''.join(filter(lambda y: y.strip(), x)) onedom = minidom.parseString(one) twodom = minidom.parseString(two) # a hugely hackish way to remove the elements, not full proof, but being # a test situation, we should be providing very controlled input for element in removeElements: oneremovenodes = onedom.getElementsByTagName(element) tworemovenodes = twodom.getElementsByTagName(element) for removenode in oneremovenodes: removenode.parentNode.removeChild(removenode) for removenode in tworemovenodes: removenode.parentNode.removeChild(removenode) return sf(onedom.toxml()) == sf(twodom.toxml())