content
stringlengths
42
6.51k
def identify_target_ligand(ligand_residues): """Attempts to guess the target ligand""" # If there is only one target ligand then that must be the target # even if there are multiple instances. That could be the case if # the compound is peptidic for example. if len(ligand_residues) == 1: return list(ligand_residues.keys())[0] # Alternatively, if there are multiple ligands count them and if # one is found to only have one instance use that after printing # a relevant message indeces = [ligand_residues[_] == 1 for _ in ligand_residues] if indeces.count(True) == 1: index = list(ligand_residues.values()).index(1) return list(ligand_residues.keys())[index] else: return None
def get_divisors_sum(number): """ Gives the sum of divisors of a number = S According to the Zur algorithm, S should be equal to total number of trans_matrices """ if number == 0: return 0 divisors_list = [] for i in range(number+1): j = i + 1 if number % j == 0: divisors_list.append(j) return sum(divisors_list)
def RCI_calc(mutual_information, reference_entropy): """ Calculate Relative classifier information (RCI). :param mutual_information: mutual information :type mutual_information: float :param reference_entropy: reference entropy :type reference_entropy: float :return: RCI as float """ try: return mutual_information / reference_entropy except Exception: return "None"
def reorder_columns(colnames): """ :param colnames: :return: """ reordered = [] idx = 5 for col in colnames: if col == 'chrom': reordered.append((0, col)) elif col == 'start': reordered.append((1, col)) elif col == 'end': reordered.append((2, col)) elif col == 'name': reordered.append((3, col)) elif col == 'score': reordered.append((4, col)) else: reordered.append((idx, col)) idx += 1 return [t[1] for t in sorted(reordered)]
def concatenate_rounds(rounds_1, rounds_2): """ :param rounds_1: list - first rounds played. :param rounds_2: list - second set of rounds played. :return: list - all rounds played. """ res = list() res.extend(rounds_1) res.extend(rounds_2) return res
def _any_phrase_capitalised(lower_case_phrases, upper_case_phrases): """tests if any of the phrases in lower_case_phrases, when capitalised, are present in upper_case_phrases""" for lc_p in lower_case_phrases: for uc_p in upper_case_phrases: if lc_p.capitalize() == uc_p: return True return False
def divide(numbers): """Function for dividing numbers. Parameters ---------- numbers : list List of numbers that the user inputs. Returns ------- result : int Integer that is the result of the numbers divided. """ result = numbers[0] for n in numbers[1:]: result = result / n return result
def fat(a=7, show=False): """ :param a: is the value the user wants to see the factorial of :param show: checks if it should show the formula behind the calculation :return: the factorial value of the number """ f = 1 for c in range(a, 0, -1): f *= c if show: if c == 1: print(f'{c} = ', end='') else: print(f'{c} x ', end='') return f
def _parse_timespan(timespan): """Parse a time-span into number of seconds.""" if timespan in ('', 'NOT_IMPLEMENTED', None): return None return sum(60 ** x[0] * int(x[1]) for x in enumerate( reversed(timespan.split(':'))))
def dec2bin(number): """Convert a decimal number to binary""" return bin(number)[2:]
def calc_RC_via_bulk_time(capacitance, L, sigma): """ Characteristic time for induced double layer to form considering a capacitance. units: s Notes: Squires, 2010 - "characteristic time for induced double layer to form" Inputs: capacitance: F/m^2 C^2*s^2/kg/m^2/m^2 (total capacitance of double layer system) L_bpe: m m (characteristic length of BPE) sigma: S/m C^2*s/kg/m^2/m (conductivity of electrolyte/buffer) Outputs: tau: s """ tau = capacitance*L/sigma return tau
def parse_eei_load(ldstr): """Helper function to parse load column from EEI format files.""" load = [ldstr[0 + i : 5 + i] for i in range(0, len(ldstr), 5)] try: load = [int(l) for l in load] except TypeError: print("Load variable cannot be mapped to integer value.") return load
def timedelta_to_seconds(td): """ Converts a timedelta to total seconds, including support for microseconds. Return value is (potentially truncated) integer. (This is built-in in Python >= 2.7, but we are still supporting Python 2.6 here.) :param td: The timedelta object :type td: :class:`datetime.timedelta` :return: The number of total seconds in the timedelta object. :rtype: int """ if not td: return None return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
def parsing_args(argstr) : """ Returns a dictionary of argument-value pairs """ dic = {} if argstr : bits = argstr.split() for bit in bits : letter = bit[0] coord = float(bit[1:]) dic[letter] = coord return dic
def get_region(b): """Tries to get the bucket region from Location.LocationConstraint Special cases: LocationConstraint EU defaults to eu-west-1 LocationConstraint null defaults to us-east-1 Args: b (object): A bucket object Returns: string: an aws region string """ remap = {None: 'us-east-1', 'EU': 'eu-west-1'} region = b.get('Location', {}).get('LocationConstraint') return remap.get(region, region)
def emit_options(options): """Emit the analysis options from a dictionary to a string.""" return ",".join("%s=%s" % (k, v) for k, v in sorted(options.items()))
def convert_float(*args, **kwargs): """ Handle converter type "float" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'number', 'format': 'float', } return schema
def change_flat_notation(s: str): """Change flat notation from `-` to `b`""" return s.replace("-", "b")
def temp_humidity(p_temp, h_temp): """ Use this function as :attr:`~SenseEnviron.temp_source` if you want to read temperature from the humidity sensor only. """ # pylint: disable=unused-argument return h_temp
def get_midpoint_uv_list(uv_list): """ Gets the mid point of the sorted 2d points in uv_list. """ u_mid = 0.5*(uv_list[0][0] + uv_list[-1][0]) v_mid = 0.5*(uv_list[0][1] + uv_list[-1][1]) return u_mid, v_mid
def validate_email(email): """ Assignment 2 updated """ allowed_chars = "abcdefghijklmnopqrstuvwxyz._-@0123456789" for i in email: if i not in allowed_chars: return False if email.count("@") == 1 and email.islower(): first, end = email.split("@") if end.count(".") >= 1 and first: for i in end.split("."): if len(i) < 1: return False if 1 < len(end.split(".")[-1]) < 4: return True return False
def split_exclude_string(people): """ Function to split a given text of persons' name who wants to exclude with comma separated for each name e.g. ``Konrad, Titipat`` """ people = people.replace('Mentor: ', '').replace('Lab-mates: ', '').replace('\r\n', ',').replace(';', ',') people_list = people.split(',') return [p.strip() for p in people_list if p.strip() is not '']
def AISC_J24(PlateThck): """ From AISC WSD Table J2.4 Minimum Size of Fillet Welds """ # # To 1/4 inclusive if PlateThck < 6.35: # Minimum zise 1/8 _MinWeldSize = 3.20 # Over 3/4 elif PlateThck > 19.0: # Minimum zise 5/16 _MinWeldSize = 8.0 else: # Over 1/4 to 1/2 if PlateThck < 12.7: # Minimum zise 3/16 _MinWeldSize = 4.80 # Over 1/2 to 3/4 else: # Minimum zise 1/4 _MinWeldSize = 6.35 # return _MinWeldSize
def isValidLatitude(lat): """ Validates the latitude value. lat -- the latitude coordinate """ eps = 0.000001 if (-90 - eps < lat) and (lat < 90 + eps): return True return False
def get_epsilon(epsilon, n, i): """ n: total num of epoch i: current epoch num """ return epsilon / ( 1 + i/float(n))
def clip(x, vmin, vmax): """Clip a value x within bounds (vmin, vmax)""" if x < vmin: return vmin elif x > vmax: return vmax else: return x
def checkFormat_coordinate0(coordinate0): """Function that probe the coordinates are in a number list""" if type(coordinate0) == list: if len(coordinate0) == 3: for elem in coordinate0: try: float(elem) except Exception as e: raise Exception("The coordinate '" + str(elem) + "' is not a number") else: raise Exception("Missing coordinates, there is only: {}".format(len(coordinate0))) else: raise Exception("Incorrect coordinate format. Most be a list with 3 coordinate.") return True
def sum_numbers(first_int, second_int): """Returns the sum of the two integers""" result = first_int + second_int return result
def similarity_tannimoto(left, right): """ :param left: Dictionary <key, value> :param right: Dictionary <key, value> :return: """ in_common = 0 total = 0 for left_fragment_key in left: for right_fragment_key in right: left_fragment = left[left_fragment_key] right_fragment = right[right_fragment_key] if not left_fragment["value"] == right_fragment["value"]: continue # Add shared number (ie. min) to in_common - intersenction. in_common += min(left_fragment["counter"], right_fragment["counter"]) # Add to total counter - union. total += left_fragment["counter"] + right_fragment["counter"] if not total == 0: # They have no fragments, this might happen if the molecules # are too small.. return in_common / (float)(total) else: return 0
def contains_any(haystack, needles): """Tests if any needle is a substring of haystack. Args: haystack: a string needles: list of strings Returns: True if any element of needles is a substring of haystack, False otherwise. """ for n in needles: if n in haystack: return True return False
def fib(n): """ This function calculate fib number. Example: >>> fib(10) 55 >>> fib(-1) Traceback (most recent call last): ... ValueError """ if n < 0: raise ValueError('') return 1 if n<=2 else fib(n-1) + fib(n-2)
def subsumed(origx, words, wild='*', report=True): """See whether origx is subsumed by a wildcarded entry in words.""" if origx[-1] == wild: x = origx[:-2] + wild else: x = origx + wild while len(x) > 1: if x in words: if report: print(x, 'subsumes', origx) return x else: x = x[:-2] + wild return False
def NLR_analysis(NLR): """ Analysis NLR(Negative likelihood ratio) with interpretation table. :param NLR: negative likelihood ratio :type NLR: float :return: interpretation result as str """ try: if NLR == "None": return "None" if NLR < 0.1: return "Good" if NLR >= 0.1 and NLR < 0.2: return "Fair" if NLR >= 0.2 and NLR < 0.5: return "Poor" return "Negligible" except Exception: # pragma: no cover return "None"
def timeToString(seconds_input): """Description. More... """ mmss = divmod(seconds_input, 60) if mmss[0] < 10: minutes = "0" + str(mmss[0]) else: minutes = str(mmss[0]) if mmss[1] < 10: seconds = "0" + str(mmss[1]) else: seconds = str(mmss[1]) if mmss[0] > 99: return ("99", "++") else: return minutes, seconds
def make_python_name(name): """ Convert Transmission RPC name to python compatible name. """ return name.replace('-', '_')
def indent(amount: int, s: str) -> str: """Indents `s` with `amount` spaces.""" prefix = amount * " " return "\n".join(prefix + line for line in s.splitlines())
def tags(tag_coll): """Serializes the given tags to a JSON string. :param set[str] tag_coll: a set of tags :return: a dictionary suitable for JSON serialization :rtype: dict """ return {'tags': sorted(tag_coll)}
def get_unsigned_character(data, index): """Return one byte from data as an unsigned char. Args: data (list): raw data from sensor index (int): index entry from which to read data Returns: int: extracted unsigned 16-bit value """ result = data[index] & 0xFF return result
def intercept_file_option(argv): """ Find and replace value of command line option for input file in given argv list. Returns tuple: * file_arg: the filename (value of -f option) * new_argv: argv with the filename replaced with "-" (if found) """ file_arg = None # value of -f option in sys.argv file_idx = None # index of value of -f option in sys.argv # if the file is not specified, no change in argv is needed new_argv = argv for i, arg in enumerate(argv[1:], start=1): if arg != "-f": continue file_idx = i+1 if len(argv) <= file_idx: # it looks like '-f' is the last option, let's not interfere break file_arg = argv[file_idx] new_argv = argv.copy() new_argv[file_idx] = "-" return file_arg, new_argv
def _tag_to_snake(name: str) -> str: """Conversts string to snake representation. 1. Converts the string to the lower case. 2. Converts all spaces to underscore. Parameters ---------- name: string The name to convert. Returns ------- str: The name converted to the snake representation. """ _name = name.strip().lower() if len(_name.split()) > 1: _name = "_".join(_name.split()) return _name
def bytes_to_str(s, encoding='utf-8'): """Returns a str if a bytes object is given. >>> 'example' == bytes_to_str(b"example") True """ if isinstance(s, bytes): value = s.decode(encoding) else: value = s return value
def oconner(w, r): """ Optimistic for low reps. Between Lombardi and Brzycki for high reps. """ return w * (1 + r/40)
def order_toc_list(toc_list): """Given an unsorted list with errors and skips, return a nested one. [{'level': 1}, {'level': 2}] => [{'level': 1, 'children': [{'level': 2, 'children': []}]}] A wrong list is also converted: [{'level': 2}, {'level': 1}] => [{'level': 2, 'children': []}, {'level': 1, 'children': []}] """ ordered_list = [] if len(toc_list): # Initialize everything by processing the first entry last = toc_list.pop(0) last['children'] = [] levels = [last['level']] ordered_list.append(last) parents = [] # Walk the rest nesting the entries properly while toc_list: t = toc_list.pop(0) current_level = t['level'] t['children'] = [] # Reduce depth if current level < last item's level if current_level < levels[-1]: # Pop last level since we know we are less than it levels.pop() # Pop parents and levels we are less than or equal to to_pop = 0 for p in reversed(parents): if current_level <= p['level']: to_pop += 1 else: break if to_pop: levels = levels[:-to_pop] parents = parents[:-to_pop] # Note current level as last levels.append(current_level) # Level is the same, so append to the current parent (if available) if current_level == levels[-1]: (parents[-1]['children'] if parents else ordered_list).append(t) # Current level is > last item's level, # So make last item a parent and append current as child else: last['children'].append(t) parents.append(last) levels.append(current_level) last = t return ordered_list
def solution(A, B): """ :param A: :return: """ len_str1 = len(A) len_str2 = len(B) if len_str1 != len_str2: return False # max number in ascii temp_storage = [0] * 256 for c in A: temp_storage[ord(c)] += 1 for c in B: temp_storage[ord(c)] -= 1 for num in temp_storage: # greater than zero if num: return False return True
def text_is_list(text) -> bool: """check if text is wrapped in square brackets""" text = text.strip() return text[0] == '[' and text[-1] == ']'
def RPL_REHASHING(sender, receipient, message): """ Reply Code 382 """ return "<" + sender + ">: " + message
def ftimeout(func, args=(), kwargs={}, timeout_duration=1, default=None): """http://stackoverflow.com/a/13821695""" import signal class TimeoutError(Exception): pass def handler(signum, frame): raise TimeoutError() # set the timeout handler signal.signal(signal.SIGALRM, handler) signal.alarm(timeout_duration) try: result = func(*args, **kwargs) to = False except TimeoutError as exc: to = True result = default finally: signal.alarm(0) return result, to
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_uniqueness_in_rows(['***21**', '452453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) False >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*553215', '*35214*', '*41532*', '*2*1***']) False """ for line in board[1:-1]: line = set(line[1:-1]) if '*' in line and len(set(line)) == 6: return True elif len(set(line)) != 5: return False return True
def get_slice_length(nominal: float, total: int) -> int: """Calculate actual number of sentences to return Arguments: nominal {float} -- fraction of total/absolute number to return of {int} -- total number of sentences in body Raises: ValueError -- invalid length argument Returns: int -- number of sentences to return """ slice_len = nominal if nominal <= 0: raise ValueError('Invalid summary length: ' + str(nominal)) if nominal < 1: slice_len = nominal * total return round(min(slice_len, total))
def update_params(old_params, new_params, check=False): """Update old_params with new_params. If check==False, this merely adds and overwrites the content of old_params. If check==True, this only allows updating of parameters that are already present in old_params. Parameters ---------- old_params : dict new_params : dict check : bool, optional (default: False) Returns ------- updated_params : dict """ updated_params = dict(old_params) if new_params: # allow for new_params to be None for key, val in new_params.items(): if key not in old_params and check: raise ValueError('\'' + key + '\' is not a valid parameter key, ' + 'consider one of \n' + str(list(old_params.keys()))) if val is not None: updated_params[key] = val return updated_params
def merge_dicts(*dict_args): """Merge all Python dictionaries into one.""" dict_args = [] if dict_args is None else dict_args result = {} for d in dict_args: result.update(d) return result
def getColor(k) : """Homemade legend, returns a nice color for 0 < k < 10 :param k : indice """ colors = ["#862B59","#A10000","#0A6308","#123677","#ff8100","#F28686","#6adf4f","#58ccdd","#3a3536","#00ab7"] return colors[k]
def encode_all( header: bytes, stream: bytes, funcs: bytes, strings: bytes, lib_mode: bool ) -> bytes: """ Combine the various parts of the bytecode into a single byte string. Parameters ---------- header: bytes The bytecode's header data. stream: bytes The actual bytecode instructions. funcs: bytes The function pool. strings: bytes The string pool. lib_mode: bool Whether to build a library bytecode file or an application one. Returns ------- bytes The full bytecode file as it should be passed to the VM. """ if lib_mode: return b"".join((header, b"\r\n\r\n\r\n", strings, b"\r\n\r\n", funcs)) return b"".join( (header, b"\r\n\r\n\r\n", strings, b"\r\n\r\n", funcs, b"\r\n\r\n", stream) )
def min_max(x, mn, mx): """ recales x such that it fits in the range: [-1, 1] """ return 2 * ((x - mn) / (mx - mn)) - 1
def parse_version(version: str): """ Returns parsed version from .ezdeps.json """ eq_type = '==' if version[0] == '^': eq_type = r'\>=' version = version[1:] return eq_type + version
def detokenize_smiles(tokenized_smiles: str) -> str: """ Detokenize a tokenized SMILES string (that contains spaces between the characters). Args: tokenized_smiles: tokenized SMILES, for instance 'C C ( C O ) = N >> C C ( C = O ) N' Returns: SMILES after detokenization, for instance 'CC(CO)=N>>CC(C=O)N' """ return tokenized_smiles.replace(' ', '')
def validate_input_gui(user_input): """ This function validates the input of the user during 2nd menu :param user_input: :return: bool """ if user_input in ('0', '1', '2', '3', '4'): return True return False
def my_add(argument1, argument2): """ adds two input arguments. Parameters ---------- argument1 : int, float, str input argument 1 argument2 : int, float, str input arguement 2 Returns ------- results : int, float or str the two added input arguments """ result = argument1 + argument2 return result
def D_theo(D0, T, Tc, mu): """ Calculates the theoretical value for spinwave stiffness D as a function of temperature Parameters ---------- D0 : float spin-wave stiffness at 0 K meV/angstroem^2 T : float temperature of the system in K (needs to be <= Tc) Tc : float Curie temperature of the material in K beta : float, optional critical exponent from dynamical scaling theory beta = 1/3 is exact within the theory Return ------ Note ---- * D0_Fe = 280 meV / angstroem^2 * D0_Ni = 430 meV / angstroem^2 """ return D0*(1-T/Tc)**mu
def remove_duplicates(lst): """ Return input list without duplicates. """ seen = [] out_lst = [] for elem in lst: if elem not in seen: out_lst.append(elem) seen.append(elem) return out_lst
def is_postorder(nums): """ :param nums: :return: """ def recur(i,j) : if i >= j : return True p = i while nums[p] < nums[j] : p += 1 m = p while nums[p] > nums[j] : p += 1 return p ==j and recur(i,m-1) and recur(m,j-1) return recur(0,len(nums)-1)
def PosTM2Topo(posTM, seqLength, NtermState):#{{{ """ Get the membrane protein topology by given TM helix segment lists and location of N-terminus posTM : a list of tuples, e.g. [(10,30),(35,44), ...] defining TM segments, index start and end index is not included seqLength : length of the sequence NtermState: location of the N-terminus, in or out return a string defining the topology of TM protein """ # ChangeLog 2014-10-10 # NtermState can be in the format of ["i", "in"], before it was only "i" if NtermState == "": return "" topList = [] statelist = ["i", "o"] idx = 0 if NtermState in ['i', "in", "IN", "I"]: idx = 0 else: idx = 1 state = statelist[idx] if len(posTM) < 1: topList += [state]*seqLength else: for j in range(len(posTM)): state = statelist[idx%2] if j == 0: seglen = posTM[j][0] else: seglen = posTM[j][0] - posTM[j-1][1] topList += [state]*seglen topList += ['M'] * (posTM[j][1]-posTM[j][0]) idx += 1 #print posTM, seqLength if posTM[len(posTM)-1][1] < seqLength: state = statelist[idx%2] topList += [state] * (seqLength - posTM[len(posTM)-1][1]) top = "".join(topList) return top
def average(num1: float, num2: float) -> float: """Return the average of num1 and num2. >>> average(10,20) 15.0 >>> average(2.5, 3.0) 2.75 """ return (num1 + num2) / 2
def handle_empty_item(item): """Handles faulty return values from SSH calls""" try: return float(item) except: return float(999999)
def noid(seq): """ Removes values that are not relevant for the test comparisons """ for d in seq: d.pop('id', None) d.pop('action_id', None) return seq
def get_all(futures, timeout=None): """ Collect all values encapsulated in the list of futures. If ``timeout`` is not :class:`None`, the method will wait for a reply for ``timeout`` seconds, and then raise :exc:`pykka.Timeout`. :param futures: futures for the results to collect :type futures: list of :class:`pykka.Future` :param timeout: seconds to wait before timeout :type timeout: float or :class:`None` :raise: :exc:`pykka.Timeout` if timeout is reached :returns: list of results """ return [future.get(timeout=timeout) for future in futures]
def pi_list_to_str(pi_list): """ Parameters ---------- pi_list list of pi number expressions Returns A string representation ------- """ out_set = "" if len(pi_list) > 0: for i in range(len(pi_list)): if pi_list[i] is not None: out_set += f"pi{i + 1} = {pi_list[i]} | " if len(out_set) > 2: out_set = out_set[:-2] return out_set
def valid_url(url): """ Validate a URL and make sure that it has the correct URL syntax. Args: url (str): URL string to be evaluated. Returns: True if the URL is valid. False if it is invalid. """ if "http://" not in url and "https://" not in url: return False return True
def tenures_burnt(qs, arg=None): """ Usage:: {{ qs|filter_tenures_burnt:"string" }} """ qs = qs.filter(tenure__name=arg) if qs else None return round(qs[0].area, 2) if qs else 0
def lorentzianAmp(x, x0, gamma): """lorentzian peak""" return 1 / (1 + ((x - x0) / gamma)**2)
def lerp(global_step, start_step, end_step, start_val, end_val): """Utility function to linearly interpolate two values.""" interp = (global_step - start_step) / (end_step - start_step) interp = max(0.0, min(1.0, interp)) return start_val * (1.0 - interp) + end_val * interp
def _args_to_recodings(*args, _force_index=False, **kwargs): """Convert arguments to replaceable""" values = {} for i, arg in enumerate(args): if isinstance(arg, dict): values.update(arg) else: values[i] = arg values.update(kwargs) if _force_index: for key in list(values): if isinstance(key, str) and key.isdigit(): values[int(key)] = values.pop(key) return values
def search_entities(raw_text_string, search): """Searches for known entities in a string. Helper function for construct_entity_conet(). Iterates over a list of entities and looks to see if they are present in a given text string. If they are, then it will append the entity to a list for each text. These lists of ents appearing in texts can be used to construct a network of entities that co-occurr within texts. """ ents = [] for entity in search: if entity.lower() in raw_text_string.lower(): ents.append(entity.lower()) return ents
def preceding(iterable, item): """The item which comes in the series immediately before the specified item. Args: iterable: The iterable series in which to search for item. item: The item to search for in iterable. Returns: The previous item. Raises: ValueError: If item is not present in iterable beyond the first item. """ iterator = iter(iterable) try: current = next(iterator) if current == item: raise ValueError(f"No item preceding {item!r} in iterable series") except StopIteration: raise ValueError("Iterable series is empty") previous = current for current in iterator: if current == item: return previous previous = current raise ValueError(f"No item {item!r} in iterable series for which to return the preceding item")
def sort_ipv4(ips): """ Sort a list of ipv4 addresses in ascending order """ for i in range(len(ips)): ips[i] = "%3s.%3s.%3s.%3s" % tuple(ips[i].split(".")) ips.sort() for i in range(len(ips)): ips[i] = ips[i].replace(" ", "") return ips
def check_tags_contain(actual, expected): """Check if a set of AWS resource tags is contained in another Every tag key in `expected` must be present in `actual`, and have the same value. Extra keys in `actual` but not in `expected` are ignored. Args: actual (list): Set of tags to be verified, usually from the description of a resource. Each item must be a `dict` containing `Key` and `Value` items. expected (list): Set of tags that must be present in `actual` (in the same format). """ actual_set = set((item["Key"], item["Value"]) for item in actual) expected_set = set((item["Key"], item["Value"]) for item in expected) return actual_set >= expected_set
def _cachefile(dataset, year, day): """Returns the cache file name for a given day of data.""" return f'cache/{dataset}.{year:04}.{day:02}.html'
def get_fuel_required(module_mass: float) -> float: """Get the fuel required for a module. Args: module_mass: module mass Returns: fueld required to take off """ return int(module_mass / 3.0) - 2.0
def parseTime(t): """ Parses a time value, recognising suffices like 'm' for minutes, 's' for seconds, 'h' for hours, 'd' for days, 'w' for weeks, 'M' for months. >>> endings = {'s':1, 'm':60, 'h':60*60, 'd':60*60*24, 'w':60*60*24*7, 'M':60*60*24*30} >>> not False in [endings[i]*3 == parseTime("3"+i) for i in endings] True Returns time value in seconds """ if not t: raise Exception("Invalid time '%s'" % t) if not isinstance(t, str): t = str(t) t = t.strip() if not t: raise Exception("Invalid time value '%s'"% t) endings = {'s':1, 'm':60, 'h':3600, 'd':86400, 'w':86400*7, 'M':86400*30} lastchar = t[-1] if lastchar in list(endings.keys()): t = t[:-1] multiplier = endings[lastchar] else: multiplier = 1 return int(t) * multiplier
def combine_groups(groups): """Combine :obj:`list` of groups to a single :obj:`str`. Parameters ---------- groups : list of str List of group names. Returns ------- str Combined :obj:`str`. """ new_str = ', '.join(groups) return new_str
def is_iterable(obj): """Portable way to check that an object is iterable""" try: iter(obj) return True except TypeError: return False
def escape(html): """ Returns the given HTML with ampersands, quotes and angle brackets encoded. """ return html.replace('&', '&amp;')\ .replace('<', '&lt;')\ .replace('>', '&gt;')\ .replace('"', '&quot;')\ .replace("'", '&#39;')
def phi(n: int) -> int: """Euler function Parameters: n (int): Number Returns: int: Result """ res, i = n, 2 while i * i <= n: if n % i == 0: while n % i == 0: n //= i res -= res // i i += 1 if n > 1: res -= res // n return res
def _cal_mapped_len(mapped_intervals, chr_name, win_start, win_end): """ Description: Helper function for calculating length of mapped region in a given window. Arguments: mapped_intervals dict: Dictionary of tuples containing mapped regions across the genome. chr_name str: Name of the chromosome for calculating the length of the mapped region. win_start int: Start position of a window. win_end int: End position of a window. Returns: mapped_len int: Length of the mapped region. """ if (mapped_intervals == None) or (chr_name not in mapped_intervals.keys()): mapped_len = win_end - win_start else: overlaps = [(idx[0], idx[1]) for idx in mapped_intervals[chr_name] if (win_start>=idx[0] and win_start<=idx[1]) or (win_end>=idx[0] and win_end<=idx[1]) or (win_start<=idx[0] and win_end>=idx[1])] mapped_len = 0 for idx in overlaps: if (idx[0]<=win_start) and (idx[1]>=win_end): mapped_len += win_end - win_start elif (idx[0]>=win_start) and (idx[1]<=win_end): mapped_len += idx[1] - idx[0] elif (idx[0]<=win_start) and (idx[1]<=win_end): mapped_len += idx[1] - win_start else: mapped_len += win_end - idx[0] mapped_len = mapped_len // 1000 * 1000 return mapped_len
def normalize(numbers): """ normalize :param numbers: :return: """ total = sum(numbers) result = [] for value in numbers: percent = 100 * value / total result.append(percent) return result
def plural(n, s, pl=None): """ Returns a string like '23 fields' or '1 field' where the number is n, the stem is s and the plural is either stem + 's' or stem + pl (if provided). """ if pl is None: pl = 's' if n == 1: return '%s %s' % (n, s) else: return '%s %s%s' % (n, s, pl)
def guideline_amounts_difference_c(responses, derived): """ Return the difference between the guideline amounts to be paid by claimant 1 and claimant 2 for Factsheet C """ try: amount_1 = float(responses.get('your_child_support_paid_c', 0)) except ValueError: amount_1 = 0 try: amount_2 = float(responses.get('your_spouse_child_support_paid_c', 0)) except ValueError: amount_2 = 0 return abs(amount_1 - amount_2)
def tokenize(smiles, tokens): """ Takes a SMILES string and returns a list of tokens. Atoms with 2 characters are treated as one token. The logic references this code piece: https://github.com/topazape/LSTM_Chem/blob/master/lstm_chem/utils/smiles_tokenizer2.py """ n = len(smiles) tokenized = [] i = 0 # process all characters except the last one while (i < n - 1): # procoss tokens with length 2 first c2 = smiles[i:i + 2] if c2 in tokens: tokenized.append(c2) i += 2 continue # tokens with length 2 c1 = smiles[i] if c1 in tokens: tokenized.append(c1) i += 1 continue raise ValueError( "Unrecognized charater in SMILES: {}, {}".format(c1, c2)) # process last character if there is any if i == n: pass elif i == n - 1 and smiles[i] in tokens: tokenized.append(smiles[i]) else: raise ValueError( "Unrecognized charater in SMILES: {}".format(smiles[i])) return tokenized
def truncate(f, n): """ Truncates/pads a float f to n decimal places without rounding """ s = '{}'.format(f) if 'e' in s or 'E' in s: return '{0:.{1}f}'.format(f, n) i, p, d = s.partition('.') return '.'.join([i, (d + '0' * n)[:n]])
def nspath_eval(xpath, nsmap): """Return an etree friendly xpath""" out = [] for chunks in xpath.split('/'): namespace, element = chunks.split(':') out.append('{%s}%s' % (nsmap[namespace], element)) return '/'.join(out)
def findAnEven(L): """assumes L is a list of integers returns the first even number in L Raises ValueError if L does ont contain an even number""" for k in L: if k % 2 == 0 and k>0: return k break raise ValueError('no even numbers provided')
def times_within(time1, time2, gap): """Checks whether the gap between two times is less than gap""" if time1 is None or time2 is None: return None return abs(time1 - time2) < gap
def minimum_absolute_difference(arr): """https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array""" sorted_array = sorted(arr) return min(abs(x - y) for x, y in zip(sorted_array, sorted_array[1:]))
def get_errors(cm, i): """Get the sum of all errornous classified samples of class i.""" n = len(cm) return sum([cm[i][j] for j in range(n)])
def solve(grades): """ Return grades rounded up to nearest 5 if above 38, otherwise, do not round the score. """ rounded_grades = [] for grade in grades: if grade >= 38: rounded = ((grade + 5) / 5) * 5 if rounded - grade < 3: grade = rounded rounded_grades.append(grade) return rounded_grades
def split_call(lines, open_paren_line=0): """Returns a 2-tuple where the first element is the list of lines from the first open paren in lines to the matching closed paren. The second element is all remaining lines in a list.""" num_open = 0 num_closed = 0 for i, line in enumerate(lines): c = line.count('(') num_open += c if not c and i==open_paren_line: raise Exception('Exception open parenthesis in line %d but there is not one there: %s' % (i, str(lines))) num_closed += line.count(')') if num_open == num_closed: return (lines[:i+1], lines[i+1:]) print(''.join(lines)) raise Exception('parenthesis are mismatched (%d open, %d closed found)' % (num_open, num_closed))
def utc_time(source): """Convert source bytes to UTC time as (H, M, S) triple HHMMSS.000 >>> utc_time(b'123456.000') (12, 34, 56.0) """ if source: return int(source[:2]), int(source[2:4]), float(source[4:]) return None, None, None
def lempel_ziv_complexityLOCAL(binary_sequence): """ Manual implementation of the Lempel-Ziv complexity. It is defined as the number of different substrings encountered as the stream is viewed from begining to the end. As an example: >>> s = '1001111011000010' >>> lempel_ziv_complexity(s) # 1 / 0 / 01 / 1110 / 1100 / 0010 6 Marking in the different substrings the sequence complexity :math:`\mathrm{Lempel-Ziv}(s) = 6`: :math:`s = 1 / 0 / 01 / 1110 / 1100 / 0010`. - See the page https://en.wikipedia.org/wiki/Lempel-Ziv_complexity for more details. Other examples: >>> lempel_ziv_complexity('1010101010101010') # 1 / 0 / 10 3 >>> lempel_ziv_complexity('1001111011000010000010') # 1 / 0 / 01 / 1110 / 1100 / 0010 / 000 / 010 7 >>> lempel_ziv_complexity('100111101100001000001010') # 1 / 0 / 01 / 1110 / 1100 / 0010 / 000 / 010 / 10 8 - Note: it is faster to give the sequence as a string of characters, like `'10001001'`, instead of a list or a numpy array. - Note: see this notebook for more details, comparison, benchmarks and experiments: https://Nbviewer.Jupyter.org/github/Naereen/Lempel-Ziv_Complexity/Short_study_of_the_Lempel-Ziv_complexity.ipynb - Note: there is also a Cython-powered version, for speedup, see :download:`lempel_ziv_complexity_cython.pyx`. """ u, v, w = 0, 1, 1 v_max = 1 length = len(binary_sequence) complexity = 1 while True: if binary_sequence[u + v - 1] == binary_sequence[w + v - 1]: v += 1 if w + v >= length: complexity += 1 break else: if v > v_max: v_max = v u += 1 if u == w: complexity += 1 w += v_max if w > length: break else: u = 0 v = 1 v_max = 1 else: v = 1 return complexity
def c2f(celsius): """ Covert Celsius to Fahrenheit :param celsius: [float] Degrees Celsius :return: [float] Degrees Fahrenheit """ return (9 / 5 * celsius) + 32
def query_for_id(sql, keys, trg_db): """Execute the provided sql string on the target database. Issue a meaningful error message contianing keys_as_string if there is a problem. Arguments: - `sql`:a sql statement that is intended t oretrieve the id of a parent record. The sql string should return a scalar value (id) - `keys_as_string`: nicely formatted string contianing the key-values pairs in sql - `trg_db`: path a sqlite database """ # trg_conn = sqlite3.connect(trg_db, uri=True) # trg_cur = trg_conn.cursor() # rs = trg_cur.execute(sql) # try: # id = rs.fetchone()[0] # except: # msg = "Unable to find record with key values: \n{}" # print(msg.format(keys)) # id = None # finally: # trg_conn.close() # return id import sqlite3 as db with db.connect(trg_db) as trg_conn: trg_cur = trg_conn.cursor() try: rs = trg_cur.execute(sql) id = rs.fetchone()[0] except: msg = "Unable to find record with key values: \n{}" print(msg.format(keys)) id = None return id