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 ...
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...
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":...
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: re...
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 (...
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 =...
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 t...
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 ...
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). ""...
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,...
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: ...
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: ...
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_a...
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 ...
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: ...
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/charlesd...
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 eleme...
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.appen...
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...
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 le...
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 ...
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...
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.repla...
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, whic...
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...
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_li...
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 ...
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,pv...
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]: ...
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...
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 f...
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 ExpFuncSpe...
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): ...
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 ...
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 ...
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 ...
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.form...
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') Fal...
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 cor...
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 = cur...
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 be...
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))...
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(v...
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(caracte...
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_...
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()] re...
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[nod...
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...
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, lengt...
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 k...
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 arr...
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": "e1...
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 ...
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 """ ...
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) d...
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. @...
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 = mi...