content
stringlengths
42
6.51k
def get_key(url): """ Given a URL path convert it to an S3 Key by replacing some parts of the path with empty strings """ return url.replace("/v0/submission/", "").replace("/files", "")
def remove_last_line_from_string(data): """ Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) Common function to remove the last line of the string :param data: :return: """ return data[:data.rfind('\n')]
def getResults(workers): """ Converts a list of finished workers into a result. :param workers: Finished workers. :return: Results """ results = [] for worker in workers: results += worker.getResults() return results
def unique_number_from_list(input_list): """ Produce a list of integers corresponding to the number of times an element in the input list has been observed. Parameters ---------- input_list : list list of values Returns ------- occurrence : list integer list Ex...
def PrintBox(loc, height, width, style='r-'): """A utility function to help visualizing boxes.""" xmin, ymin, xmax, ymax = loc[0] * width, loc[1] * height, loc[2] * width, loc[3] * height #pyplot.plot([xmin, xmax, xmax, xmin, xmin], [ymin, ymin, ymax, ymax, ymin], style) return [xmin, ymin, xmax, ymax]
def _split_comma_separated(string): """Return a set of strings.""" return set(filter(None, string.split(',')))
def trimVersionString(version_string): ### from munkilib.updatecheck """Trims all lone trailing zeros in the version string after major/minor. Examples: 10.0.0.0 -> 10.0 10.0.0.1 -> 10.0.0.1 10.0.0-abc1 -> 10.0.0-abc1 10.0.0-abc1.0 -> 10.0.0-abc1 """ if version_string == Non...
def processLine(sym_line): """Reverses symbols in line""" new_line = list(reversed(sym_line)) return new_line
def underscore_to_camelcase(value): """ Converts underscore notation (something_named_this) to camelcase notation (somethingNamedThis) >>> underscore_to_camelcase('country_code') 'countryCode' >>> underscore_to_camelcase('country') 'country' >>> underscore_to_camelcase('price_GBP') 'pri...
def corrfac(z, params): """ Correlation coefficient between galaxy distribution and velocity field, r(z). """ r_g = params['r_g'] #0.98 return r_g + 0.*z
def _to_w2v_indexes(sentence, w2v_vocab): """ Return which tokens in a sentence cannot be found inside the given embedding :param sentence: current sentence (tokenized) :param w2v_vocab: embedding matrix :return: a list of the tokens which were not found """ total_missing = [] for wo...
def get_column_positions(column_headings, feature_list): """ Return a list of the corresponding position within column_headings of each feature in feature_list. This can be used to get the position of lists of features for use in pipelines and transformers where one cannot rely on the input being a pand...
def first_not_null(*args): """ get list obj first not-null object >>> first_not_null(None, 'a', 'b') return 'a' """ if args is not None: for arg in args: if arg is not None: return arg return None
def is_under_remote(ref, remote): """Return True if a Git reference is from a particular remote, else False. Note that behavior is undefined if the ref is not fully qualified, i.e. does not begin with 'refs/'. Usage example: >>> is_under_remote("refs/remotes/origin/mywork", "origin") T...
def normalize_rgb(rgb): """ Normalize rgb to 0~1 range :param rgb: the rgb values to be normalized, could be a tuple or list of tuples :return: """ if isinstance(rgb, tuple): return tuple([float(a)/255 for a in rgb]) elif isinstance(rgb, list): norm_rgb = [] for item ...
def sentence2id(sent, word2id): """ :param sent: :param word2id: :return: """ sentence_id = [] for word in sent: if word.isdigit(): word = '<NUM>' if word not in word2id: word = '<UNK>' sentence_id.append(word2id[word]) return sentence_id
def pluck(input_dictionary): """Destructures a dictionary (vaguely like ES6 for JS) Results are SORTED by key alphabetically! You must sort your receiving vars """ items = sorted(input_dictionary.items()) return [item[1] for item in items]
def get_readme(readme_file_location="./README.md"): """ Purpose: Return the README details from the README.md for documentation Args: readme_file_location (String): Project README file Return: requirement_files (List of Strings): Requirement Files """ readme_data = "Desc...
def strip_ws(puzzle_string): """Remove newline and space characters from a string.""" return puzzle_string.replace('\n', '').replace(' ','')
def get_filenames(fileNameA): """ Custom function for this specific dataset. It returns the names of corresponding files in the 2 classes along with the common name by which it should be saved. Args: fileNameA(str) : Filename in the first class Created By Leander Maben """ return fileNa...
def sparsifyApprox(probs, err_thresh): """ Sparsify a probability vector. """ # FIXME # sorted_indices = None return probs
def us_territories(): """USA postal abbreviations for territories, protectorates, and military. The return value is a list of ``(abbreviation, name)`` tuples. The locations are sorted by name. """ # From http://www.usps.com/ncsc/lookups/abbreviations.html # Updated 2008-05-01 return [ ...
def binary_search_recursive(array, left, right, key): """ Funkce rekurzivne ve vzestupne usporadanem poli 'array' vyhleda klic 'key'. Hleda se pouze v rozsahu od indexu 'left' do indexu 'right'. Funkce vraci index nalezeneho prvku, pokud prvek v posloupnosti neni, vraci -1. """ if left == ri...
def _host_is_same(host1: str, host2: str) -> bool: """Check if host1 and host2 are the same.""" return host1.split(":")[0] == host2.split(":")[0]
def decode_read_data(read: list, encoding='utf-8'): """ Interprets bytes under the specified encoding, to produce a decoded string. """ decoded = "" try: decoded = bytes(read).decode(encoding).rstrip('\0') except UnicodeDecodeError: return decoded return decoded
def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> fahrenheit_to_kel...
def git_unicode_unescape(s: str, encoding: str = "utf-8") -> str: """Undoes git/gitpython unicode encoding.""" if s is None: return "" if s.startswith('"'): return s.strip('"').encode("latin1").decode("unicode-escape").encode("latin1").decode(encoding) return s
def purge_key_deep(a_dict, key): """Removes given key from all nested levels of a_dict """ try: a_dict.pop(key) except KeyError: pass for k in a_dict.keys(): if isinstance(a_dict[k], dict): a_dict[k] = purge_key_deep(a_dict[k], key) return a_dict
def get_download_url_from_commit(package, commit): """ Return the download URL for this commit @package - :user/:repo combination @commit - commit hash """ return "https://codeload.github.com/%s/legacy.tar.gz/%s" % (package, commit)
def dicts_are_essentially_equal(a, b): """Make sure that a is a subset of b, where None entries of a are ignored.""" for k, v in a.items(): if v is None: continue if b.get(k) != v: return False return True
def frozendict (d): """Convert a dictionary to a canonical and immutable form.""" return frozenset(d.items())
def seconds(data, freq): """ Returns number of seconds from track data based on frequency :param track: wav audio data :param freq: frequency of audio data :return: number of seconds """ return len(data)/freq
def appn(s1, s2): """Append two strings, adding a space between them if either is nonempty. Args: s1 (str): The first string s2 (str): The second string Returns: str: The two strings concatenated and separated by a space. """ if not s1: return s2 elif not s2: return s1 else: return s1 ...
def is_match(str_a, str_b): """Finds if `str_a` matches `str_b` Keyword arguments: str_a -- string str_b -- string """ len_a, len_b = len(str_a) + 1, len(str_b) + 1 matches = [[False] * len_b for _ in range(len_a)] # Match empty string with empty pattern matches[0][0] = True ...
def split_required_col(req): """ >>> split_required_col('col_a') ('col_a', None) >>> split_required_col('col_B,integer') ('col_b', 'integer') >>> split_required_col('col_c,some(parametric,type)') ('col_c', 'some(parametric,type)') """ split = req.lower().split(',', 1) # no type...
def getEndIndex(string): """Returns the index of the space after the value before its units >>> string = ' R2 = 1 173 Ohm\\n' >>> getEndIndex(string) 13 """ lastIndex = len(string) - 1 while string[lastIndex] != ' ': lastIndex -= 1 return lastIndex
def buildIndirectMapping(a, b): """Given a maps x->y, b maps y->z, return map of x->z.""" assert(len(a) == len(b)) assert(isinstance(list(b.keys())[0], type(list(a.values())[0]))) c = dict() for x in a.keys(): y = a[x] z = b[y] c[x] = z return c
def find_empty(board): """ Finds an empty cell and returns its position as a tuple :param board: the board to search """ for i in range(9): for j in range(9): if board[i][j] == 0: return i, j
def mulND(v1, v2): """Returns product of two nD vectors (same as itemwise multiplication)""" return [vv1 * vv2 for vv1, vv2 in zip(v1, v2)]
def matrix2bytes(matrix): """ Converts a 4x4 matrix to bytes """ return bytes(sum(matrix, []))
def compute_capacity(n_seats, aw2_capacity, target_density): """ Compute RS capacity for target density """ return (aw2_capacity - n_seats) * target_density / 4 + n_seats
def _convert_key_and_value(key, value): """Helper function to convert the provided key and value pair (from a dictionary) to a string. Args: key (str): The key in the dictionary. value: The value for this key. Returns: str: The provided key value pair as a string. """ upda...
def input_2_word(word_in): """ This function takes a string from the input file ''word_in'', and returns an array of that ''word'' in a format which is more useable by the rest of the code. The input file is a .txt file written in the following way: 1,13,18,25,... 5,11,12,19,... ....
def get_matched_primer_pair(le,ri): """ Inputs: two lists of primers get matching primers from a list (get primer pair from same amplicon) Returns: matched primer pair (same amplicon) if any """ for l in le: for r in ri: if l[2] == r[2]: ...
def get_location(http_info): """Extract the redirect URL from a pysaml2 http_info object""" assert 'headers' in http_info headers = http_info['headers'] assert len(headers) == 1 header_name, header_value = headers[0] assert header_name == 'Location' return header_value
def get_brief_classification(crslt): """ crslt: dictionary of classification results """ return {cat: cla[0] for cat, cla in crslt.items()}
def remove_nipsa_action(index, annotation): """Return an Elasticsearch action to remove NIPSA from the annotation.""" source = annotation["_source"].copy() source.pop("nipsa", None) return { "_op_type": "index", "_index": index, "_type": "annotation", "_id": annotation["_...
def get_sentence(line: str, column_number: int) -> str: """ Parse the Tab Separated Line to return the sentence coloumn. """ sentence_list = line.split('\t') # Tab separation sentence_column = sentence_list[1] # Second Column sentence = sentence_column[:-1] # Remove newline return se...
def _get_complete_session_attribute_name(session_attribute_name, namespace_name = None): """ Retrieves the complete session attribute name from the session attribute name and the namespace name. :type session_attribute_name: String :param session_attribute_name: The session attribute name. ...
def is_triangular(num): """ Determine if a number is of the form (1/2)n(n+1). """ from math import floor, sqrt assert isinstance(num, int) and num > 0 near_sqrt = floor(sqrt(2 * num)) return bool(int((1 / 2) * near_sqrt * (near_sqrt + 1)) == num)
def add_css_to_html(html: str, css: str) -> str: """Sticks the css into a <style> tag.""" return f'''<style>{css}</style>{html}'''
def is_started_with(src, find, ignore_case=True): """Verifies if a string content starts with a specific string or not. This is identical to ``str.startswith``, except that it includes the ``ignore_case`` parameter. Parameters ---------- src : str Current line content. find : str ...
def is_magic(name: str) -> bool: """ Checks whether the given ``name`` is magic. >>> is_magic('__init__') True >>> is_magic('some') False >>> is_magic('cli') False >>> is_magic('__version__') True >>> is_magic('__main__') True """ return name.startswith('__'...
def verify_authorization(perm, action): """Check if authorized or not. """ if perm == 'all': return True if perm == 'read': return action not in { 'token', 'lock', 'unlock', 'mkdir', 'mkzip', 'save', 'delete', 'move', 'copy', 'backup', 'unbackup', 'ca...
def _split_digits(number, sign_literal): """ Split given number per literal and sign :param number: :type number: int | str :param base: :type base: int :param sign_literal: :type sign_literal: str :return: sign, digits :rtype: int, list """ digits = list(str(number))...
def _parse_detector(detector): """ Check and fix detector name strings. Parameters ---------- detector : `str` The detector name to check. """ oklist = ['n0', 'n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9', 'n10', 'n11'] altlist = [str(i) for i in range(12)] ...
def embedding_name(model_key): """ 'src_embed.query_emb.language.lut.weight', 'src_embed.query_emb.main.lut.weight', 'trg_embed.lut.weight'""" if "embed" in model_key and model_key.endswith("lut.weight"): name_parts = model_key.split('.') if name_parts[0] == "enc_embeds": ...
def merge_list_of_dicts(list_of_dicts): """ Merge list of dicts into one dict. Paramters --------- list_of_dicts : STRING list of dicts to be merged. Returns ------- merged_dict : STRING """ merged_dict = {k: v for d in list_of_dicts for k, v in d.items()} return me...
def yesno(obj: object) -> str: """ Convert an object into 'Yes' or 'No'. """ return "Yes" if obj else "No"
def TransformExtract(r, *keys): """Extract an ordered list of values from the resource for the specified keys. Args: r: A JSON-serializable object. *keys: The list of keys in the resource whose associated values will be included in the result. Returns: The list of extracted values. """ t...
def get_entangler_map(map_type, num_qubits, offset=0): """Utility method to get an entangler map among qubits. Args: map_type (str): 'full' entangles each qubit with all the subsequent ones 'linear' entangles each qubit with the next 'sca' (shifted circul...
def number_checker(input): """Finds type of input (in, float, other). Args: input : a string of alphanumeric characters Returns: input : the string converted to an int, float or error message depending on contents of string. """ # handling an integer if input.isnumeri...
def last_patient_wait_time(total_patients: int, time_duration: int) -> int: """Calculate the wait time for the last patient. Return wait time in minutes. """ # Find the max wait time for all patients ahead of the last patient. total_max_wait = ((total_patients - 1) * time_duration) # Find the t...
def process_pane_capture_lines(data, nlines=None): """Given the string blob of data from `tmux capture-pane`, returns an array of line strings. Arguments: data -- String blob of data from `tmux capture-pane` nlines -- Maximum number of lines to return Returns: An array of line strings. Each line string corr...
def reduce_reflex_angle_deg(angle: float) -> float: """ Given an angle in degrees, normalises in [-179, 180] """ # ATTRIBUTION: solution from James Polk on SO, # https://stackoverflow.com/questions/2320986/easy-way-to-keeping-angles-between-179-and-180-degrees# new_angle = angle % 360 if new_angle >...
def module_to_xapi_vm_power_state(power_state): """Maps module VM power states to XAPI VM power states.""" vm_power_state_map = { "poweredon": "running", "poweredoff": "halted", "restarted": "running", "suspended": "suspended", "shutdownguest": "halted", "rebootgu...
def distribute_atoms(atoms, n): """ split a 1D list atoms into n nearly-even-sized chunks. """ k, m = divmod(len(atoms), n) return [atoms[i*k+min(i,m) : (i+1)*k+min(i+1,m)] for i in range(n)]
def m_to_mile(value): """Converts distance in meters to miles Args: value: floating point representing the distance in meters Returns: distance in miles """ if value is None: return None return value / 1609
def get_binary(number): """ Return the binary string of number (>=0) without 0b prefix. For e.g 5 returns "101", 20 returns "10100" etc. """ return bin(number)[2:]
def get_entities_bio(seq): """Gets entities from sequence. note: BIO Args: seq (list): sequence of labels. Returns: list: list of (chunk_type, chunk_start, chunk_end). Example: seq = ['B-PER', 'I-PER', 'O', 'B-LOC', 'I-PER'] get_entity_bio(seq) #output ...
def find_symmetric_difference(list1, list2): """ show difference :param list1: :type list1: :param list2: :type list2: :return: :rtype: """ difference = set(list1).symmetric_difference(set(list2)) list_difference = list(difference) return list_difference
def getFibonacciIterative(n: int) -> int: """ Calculate the fibonacci number at position n iteratively """ a = 0 b = 1 for i in range(n): a, b = b, a + b return a
def transform(string): """ Capitalizes string, deletes all whitespaces and counts the len of the product. """ string = string.upper() string = string.replace(" ", "") length = len(string) return (string, length)
def splitpasswd(user): """splitpasswd('user:passwd') -> 'user', 'passwd'.""" user, delim, passwd = user.partition(':') return user, (passwd if delim else None)
def make_status_readable(status): """ Returns a readable status """ if not status: return "None" return '%.2f%% (d: %.1f kb/s up: %.1f kB/s p: %d)\r' % ( status.progress * 100, status.download_rate / 1000, status.upload_rate / 1000, status.num_peers )
def map_ips_from_nodes(all_nodes): """Creates a mapping of IP address to Node ID and IP Alias. {'1.1.1.1': {'node_id': 12, 'alias': '2.2.2.2'}, '1.2.3.4': {'node_id': 3, 'alias': None}} """ filtered_node_ips = {} for node in all_nodes: node_ips = {} for alloc in node['relation...
def average_timeseries(timeseries): """ Give the timeseries with avg value for given timeseries containing several values per one timestamp :param timeseries: :return: """ avg_timeseries = [] for i in range(len(timeseries)): if len(timeseries[i])>1: count = len(timeserie...
def json_str_formatter(str_dict): """Formatting for json.loads Args: str_dict (str): str containing dict of spead streams (received on ?configure). Returns: str_dict (str): str containing dict of spead streams, formatted for use with json.loads """ # Is there a better way of doing ...
def do_import(name): """Helper function to import a module given it's full path and return the module object. """ mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod
def get_config_option(config, option, required=True): """ Get an option (value of key) from provided config dictionary. If the key does not exist, exit with KeyError (required=True) or return None (required=False). """ try: value = config[option] return value except KeyError:...
def as_gb(in_size: int) -> int: """ Converter functions to convert the size in bytes to gigabytes. """ conv = 1024 * 1024 * 1024 return in_size // conv
def activityToType(jobActivity): """ Function to map a workflow activity to a generic CMS job type. :param jobActivity: a workflow activity string :return: string which it maps to NOTE: this map is based on the Lexicon.activity list """ activityMap = {"reprocessing": "production", ...
def make_tag_dict(tag_list): """Returns a dictionary of existing tags. Args: tag_list (list): a list of tag dicts. Returns: dict: A dictionary where tag names are keys and tag values are values. """ return {i["Key"]: i["Value"] for i in tag_list}
def GC_skew(seq, window=100): """Calculates GC skew (G-C)/(G+C) for multiple windows along the sequence. Returns a list of ratios (floats), controlled by the length of the sequence and the size of the window. Does NOT look at any ambiguous nucleotides. """ # 8/19/03: Iddo: added lowercase ...
def _jupyter_labextension_paths(): """Called by Jupyter Lab Server to detect if it is a valid labextension and to install the widget. Returns: src: Source directory name to copy files from. Webpack outputs generated files into this directory and Jupyter Lab copies from this directory ...
def stringify_groups(groups): """Change a list of Group (or skills) objects into a space-delimited string. """ return u','.join([group.name for group in groups])
def maximumAbove(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by a constant n. Draws only the metrics with a maximum value above n. Example: .. code-block:: none &target=maximumAbove(system.interface.eth*.packetsSent,1000) This would only display interfaces ...
def parse_int(text: str) -> int: """ Takes in a number in string form and returns that string in integer form and handles zeroes represented as dashes """ text = text.strip() if text == '-': return 0 else: return int(text.replace(',', ''))
def _split_escape_string(input, keep_escape = True, splitchar = ',', escapechar = '\\'): """ Splits a string but allows escape characters """ results = [] string = "" escaped = False for c in input: if not escaped and c == escapechar: escaped = True if keep_escape:...
def get_server_port(meta, server, val=None): """ Gets the server port value from configuration. """ val = server.getConf('port') if val is None else val if '' == val: val = meta.getDefaultConf().get('port', 0) val = int(val) + server.id() - 1 return int(val)
def url_encode(string: str): """Take a raw input string and URL encode it.""" replacements = {"!": "%21", "#": "%23", "$": "%24", "&": "%26", "'": "%27", "(": "%28", ")": "%29", "*": "%2A", "+": "%2B", ",": "%2C", "/": "%2F", ":": "%3A", ";": "%3B", "=": "%3D", "?": "%3F"...
def hex_to_dec(val): """Converts hexademical string to integer""" return int(val, 16)
def valid_lecture(lecture_number, lecture_start, lecture_end): """Testing if the given lecture number is valid and exist.""" if lecture_start and lecture_end: return lecture_start <= lecture_number <= lecture_end elif lecture_start: return lecture_start <= lecture_number else: re...
def fetch_parts(summary): """Picks out elements of the document summary from Entrez""" AssemblyAccession = summary["AssemblyAccession"] AssemblyStatus = summary["AssemblyStatus"] WGS = summary["WGS"] Coverage = summary["Coverage"] SubmissionDate = summary["SubmissionDate"] LastUpdateDate = s...
def _is_user_option_true(value): """ Convert multiple user inputs to True, False or None """ value = str(value) if value.lower() == 'true' or value.lower() == 't' or value.lower() == 'yes' or value.lower() == 'y' or value.lower() == '1': return True if value.lower() == 'false' or value.lower() =...
def _reset_nuisance(x, like, cache): """Internal function which sets the values of the nuisance parameters to those found in a previous iteration of the optimizer. Not intended for use outside of this package.""" sync_name = "" icache = 0 if x in cache: params = cache[x] for ipar...
def matchKeys(keyA, keyB): """Return the tuple (keyA, keyB) after removing bits where Bob's measured photon was absorbed. Assumes a value of -1 in keyB represents an absorbed photon. """ match = [False if k == -1 else True for k in keyB] keyB = [keyB[k] for k in range(len(keyB)) if match[k]] ...
def find_url(list_of_links): """ There are many apis which get same work done. The idea here is to show the best one. Here is the logic for picking the best one. * if there is only one element in the list, the choice is obvious. * if there are more than one: return for a link which does ...
def lc(value): """Lower case and remove any periods to normalize for comparison.""" if not value: return '' return value.lower().strip('.')
def mod_pow(base, power, mod): """ Solve x = a^b % c :param base: a :param power: b :param mod: c :return: x """ if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> ...