content
stringlengths
42
6.51k
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: O(n) Space Complexity: O(1) """ if not nums: return 0 max_ = 0 end = nums[0] for num in nums: max_ = ma...
def quoted(text): """Quoted text, with single or double-quotes""" if text: if "\n" in text: return '"""%s"""' % text if '"' in text: return "'%s'" % text return '"%s"' % text
def merge_dicts(dicts_list): """Merge a list of dicts.""" ret = {} for d in dicts_list: ret.update(d) return ret
def xor(*args) -> bool: """True if exactly one of the arguments of the iterable is True. >>> xor(0,1,0,) True >>> xor(1,2,3,) False >>> xor(False, False, False) False >>> xor("kalimera", "kalinuxta") False >>> xor("", "a", "") True >>> xor("", "", "") False """ ...
def cd_to_uHz(freq_cd): """Transforms the input frequency from cycles per day to microHerz.""" freq_uHz = freq_cd * 11.574074 # [microHz] return freq_uHz
def display_string(w_len, target_line): """ Display the line base on the max length of window length :param w_len: length of window :param target_line: the target display string :type w_len: int :type target_line: str :return: The final displaying string :rtype: str """ return t...
def pow(X, varX, n): """X**n with error propagation""" # Direct algorithm # Z = X**n # varZ = n*n * varX/X**2 * Z**2 # Indirect algorithm to minimize intermediates Z = X**n varZ = varX/X varZ /= X varZ *= Z varZ *= Z varZ *= n**2 return Z, varZ
def button_string(channel, output, data): """Returns the string representation of a Single Output Mode button.""" return 'CH{:s}_{:s}_{:s}'.format(channel, output, data)
def get_prof_json(prof): """This method returns the JSON of the professor object""" prof_json = { 'userid': prof[0], 'username': prof[1], 'age': int(prof[2]), 'gender': prof[3], 'userscore': prof[4], 'joblocation': prof[5], 'zipcode': prof[6], 'ty...
def keygen(*path, meta=None): """Creates a database key. Key schema is ``path:to:item[.metafield]``. """ keypath = ":".join(map(str, path)) key = ".".join(map(str, filter(None, [keypath, meta]))) return key
def fine_trigger(truth): """ :param truth: :return: """ return truth["TRIGGER_TYPE"]+'_'+str(truth["TRIGGER_TYPE_OPTION"])
def skip_run_cmd(cmd, sin="", shell=True, wait=False, log_error=True, stop_running_if=None, encerror="ignore", encoding="utf8", change_path=None, communicate=True, preprocess=True, timeout=None, catch_exit=False, fLOG=None, timeout_listen=None, tell_if...
def crop_box_center(current_size, target_size): """ Returns box coordinates (x1, y1, x2, y2) to crop image to target size from center. """ cur_w, cur_h = current_size trg_w, trg_h = target_size if trg_w < cur_w: x1 = int((cur_w - trg_w) / 2) x2 = cur_w - x1 else: ...
def get_fl_from_id(members): """Get number of FLNC reads from read ids.""" assert isinstance(members, list) # ex: 13cycle_1Mag1Diff|i0HQ_SIRV_1d1m|c139597/f1p0/178 try: return sum(int(_id.split('/')[1].split('p')[0][1:]) for _id in members) except (IndexError, ValueError): raise Valu...
def get_root_name(nodes): """ Find the root of the hierarchy. :param nodes: Dictionary with skeleton hierarchy. :type nodes: dict :return: Name of root joint. :rtype: str """ for joint, properties in nodes.items(): if not properties['parent']: return joint return...
def get_normalized_intensity(peak_intensity, normalization_factor): """ Normalize using highest theoretical envelope intensity""" normalized_intens = peak_intensity/normalization_factor return normalized_intens
def save_params(net, best_metric, current_metric, epoch, save_interval, prefix): """Logic for if/when to save/checkpoint model parameters""" if current_metric < best_metric: best_metric = current_metric net.save_parameters('{:s}_best.params'.format(prefix, epoch, current_metric)) with op...
def explode_array(list_str, separator = ","): """ Explode list string into array """ if not list_str: return [] return [item.strip() for item in list_str.split(separator) if item.strip() != '']
def _calc_crop(s1, s2): """Calc the cropping from the padding.""" a1 = abs(s1) if s1 < 0 else None a2 = s2 if s2 < 0 else None return slice(a1, a2, None)
def score75(total, correct, wrong): """ >>> score75(20, 20, 0) 100.0 >>> score75(20, 15, 0) 100.0 >>> score75(20, 15, 5) 100.0 >>> score75(20, 10, 5) 83.33333333333334 >>> score75(20, 0, 20) 50.0 """ return ( min(max(total * 0.75 - correct, 0), wrong) + ...
def parse_partner_string(s): """Return a dict of partner labels to percentages summing to one.""" L = [x.strip().split(" ") for x in s.split(",")] # Numberless spec indicates equal weighting. if all(len(x) <= 1 for x in L): return {t[0]: 100 / len(L) for t in L} # There should be no more t...
def rc_dna(seq): """ Reverse complement the DNA sequence >>> assert rc_seq("TATCG") == "CGATA" >>> assert rc_seq("tatcg") == "cgata" """ rc_hash = { "A": "T", "T": "A", "C": "G", "G": "C", "a": "t", "t": "a", "c": "g", "g": "c", ...
def change_parameter_unit(parameter_dict, multiplier): """ used to adapt the parameters according their unit - for example, could be used for models that are running in time steps that are different from the time step assumed by the input parameter :param parameter_dict: dict dictionary who...
def song_playlist(songs, max_size): """ songs: list of tuples, ('song_name', song_len, song_size) max_size: float, maximum size of total songs that you can fit Start with the song first in the 'songs' list, then pick the next song to be the one with the lowest file size not already picked, repeat ...
def release_vcf_path(data_type: str, version: str, contig: str) -> str: """ Publically released VCF. Provide specific contig, i.e. "20", to retrieve contig specific VCF. :param data_type: One of "exomes" or "genomes" :param version: One of the release versions of gnomAD on GRCh37 :param contig: Sin...
def build_encrypt_wiring(dec_wiring): """This function builds a reciprocal encrypt wiring table from the supplied decrypt wiring table. """ enc_wiring = [] for level in dec_wiring: enc_wiring.append( [level.index(n) for n in range(len(level))]) return enc_wiring
def has_admin_access(user): """Check if a user has admin access.""" return user == 'admin'
def remove_prefix_0x(s): """remove prefix '0x' or '0X' from string s :param s: str :return: str, the substring which remove the prefix '0x' or '0X' """ if s[:2].lower() == '0x': s = s[2:] return s
def NormalizeGoogleStorageUri(uri): """Converts gs:// to http:// if uri begins with gs:// else returns uri.""" if uri and uri.startswith('gs://'): return 'http://storage.googleapis.com/' + uri[len('gs://'):] else: return uri
def mergesort(lyst): """This is a merge sort """ if len(lyst) > 1: mid = len(lyst) // 2 left_lyst = lyst[:mid] right_lyst = lyst[mid:] mergesort(left_lyst) mergesort(right_lyst) left_ind = 0 right_ind = 0 new_ind = 0 while left_ind <...
def func_a(arg1): """ Args: arg1 (int): description of arg1. Returns: bool: description of return val. """ print(arg1) return True
def invalid_direction(direction): """Validate the `direction` parameter.""" valid_directions = ["forwards", "backwards"] if direction not in valid_directions: return f"`direction` must be one of [{', '.join(valid_directions)}]" return False
def is_unique_letters(word): """ Return whether the word has only unique letters. """ if len(word) == 1: return True first = word[0] for pos in range(1, len(word)): if first == word[pos]: return False return is_unique_letters(word[1:])
def regularize_truncation(truncation): """ regularize_truncation( (code, cutoff) ) -> (N1b,N2b) Converts a mnemonic description ("ob",N1b) or ("tb",N2b) to the appropriate (N1b,N2b) pair for a two-body interaction file. """ (code, N) = truncation if (code == "ob"): return (N,2*N) e...
def index_get(array, *argv): """ checks if a index is available in the array and returns it :param array: the data array :param argv: index integers :return: None if not available or the return value """ try: for index in argv: array = array[index] return array...
def ByNestedComprehnsionAlogrithm(*sets): """Returns a list of all element combinations from the given sets. A combination is represented as a tuple, with the first tuple element coming from the first set, the second tuple element coming from the second set and so on. A set may be any iterabl...
def levenshtein(s1, s2, D=2, i1=0, i2=0): """ Returns True iff the edit distance between the two strings s1 and s2 is lesser or equal to D """ def aux(i1, i2, D): if i1 == len(s1): return len(s2) - i2 <= D if D > 0: if aux(i1 + 1, i2, D - 1): ...
def move_elevator(elevator, direction): """Move elevator according to direction.""" directions = {'up': 1, 'down': -1} return elevator + directions[direction]
def hour_min_sec(secs: int, hms=False): """Convert seconds into a more readable hh:mm:ss representation :secs Number of seconds :hms Hours:Minutes:Seconds representation, rather than the default seconds.""" if secs is not None: m, s = divmod(secs, 60) m = int(m) s = int(s) ...
def flatten(seq: list): """ this is the implementation of function flatten without recursion. """ head = [] store = [] tmp = seq idx = [0] while True: if len(tmp) >= idx[-1]+1: item = tmp[idx[-1]] else: if head and tmp: tmp = he...
def _f1_bigger(best_eval_result, current_eval_result): """Compares two evaluation results and returns true if the 2nd one is smaller. Both evaluation results should have the values for MetricKeys.LOSS, which are used for comparison. Args: best_eval_result: best eval metrics. current_eval_r...
def index_tuples_linear(factor, factors, period): """Index tuples for linear transition function.""" ind_tups = [("transition", period, factor, rhs_fac) for rhs_fac in factors] return ind_tups + [("transition", period, factor, "constant")]
def pow2_ru(n): """Given an integer >= 1, return the next power of 2 >= to n.""" assert n <= 2 ** 31 n -= 1 n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 n += 1 return n
def _pick_final_batch_size(data_size: int, batch_size: int, num_batch_size_buckets: int) -> int: """Picks the final batch size for a given dataset size.""" # Determine the batch size for the final batch. final_batch_size = data_size % batch_size if final_batch_size == 0: # No padd...
def flag_to_strand(flag): """ Takes integer flag as argument. Returns strand ('+' or '-') from flag. """ if flag & 16: return "-" return "+"
def json_get(item, path, default=None): """ Return the path of the field in a dict. Arguments: item (dict): The object where we want to put a field. path (str): The path separated with dots to the field. default: default value if path not found. Return: The value. """...
def set_indent(s: str, indent: int, newline: bool) -> str: """set the indent of each line in `s` `indent`""" lines = s.splitlines(False) new_lines = [] for line in lines: line = ' '*indent + line new_lines.append(line) return '\n'.join(new_lines)+('\n' if newline else '')
def get_params_for_component(params, component): """ Returns a dictionary of all params for one component defined in params in the form component__param: value e.g. >> params = {"vec__min_df": 1, "clf__probability": True} >> get_params_for_component(params, "vec") {"min_df": 1} """ ...
def cell_content_to_str(v): """ Convert the value of a cell to string :param v: Value of a cell :return: """ if v: if isinstance(v, float) or isinstance(v, int): return str(int(v)) else: return str(v).strip() else: return None
def _get_mc_host(host=None): """Gets the host of the ModelCatalog""" if host is None: return "model-catalog"
def flatten(list_): """ Method returns a new list that is a one-dimensional flattening of `list_` (recursively) :param list_: an object of instance-type `list` composed of zero or more elements each of which may in turn be n-dimensional lists. :return: a new list that is a one-dimensiona...
def get_category_id(url_category): """ Get the category id from the url category """ category_part = url_category.split('/')[-2] category_id = int(category_part.split('_')[-1]) -1 return category_id
def get_installation_paths(designer_versions): """ Returns the installation folder of Substance Designer :param designer_versions: list(str) :return: """ versions = dict() return {'4R8': 'C://Program Files//Pixologic//ZBrush 4R8//ZBrush.exe'}
def extract_field_name(field): """ Pre-processes 'field' from URL query params. Solely handles converting 'type' to '@type' and discarding the not (!) qualifier. :param field: field name to process :return: correct field_name to search on """ use_field = '@type' if field == 'type' else fiel...
def view_score(lst_50, lst_100): """Calculate Weighted View Score Purpose: list of weighted view scores. Notes: Does not currently test that the lists are of equal length. """ lst = [] # add test for equal length of lists? (robust check, but shouldn't happen) for i, item in enumerate(lst_50)...
def map_gen_to_table(generation: int): """This function returns the correct type table for a given generation, as multiple generations will share a type table.""" if generation == 1: return 'gen1' elif 2 <= generation < 6: return 'gen2' else: return 'gen6'
def fixed_point_integer_part(fixed_point_val: int, precision: int) -> int: """ Extracts the integer part from the given fixed point value. """ if (precision >= 0): return fixed_point_val >> precision return fixed_point_val << precision
def strip_label(string): """ Removes any labels that are delimited by a colon. ex: "Trainer: Unnamed Unicorn Stallion #7", this removes the "Trainer: " part. """ i = string.find(':') return string[i + 1:].strip()
def sort_nested(lst, level=1): """ Sort a list of lists up to the given level: 0 = don't sort 1 = sort outer list but keep inner lists untouched 2 = sort inner lists first and then sort outer list """ if level == 0: return lst elif level == 1: return sorted(lst) elif...
def _default_dcos_error(message=""): """ :param message: additional message :type message: str :returns: dcos specific error message :rtype: str """ return ("Service likely misconfigured. Please check your proxy or " "Service URL settings. See dcos config --help. {}").format( ...
def solution(number): # O(N) """ Write a function to calculate the factorial of a number >>> solution(0) 1 >>> solution(1) 1 >>> solution(6) 720 """ m = { 0: 1, 1: 1 } ...
def get_run_script(config_name): """ :param config_name: str Name of the configuration :return: str Name of sim_telarray run script """ return "run_sim_template_" + config_name
def swap(state, one, the_other): """ Takes a n-puzzle state and two tupples as arguments. Swaps the contents of one coordinate with the other. Returns the result. """ x1, y1 = one[0], one[1] x2, y2 = the_other[0], the_other[1] state[x1][y1], state[x2][y2] = state[x2][y2], state[x1][y1] r...
def is_valid(name_string): """Function to handle special characters in inputs""" special_character = "~!@#$%^&*()_={}|\[]<>?/,;:" return any(char in special_character for char in name_string)
def pbin(num): """ convert int to 8 characters binary string which not contain '0b' in begin """ return bin(int(num))[2:].zfill(8)
def get_signer_name(fqdn) -> str: """Gets the signer name for the given fqdn. When checking signatures for a signature by a authored legal entity, one should search for a signer that matches this name. """ return 'legalentity:' + fqdn
def bin2balance_raw(b): """ Convert balance in binary encoding to raw (a.k.a. xrb) Returns a long integer, which has the required 128-bit precision """ assert isinstance(b, bytes) return int.from_bytes(b, 'big')
def _d(s: str) -> int: """ Converts the digit character to its int form. """ return ord(s) - ord('0')
def tfunc(session, a): """Test function to call as a mocked OCS Task. We double it as the start and stop methods for test Processes too. """ # These were useful in debugging twisted interactions # They're annoying when actually running tests though, as pytest can't # suppress the prints # p...
def fibonacci_search(num: int, array: list) -> int: """ @param int num position to check @param list array to store solved trees """ if num < 2: return num array[num] = fibonacci_search(num - 1, array) + fibonacci_search(num - 2, array) return array[num]
def to_unicode(obj): """ Converts any string values into unicode equivalents. This is necessary to allow comparisons between local non-unicode strings and the unicode values returned by the api. :param obj: a string to be converted to unicode, or otherwise a dict, list, set which will be recursi...
def get_valid_header_file_name(file_name: str) -> str: """ :param file_name: file name to test :return: Return given string if compatible to header encoding, or download.ext if not. """ try: file_name.encode('iso-8859-1') return file_name except UnicodeEncodeError: sp...
def shomo(S,f): """In : S (string) f (function from char to char) Out: String homomorphism of S wrt f. Example: S = "abcd" f = lambda x: chr( (ord(x)+1) % 256 ) shomo("abcd",f) -> 'bcde' """ return "".join(map(f,S))
def filesize_converter(size): """ Convert filesize unit to KB, MB and GB based on the size value. # Arguments: size: number of bytes # Returns: converted size. """ if size <= 1024: size_report = str(round(size, 2)) + " KB" elif size <= 1024*1024: size_repor...
def IsWordInCapital(word): """ Test if word is in capital """ boo = True if len(word)>1 : for letter in word[:-1]: if letter.isupper(): pass else: boo = False else: boo = False return boo
def trim_to_even(seq): """Trim a sequence to make it have an even number of elements""" if len(seq) % 2 == 0: return seq else: return seq[:-1]
def numberOfBoomerangs(points): """ :type points: List[List[int]] :rtype: int """ ans = 0 for i in range(0,len(points)): nums_dict = {} for j in range(0,len(points)): if i != j: dis = (points[i][0] - points[j][0]...
def merge_stencil_dicts(short, extrapolation): """Merges the shortened stencil with the extrapolations""" return {key: short.get(key, 0) + extrapolation.get(key, 0) for key in set(short) | set(extrapolation)}
def get_output_detections_image_file_path(input_file_path, suffix="--detections"): """Get the appropriate output image path for a given image input. Effectively appends "--detections" to the original image file and places it within the same directory. Parameters ----------- input_file_path: s...
def add(x, y): """Compute the sum of x and y.""" return x+y-y+y-y+y-y+y-y+y-y+y-y+y-y+y-y+y-y+y-y+y-y+y-y+y-y+y-y+y-y+y-y+y
def col_to_num(col_ind): """Generate Excel Column Name String based on an intger input. E.g. 1 is A and 27 is AA. Args: col_ind (integer): Column index to use Raises: TypeError: if col_ind is boolean, or a string that cannot be converted to an integer Value...
def decrypt(text: str, shift: int) -> str: """ Decrypt given text using caesar cipher. @param string text text to be decrypted @param int shift number of shifts to be applied @return string new decrypted text """ output_string = "" for i in range(len(text)): output_string += chr(...
def create_groups(items, n): """Splits items into n groups of equal size, although the last one may be shorter.""" # determine the size each group should be try: # this line could cause a ZeroDivisionError exception size = len(items) // n except ZeroDivisionError: print('WARNING:...
def url_join(*args): """ Joins given arguments into an url. Trailing but not leading slashes are stripped for each argument. """ return "/".join(map(lambda x: str(x).rstrip('/'), args))
def create_node_fair_uri(node, fair_prefixes): """ Create the RDF subject. Currently hard-coded to gene with the ecogene prefix :param node :param fair_prefixes :return: """ prefix = fair_prefixes.get(node['class'], 'unknown') return 'http://synbiomine.org/%s:%s' % (prefix, node['id'])
def is_subdict(subset: dict, superset: dict) -> bool: """Return whether one dict is a subset of another.""" if isinstance(subset, dict): return all( key in superset and is_subdict(val, superset[key]) for key, val in subset.items() ) if isinstance(subset, list) and isinstance(sup...
def assemble_result_str(ref_snp, alt_snp, flanking_5, flanking_3): """ (str, str, str, str) -> str ref_snp : str DESCRIPTION: 1 character (A, T, G or C), the reference SNP. alt_snp : str DESCRIPTION: 1 character (A, T, G or C), the variant SNP. flanking_5 : str DESCRIPTI...
def mac_format(mac): """Converts double columns to dashes of a mac address""" return mac.replace(':', '-')
def contains(value, arg): """ Test whether a value contains any of a given set of strings. `arg` should be a comma-separated list of strings. """ return any(s in value for s in arg.split(','))
def get_relation_statistics(command_structs): """ Return a dictionary, (relation, position) with counts """ stats = {} for i in range(2): # at max 2! stats[f"position-{i}"] = {} for command in command_structs: pos_id = 0 for k, v in command["rel_map"].items(): ...
def is_core(d, ntaxa, frac, copies_per_genome): """ True if present for all taxa & one copy per each taxon """ # fraction of taxa that gene is present if round(len(d.keys()) / float(ntaxa),2) < frac: return False # copy number if any([x > copies_per_genome for x in d.values()]): ...
def w_ord(chr): """ Python ord() with surrogate pair support """ if len(chr) == 1: return ord(chr) elif len(chr) == 2: return 0x10000 + (ord(chr[0]) - 0xD800) * 0x400 + (ord(chr[1]) - 0xDC00) else: raise Exception("ord() needs either a single Unicode character or a Unicod...
def is_digit(texts_lst): """ texts_lst = ["my", " SS", "N", " is", " 123", "456"] return: [0, 0, 0, 0, 1, 1] """ is_private = [int(tok.strip().isdigit()) for tok in texts_lst] return is_private
def get_vendor_name(cardname): """ Returns human-readable name of card vendor based on provided card name @param cardname: string with card name, e.g., 'NXP JCOP J2A080 80K' @returns human-readable vendor string """ if cardname.find('Feitian') != -1: return 'Feitian', None if cardname.find('...
def convert_byte(num): """ this function will convert bytes to MB.... GB... etc """ step_unit = 1024 # base the size for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < step_unit: return "%3.1f %s" % (num, x) num /= step_unit
def cleanLinks(url_col): """ Convert links from json to a str. Creates hyperlink""" links_out = [] for link in url_col: links_out.append(link['url']) return links_out
def count_files_per_issue(aggregated): """Count the number of files for each issue. :param aggregated: {issue: [file, ...], ...} >>> i = count_files_per_issue(dict((('TEST-1111', ('A', 'B', 'C')), ('TEST-1112', ('A', 'D'))))) >>> i.sort() >>> i [('TEST-1111', 3), ('TEST-1112', 2)] """ ...
def write_messages(messages): """ Takes Groupy filtered list of Messages, writes them to a .txt file for each user and then returns a list of filenames :param messages: A Groupy FilteredList of Messages :return: file_names - a list of file names; :return: user_names - a list of user names ""...
def find_earliest_departure(start_time, buses): """ Returns: bus_id, time_of_departure """ for time_of_departure in range (start_time, start_time + min(buses)): for bus_id in buses: if time_of_departure % bus_id == 0: return bus_id, time_of_departure return -1, -1
def is_one_line_function_declaration_line(line: str) -> bool: # pylint:disable=invalid-name """ Check if line contains function declaration. """ return 'def ' in line and '(' in line and '):' in line or ') ->' in line