content
stringlengths
42
6.51k
def normalise_version_str(version_num, normal_len): """Normalise the length of the version string by adding .0 at the end >>> normalise_version_str(1.0, 3) 1.0.0 >>> normalise_version_str(1.0.0, 4) 1.0.0.0 """ version_num_parts = len(version_num.split(".")) if version_num_parts < norma...
def intersection(a,b): """ :param a: rect :param b: rect :return: intersection area """ x = max(a[0], b[0]) y = max(a[1], b[1]) w = min(a[0]+a[2], b[0]+b[2]) - x h = min(a[1]+a[3], b[1]+b[3]) - y if w<0 or h<0: return () # does not intersect return (x, y, w, h)
def format_value_with_percentage(original_value): """ Return a value in percentage format from an input argument, the original value """ percentage_value = "{0:.2%}".format(original_value) return percentage_value
def expand_layers_dim(input_dim, mid_dim, output_dim, layers): """ Returns a list [(in dim, out dim), ...] with layers count of elements. """ if layers < 0: raise ValueError("Expecting layers >= 0 but received layers = {layers}".format(layers=layers)) if layers == 0: layers_dim = []...
def flipbit( binstr, pos, nbits ): """ flip a given bit in the string """ mask = (1 << pos) return (binstr ^ mask)
def binary_search(ordered_list, element): """Finds an element in a list using binary search. Parameters ---------- ordered_list : list The list from which an element is to be searched element : any The element to be searched in the list Returns ...
def always_cooperate(p, p_other_lag, p_own_lag, rounder_number): """ Return 1 if price corresponds to cooperation at the monopoly price and 0 else. """ return 1 if p == 4 else 0
def get_bridgedomains(yaml): """Return a list of all bridgedomains.""" ret = [] if not "bridgedomains" in yaml: return ret for ifname, _iface in yaml["bridgedomains"].items(): ret.append(ifname) return ret
def pack_code(rep): """ Encodes symbolic Morse repr as binary >>> pack_code("--.---") (0b111011, 6) >>> pack_code("-.") (0b10, 2) """ return (sum((1 if c == '-' else 0) << i for i, c in enumerate(rep)), len(rep))
def _end_format(header, ender, dat_str): """ Write a block with an end """ return ( header + '\n' + dat_str + '\n' + ender )
def msg_to_bytes(msg, standard="utf-8"): """Encode text to bytes.""" return bytes(msg.encode(standard))
def perform(function_name, *arguments): """ Parameters ---------- function_name : python function handle name of functio we want to call and run *arguments : Python list list of arguments to be passed to function_name :return: bool """ return function_name(*argument...
def transform_ipnet_strings(ipnets, transformed_ipnets=set()): """ Creates a set of ip strings for ip-checking purposes. # Ideally, we should use ipaddress library to combine overlapping ip address ranges from multiple sources, # but the memory usage blows up to GBs # Instead, we do a naive set com...
def calc_position(input_data): """ Computes the horizontal and depth position based on a set of different input commands. :param input_data: String array of different movement commands :return: The position based on the multiplication of the horizontal and vertical position """ _depth, _horizon...
def yandex_operation_is_in_progress(data: dict) -> bool: """ :returns: Yandex response contains status which indicates that operation is in progress. """ return ( ("status" in data) and (data["status"] == "in-progress") )
def all_equal(seq): """ whether or not all elements of a sequence are equal """ return len(set(seq)) == 1
def list_omit_none(value): """Returns a list of the value, or the empty list if None.""" return [value] if value else []
def clean_format(image_format: str, extension: str): """ Return working options of JPG images. """ if extension.lower() == "jpeg": extension = "jpg" if image_format.lower() == "jpg": image_format = "JPEG" return image_format, extension
def _str2bool(s): """ Convert string to boolean Used by XML serialization """ s = s.strip().lower() if s in ["1", "true"]: return True if s in ["0", "false"]: return False raise ValueError("Invalid boolean value %r" % (s))
def trip_deuce(word): """Predicate to determine if word has three consecutive double letters """ count = 0 # Number of double words in a row currently i=0 # Position in word word = word.lower() # Make it lower case for comparison's sake # Run through the word, up through the second to last lett...
def fib(index: int) -> int: """ Calculate the fibonacci by index. :param index: The index to calculate to. :return: The fibonacci value at that index. """ return index if index <= 1 else fib(index - 1) + fib(index - 2)
def part01(adapters: list) -> int: """ x """ one_jumps = 0 three_jumps = 0 highest = max(adapters) adapters.append(highest + 3) adapters.append(0) # Need to include the jump from 0 to 1 adapters = sorted(adapters) for i in range(len(adapters) - 1): if adapters[i + 1] ...
def commdct2grouplist(gcommdct): """extract embedded group data from commdct. return gdict -> {g1:[obj1, obj2, obj3], g2:[obj4, ..]}""" gdict = {} for objidd in gcommdct: group = objidd[0]['group'] objname = objidd[0]['idfobj'] if group in gdict: gdict[group].append(o...
def filter_by_id(lst, ids=[]): """ filter list by supplied IDs """ return [x for i,x in enumerate(lst) if i in ids]
def uuid_prefix_len(uuids, step=4, maxlen=32): """Get smallest multiple of `step` len prefix that gives unique values. The algorithm is not fancy, but good enough: build *sets* of the ids at increasing prefix lengths until the set has all ids (no duplicates). Experimentally this takes ~.1ms for 1000 du...
def quick_format_print(data, precision=3): """ parses array to string with precision decimals """ string = "{:." + str(precision) + "f}" formatter = string.format return formatter(data)
def data_value(value: str) -> float: """Convert to a float; some trigger values are strings, rather than numbers (ex. indicating the letter); convert these to 1.0.""" if value: try: return float(value) except ValueError: return 1.0 else: # empty string ...
def isvalid_sudoku(board): """ Verifies that the board complies with the following conditions: -Each row must contain the digits 1-9 without repetition. -Each column must contain the digits 1-9 without repetition. -Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without rep...
def _dedupe_deps(deps): """ Deduplicate a set of string labels in a deps argument. """ if deps == None: return deps depindex = [] for i in deps: if i not in depindex: depindex.append(i) return depindex
def hole_current_density(mu=0,density=0,d_phi_d_z=0, diffusivity=0,dp_dz=0): """ returns the hole current density Parameters ---------- mu : TYPE, required DESCRIPTION. The default is 0. density : TYPE, required DESCRIPTION. The default is 0. d_phi_d...
def parse_cli_output(output): """helper for testing parse the CLI --list output and return value of all set attributes as dict""" import re results = {} matches = re.findall(r"^(\w+)\s+.*\=\s+(.*)$", output, re.MULTILINE) for match in matches: results[match[0]] = match[1] return res...
def sqsum(n): """" Calculates 6 * (sum of numbers from 1 to n) (we want to avoid division for large numbers because Python is not good with it). See https://trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm """ return n * (n + 1) * (2 * n + 1)
def sigma_to_gamma(sigma: float) -> float: """Transforms the sigma parameter into gamma using the following relationship: 1 gamma = ----------- 2 * sigma^2 """ return 1 / (2 * sigma ** 2)
def strZip(list1, list2, string): """ Return a list of strings of the form x1stringx2 where x1 and x2 are elements of list1 and list2 respectively. """ result = [] for x1, x2 in zip(list1, list2): result.append(str(x1)+string+str(x2)) return result
def get_list_from_container(param, prop: str, t): """ Takes proto parameter and extracts a value it stores. Args: param: proto parameter prop: name of the property to take t: type of the value (int, float etc.) - only primitive ones Returns: If it is a container, returns...
def purge_duplicates(list_in): """Remove duplicates from list while preserving order. Parameters ---------- list_in: Iterable Returns ------- list List of first occurrences in order """ # Algorithm taken from Stack Overflow, # https://stackoverflow.com/questions/480214....
def sample_width_to_string(sample_width): """Convert sample width (bytes) to ALSA format string.""" return {1: 's8', 2: 's16', 4: 's32'}[sample_width]
def dimensiones(listaPal): """Modulo el cual genera las dimensiones para la sopa de letras""" max=0 for i in listaPal: if len(i) >= max: max= len(i) cantPalabras= len(listaPal) return (max,cantPalabras)
def generate_sub_codons_left(codons_dict): """Generate the sub_codons_left dictionary of codon prefixes. Parameters ---------- codons_dict : dict Dictionary, keyed by the allowed 'amino acid' symbols with the values being lists of codons corresponding to the symbol. Returns ---...
def freqDataToProbData(y, nodeNumber): """ gives prob distribution which is used for power law calculation :param y: # of channels :param nodeNumber: total numbers :return: """ newy = [] for ele in y: newy += [ele/nodeNumber] return newy
def _perp(t: tuple) -> tuple: """ Obtain the point whose corresponding vector is perpendicular to t. Parameters ---------- t : tuple Point (x, y) Returns ------- tuple: (-y, x) """ return -t[1], t[0]
def match_concentrations_with_different_sums(conc1, conc2): """ Given two lists with each item to be a tuple (species label, concentration) conc1 and conc2 with different total concentrations, the method returns matched species labels and concentrations. Example: conc1 = [('a', 1), ('b', 3), ('c', 1)]...
def get_light_threshold(response): """Get light from response.""" light_threshold = response.get("highlight") return light_threshold
def downcase_string(s): """Convert initial char to lowercase""" return s[:1].lower() + s[1:] if s else ''
def distance_vector_between(point_1, point_2): """Compute and return the vector distance between two points.""" return [point_2[0] - point_1[0], point_2[1] - point_1[1]]
def is_int(value, base=10): """ Tests if a value can be converted to an integer. """ isint = False try: int(value, base) isint = True except ValueError: pass return isint
def _get_all_points_top(table): """Reflect point table from `create_point_table` to quadrant 2 to form top of H-dipole""" coordinates = [] for point in table: if point[0] != 0.: reflection = [-point[0], point[1]] coordinates.append(reflection) coordinates = table + coord...
def formatstr(text): """Extract all letters from a string and make them uppercase""" return "".join([t.upper() for t in text if t.isalpha()])
def str2tuple(s, sep="/"): """ Given the string representation of a tagged token, return the corresponding tuple representation. The rightmost occurrence of *sep* in *s* will be used to divide *s* into a word string and a tag string. If *sep* does not occur in *s*, return (s, None). >>> s...
def get_item(dictionary, key): """ Return the value at dictionary[key]. For some reason this isn't allowed directly in Django templates. """ return dictionary.get(key)
def pytest_assertrepr_compare(config, op, left, right): """See full error diffs""" if op in ("==", "!="): return ["{0} {1} {2}".format(left, op, right)]
def create_set(package_list, delimiter): """ Create a set of packages to be excluded. This function receives a list of strings, takes the packages' names and transforms them to a set. If the list contains packages with @ but the delimiter input is '==', then the package is ignored. Parame...
def get_model_name(url): """ Return a model short name based on its endpoint. Examples -------- >>> url = ('http://omgsrv1.meas.ncsu.edu:8080/thredds/dodsC/fmrc/sabgom/' ... 'SABGOM_Forecast_Model_Run_Collection_best.ncd') >>> get_model_name(url) 'fmrc-SABGOM_Forecast_Model_Run_C...
def splitdrive(path): """Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either a drive specification or the empty string. On systems which do not use drive specifications, *drive* will always be the empty string. In all cases, ``drive + tail`` will be the same as *pa...
def is_string(item): """ Return True if the item behaves like a string. :type item: str :param item: """ try: # noinspection PyUnusedLocal v = item + '' return True except TypeError: return False
def is_valid_sanc_no(sanc_no): """A very basic sanc_no validation check""" return len(sanc_no) >= 1
def _group_xy_items(xy, iterfunction): """Seperate items in xy, grouping either the keys or the values. Warnings -------- This method is intended for internal use only. """ return [i for i in list(iterfunction(xy))]
def dbsnap_verify_identifier(identifier): """ Args: identifier (str): The database instance identifier to derive new name. """ new_identifier = "dbsv-{}".format(identifier) if len(new_identifier) > 63: # then generated identifier for the restore much be between 1-63 charecters. ...
def list_exp(s): """ expand array of strings by multiplying the strings with the leading number. """ ret = [] i = 0 while i < len(s): for j in range(0, s[i]): ret.append(s[i+1]) i += 2 return ret
def build_ranges_dict(fault_dict): """ build range, however allows to define type with a dict. """ if fault_dict["type"] == "shift": ret = [] if len(fault_dict["range"]) != 3: raise ValueError("For Shift 3 element list is needed") for i in range(fault_dict["range"][1]...
def get_board_columns(board): """ Get board columns >>> get_board_columns(['***21**', '412453*', '423145*', '*543215', \ '*35214*', '*41532*', '*2*1***']) ['*125342', '*23451*', '2413251', '154213*', '*35142*'] """ columns = [] for i in range(1, 5 + 1): column = '' for ro...
def do_print(nev): """Returns true for sparcified event numbers. """ return nev<10\ or (nev<50 and (not nev%10))\ or (nev<500 and (not nev%100))\ or not nev%1000
def import_names(package, names): """ Dynamic import of a list of names from a module :param package: String with the name of the package :param names: Name or list of names, string or list of strings with the objects inside the package :return: The list (or not) of objects under those names ""...
def get_data_matching_filter(filter_by, raw_data): """ Returns a list of data matching filter_by from a given STB's raw_data :param filter_by: Tuple containing (filter_name, filter_value) :param raw_data: Dictionary of raw stb_data for 1 STB. :return: List of dictionary entries from flattened STB ma...
def early_stopping(cost, opt_cost, threshold, patience, count): """function that determines if you should stop gradient descent early""" early_stopping = False if opt_cost - cost <= threshold: count += 1 else: count = 0 if count == patience: early_stopping = True retu...
def MSEQNO(mft_reference): """ Given a MREF/mft_reference, return the sequence number part. """ return (mft_reference >> 48) & 0xFFFF
def compose_insert(table, fields, values): """Compose insert command string. Arguments --------- table : str Real table name. fields : str List of table fields. values : dict Dictionary of table fields and their values. Returns ------- str Query stri...
def assign_none(subs, uniq=False): """Assign query to subjects without using a classification system. Parameters ---------- subs : tuple of str Subjects. uniq : bool, optional Assignment must be unique. Returns ------- str or list or None Unique subject or list ...
def map_on_off(x): """ Map 'On' to True and 'Off' to False. """ if str(x).lower() == 'on': return True elif str(x).lower() == 'off': return False else: return None
def norm_page_cnt(page, max_number=None): """ Normalize a integer (page). * Ensure that it is greater than Zero, and is not None. - If less than 1, or None, set it to 1 * if max_number is None, then do not check for max_number * if greater than max_number, reset it to be max_number ...
def byDet(specs, det): """byDet(specs, det) Returns the subset of spectra in specs collected on detector det.""" res = [] for spec in specs: if spec.getProperties().getDetector() == det: res.append(spec) return tuple(res)
def select_optimizer(method): """Use the method name to get optimizer. `method` is a string e.g. `GPMin`""" try: opt = globals()[method] except KeyError: opt = None return opt
def make_date(v): """ Convert a date string in DD.MM.YYYY format to YYYY-MM-DD. >>> make_date("01.02.2003") '2003-02-01' """ return "-".join(reversed(v.split(".")))
def horizontal_weight_zreda2008b(r, a1=1.311e-2, a2=9.423e-5, a3=3.2e-7, a4=3.95e-10): """Presented by Bogena et al. (2013, Eq. 13), fitted to Zreda et al. (2008). Bogena et al. (2013) fitted a polynomial function through the relationship between cumulative fraction of counts (CFoC) and CRP footprint r...
def plato2sg(plato): """Convert Plat to Specific Gravity """ return 259.0 / (259.0 - float(plato))
def _args(param): """Return a string with all the inputs property formatted. """ if not param: return '' return '%s, ' % ', '.join([par['name'][1:-1] for par in param])
def fv_annuity(pmt, interest_rate, years, m=1): """ m: number of times interst is compounded in a year """ i = interest_rate return pmt * ((1 + interest_rate / m) ** (years * m) - 1) / (i / m)
def lone_pair_count(sym): """ lone pair count """ return {'H': 0, 'HE': 1, 'C': 0, 'N': 1, 'O': 2, 'S': 2, 'F': 3, 'CL': 3, 'NE': 4, 'AR': 4}[sym.upper()]
def sum_scores(scores, query): """Sums all the scores""" return sum(scores.values())
def lenToBytes(value): """ Calculates the array of bytes that must be included into an ASN1 Tag to correctly represent its length :param value: the size of the tag :return: the array of integers """ if value < 0x80: return [value] if value <= 0xff: return [0x81, value] ...
def find_def_class(obj, method): """finds the parent class where the method of the child object is defined""" for typ in type(obj).mro(): if method in typ.__dict__: return typ
def genomic_dup1_38_vac(genomic_dup1_seq_loc): """Create test fixture for absolute copy number dup1 on GRCh38""" return { "type": "AbsoluteCopyNumber", "_id": "ga4gh:VAC.nZodtrYoDtBJ1kdKCO6zLd7QR7ho4s9v", "subject": genomic_dup1_seq_loc, "copies": {"type": "Number", "value": 3} ...
def help_msg(dh_data): """ print help function """ return '\033[92m[\033[91m{}\033[92m]\033[0m\n'.format(dh_data)
def model_query_properties_helper(form): """ Accepts JSON of cortex form and returns formatted properties. """ data = {} for prop, valu in form.get('props').items(): data[prop] = valu.get('doc', 'N/A') return data
def _inputs_swap_needed(mode, shape1, shape2, axes=None): """Determine if inputs arrays need to be swapped in `"valid"` mode. If in `"valid"` mode, returns whether or not the input arrays need to be swapped depending on whether `shape1` is at least as large as `shape2` in every calculated dimension. ...
def parse_ascii(state: str, size: int) -> str: """ Args: state: an ascii picture of a cube size: the size of the cube Returns: a string of the cube state in ULFRBD order """ U = [] L = [] F = [] R = [] B = [] D = [] lines = [] for line in state.s...
def fib(n, start=(0, 1)): """tail-recursive fibonacci function""" def aux(n, a, b): if n > 0: return aux(n - 1, b, a + b) else: return a return aux(n, *start)
def _robust_column_name(base_name, column_names): """ Generate a new column name that is guaranteed not to conflict with an existing set of column names. Parameters ---------- base_name : str The base of the new column name. Usually this does not conflict with the existing colum...
def _R(T, Cr, n): """ Basic function for calculating relaxation time due to the Raman mechanism. For canonical definition, see fx. DOI: 10.1039/c9cc02421b Input T: temperature for the calculation Cr: Raman pre-factor n: Raman exponent Output tau: relaxation time due to ...
def med_is_decimal(s): """Takes a string and returns whether all characters of the string are digits.""" return set(s) <= set('1234567890')
def divide_word(word): """ Divides a word, creating an array of 32 bits """ res = [] for i in range(32): b = (word & (1<<(31-i))) >> (31-i) assert(b==0 or b==1) res.append(b) return res
def detectFileFormat(filename): """ return format name by examining the last suffix of file name """ suffixFormatDict = { 'gb': 'GenBank', 'fa': 'FASTA', 'fasta': 'FASTA', 'gff3': 'GFF3'} suffix = file...
def unmodify(peptide): """ >>> from re import sub >>> sub(r'\[(\-|\d|\.)+\]', '', 'A[-12.34]B') 'AB' """ from re import sub peptide = sub(r'\[(\-|\d|\.)+\]', '', peptide) peptide = sub(r'^.\.|\..$|n|c', '', peptide) #peptide = sub(r'\..$', '', peptide) #peptide = sub(r'\[.+\]', ...
def longest_oscillation(L): """ Function that finds the longest oscillation @param L The list we wish to get the longest oscillation from @return long_osc The length of the longest oscillation @return osc_index_list List of the longest oscillation @complexity ...
def replace_chars(string: str) -> str: """Replace certain strings from an html string""" string = string.replace("../../images/stars/Star", "").replace("/images/stars/Star", "").replace("_clear.gif", "").replace("_grey.gif", "").replace("_red.gif", "") return string
def get_requirements_text(repo_dependencies): """ :param repo_dependencies: A list of git repositories. You can optionall add pip arguments such as '-e' (install as source). e.g.: ['-e git+http://github.com/QUVA-Lab/artemis.git#egg=artemis', '-e git+http://github.com/petered/plato.git#egg=plato'] :...
def number_of_zeros(lst): """ a function that returns the number of zeros in a given simple list of numbers lst. """ return len(list(filter(lambda x: x == 0, lst)))
def calculate_padding_size(bigger_shape, smaller_shape): """ Find difference between shapes of bigger and smaller image. """ diff = bigger_shape - smaller_shape if diff == 1: dim1 = 1 dim2 = 0 elif diff % 2 != 0: dim1 = int(diff // 2) dim2 = int((diff // 2) + 1) else...
def get_url_for_artist(country, gender, apikey): """ This function writes a url(a string) for Harvard Art Museums API to get a dataset with all female or male artists who are from a country(culture). Parameters ---------- country: str A string of a culture name that you wish to find in ...
def _prefill_placeholders(placeholders, files, user_values): """Search through existing file aliases to pre-fill placeholder values. Parameters ---------- placeholders : list of str The list of placeholder names that were found in the template string. files : list of str A list of fi...