content
stringlengths
42
6.51k
def __row_helper(title, value, unit=None, seperator=None): """Helps format system information in a standardized way. Args: title (str): The title of the value. Left aligned. value (any): The value to be displayed. unit (str, optional): The value's unit. seperator (str): The sepe...
def get_class_qualname(cls): """ Give a fully qualified name for a class (and therefore a function ref as well). Example: 'combtest.action.Action'. Note: Python3 has this, or something like it, called ``__qualname__``. We implement our own here to retain control of it, and give us Pytho...
def SUCCESS(obj): """Format an object into string of success color (green) in console. Args: obj: the object to be formatted. Returns: None """ return '\x1b[1;32m' + str(obj) + '\x1b[0m'
def _number_of_set_bits(x): """ Returns the number of bits that are set in a 32bit int """ # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16...
def _findall(s, item): """Return index of each element equal to item in s""" return [i for i,x in enumerate(s) if x == item]
def format_vote_average(pick_vote_average): """ Ensures the movie rating is properly formatted (parameter is the inputted vote average) """ if bool(pick_vote_average) == True: vote_average = float(pick_vote_average) else: vote_average = None return vote_average
def port_str_to_int(port): """ Accepts a string port, validates it is a valid port, and returns it as an int. :param port: A string representing a port :return: The port as an int, or None if it was not valid. """ try: port = int(port) if port is None or port < 1024 or po...
def _determinant(v1, v2, v3) -> float: """ Returns determinant. """ e11, e12, e13 = v1 e21, e22, e23 = v2 e31, e32, e33 = v3 return e11 * e22 * e33 + e12 * e23 * e31 + \ e13 * e21 * e32 - e13 * e22 * e31 - \ e11 * e23 * e32 - e12 * e21 * e33
def pluralize(singular, using, pluralized=None): """Pluralize a word for output. >>> pluralize("job", 1) 'job' >>> pluralize("job", 2) 'jobs' >>> pluralize("datum", 2, "data") 'data' """ return ( singular if using == 1 else (pluralized if pluralized is not No...
def has_method(o, name): """ return True if `o` has callable method `name` """ op = getattr(o, name, None) return op is not None and callable(op)
def getByte(arg: bytes, index: int) -> bytes: """ Return the single byte at index""" return arg[index:index+1]
def number_of_occurrences(element, sample): """ Function that returns the number of occurrences of an element in an array. :param element: an integer value. :param sample: an array of integers. :return: the number of occurrences of an element in an array. """ return sample.count(element)
def sorted_degree_map( degree_map ): """ Function which sorts hashtags by their degrees Args: degree_map: Returns: Sorted mapping """ ms = sorted( iter( degree_map.items() ), key=lambda k_v: (-k_v[ 1 ], k_v[ 0 ]) ) return ms
def _update_crystals(data, v): """Update rotation angle from the parameters value. Args: data: list of beamline elements from get_beamline() function. v: object containing all variables. Returns: data: updated list. """ for i in range(len(data)): if data[i]['type']...
def get_int_in_range(first, last): """ (int, int) -> int Prompt user for an integer within the specified range <first> is either a min or max acceptable value. <last> is the corresponding other end of the range, either a min or max acceptable value. Returns an acceptabl...
def eval_kt2(va, va0): """ evaluate kt2 from phase velocity. va: phase velocity with piezoelectric effect va0: phase velocity without piezoelectric effect """ K2 = (va/va0)**2 - 1 kt2 = K2/(1 + K2) return kt2
def sort_graded(task): """Sorts all tasks in the tasks_graded list, where tasks with the highest score is placed last in the list """ return task['score']
def ot2bio_absa(absa_tag_sequence): """ ot2bio function for ts tag sequence """ #new_ts_sequence = [] new_absa_sequence = [] n_tag = len(absa_tag_sequence) prev_pos = '$$$' for i in range(n_tag): cur_absa_tag = absa_tag_sequence[i] if cur_absa_tag == 'O': new_...
def quote_str(value): """ Return a string in double quotes. Parameters ---------- value : str Some string Returns ------- quoted_value : str The original value in quote marks Example ------- >>> quote_str('some value') '"some value"' """ return ...
def diffa(dist, alpha, r): """ Compute the derivative of local-local BDeu score. """ res = 0.0 for n in dist: for i in range(n): res += 1.0/(i*r+alpha) for i in range(sum(dist)): res -= 1.0/(i+alpha) return res
def find_integer(f): """Finds a (hopefully large) integer such that f(n) is True and f(n + 1) is False. f(0) is assumed to be True and will not be checked. """ # We first do a linear scan over the small numbers and only start to do # anything intelligent if f(4) is true. This is because it's ve...
def histogram_as_list_of_lists_(source_text_as_list): """Return histogram as a list of lists: [['one', 1], ['fish', 4]]...""" output_dict = {} output_list_of_lists = [] for word in source_text_as_list: if word in output_dict.keys(): output_dict[word] += 1 else: o...
def batch_matmul_alter_layout(attrs, inputs, tinfos, out_type): """Change batch_matmul layout.""" # not to change by default return None
def bytes2int(bytes): """PKCS#1 bytes to integer conversion, as used by RSA""" integer = 0 for byte in bytes: integer *= 256 if isinstance(byte,str): byte = ord(byte) integer += byte return integer
def hammingDistance(str1, str2): """ Returns the number of `i`th characters in `str1` that don't match the `i`th character in `str2`. Args --- `str1 : string` The first string `str2 : string` The second string Returns --- `differences : int` The differences between `str1` and `str2` ...
def dict_to_string(d, order=[], exclude=[], entry_sep="_", kv_sep=""): """ Turn a dictionary into a string by concatenating all key and values together, separated by specified delimiters. d: a dictionary. It is expected that key and values are simple literals e.g., strings, float, integers, no...
def post_process_weird(system_mentions): """ Removes all mentions which are "mm", "hmm", "ahem", "um", "US" or "U.S.". Args: system_mentions (list(Mention): A list of system mentions. Returns: list(Mention): the filtered list of mentions. """ return sorted( [mention for...
def get_ip_parameters(ip_layer): """ Extract the ip parameters that are relevant to OS detection from an IP layer :param ip_layer: an IP packet (scapy.layers.inet.IP) :return: tuple - ip parameters. (df, ttl) """ if ip_layer is None: return None df = int(format(ip_layer.flags.value, "03b")[1]) ttl = ip_layer....
def build_mapping(triples, entity_path, relation_path): """build mapping of entities and triples""" entity2id = {} relation2id = {} for triple in triples: head, rel, tail = triple[0], triple[1], triple[2] if head not in entity2id.keys(): entity2id[head] = len(entity2id) ...
def nframes(dur, hop_size=3072, win_len=4096) -> float: """ Compute the numbero of frames given a total duration, the hop size and window length. Output unitiy of measure will be the same as the inputs unity of measure (e.g. samples or seconds). N.B. This returns a float! """ return (dur - ...
def kmerize(ip_string, kmer_size): """ function that kmerizes an input_string and returns a list of kmers """ return [ip_string[i:i + kmer_size] for i in range(0, len(ip_string) - kmer_size + 1, 1)]
def nested_set(dictionary: dict, keys: list, value): """Set value to dict for list of nested keys >>> nested_set({'key': {'nested_key': None}}, keys=['key', 'nested_key'], value=123) {'key': {'nested_key': 123}} """ nested_dict = dictionary for key in keys[:-1]: nested_dict = nested_dic...
def is_name_dict_tuple(transform): """Check the transform is somehow like ('normalize_adj', dict(rate=1.0)) """ return len(transform) == 2 and isinstance(transform[0], str) and isinstance(transform[1], dict)
def upperLeftOrigin( largeSize, smallSize ): """ The upper left coordinate (tuple) of a small rectangle in a larger rectangle (centered) """ origin = tuple( map( lambda x: int( ( (x[0]-x[1])/2 ) ), zip( largeSize, smallSize )) ) return origin
def identity_index(obj, val): """ Same as obj.index(val) but will only return a position if the object val is found in the list. i.e. >>> identity_index(["1"], "1") will raise a ValueError because the two strings are different objects with the same content. >>> a = "1" >>> identity...
def _compute_new_shape(length, height, width, trunc=True): """Computes the new target shape that results in the shortest side length. Parameters ---------- length : float Length of the resulting shortest side height : float Image height width : float Image width Ret...
def real_client_ip(xforwardedfor): """Only the last-most entry listed is the where the client connection to us came from, so that's the only one we can trust in any way.""" return xforwardedfor.split(',')[-1].strip()
def kth_node_in_BST(root, k): """ :param root: Binary Search Tree root :param k: kth smallest :return: kth smallest node """ def recursion(root, k): nonlocal target if not root: return k k = recursion(root.left, k) if not target: if k == 1...
def parseinput(inp):# with name """returns the times as a tuple of (start, end, name) in ints""" inp=inp.splitlines() if len(inp[0].split())>2: return [(int(i.split()[0]), int(i.split()[1]), ''.join(i.split(" ",2)[2:])) for i in inp] else: return [(int(i.split()[0]), int(i.split()[1])) f...
def torch_unravel_index(index, shape): """ x = torch.arange(30).view(10, 3) for i in range(x.numel()): assert i == x[unravel_index(i, x.shape)] https://discuss.pytorch.org/t/how-to-do-a-unravel-index-in-pytorch-just-like-in-numpy/12987/2 Parameters ---------- index : [type] ...
def binary_sample_generator(meta, seqlen, n_bytes): """This function takes in the filesystem metadata generated by the main ``Consumer`` class, ``seqlen``, ``n_bytes`` and returns all the samples in the dataset. Each sample looks like this: .. code-block::python sample = { "data": [ ...
def sequences_match(seq1,seq2,max_mismatches=0): """Determine whether two sequences match with specified tolerance Returns True if sequences 'seq1' and 'seq2' are consider to match, and False if not. By default sequences only match if they are identical. This condition can be loosen by specify a ...
def int_to_tag_hex(value: int) -> str: """ Converts the *int* representation of tags to a *hex* string. Parameters ---------- value : int Raw tag representation as integer Returns ------- str Hexadecimal string representation """ return format(value, "x").zfill(...
def _getTagsWith(s, cont, toClosure=False, maxRes=None): """Return the html tags in the 's' string containing the 'cont' string; if toClosure is True, everything between the opening tag and the closing tag is returned.""" lres = [] bi = s.find(cont) if bi != -1: btag = s[:bi].rfind('<') ...
def _compute_yield_pf_q30(metrics): """ Compute the number of bases passing filter + Q30 from a populated metrics dictionary generated by get_illumina_sequencing_metrics() """ if not metrics.get('num_clusters_pf'): return None num_q30_bases = 0 num_clusters_pf = metrics.get('num_clu...
def is_local_link_information_valid(local_link_information_list): """Verify if a local link information list is valid. A local link information list is valid if: 1 - the list has only one local link information 2 - It has switch info defined 3 - The switch info has a server_hardware_id 4 - The ...
def get( coin, in_coin, try_conversion=None, exchange=None, aggregate=None, limit=None, all_data=None, to_timestamp=None, extra_params=None, sign=None, ): """ Get open, high, low, close, volumefrom and volumeto from the dayly hi...
def comment(text, prefix): """Returns commented-out text. Each line of text will be prefixed by prefix and a space character. Any trailing whitespace will be trimmed. """ accum = ['{} {}'.format(prefix, line).rstrip() for line in text.split('\n')] return '\n'.join(accum)
def split_in_groups(item, group_size): """Splits an iterable in groups of tuples. If we take an incoming list/tuple like: ('id1', 'val1', 'id2', 'val2') and split it with group_size 2, we'll get: [('id1', 'val1'), ('id2', 'val2')] If we take a string like: 'abcdef' and split it with group_size 2, ...
def get_schema(is_ipv6, octet): """Get the template with word slots""" new_line = '\n' period = '.' space = ' ' non_words = [new_line, period, space] if is_ipv6: schema = [octet, octet, 'and', octet, octet, new_line, octet, octet, octet, octet, octet, octet, octet, peri...
def calc_U_slip_quasisteady(eps, E, x, mu): """ Slip velocity (quasi-steady limit) """ u_slip_quasisteady = -eps*E**2*x/(2*mu) return u_slip_quasisteady
def get_prep_pobj_text(preps): """ Parameters ---------- preps : a list of spacy Tokens Returns ------- info : str The text from preps with its immediate children - objects (pobj) Raises ------ IndexError if any of given preps doesn't have any children """ ...
def mutate_dict(inValue, keyFn=lambda k: k, valueFn=lambda v: v, keyTypes=None, valueTypes=None, **kwargs): """ Takes an input dict or list-of-dicts and applies ``keyfn`` function to all of the keys in both the top-level and any...
def reduced_mass(a,b): """ Calculates the reduced mass for mass a and mass b Parameters ---------- a : Float Mass value. b : Float Mass value. Returns ------- red_m : Float Reduced mass of masses a and b. """ red_m = (a*b)/(a+b) return red_m
def word2vec(voca_list, input_set): """ (function) word2vec ------------------- Set a vector from the words Parameter --------- - None Return ------ - word vector """ # Convert words to a vector vec = [0] * len(voca_list) for word in input_set: if word i...
def coin_sum(coins, target): """Return the number of combinations of currency denominations. This function can be used to solve problems like how many different ways can the value `target` be made using any number of values within `coins`. Parameters ---------- coins : array_like ...
def motif_factors(m, M): """ Generates the set of non redundant motif sizes to be checked for division rule. Parameters ---------- m : <int> minimum motif size M : <int> maximum motif size Returns ------- factors : <list> sorted(descending) list of non-redundant motifs. ""...
def reverse_dictionary(a): """Inverts a dictionary mapping. Args: a: input dictionary. Returns: b: output reversed dictionary. """ b = {} for i in a.items(): try: for k in i[1]: if k not in b.keys(): b[k] = [i[0]] ...
def get_delta_angle(a1: float, a2: float, ) -> float: """ Get the difference between two (dihedral or regular) angles. Examples:: 3 - 1 = 2 1 - 3 = 2 1- 359 = 2 Args: a1 (float): Angle 1 in degrees. a2 (float): Angle 2 in ...
def GetTargetAndroidVersionNumber(lines): """Return the Android major version number from the build fingerprint. Args: lines: Lines read from the tombstone file, before preprocessing. Returns: 5, 6, etc, or None if not determinable (developer build?) """ # For example, "Build fingerprint: 'Android/ao...
def remove_header(data): """Remove first two bytes of file to fix the characters""" return data[2:]
def hexify(x): """Returns a single hex transformed value as a string""" return hex(x).split('x')[1] if x > 15 else '0' + hex(x).split('x')[1]
def is_using_reverse_process(input_shape): """Check if output of attention meachanism is a single Attention matrix or 2 attention matrices - one for A_in one for A_out [description] Arguments: input_shape {[tuple]} -- input_shape """ # dimension of attention layer output dim =...
def list_deb (archive, compression, cmd, verbosity, interactive): """List a DEB archive.""" return [cmd, '--contents', '--', archive]
def move_down_left(rows, columns, t): """ A method that takes coordinates of the bomb, number of rows and number of columns of the matrix and returns coordinates of neighbour which is located at the left-hand side and bellow the bomb. It returns None if there isn't such a neighbour """ x, y = t...
def absolute_value(num): """This function returns the absolute value of the number""" if num >= 0: return num else: return -num
def FixDiffLineEnding(diff): """Fix patch files generated on windows and applied on mac/linux. For files with svn:eol-style=crlf, svn diff puts CRLF in the diff hunk header. patch on linux and mac barfs on those hunks. As usual, blame svn.""" output = '' for line in diff.splitlines(True): if (line.starts...
def string_has_vlans(option): """Check if a string is a valid list of VLANs""" for r in option.split(","): r = r.strip().split("-") if not all(s.isdigit() and 0 < int(s) <= 4096 for s in r): return False return True
def _parse_wms(**kw): """ Parse leaflet TileLayer.WMS options. http://leafletjs.com/reference-1.2.0.html#tilelayer-wms """ return { 'layers': kw.pop('layers', ''), 'styles': kw.pop('styles', ''), 'format': kw.pop('fmt', 'image/jpeg'), 'transparent': kw.pop('transpare...
def GetLinkType(messages, link_type_arg): """Converts the link type flag to a message enum. Args: messages: The API messages holder. link_type_arg: The link type flag value. Returns: An LinkTypeValueValuesEnum of the flag value, or None if absent. """ if link_type_arg is None: return None e...
def parse_biases(m, bias_model, bias_params): """ parse the biases in the ouput model inputs: m: model vector bias_model: the bias model bID_dict: the bias parameter dictionary from assign_bias_ID output: ID_dict: a dictionary giving the param...
def resource_name_for_asset_type(asset_type): """Return the resource name for the asset_type. Args: asset_type: the asset type like 'google.compute.Instance' Returns: a resource name like 'Instance' """ return asset_type.split('.')[-1]
def convert_coord(x_center, y_center, radius): """ Convert coordinates from central point to top left point :param x_center: x coordinate of the center :param y_center: y coordinate of the center :param radius: the radius of the ball :return: coordinates of top left point of the surface """ ...
def get_from_config(name, config): """ Get value from any level of config dict. Parameters ---------- name : str Name (key) of the value. config : dict Config dictionary. Returns ------- Requested value. Raises ------ ValueError If there is more...
def isdir(path, **kwargs): """Check if *path* is a directory""" import os.path return os.path.isdir(path, **kwargs)
def single_pairwise(arr, arg, taken): """Get a single index pair (i, j), where arr[i] + arr[j] == arg. Arguments: arr: an array of numbers arg: the target sum to look for taken: an array as long as arr designating if a particular index can be in a new index ...
def merge(header_predictions, predictions, citations, dois, binder_links, long_title): """ Function that takes the predictions using header information, classifier and bibtex/doi parser Parameters ---------- header_predictions extraction of common headers and their contents predictions predictio...
def _row_name(index): """ Converts a row index to a row name. >>> _row_name(0) '1' >>> _row_name(10) '11' """ return '%d' % (index + 1)
def lump_discount(text, sessions=8): """Take the price of one event and multiply by the number of sessions - 1.""" total = float(text) * (int(sessions) - 1) return "{total:.2f}".format(total=total)
def has_attribute(t, key: str) -> bool: """ Check if a callable has an attribute :param t: the callable :param key: the key, the attributes name :return: True if callable contains attribute, otherwise False """ return hasattr(t, key)
def enum_name(cls): """ Return the name used for an enum identifier for the given class @param cls The class name """ return cls.upper()
def sort_tuples_by_idx(list_of_tuples, tuple_idx=1, reverse_flag=False): """Sort a list of (pam, score) tuples Args: list_of_tuples: list of tuples of the format [(str, float), ... , (str, float)] tuple_idx: [default: 1] tuple index which defines sorting reverse_flag: [default: False] if...
def _conn_str_sort_key(key): """Provide pseudo-consistent ordering of components of a connection string. This is of no value except to aid in debugging. :param key: key :return: numeric `key` value usable by e.g. `sorted` """ if key == 'host': return ' 1' if key == 'port': ...
def MessageCrossRefLabel(msg_name): """Message cross reference label.""" return 'envoy_api_msg_%s' % msg_name
def add_coefficient(c): """ Simple function for converting coefficient into string """ if c < 0: return f'- {abs(c)}' elif c > 0: return f'+ {c}' else: return ''
def _parse_port_list(data, port_list=None): """return a list of port strings""" # 1,2,3,4,5,6,7,8,9,10,9,30,80:90,8080:8090 # overlapping and repeated port numbers are allowed if port_list is None: port_list = [] data = data.split(',') data_list = [p.strip() for p in data if ':' not in...
def frame_idx(fname): """Get frame index from filename: `name0001.asc` returns 1""" return int(fname[-8:-4])
def rstrip(val: str) -> str: """Remove trailing whitespace.""" return val.rstrip()
def strip_simple_quotes(s): """Gets rid of single quotes, double quotes, single triple quotes, and single double quotes from a string, if present front and back of a string. Otherwiswe, does nothing. """ starts_single = s.startswith("'") starts_double = s.startswith('"') if not starts_single...
def remove_none_from_dict(dictionary): """ Recursively removes None values from a dictionary :param dictionary: the dictionary to clean :return: a copy of the dictionary with None values removed """ if not isinstance(dictionary, dict): return dictionary return {k: remove_none_from_d...
def create_gps_markers(coords): """Build Marker based on latitude and longitude.""" geojson_dict = [] for i in coords: node = {"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": None}} node["properties"]["name"] = i.name node["geometry"]["coordinates"] = [i.latitude, i.longitude]...
def count_trees(map_input): """ Count the trees across the right/down path Args: map_input: Map data read from file Returns" total_trees: The total number of trees """ # Instantiate counter for trees total_trees = 0 # Start at position 0 for the toboggan toboggan_l...
def result_passes_filter(summary,param_name,param_min,param_max): """ This will check if the parameter is between the two specified values """ passes_filter=True for ii in range(len(param_name)): if param_name[ii] in summary: passes_filter*=summary[param_name[ii]]>=param_m...
def chat_participants(participants_dict): """ "participants": [ { "name": "Akanksha Priyadarshini" }, { "name": "Saurav Verma" } """ return [e.get("name") for e in participants_dict]
def is_cat(label): """ Returns true iff the given label is a category (non-terminal), i.e., is marked with an initial '$'. """ return label.startswith('$')
def octets_from_int(i: int, bytesize: int) -> bytes: """Return an octet sequence from an integer. Return an octet sequence from an integer according to SEC 1 v.2, section 2.3.7. """ return i.to_bytes(bytesize, 'big')
def get_first_author_last_name(author_string): """ returns the last name of the first author of one of our normalised author strings. :param authors: :return: """ if author_string: parts = author_string.split(';') if parts: return parts[0].split(",")[0] return No...
def _get_storage_account_name(storage_endpoint): """ Determines storage account name from endpoint url string. e.g. 'https://mystorage.blob.core.windows.net' -> 'mystorage' """ # url parse package has different names in Python 2 and 3. 'six' package works cross-version. from six.moves.urllib.par...
def remove_revoked_deprecated(stix_objects): """Remove any revoked or deprecated objects from queries made to the data source""" # Note we use .get() because the property may not be present in the JSON data. The default is False # if the property is not set. return list( filter( lamb...
def findXYOffset(tuple): """ Old implementation of implementing cell to cm conversion """ homeX = -4.5 homeY = 4.5 baseX = -9 baseY = 9 xScale = 2-tuple[0] yScale = 2-tuple[1] xOffset = homeX + baseX * xScale yOffset = homeY + baseY * yScale unitScale = 1 #use this for c...