content
stringlengths
42
6.51k
def to_bytes(key: str, encoding: str = 'utf-8'): """ crypto lib expect 'bytes' keys, convert 'str' keys to 'bytes' """ return key.encode(encoding)
def perfect_score(student_info): """ :param student_info: list of [<student name>, <score>] lists :return: first `[<student name>, 100]` or `[]` if no student score of 100 is found. """ for info in student_info: if info[1] == 100: return info return []
def _can_be_quoted(loan_amount, lent_amounts): """ Checks if the borrower can obtain a quote. To this aim, the loan amount should be less than or equal to the total amounts given by lenders. :param loan_amount: the requested loan amount :param lent_amounts: the sum of the amounts given by lenders :return: True if the borrower can get a quote, False otherwise """ return sum(lent_amounts) - loan_amount >= 0;
def one_hot_encoding(x, allowable_set, encode_unknown=False): """One hot encoding of the element x with respect to the allowable set. If encode unknown is true, and x is not in the allowable set, then x is added to the allowable set. Args: :param x (elem) : [the element to encode] :param allowable_set (list): [ The list of elements] :param encode_unknown (bool, optional): [Whether to add x to the allowable list, if x is already not present]. Defaults to False. :return one hot encoding of x """ if encode_unknown and (x not in allowable_set): allowable_set.append(x) return list(map(lambda s: x == s, allowable_set))
def countSegments(s): """ :type s: str :rtype: int """ return len(s.split())
def get_decades(start_year, end_year): """Get a list of decades to process (usually only 1) Args: start_year (int) : Start year. end_year (int) : End year. Returns: list : List of decades to process. """ # Convert to decades start_decade = start_year // 10 end_decade = end_year // 10 # Degenerate case, just do a single decade if start_decade == end_decade: return [start_decade] return range(start_decade, end_decade + 1)
def is_every_n_steps(interval, current_step, skip_zero=False): """ Convenient function to check whether current_step is at the interval. Returns True if current_step % interval == 0 and asserts a few corner cases (e.g., interval <= 0) Args: interval (int): target interval current_step (int): current step skip_zero (bool): whether to skip 0 (return False at 0) Returns: is_at_interval (bool): whether current_step is at the interval """ if interval is None: return False assert isinstance(interval, int) and interval > 0 assert isinstance(current_step, int) and current_step >= 0 if skip_zero and current_step == 0: return False return current_step % interval == 0
def linearSearch(searchList, target): """ Returns index position of the target if found else return None. """ for i in range(0, len(searchList)): if searchList[i] == target: return i return None # The above is a linear runtime algorithm: O(n) - sequentially goes through the list.
def get_filenames_from_urls(urls): """ Returns a list of filenames from a list of urls""" return [url.split("/")[-1] for url in urls]
def pct(numerator, denominator, precision=None): """Makes into a percent, avoiding division by zero""" if numerator > 0 and denominator > 0: value = (100.0 * numerator) / denominator else: value = 0.0 if precision is not None: value = round(value, precision) return value
def NoTestRunnerFiles(path, dent, is_dir): """Filter function that can be passed to FindCFiles or FindHeaderFiles in order to exclude test runner files.""" # NOTE(martinkr): This prevents .h/.cc files in src/ssl/test/runner, which # are in their own subpackage, from being included in boringssl/BUILD files. return not is_dir or dent != 'runner'
def normalize(string : str) -> str: """Removes all extra fluff from a text to get the barebone content""" return string.replace(",", "").replace("members", "").replace("member", "").strip()
def jsonify(form): """Cast WTForm to JSON object. """ return { 'form': [ { 'id': field.id, 'label': str(field.label), 'html': str(field), 'description': str(field.description) } for field in form ] }
def temperature_to_state(temperature, undefined_temperature): """Convert temperature to a state.""" return temperature if temperature > undefined_temperature else None
def two_sum(nu, t): """ Looking for the target between two numbers in 'the list' :param nu: list numbers [] :param t: target or goal :return: key:value, and iteration if find result (target - each number) and the iteration it ended up. if no result is found,it'll return -1 """ d = dict() for i in range(len(nu)): if t - nu[i] in d: print(d) return d[t - nu[i]], i d[nu[i]] = i return -1
def edges_from_path(path): """ Converts the list of path nodes into a list of path edges ---------- path: list of path nodes Returns ------- path of edge: list of path edges """ return list(zip(path,path[1:]))
def average_list(lst): """averages a list""" return sum(lst)/len(lst)
def parse_values(string, prefix): """Parse the value name pairs output by rndc. Parse the lines output by rndc with a value and name that are separated by a space character. Spaces are removed from the, it is converted to lower case, and prefixed with the prefix variable before becoming the key to the dict that is returned. The value gets converted to an integer and is the value in the dict for the key. The string passed to the function can contain multiple lines separated by the '\n' character. A dict of all of the parsed key/value pairs is returned. """ ret = dict() for match in string.splitlines(): val, name = match.strip().split(' ', 1) idx = prefix + name.replace(' ', '').lower() ret[idx] = int(val) return ret
def maxsum(sequence): """Return maximum sum.""" maxsofar, maxendinghere = 0, 0 for x in sequence: # invariant: ``maxendinghere`` and ``maxsofar`` are accurate for ``x[0..i-1]`` maxendinghere = max(maxendinghere + x, 0) maxsofar = max(maxsofar, maxendinghere) return maxsofar
def ERR_NORECIPIENT(sender, receipient, message): """ Error Code 411 """ return "ERROR from <" + sender + ">: " + message
def get_plant_status(num): """"Return a number so that the appropriate image can be called""" if num < -0.5: return 1 elif num < 0: return 2 elif num < 0.5: return 3 elif num < 1: return 4
def is_punkt(token): """ Return if token consists of only punctuation and whitespace Args: token: single token Returns: Boolean Raises: None Examples: >>> is_punkt(" ") True >>> is_punkt(", ,") True >>> is_punkt("?!!") True >>> is_punkt("x") False """ #punkt = string.punctuation punkt = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' return all(letter in punkt or letter.isspace() for letter in token)
def l3_interface_group_id(ne_id): """ L3 Interface Group Id """ return 0x50000000 + (ne_id & 0x0fffffff)
def error_compatibility_score(h1_output_labels, h2_output_labels, expected_labels): """ The fraction of instances labeled incorrectly by h1 and h2 out of the total number of instances labeled incorrectly by h1. Args: h1_output_labels: A list of the labels outputted by the model h1. h2_output_labels: A list of the labels output by the model h2. expected_labels: A list of the corresponding ground truth target labels. Returns: If h1 has any errors, then we return the error compatibility score of h2 with respect to h1. If h1 has no errors then we return 0. """ h1_error_count = 0 h1h2_error_count = 0 for i in range(len(expected_labels)): h1_label = h1_output_labels[i] h2_label = h2_output_labels[i] expected_label = expected_labels[i] if h1_label != expected_label: h1_error_count = h1_error_count + 1 if h1_label != expected_label and h2_label != expected_label: h1h2_error_count = h1h2_error_count + 1 if h1_error_count > 0: return (h1h2_error_count / h1_error_count) return 0
def _get_inverted_node_graph(node_graph, node_to_ignore): """Get the graph {node_id: nodes that depend on this one} Also this graph does not contain the nodes to ignore """ inverted = dict() for node, dependencies in node_graph.items(): if node not in node_to_ignore: for dependency in dependencies: if dependency not in node_to_ignore: inverted.setdefault(dependency, list()) inverted[dependency].append(node) return inverted
def kmer_create(string,k): """ Disassemble to k-mer. """ return [string[i:k+i] for i in range(len(string)-k+1)]
def nt2aa(ntseq): """Translate a nucleotide sequence into an amino acid sequence. Parameters ---------- ntseq : str Nucleotide sequence composed of A, C, G, or T (uppercase or lowercase) Returns ------- aaseq : str Amino acid sequence Example -------- >>> nt2aa('TGTGCCTGGAGTGTAGCTCCGGACAGGGGTGGCTACACCTTC') 'CAWSVAPDRGGYTF' """ nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3, 'a': 0, 'c': 1, 'g': 2, 't': 3} aa_dict ='KQE*TPASRRG*ILVLNHDYTPASSRGCILVFKQE*TPASRRGWMLVLNHDYTPASSRGCILVF' return ''.join([aa_dict[nt2num[ntseq[i]] + 4*nt2num[ntseq[i+1]] + 16*nt2num[ntseq[i+2]]] for i in range(0, len(ntseq), 3) if i+2 < len(ntseq)])
def join(directory, path): """Compute the relative data path prefix from the data_path attribute. Args: directory: The relative directory to compute path from path: The path to append to the directory Returns: The relative data path prefix from the data_path attribute """ if not path: return directory if path[0] == "/": return path[1:] if directory == "/": return path return directory + "/" + path
def convert_pascal_bbox_to_coco(xmin, ymin, xmax, ymax): """ pascal: top-left-x, top-left-y, x-bottom-right, y-bottom-right coco: top-left-x, top-left-y, width and height """ return [xmin, ymin, xmax - xmin, ymax - ymin]
def exp(x, n): """Computes x raised to the power of n. >>> exp(2, 3) 8 >>> exp(3, 2) 9 """ if n == 0: return 1 else: return x * exp(x, n - 1)
def url(base_url: str, region: str) -> str: """Returns a regionalized URL based on the default and the given region.""" if region != "us": base_url = base_url.replace("https://", f"https://{region}-") return base_url
def square_pyramidal_numbers(n): """[Square Pyramidal Numbers - A000330](https://oeis.org/A000330) Arguments: n (Integer): Index of the sequence Returns: Integer: Value of this sequence at the specified index """ return n * (n + 1) * (2 * n + 1) / 6
def normal_dt(x, a, b): """ normal trend of transit time Parameters ---------- x : 1-d ndarray depth to convert """ return a - b * x
def _quote(text): """ Quote the given string so ``_split_quoted`` will not split it up. :param unicode text: The string to quote: :return: A unicode string representing ``text`` as protected from splitting. """ return ( '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"' )
def filter_regex(names, regex): """ Return a tuple of strings that match the regular expression pattern. """ return tuple(name for name in names if regex.search(name) is not None)
def _name(ref): """Return the username or email of a reference.""" return ref.get('username', ref.get('email'))
def mmgray(f): """Convert a binary image into a gray-scale image.""" return [255 if item == 1 else 0 for item in f]
def gf_add_ground(f, a, p, K): """ Compute ``f + a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``. **Examples** >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_add_ground >>> gf_add_ground([3, 2, 4], 2, 5, ZZ) [3, 2, 1] """ if not f: a = a % p else: a = (f[-1] + a) % p if len(f) > 1: return f[:-1] + [a] if not a: return [] else: return [a]
def str_join(*members): """join_memebers(member1, ...) takes an orbitrary number of arguments of type 'str'and concatinates them with using the '.' separator""" return ".".join(members)
def sort_allAPI(allAPI): """Design Note: A dictionary with the key:value pair id:name is needed for this to work because these are sorting commerceprices data from the API, and only returns the following: {'id': 79423, 'whitelisted': False, 'buys': {'quantity': 13684, 'unit_price': 114}, 'sells': {'quantity': 22649, 'unit_price': 119}} """ api_unid_prices = {85016:'Fine',84731:'Masterwork',83008:'Rare'} api_unrefined_prices = {19701:'Orichalcum Ore',19725:'Ancient Wood Log',19745:'Gossamer Scrap',19732:'Hardened Leather Section', 19700:'Mithril Ore',19722:'Elder Wood Log',19748:'Silk Scrap',19729:'Thick Leather Square', 19721:'Ectoplasm', 89140:'Lucent Mote', 89098:'Symbol of Control',89141:'Symbol of Enhancement',89182:'Symbol of Pain', 89103:'Charm of Brilliance',89258:'Charm of Potence',89216:'Charm of Skill'} api_refined_prices = {19685:'Orichalcum Ingot',19712:'Ancient Wood Plank',19746:'Bolt of Gossamer',19737:'Cured Hardened Leather Square', 19684:'Mithril Ingot',19709:'Elder Wood Plank',19747:'Bolt of Silk',19735:'Cured Thick Leather Square', 89271:'Pile of Lucent Crystal'} #Return dictionaries with 'item':[buy sell] key:value pairs unid_prices= {} unrefined_prices = {} refined_prices = {} for entryAPI in allAPI: if entryAPI['id'] in api_unid_prices:#special case because there's only 1 unid_prices[api_unid_prices[entryAPI['id']]] = [entryAPI['buys']['unit_price'], entryAPI['sells']['unit_price']] elif entryAPI['id'] in api_unrefined_prices: unrefined_prices[api_unrefined_prices[entryAPI['id']]] = [entryAPI['buys']['unit_price'], entryAPI['sells']['unit_price']] elif entryAPI['id'] in api_refined_prices: refined_prices[api_refined_prices[entryAPI['id']]] = [entryAPI['buys']['unit_price'], entryAPI['sells']['unit_price']] else: print("Unexpected API return") print(entryAPI) return unid_prices,unrefined_prices,refined_prices
def set_test_mode(user_id, prefix='', rconn=None): """Set this user with test mode. Return True on success, False on failure""" if user_id is None: return False if rconn is None: return False try: result = rconn.set(prefix+'test_mode', user_id, ex=3600, nx=True) # expires after one hour, can only be set if it does not exist except: return False if result: return True return False
def joinPath(modname, relativePath): """Adjust a module name by a '/'-separated, relative or absolute path""" module = modname.split('.') for p in relativePath.split('/'): if p=='..': module.pop() elif not p: module = [] elif p!='.': module.append(p) return '.'.join(module)
def sorted_committees(committees): """ sorts a list of committees, ensures that committees are sets """ return sorted([set(committee) for committee in committees], key=str)
def bc(temp): """ Calculate Bolometric Correction Using the Teff from the previous equation. This correction is for main sequence stars of the Teff range given above. """ return (-1.007203E1 + temp * 4.347330E-3 - temp**2 * 6.159563E-7 + temp**3 * 2.851201E-11)
def iscurried(f): """Return whether f is a curried function.""" return hasattr(f, "_is_curried_function")
def fibonacci(n): """Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, ... """ if n <= 1: return n a = 0 b = 1 c = 1 for i in range(2, n): a = b b = c c = a + b return c
def leaf_fanouts(conn_graph_facts): """ @summary: Fixture for getting the list of leaf fanout switches @param conn_graph_facts: Topology connectivity information @return: Return the list of leaf fanout switches """ leaf_fanouts = [] conn_facts = conn_graph_facts['device_conn'] """ for each interface of DUT """ for intf in conn_facts: peer_device = conn_facts[intf]['peerdevice'] if peer_device not in leaf_fanouts: leaf_fanouts.append(peer_device) return leaf_fanouts
def parse_orcid(text): """ parse OI field """ if not text or str(text) == 'nan': return [] state = 'NAME' # NAME | ORCID name = '' orcid = '' results = [] for c in text: if state == 'NAME': if c == '/': state = 'ORCID' continue elif name == '' and c in [' ', ';']: continue else: name += c elif state == 'ORCID': if len(orcid) == 19: results.append((name, orcid)) state = 'NAME' name = '' orcid = '' continue elif c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', 'X']: orcid += c else: state = 'NAME' name += c continue else: raise ValueError(state) if name and orcid: results.append((name, orcid)) return results
def child_is_flat(children, level=1): """ Check if all children in section is in same level. children - list of section children. level - integer, current level of depth. Returns True if all children in the same level, False otherwise. """ return all( len(child) <= level + 1 or child[(level + 1) :][0].isalpha() for child in children )
def hard_piecewise(x, f, g): """ This function harshly glues together f and g at the origin. @param x: independent variable @param f: dominant function when x < 0 @param g: dominant function when 0 < x """ #FIXME: the comparison does not currently vectorize, # not that I really expected it to, or necessarily hope that it will. # But maybe some kind of replacement can be invented? if x <= 0: return f(x) else: return g(x)
def get_smallest_best_parameters(group): """Sets defaults based on the smallest values of all known entries. The average might be better for performance but some parameters might not be supported on other devices.""" # Counts the number of devices in this group assert len(group) > 0 # Find the smallest values of the parameters min_parameters = {} for section in group: assert len(section["results"]) > 0 minimum_time = min([result["time"] for result in section["results"]]) for result in section["results"]: if result["time"] == minimum_time: for parameter in result["parameters"]: if parameter in min_parameters: min_parameters[parameter] = min(min_parameters[parameter], result["parameters"][parameter]) else: min_parameters[parameter] = result["parameters"][parameter] return min_parameters
def strip_word(string): """ This function strips the words of any surrounding spaces or quotation marks from an input string, but does not replace any single quotes inside words (e.g. "isn't") """ return string.strip().strip("'").strip('"')
def retag_from_strings(string_tag) : """ Returns only the final node tag """ valure = string_tag.rfind('+') if valure!= -1 : tag_recal =string_tag [valure+1:] else : tag_recal = string_tag return tag_recal
def reverse_byte(byte): """ Fast way to reverse a byte on 64-bit platforms. """ #return (byte * 0x0202020202L & 0x010884422010L) % 1023 return(byte * 0x0202020202 & 0x010884422010) % 1023
def extract_name(in_line: str) -> str: """ Extracts the name from the type construct. Information that is not needed will be removed such as the stereotype. """ types = {'package', 'class', 'abstract', 'interface', 'enum', 'abstract class', 'entity'} process_type: str = '' for item_type in types: if in_line.startswith(item_type): process_type = item_type break process_line = in_line.replace(' ', '') if '<<' in process_line: process_line = process_line.split('<<')[0] process_line = process_line.replace(process_type, '') found_name = process_line.split('{')[0] return found_name
def flip_mat_pat(snps): """Take a dictionary of SNPs and flip all mat and pat sites. Note: This changes the original dictionary and does not make a copy. """ for chr, poss in snps.items(): for pos, snp in poss.items(): mat = snp.mat pat = snp.pat snp.mat = pat snp.pat = mat return snps
def wrap_bits_left(binary, amount): """Move the characters of the binary string to the left. Bits will be wrapped. E.g. shift_bits('1011', 1) -> '0111'. """ return ''.join([binary[(place + amount) % len(binary)] for place in range(len(binary))])
def is_sorted(items): """Checks whether the list is sorted or not""" return all(items[i] <= items[i + 1] for i in range(len(items) - 1))
def newick_semicolon_check(tree_str): """ This function will check the last character of the tree in newick form and ensure that is ends in ";". """ if list(tree_str)[-1] != ";": tree_str += ';' return tree_str else: return tree_str
def rebound_starting_vals(bounds, starting_vals): """ Takes the user's starting guess for a resonator fit parameter and makes sure it's within the bounds for the fit If not, it adjusts the guess to be the closest in-bounds value Returns a new list of guess parameters, which should be the list actually supplied to the fitter """ new_starting_vals = [] for i in range(0, len(starting_vals)): if (starting_vals[i] > bounds[0][i]) and (starting_vals[i] < bounds[1][i]): new_starting_vals.append(starting_vals[i]) elif starting_vals[i] <= bounds[0][i]: new_starting_vals.append(bounds[0][i]) elif starting_vals[i] >= bounds[1][i]: new_starting_vals.append(bounds[1][i]) # new_starting_vals = np.array(new_starting_vals) return new_starting_vals
def force_list(value): """ Coerce the input value to a list. If `value` is `None`, return an empty list. If it is a single value, create a new list with that element on index 0. :param value: Input value to coerce. :return: Value as list. :rtype: list """ if value is None: return [] elif type(value) == list: return value else: return [value]
def _col_name(c): """Convert a zero-based index into an Excel column name.""" if c < 26: return chr(65+c) elif c < 26*27: return chr(64+c//26) + chr(65+c%26) else: raise Exception("Too many products")
def days_in_frequency_target(target: int) -> int: """ Returns number in a frequence period. e.g. in Mallard, frequence period may be 12, 6, 18, etc to represent the numbner of months between inspections - ideally. We are simply converting that to days. """ return int((target / 12) * 365)
def escape(term): """ escapes a term for use in ADQL """ return str(term).replace("'", "''")
def get_var_list(func): """ get variable names of func, exclude "self" if there is """ func_code = func.__code__ var_list = func_code.co_varnames[:func_code.co_argcount] var_list = [var for var in var_list if var != 'self'] return var_list
def extract_bounds(line): """ @@ -1,4 +1,4 @@ """ args = line.split("@@") line = args[1] a, b = line.strip().split(" ") sa, ea = a.split(",") sb, eb = b.split(",") bnds = (sa[1:], ea, sb, eb) a, b, c, d = [int(x) for x in bnds] print(line) return a, b, c, d # return (int(sa[1:]), int(ea)), (int(sb), int(eb))
def remove_white_space(txt_list): """ Remove unwanted white space and replaced them with single white space params: ------- txt_list list(): of str() that contains the text to clean :return: -------- txt_list list(): of str() transformed """ return [" ".join(txt.split()) for txt in txt_list]
def zstrip(chars): """Strip all data following the first zero in the string""" if '\0' in chars: return chars[:chars.index("\0")] return chars
def get_class_id(cls_names, classes): """ Get list of UIDs matching input class names :param cls_names: :param classes: :return: """ cls_uids = [] for cls_name in cls_names: lower_name = cls_name.lower() matches = [ uid for uid, info in classes.items() if lower_name == info['name'].lower() or lower_name in [a.lower() for a in info['aliases']] ] if matches: cls_uids.append(matches[0]) else: cls_uids.append(cls_name) return cls_uids
def sanitize_pg(pg_def): """ sanitize the processGroup section from parameterContext references, does a recursive cleanup of the processGroups if multiple levels are found. """ if "parameterContextName" in pg_def: pg_def.pop("parameterContextName") if "processGroups" not in pg_def or len(pg_def["processGroups"]) == 0: return pg_def for pg in pg_def["processGroups"]: sanitize_pg(pg)
def reflected_name(constant_name): """Returns the name to use for the matching constant name in blink code. Given an all-uppercase 'CONSTANT_NAME', returns a camel-case 'kConstantName'. """ # Check for SHOUTY_CASE constants if constant_name.upper() != constant_name: return constant_name return 'k' + ''.join(part.title() for part in constant_name.split('_'))
def _convert_schedule_to_task_rng(schedule): """Convert the schedule to dict{task: starting time range}""" task_start_rng = dict() for record in schedule: # parse schedule entry task = record[4] t_start = record[5] # process start time task_start_rng[task] = (t_start, t_start+1) return task_start_rng
def gcd(a, b): """Calculate the Greatest Common Divisor of (a, b). """ while b != 0: a, b = b, a % b return a
def bio_tags(off, entity_info): """ Creates list with BIO tags in a sentence. Parameters: ----------- xml_sent: sentence in xml format Returns: -------- list of BIO tags """ for (span, e_type) in entity_info : e_start, e_end = span[0], span[1] if off[0] == e_start and off[1] <= e_end: return "B-%s" % e_type elif off[0] >= e_start and off[1] <= e_end: return "I-%s" % e_type return "O"
def colorize(msg, color): """ Wrap a message in ANSI color codes. """ return '\033[1;{0}m{1}\033[1;m'.format(color, msg)
def reconstruct_text(text_list): """ We split the text into a list of words, reconstruct that text back from the list. """ return ''.join(text_list)
def merge_st(S1, S2): """Merge two sorted Python Lists S1 and S2 into properly sized list S""" i = j = 0 S = S1+S2 while i+j < len(S): if j == len(S2) or (i < len(S1) and S1[i] < S2[j]): S[i+j] = S1[i] i = i+1 else: S[i+j] = S2[j] j = j+1 return S
def get_index2word(word2idx): """ :param word2idx: dictionary of word to index :return: reverse order of input dictionary """ idx2word = dict([(idx, word) for word, idx in word2idx.items()]) return idx2word
def prune_satisfied_clauses(clauses, variables): """Remove any clause that is already satisfied (i.e. is True) from the given clause set. Parameters ---------- clauses: seq Sequence of clauses variables: dict variable name -> bool mapping Returns ------- clauses: seq or None Sequence of clauses that are not yet satisfied. If None, it means at least one clause could not be satisfied """ new_clauses = [] for clause in clauses: evaluated_or_none = variables.satisfies_or_none(clause) if evaluated_or_none is None: new_clauses.append(clause) elif evaluated_or_none is False: return None return new_clauses
def _get_document_type(abs_path: str) -> str: """ The data is downloaded such that the lowest subdirectory is the name of the document type. i.e.) In the path /hcs-na-v2/new-mat/bunge/han53-2005.shu, the document type is "bunge" """ return abs_path.split('/')[-2]
def parse_response(resp): """split the response up by commas""" response_list = resp[0].split(',') return response_list
def write_variant(number): """Convert an integer to a protobuf variant binary buffer.""" if number < 128: return bytes([number]) return bytes([(number & 0x7F) | 0x80]) + write_variant(number >> 7)
def sig_cmp(u, v, order): """ Compare two signatures by extending the term order to K[X]^n. u < v iff - the index of v is greater than the index of u or - the index of v is equal to the index of u and u[0] < v[0] w.r.t. order u > v otherwise """ if u[1] > v[1]: return -1 if u[1] == v[1]: #if u[0] == v[0]: # return 0 if order(u[0]) < order(v[0]): return -1 return 1
def word_list_to_long(val_list, big_endian=True): """Word list (16 bits int) to long list (32 bits int) By default word_list_to_long() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 16 bits int value :type val_list: list :param big_endian: True for big endian/False for little (optional) :type big_endian: bool :returns: list of 32 bits int value :rtype: list """ # allocate list for long int long_list = [None] * int(len(val_list) / 2) # fill registers list with register items for i, item in enumerate(long_list): if big_endian: long_list[i] = (val_list[i * 2] << 16) + val_list[(i * 2) + 1] else: long_list[i] = (val_list[(i * 2) + 1] << 16) + val_list[i * 2] # return long list return long_list
def response_plain_context_ga(output, attributes, continuesession): """ create a simple json plain text response """ return { "payload": { 'google': { "expectUserResponse": continuesession, "richResponse": { "items": [ { "simpleResponse": { "textToSpeech": output } } ] } } }, "outputContexts": attributes }
def ipv4_int(ipv4_str): """Returns an integer corresponding to the given ipV4 address.""" parts = ipv4_str.split('.') if len(parts) != 4: raise Exception('Incorrect IPv4 address format: %s' % ipv4_str) addr_int = 0 for part in parts: part_int = 0 try: part_int = int(part) except Exception: raise Exception('Incorrect IPv4 address format: %s' % ipv4_str) addr_int = addr_int * 256 + part_int return addr_int
def convert_box(x1, y1, width, height, img_width, img_height): """ Convert from x1, y1, representing the center of the box and its width and height to the top left and bottom right coordinates. :param x1: the x coordinate for the center of the bounding box :param y1: the y coordinate for the center of the bounding box :param width: with of the bounding box :param height: height of the bounding box :param img_width: the width of the image :param img_height: the height of the image :return: the top left and bottomg right coordinates (corner) of the bounding box. """ left = (x1 - width // 2) right = (x1 + width // 2) top = (y1 - height // 2) bot = (y1 + height // 2) if left < 0: left = 0 if right > img_width - 1: right = img_width - 1 if top < 0: top = 0; if bot > img_height - 1: bot = img_height - 1 return left, top, right, bot
def get_host(environ): """Return the real host for the given WSGI environment. This takes care of the `X-Forwarded-Host` header. :param environ: the WSGI environment to get the host of. """ scheme = environ.get('wsgi.url_scheme') if 'HTTP_X_FORWARDED_HOST' in environ: result = environ['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in environ: result = environ['HTTP_HOST'] else: result = environ['SERVER_NAME'] if (scheme, str(environ['SERVER_PORT'])) not \ in (('https', '443'), ('http', '80')): result += ':' + environ['SERVER_PORT'] if result.endswith(':80') and scheme == 'http': result = result[:-3] elif result.endswith(':443') and scheme == 'https': result = result[:-4] return result
def bool_to_private_text(private_bool): """ If is_name_private returns false, return 'public', if true return 'public' """ if private_bool: return "Private" return "Public"
def rayTracingResultsFileName( site, telescopeModelName, sourceDistance, zenithAngle, label ): """ Ray tracing results file name. Parameters ---------- site: str South or North. telescopeModelName: str LST-1, MST-FlashCam, ... sourceDistance: float Source distance (km). zenithAngle: float Zenith angle (deg). label: str Instance label. Returns ------- str File name. """ name = "ray-tracing-{}-{}-d{:.1f}-za{:.1f}".format( site, telescopeModelName, sourceDistance, zenithAngle ) name += "_{}".format(label) if label is not None else "" name += ".ecsv" return name
def writesLabelsToJsonFile(labels): """Convert labels dict to the form that's expected""" tmpLabels = dict(labels) for label in labels: tmpLabels[label] = list(labels[label]) return tmpLabels
def usage(): """Print Usage Statement. Print the usage statement for running slack.py standalone. Returns: msg (str): usage statement Example: >>> import slack >>> msg = stream.usage() >>> msg 'stream.py usage:\n$ python slack.py "<YOUR_SLACK_WEB_API_TOKEN>"' """ msg = "slack.py usage:\n" msg = msg + "$ python slack.py \"<YOUR_SLACK_WEB_API_TOKEN>\"" return msg
def get_neighbors(x2y, y2x): """Get all neighboring graph elements of the same type. Parameters ---------- x2y : list or dict Element type1 to element type2 crosswalk. y2x : list or dict Element type2 to element type1 crosswalk. Returns ------- x2x : dict Element type1 to element type1 crosswalk *OR* element type2 to element type2 crosswalk in the form: ``{x1: [x2,x3]}``. """ x2x = {} for k, vn in list(x2y.items()): x2x[k] = set() for v in vn: x2x[k].update(y2x[v]) x2x[k].discard(k) x2x = {k: sorted(list(v)) for k, v in x2x.items()} return x2x
def rgb_to_hex(rgb): """ Convert RGB tuple to hex. Parameters ---------- rgb : tuple[int] An RGB tuple. Returns ------- str A hex color string. """ return f"#{rgb[0]:x}{rgb[1]:x}{rgb[2]:x}".upper()
def str2float(value: str): """ Change a string into a floating point number, or a None """ if value == 'None': return None return float(value)
def m_shape(A): """ Determines the shape of matrix A. """ rows = len(A) columns = len(A[0]) if A else 0 return rows, columns
def lemma1(N, p): """return a value for prime p which is the sum of int(n/p^i) for all i where int(n/p^i) <= n""" v = 1 i = 1 tosum = [] _N = float(N) while v >= 1: v = int(_N / float(p ** i)) if v < 1: break tosum.append(v) i += 1 return sum(tosum)
def _isFloat(argstr): """ Returns True if and only if the given string represents a float. """ try: float(argstr) return True except ValueError: return False
def lr1(step: int, base_lr: float) -> float: """Medium aggression lr scheduler.""" lr = base_lr _lr = lr * 0.975 ** (step // 20) return max(_lr, lr * 1e-3)
def listOfGetCommands(glist): """ Returns a list of vclient command line options, readily compiled for the readVclientData method. """ clist = [] clist.append('-c') clist.append(','.join(glist)) return clist