content
stringlengths
42
6.51k
def translate_order(order): """ Translates 'row_major' or 'col_major' to 'C' or 'F' respectively that numpy.reshape wants as an argument Parameters ---------- order: str Must be one of ["row_major", "col_majr"] Output ------ 'C' (row major) or 'F' (col major) """ if or...
def pname(name, levels=None): """ Return a prettified taxon name. Parameters ---------- name : str Taxon name. Returns ------- str Prettified taxon name. Examples -------- .. code:: python3 import dokdo dokdo.pname('d__Bacteria;p_...
def _sabr_implied_vol_hagan_A11_fprime_by_strike( underlying, strike, maturity, alpha, beta, rho, nu): """_sabr_implied_vol_hagan_A11_fprime_by_strike See :py:func:`_sabr_implied_vol_hagan_A11`. :param float underlying: :param float strike: :param float maturity: :param float alpha: mus...
def int2hex(i): """Used to turn ints into hex for web-colors""" if i<16: return "0" + '%X'%i else: return '%X'%i
def get_payload(message): """Parses a payload from a message Parameters" message: the facebook message object (dict) Returns pay: list of payload objects (list) """ pay = None if "message" in message.keys(): if "quick_reply" in message["message"].keys(): if "...
def set_node_stack_traces_enabled(enable: bool) -> dict: """Sets if stack traces should be captured for Nodes. See `Node.getNodeStackTraces`. Default is disabled. Parameters ---------- enable: bool Enable or disable. **Experimental** """ return {"method": "DOM.setNodeStackTrace...
def swagger_escape(s): # pragma: no cover """ / and ~ are special characters in JSON Pointers, and need to be escaped when used literally (for example, in path names). https://swagger.io/docs/specification/using-ref/#escape """ return s.replace('~', '~0').replace('/', '~1')
def find_first_diff_pos(str1: str, str2: str) -> int: """Finds the first difference position. Returns `-1` if both strings are identical.""" if str1 == str2: return -1 shorter, longer = sorted((str1, str2), key=len) shorter_len = len(shorter) return next( (i for i in range(shorter_...
def varint(n): """Varint encoding.""" data = b'' while n >= 0x80: data += bytes([(n & 0x7f) | 0x80]) n >>= 7 data += bytes([n]) return data
def take(c, *items): """ Takes the specified items from collection c, creating a new collection :param c: The collection to take the items from :param items: The items to take :return: the new collection >>> take([1, 2, 3], 0, 2) [1, 3] >>> take((1, 2, 3), 1) (2,) >>> take({"a":...
def _date_string(x): """Convert two integers to a string for the date and time.""" date = x[0] # Date. Example: 19801231 time = x[1] # Time. Example: 1230 return "{0}{1:04d}".format(date, time)
def get_overlap(a, b): """ Retrieve the overlap of two intervals (number of values common to both intervals). a and b are supposed to be lists of 2 elements. """ return max(-1, min(a[1], b[1]) - max(a[0], b[0]) + 1)
def sxs_metadata_file_description(representation): """Find metadata file from highest Lev for this simulation""" from os.path import basename files = representation.get('files', []) metadata_files = [f for f in files if basename(f.get('filename', '')) == 'metadata.json'] metadata_files = sorted(meta...
def choices2list(choices_tuple): """ Helper function that returns a choice list tuple as a simple list of stored values :param choices_tuple: :return: """ return [c[0] for c in choices_tuple]
def green(s): """ Return the given string (``s``) surrounded by the ANSI escape codes to print it in green. :param s: string to console-color green :type s: str :returns: s surrounded by ANSI color escapes for green text :rtype: str """ return "\033[0;32m" + s + "\033[0m"
def _all_are_equal(list_of_objects): """Helper function to check if all the items in a list are the same.""" if not list_of_objects: return True if isinstance(list_of_objects[0], list): list_of_objects = [tuple(obj) for obj in list_of_objects] return len(set(list_of_objects)) == 1
def drop_private_keys(full_dict): """Filter for entries in the full dictionary that have numerical values""" return {key: value for key, value in full_dict.items() if key[0] != '_'}
def getreltype(reltype): """Returns search relation codes for posting requests to http://apps.webofknowledge.com/UA_GeneralSearch.do""" if reltype == 'and': rel = 'AND' elif reltype == 'or': rel = 'OR' elif reltype == 'not': rel = 'NOT' else: raise Exception('Error r...
def get_sig_indices(sig_stars_list): """ ================================================================================================= get_sig_indices(sig_stars_list) ================================================================================================= Arguments: sig_st...
def __to_int(val): """Convert val into an integer value.""" try: return int(val) except (ValueError, TypeError): return 0
def split_qname(qname): """ >>> split_qname("dnstests.fr.") ['.', 'fr.', 'dnstests.fr.'] """ splitted_qname = qname.split(".")[::-1] out = [] current = '' for entry in splitted_qname: if entry == "": out.append(".") else: current = "%s.%s" % (entry...
def parse_target_composition_row(r): """parse target composition row data in numerical values Args: r (str): input row string, like H 1 061.54 010.60 Returns: tuple of ( Symbol, Atomic number, Atomic Percent, ...
def apply(instance, args=()): """ Executes instance(*args), but just return None on error occurred """ try: code = instance(*args) except Exception: code = None return code
def count_list_freq(l): """ Find the frequency of elements in a list """ freq = {} for items in l: freq[items] = l.count(items) return freq
def compare_sequences(target, structure, ignore_gaps=True): """Compare a template sequence and a target""" assert len(target['sequence']) == len(structure['sequence']) match = 0 mismatch = 0 for i in range(len(target['sequence'])): if (target['sequence'][i] == '-') and (structure['sequen...
def sol(num): """ By definition of sparse number two 1s cannot be adjacent but zeroes can be If two 1s are adjacent and we want to make a bigger number we cannot make the either of the bits 0, so only option left is we make the third bit 1 if it is 0 or we add an extra bit """ b = list(bin(n...
def get_filter_by(by): """ convert the filter parameters from the client to list of string with the Keepers API format :param by: input dictionary from the client :return: filter by list to match the Keepers API """ filter_parameters = ["easy", "heavy", "medium"] output = [] for key, val...
def _set_extra_info(extra_info): """Check input and return extra_info dictionary.""" if extra_info is None: return {} if isinstance(extra_info, dict): return extra_info raise RuntimeError( "extra_info must be None or a dict, but got {}".format(extra_info) )
def pretty_print_table(table, bar_color_func, value_color_func): """Pretty-print the given Table""" column_widths = [max(len(str(col)) for col in row) for row in zip(*table)] colored_bar = bar_color_func("|") pretty_table = [] for row in table: pretty_row = "{0} {1} {0}".format( ...
def parseMinutes(mn): """returns a textual form of minutes""" mn = list(map(lambda x: int(x), mn)) fp = ['oh', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty'][mn[0]] sp = ['','one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'][mn[1]] result = "{} {}".forma...
def numderiv(f, xs): """numderiv(f, xarray): Numerical differentiation.""" n = len(xs) list = [] # f'(x) ~= [ f(x+h) - f(x) ] / h x0 = xs[0]; x1 = xs[1] y0 = f(x0); y1 = f(x1) list.append((y1 - y0) / (x1 - x0)) for i in range(1, n-1): # f'(x) ~= [ f(x+h) - f(x-h) ] / 2h x0 = xs[i-1]; x1 = xs[i+1] y0 = ...
def get_smiles_of_user_entity_ids(cursor, unification_table, user_entity_ids): """ Get the smiles using their BIANA user entity ids """ query_smiles = ("""SELECT SM.value, DB.databaseName FROM externalEntitySMILES SM, {} U, externalEntity E, externalDatabase DB ...
def interpret_blockstructures(blockstructures): """Conversion between short-hand and long-hand for MTL block structures. """ conversion = { 'I' : 'trueshare', 'Y' : 'mhushare', 'V' : 'split', 'W' : 'attenshare', } labels = [] for blockstructure in blockstruc...
def hex2rgb(hexstr): """ Convert a hexadecimal color format to RGB array """ _str = hexstr.lstrip("#") rgb = [int(_str[k:k+2],16) for k in range(0,len(_str),2)] return rgb
def __renumber(dictionary): """Renumber the values of the dictionary from 0 to n """ values = set(dictionary.values()) target = set(range(len(values))) if values == target: # no renumbering necessary ret = dictionary.copy() else: # add the values that won't be renumbered...
def create_entry_dict(column_type: str, column_value: str) -> dict: """ Creates an entry dictionary """ return {"type": column_type, "value": column_value}
def to_float_hours(hours, minutes, seconds): """ (int, int, int) -> float Return the total number of hours in the specified number of hours, minutes, and seconds. Precondition: 0 <= minutes < 60 and 0 <= seconds < 60 >>> to_float_hours(0, 15, 0) 0.25 >>> to_float_hours(2, 45, 9) 2.7...
def clean_doc(name: str) -> str: """Returns a clean docstring""" # replace_map = { # " ": " ", # " ": " ", # " ": " ", # " ": ",", # " ": " ", # "\n": " ", # "\n\n": " ", # } # for k, v in list(replace_map.items()): # name = name....
def flatten(l): """ Parameters: l (list) -- input list 2d array list Returns: (list) -- output list flatten """ return [item for sublist in l for item in sublist]
def tail( f, lines ): """ https://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail Parameters ---------- f : opened file object This is not the name of the file, but the object returned from Python open(). lines : integer Number of lines ...
def difference_update(d: dict, remove) -> dict: """Change and return d. d: mutable mapping, remove: iterable. There is such a method for sets, but unfortunately not for dicts. >>> d = {'a': 1, 'b': 2, 'c': 3} >>> remove = ('b', 'outlier') >>> d_altered = difference_update(d, remove) >>> d_a...
def isPracticalFactorization(f): """Test whether f is the factorization of a practical number.""" f = list(f.items()) f.sort() sigma = 1 for p,x in f: if sigma < p - 1: return False sigma *= (p**(x+1)-1)//(p-1) return True
def translate(mRNA): """ this funtion is translate mRNA to protein. """ TranList = { 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', 'CTA':'L', 'CTC':'L', 'C...
def _assert_tensors_equal(a, b, atol=1e-12, prefix=""): """If tensors not close, or a and b arent both tensors, raise a nice Assertion error.""" if a is None and b is None: return True try: if _assert_tensors_equal(a, b, atol=atol): return True raise except Exception:...
def last_node(level: int, *, fanout: int) -> int: """Return the last node at `level`.""" return (fanout ** (level + 1) - 1) // (fanout - 1)
def collatz_odd(number): """Return 3n+1 for a given number.""" return (number * 3) + 1
def is_scalar(value): """Checks if the supplied value can be converted to a scalar.""" try: float(value) except (TypeError, ValueError): return False else: return True
def query_humanize(str,fieldname,table,is_string=True): """ busca en 'str' un asignacion del campo 'fieldname' para cambiarlo por el format de la 'table' y con el is_string = True tiene en cuenta que sea un cadena """ sep='"' if is_string else ' ' strout=str fieldname0=fieldname+"="+sep ...
def sone_aproximation(loudness_level: float) -> float: """ loudness_level: in phon, >40 typically between 1 and 1024 """ return 2 ** ((loudness_level-40)/float(10))
def sim_minmax(column): """Similarity score using the range between min and max for a value Args: column: a given feature column Returns: tuple: A tuple of the form (min, max) """ return min(column), max(column)
def listmode(lst: list): """ Get the most frequently occurring value in a list. """ return max(set(lst), key=lst.count)
def strip_off_start(s: str, pre: str) -> str: """ Strips the full string `pre` from the start of `str`. See `Tools.strip_off` for more info. """ assert isinstance(pre, str), "{} is not a string".format(pre) if s.startswith(pre): s = s[len(pre):] return s
def sanitize_cr(clientscoperep): """ Removes probably sensitive details from a clientscoperep representation :param clientscoperep: the clientscoperep dict to be sanitized :return: sanitized clientrep dict """ result = clientscoperep.copy() if 'secret' in result: result['secret'] = 'no_...
def _pf1d1(val1, val2): """ """ return int(val1 + int(val2[0]))
def _safe_filter_fun(filter_function, d, i): """Helper function that returns False if an exception occurs instead of stopping the loop.""" try: return filter_function(d, i) except: return False
def index_to_sq(ix): """Convert an index to a column and rank""" return (ix % 8, ix // 8)
def check_validity(option): """Check if the input received is a valid digit 1 to 4 inclusive.""" if option.isdigit(): numeric_option = int(option) if numeric_option >=1 and numeric_option <= 5: return numeric_option else: return -1 else: return -1
def choices_to_dict_list(choices): """ :param choices: :return: """ if not choices: return None results = [] for k, v in choices: results.append({ 'value': k, 'display_name': v }) return results
def unfold(vc: set, folded_verts: list): """ Compute final vc given the partial vc and list of folded vertices (unreversed) :param vc: partial vc as a set :param folded_verts: list of folded vertices as 3-tuples :return: final vertex cover as a set """ final_vc = set(vc) for u, v, w in f...
def cleanup_document_keys(document_keys): """ Cleaning up key/value pairs that have empty values from CouchDB search request """ if document_keys: del_list = [] for key, value in document_keys.iteritems(): if not value: del_list.append(key) for key in ...
def take(n, seq): """Returns first n values from the given sequence.""" seq = iter(seq) result = [] try: for i in range(n): result.append(next(seq)) except StopIteration: pass return result
def validate_input_cli(user_input): """ This function validates the input of the user during 2nd menu :param user_input: :return: bool """ if user_input in ('0', '1', '2', '3'): return True return False
def tournamentWinner(competitions, results): """ ### Description tournamentWinner returns the team with the best score. ### Parameters - competitions: matrix containing the teams' names in each match. - results: list containing the result of every competition. ### R...
def get_techno_dicts_translator(ref_techno_dict, new_techno_dict): """ Return dict where k, v are resp. indices in reference and new techno matrix Applicable to both products (rows in A matrix) and activities (columns in A and B matrices) The names of the databases do not need to be the same, but the c...
def create_bounty_submissions_response(submissions, **kwargs): """ returns a submission response from the given submissions. """ return { 'submissions': submissions, 'meta': { 'count': kwargs.get('count', len(submissions)), 'offset': kwargs.get('offset', None), ...
def mention_user_nick_by_id(user_id): """ Mentions the user's "nick" by the user's identifier. Parameters ---------- user_id : `int` The user's identifier. Returns ------- user_nick_mention : `str` """ return f'<@!{user_id}>'
def add(key, old, new): """ doc me """ if key in old: new[key] = old[key] return new
def compose_aug_inchi_key(inchi_key, ulayer=None, player=None): """ Composes an augmented InChI Key by concatenating the different pieces as follows: XXXXXXXXXXXXXX-XXXXXXXXXX-ux,x,xxx Uses hyphens rather than forward slashes to avoid messing up file paths. """ aug_inchi_key = inchi_key ...
def attachments(*args): """Simple attachments base element containing multiple attachment""" return {'attachments': [*args]}
def as_currency(amount, rate): """ Formats the given amount as a currency. :type amount: Number (int or float). :param rate: Multiply 'amount' by 'rate'. :return: String in the format of "200.00". """ total = float(amount) * float(rate) str_total = "{:,.2f} test test".format(total) ...
def make_args(opts): """ Converts a dict to a helm-style --set and --set-string arguments. Helm allows you to set one property at a time, which is desirable because it's effectively a merge. The drawback is the redundancy and readability. This function allows a dict to represent all of the optio...
def human_string(text: str) -> str: """ Transform text to human string Args: text: string to be converted Returns: converted string Examples: >>> human_string('test_str') 'Test Str' >>> human_string("") '' """ if not text: return "" ...
def _find_used(activity, predicate): """Finds a particular used resource in an activity that matches a predicate.""" for resource in activity['used']: if predicate(resource): return resource return None
def extract_ids(records): """ Given a list of records from a remote server, return a list of ids contained therein. """ ids = [] for record in records: ids.append(record['id']) return ids
def get_references(name, references): """Generate section with references for given operator or module""" name = name[12:] # remove nvidia.dali prefix result = "" if name in references: result += ".. seealso::\n" for desc, url in references[name]: result += f" * `{desc} <....
def read_emo_lemma(aline): """ Splits a line into lemma l, emotion e, and l(e). l(e) := 1 if lemma l has emotion e according to the lexicon l(e) := 0 otherwise """ split = aline.split() return split[0], split[1], int(split[2])
def remove_closest_element(x,l): """ removes the closest element, to be used in conjunction with the previous function """ temp=[] for i in l: temp.append(abs(x-i)) u=min(temp) for j in l: if abs(x-j)==u: l.remove(j) return l
def partition_node(node): """Split a host:port string into (host, int(port)) pair.""" host = node port = 27017 idx = node.rfind(':') if idx != -1: host, port = node[:idx], int(node[idx + 1:]) if host.startswith('['): host = host[1:-1] return host, port
def clean_list(input_list): """removes unnecessary characters from a list.""" output_list = list() for i in input_list: var = i.replace('\n', '') output_list.append(var) return output_list
def calc_iou(box_a, box_b): """ Calculate the Intersection Over Union of two boxes Each box specified by upper left corner and lower right corner: (x1, y1, x2, y2), where 1 denotes upper left corner, 2 denotes lower right corner Returns IOU value """ # Calculate intersection, i.e. area of overlap between the 2 ...
def list_(project_id, user_id=None, **kwargs): """List quotas of a project (and user)""" url = '/os-quota-sets/%s' % project_id if user_id: url = '%s?user_id=%s' % (url, user_id) return url, {}
def counting_sort(arr: list) -> list: """ Time Complexity: O(n+k), where k is the range of values Space Complexity: O(k) """ first, last = min(arr), max(arr) count_arr: list = [0] * (last - first + 1) for integer in arr: count_arr[integer - first] += 1 for index in range(1, len...
def blacklist_ports(ports, blacklist): """ Removes port present on the blacklist """ new_ports = dict() for key, ports in ports.items(): new_ports[key] = [] for name, width, assoc_clock in ports: if name not in blacklist: new_ports[key].append([name, wi...
def _get_min_max_value(min, max, value=None, step=None): """Return min, max, value given input values with possible None.""" if value is None: if not max > min: raise ValueError('max must be greater than min: (min={0}, max={1})'.format(min, max)) value = min + abs(min-max)/2 ...
def hasblocks(hashlist): """Determines which blocks are on this server""" print("HasBlocks()") return hashlist
def delta_percent(a, b, warnings=False): """(float, float) => float Return the difference in percentage between a nd b. If the result is 0.0 return 1e-09 instead. >>> delta_percent(20,22) 10.0 >>> delta_percent(2,20) 900.0 >>> delta_percent(1,1) 1e-09 >>> delta_percent(10,9) ...
def _deg_ord_idx(deg, order): """Get the index into S_in or S_out given a degree and order.""" # The -1 here is because we typically exclude the degree=0 term return deg * deg + deg + order - 1
def levenshtein_distance(a, b): """Calculates the Levenshtein distance between a and b.""" n, m = len(a), len(b) if n > m: # Make sure n <= m, to use O(min(n,m)) space a,b = b,a n,m = m,n current = range(n+1) for i in range(1, m+1): previous, current = current, [i] +...
def split_lengths_for_ratios(nitems, *ratios): """Return the lengths of the splits obtained when splitting nitems by the given ratios""" lengths = [int(ratio * nitems) for ratio in ratios] i = 1 while sum(lengths) != nitems and i < len(ratios): lengths[-i] += 1 i += 1 assert sum(...
def numberformat(value): """Formats value as comma-separated""" return f"{value:,.0f}"
def convert_tag(t): """Converts tags so that they can be used by WordNet: | Tag begins with | WordNet tag | |-----------------|-------------| | `N` | `n` | | `V` | `v` | | `J` | `a` | | `R` | `r` | | Oth...
def yubico_verify_false(yubikey_otp): """ utils.yubikey_authenticate function that will always return False :param yubikey_otp: Yubikey OTP :type yubikey_otp: str :return: True :rtype: Boolean """ # Take exactly 1 argument which we will happily ignore afterwards assert yubikey_otp ...
def get_mlp_default_settings(kind): """Get default setting for mlp model.""" if kind == "hidden_sizes": return [64, 64] elif kind == "activation": return "tanh" else: raise KeyError("unknown type: {}".format(kind))
def _analyze_system_results(results): """ This helper method get list of results internal dict and return if test failed or not with summary log return dict with keys: 1. state - true\false for passing test 2. failures - list of not passing services 3. pass = list of passing services...
def formatFilename(prefix, width, height, depth, bits, unsigned): """ Generates a filename using a prefix and the base parameters of all images. """ return format("%s_%dx%dx%d_%d%s") % (prefix, width, height, depth, ...
def check_dfs_empty(fetched_data_dict): """Check whether dataframes saved in dictionary are all empty Argumentss: *fetched_data_dict*: dictionary with df saved as valyes Returns: True if all dataframes are empty, or false when at least one dataframe is not empty """ fetched_da...
def angle_difference(angle1: float, angle2: float) -> float: """The difference of two angle values. Args: angle1, angle2: The values are expected in degrees. Returns: Value in the range [-180.0, 180.0]""" return (abs(angle1 - angle2) + 180) % 360 - 180
def line_to_tensor(line, EOS_int=1): """Turns a line of text into a tensor Args: line (str): A single line of text. EOS_int (int, optional): End-of-sentence integer. Defaults to 1. Returns: list: a list of integers (unicode values) for the characters in the `line`. """ ...
def is_fq(name): """Return True if the supplied 'name' is fully-qualified, False otherwise. Usage examples: >>> is_fq('master') False >>> is_fq('refs/heads/master') True :name: string name of the ref to test :returns: bool """ return name.startswith('refs/')
def _get_fuzzer_module_name(fuzzer: str) -> str: """Returns the name of the fuzzer.py module of |fuzzer|. Assumes |fuzzer| is an underlying fuzzer.""" return 'fuzzers.{}.fuzzer'.format(fuzzer)