content
stringlengths
42
6.51k
def _guess_format_from_name(path): """Get file format by name. Parameters ---------- path : str Path to file. Returns ------- str File format as a string. """ import os fname = os.path.basename(path) if fname.endswith('.nc'): return 'netcdf' elif fname.endswith('.asc'): return 'esri-ascii' else: return None
def CeilLog10Pow2(e): """Returns ceil(log_10(2^e))""" assert e >= -1650 assert e <= 1650 return (int(e) * 78913 + (2**18 - 1)) // 2**18
def l2o(path): """ Formats a list (['bla',0,'bla']) into an ODS path format ('bla.0.bla') :param path: list of strings and integers :return: ODS path format """ return '.'.join(filter(None, map(str, path)))
def aggregate_scores_max(scores: list): """ Aggregate the given scores by choosing the highest one """ if not scores: return "N/A" end_score = -1 for score in scores: try: score = float(score) except ValueError: continue if score > end_score: end_score = score end_score = max(0, end_score) # ensure score is >= 0 end_score = min(10, end_score) # ensure score is <= 10 return end_score
def sum_non_red(obj: object) -> int: """The sum of all numbers except from maps with a \"red\" property.""" if isinstance(obj, int): return obj if isinstance(obj, str): return 0 if isinstance(obj, list): return sum(map(sum_non_red, obj)) if isinstance(obj, dict): if 'red' in obj.values(): return 0 return sum(map(sum_non_red, obj.values())) raise TypeError('Unexpected type: {}'.format(type(obj)))
def set_cover(X, subsets): """ This algorithm finds an approximate solution to finding a minimum collection of subsets that cover the set X. It is shown in lecture that this is a (1 + log(n))-approximation algorithm. """ cover = set() subsets_copy = list(subsets) while True: S = max(subsets_copy, key=len) if len(S) == 0: break cover.add(subsets.index(S)) subsets_copy.pop(subsets_copy.index(S)) for x in S: for T in subsets_copy: if x in set(T): T.remove(x) return cover
def validate(compression): """ Validate the compression string. Parameters ---------- compression : str, bytes or None Returns ------- compression : str or None In canonical form. Raises ------ ValueError """ if not compression or compression == b'\0\0\0\0': return None if isinstance(compression, bytes): compression = compression.decode('ascii') compression = compression.strip('\0') if compression not in ('zlib', 'bzp2', 'lz4', 'input'): raise ValueError( "Supported compression types are: 'zlib', 'bzp2', 'lz4', or 'input'") return compression
def ensure_safe_url(url): """Ensure the GenePattern URL ends with /gp""" if url.endswith('/'): url = url[:-1] if not url.endswith('/gp'): url += '/gp' return url
def _clean_archive_file_format(fmt: str) -> str: """Cleans the given file format string""" return fmt.lower().strip('.').strip(':')
def generate_pod_numbers(n_users, n_per_group): """ Generate pod numbers in sequence """ groups = [] for i in range(1, int(n_users / n_per_group) + 2): groups.extend([i] * n_per_group) groups = groups[:n_users] return groups
def str_to_int(string_list): """ convert list of hex strings into list of ints """ int_list = [int(x, 16) for x in string_list] return int_list
def replace_gll_link(py, simulation_directory, new_gll_directory): """ replace all gll links. """ script = f"{py} -m seisflow.scripts.structure_inversion.replace_gll_link --simulation_directory {simulation_directory} --new_gll_directory {new_gll_directory}; \n" return script
def min_count1(lst): """ Get minimal value of list, version 1 :param lst: Numbers list :return: Minimal value and its count on the list """ if len(lst) == 0: return [] count = 0 min_value = lst[0] for num in lst: if num == min_value: count += 1 elif num < min_value: count = 1 min_value = num return [min_value, count]
def find_startswith_endswith(arg_list, key, value): """Checks '--<key>anything<value>' is in arg_list.""" for i in range(len(arg_list)): if arg_list[i].startswith(key) and arg_list[i].endswith(value): return True return False
def get_features_name(npcs): """ Create the list of feature names depending on the number of principal components. Parameters ---------- npcs : int number of principal components to use Returns ------- list name of the features. """ names_root = [ 'coeff' + str(i + 1) + '_' for i in range(npcs)] + [ 'residuo_', 'maxflux_'] return [i + j for j in ['g', 'r'] for i in names_root]
def single_byte_to_hex(single_char): """ Read a single, decimal byte from the user and return a string of its hexidecimal value. This string should use lowercase and should always be exactly two characters long. Make sure you pad the beginning with a 0 if necessary, and make sure the string does NOT start with '0x'. Example test case: 255 -> "ff" """ hexaRep = (hex(int(single_char))) return hexaRep[2:]
def anagram_lst(str1, str2): """ This function takes two strings and compares if they are Anagram using Lists.""" return sorted(list(str1.lower())) == sorted(list(str2.lower()))
def escape_for_bash(str_to_escape): """ This function takes any string and escapes it in a way that bash will interpret it as a single string. Explanation: At the end, in the return statement, the string is put within single quotes. Therefore, the only thing that I have to escape in bash is the single quote character. To do this, I substitute every single quote ' with '"'"' which means: First single quote: exit from the enclosing single quotes Second, third and fourth character: "'" is a single quote character, escaped by double quotes Last single quote: reopen the single quote to continue the string Finally, note that for python I have to enclose the string '"'"' within triple quotes to make it work, getting finally: the complicated string found below. """ if str_to_escape is None: return '' str_to_escape = str(str_to_escape) escaped_quotes = str_to_escape.replace("'", """'"'"'""") return f"'{escaped_quotes}'"
def name_2_id(str_name_id): """Returns the number of a numbered object. For example: "Frame 3", "Frame3", "Fram3 3" returns 3.""" import re numbers = re.findall(r'[0-9]+', str_name_id) if len(numbers) > 0: return float(numbers[-1]) return -1
def txx(x): # pylint: disable=no-else-return """Converts tempint integer to flag. Returns: Temporal interpolation flag for smooth HDF5 filename """ if x: if int(x) == 5: return 'p' elif int(x) == 10: return 'd' else: return 'c' else: return 'n'
def _isnumber(obj): """ Function copied from putil.misc module to avoid import loops """ return ( (((obj is not None) and (not isinstance(obj, bool)) and (isinstance(obj, int) or isinstance(obj, float) or isinstance(obj, complex)))) )
def align_addr(addr: int, to_bytes: int = 8) -> int: """ align an address to `to_bytes` (meaning addr & to_bytes = 0) """ return addr + (-addr % to_bytes)
def massage(depender, components, packages): """ @param depender: A DependerData object @param components: Component names, in either package/component format, or just "naked" (hopefully unique) components. @param packages: Package names, which expand into their constituent components. @return A set of all components specified. """ ret = set() for package in packages: ret.update(depender.expand_package(package)) for component in components: if "/" in component: ret.add( tuple(component.split("/", 2)) ) else: ret.add( depender.resolve_unqualified_component(component) ) return ret
def convert_to_seconds(time): """list -> number Given a list of four numbers: days, hours, minutes, and seconds, write the function convert_to_seconds that computes the total number of seconds that is equivalent to them. >>> convert_to_seconds([0, 0, 2, 3]) 123 >>> convert_to_seconds([0, 1, 0, 0]) 3600 """ return time[0]*86400+time[1]*3600+time[2]*60+time[3]
def HSW_offset(r, rs, alpha, Rv, beta, deltac, offset): """ HSW (Hamaus-Sutter-Wendelt) function for the universal void density profile See: Hamaus et al. (2014) """ numerator = 1-(r/rs)**alpha denominator = 1+(r/Rv)**beta return deltac*numerator/denominator +offset
def unique2(s): """Implement an algorithm to determine if a string has all unique characters.""" # O(n) time, O(n) space return len(set(s)) == len(s)
def is_cutg_label(x): """Checks if x looks like a CUTG label line.""" return x.startswith('>')
def as_list(arg): """Convenience function used to make sure that a sequence is always represented by a list of symbols. Sometimes a single-symbol sequence is passed in the form of a string representing the symbol. This has to be converted to a one-item list for consistency, as a list of symbols is what many of the following functions expect. """ if isinstance(arg, str): listed_arg = [arg] else: listed_arg = arg[:] return listed_arg
def replace_at(span, string, pattern): """Return a copy of `string` where the `span` range is replaced by `pattern`. """ start, end = span return string[:start] + pattern + string[end:]
def utrue(x,y): """ Return true solution for a test case where this is known. This function should satisfy u_{xx} + u_{yy} = 0. """ utrue = x**2 - y**2 return utrue
def num_to_alpha(num): """ Convert a number > 0 and < 24 into it's Alphabetic equivalent """ num = int(num) # Ensure num is an int if num < 0: raise ValueError("wtf? num_to_alpha doesn't like numbers less than 0...") if num > 24: raise ValueError("seriously? there's no way you have more than 24 objectives...") return chr(65 + num)
def _conv_general_param_type_converter(window_strides, lhs_dilation, rhs_dilation, dim): """Convert strides, lhs_dilation, rhs_dilation to match TF convention. For example, in the 3D case, if lhs_dilation = 2, then convert it to [2, 2, 2] if lhs_dilation = (2, 2, 2), convert it also to [2, 2, 2] Args: window_strides: window_strides to be converted lhs_dilation: lhs_dilation to be converted rhs_dilation: rhs_dilation to be converted dim: dim to be converted Returns: The updated window_strides, lhs_dilation and rhs_dilation """ def _as_list_of_size(item, size): if item is None: return None return [item] * size if isinstance(item, int) else list(item) return (_as_list_of_size(window_strides, dim), _as_list_of_size(lhs_dilation, dim), _as_list_of_size(rhs_dilation, dim))
def Block_f(name, text): """ :param name: The "name" of this Block :param text: The "text" of this Block """ return '\\begin{block}{' + name + '}\n' + text + '\n\\end{block}\n'
def _generate_layer_name(name, branch_idx=None, prefix=None): """Utility function for generating layer names. If `prefix` is `None`, returns `None` to use default automatic layer names. Otherwise, the returned layer name is: - PREFIX_NAME if `branch_idx` is not given. - PREFIX_Branch_0_NAME if e.g. `branch_idx=0` is given. # Arguments name: base layer name string, e.g. `'Concatenate'` or `'Conv2d_1x1'`. branch_idx: an `int`. If given, will add e.g. `'Branch_0'` after `prefix` and in front of `name` in order to identify layers in the same block but in different branches. prefix: string prefix that will be added in front of `name` to make all layer names unique (e.g. which block this layer belongs to). # Returns The layer name. """ if prefix is None: return None if branch_idx is None: return '_'.join((prefix, name)) return '_'.join((prefix, 'Branch', str(branch_idx), name))
def word2wid(word, word2id_dict, OOV="<oov>"): """ Transform single word to word index. :param word: a word :param word2id_dict: a dict map words to indexes :param OOV: a token that represents Out-of-Vocabulary words :return: int index of the word """ for each in (word, word.lower(), word.capitalize(), word.upper()): if each in word2id_dict: return word2id_dict[each] return word2id_dict[OOV]
def _ternary_search_float(f, left, right, tol): """Trinary search: minimize f(x) over [left, right], to within +/-tol in x. Works assuming f is quasiconvex. """ while right - left > tol: left_third = (2 * left + right) / 3 right_third = (left + 2 * right) / 3 if f(left_third) < f(right_third): right = right_third else: left = left_third return (right + left) / 2
def htmlize(value): """ Turn any object into a html viewable entity. """ return str(value).replace('<', '&lt;').replace('>', '&gt;')
def remove_all(original_list:list, object_to_be_removed): """ Removes object_to_be_removed in list if it exists and returns list with removed items """ return [i for i in original_list if i != object_to_be_removed]
def get_signal_annotations(func): """Attempt pulling python 3 function annotations off of 'func' for use as a signals type information. Returns an ordered nested tuple of (return_type, (arg_type1, arg_type2, ...)). If the given function does not have annotations then (None, tuple()) is returned. """ arg_types = tuple() return_type = None if hasattr(func, '__annotations__'): # import inspect only when needed because it takes ~10 msec to load import inspect spec = inspect.getfullargspec(func) arg_types = tuple(spec.annotations[arg] for arg in spec.args if arg in spec.annotations) if 'return' in spec.annotations: return_type = spec.annotations['return'] return return_type, arg_types
def plus_replacement(random, population, parents, offspring, args): """Performs "plus" replacement. This function performs "plus" replacement, which means that the entire existing population is replaced by the best population-many elements from the combined set of parents and offspring. .. Arguments: random -- the random number generator object population -- the population of individuals parents -- the list of parent individuals offspring -- the list of offspring individuals args -- a dictionary of keyword arguments """ pool = list(offspring) pool.extend(parents) pool.sort(reverse=True) survivors = pool[:len(population)] return survivors
def bool_or_empty(string): """Function to convert boolean string to bool (or None if string is empty)""" if string: return bool(strtobool(string)) else: return None
def add_zero(s: str, i: int) -> str: """ Adds "0" as a suffix or prefix if it needs it. """ if "." in s and len(s.split(".")[1]) == 1: return s + "0" if i != 0 and len(s) == 4: return "0" + s return s
def get_dim_names_for_variables(variables): """ Analyses variables to gather a list of dimension (coordinate) names. These are returned as a set of dimension names. """ return {dim for v in variables for dim in v.dims}
def get_unicode_dicts(iterable): """ Iterates iterable and returns a list of dictionaries with keys and values converted to Unicode >>> gen = ({'0': None, 2: 'two', u'3': 0xc0ffee} for i in range(3)) >>> get_unicode_dicts(gen) [{u'2': u'two', u'0': None, u'3': u'12648430'}, {u'2': u'two', u'0': None, u'3': u'12648430'}, {u'2': u'two', u'0': None, u'3': u'12648430'}] """ def none_or_unicode(val): return str(val) if val is not None else val rows = [] for row in iterable: rows.append({str(k): none_or_unicode(v) for k, v in row.items()}) return rows
def classify_type(type): """ Reclassify the museums using Iain's classification """ type = type[:5].upper() # because they can be a bit inconsistent on wikipedia if type == 'AGRIC': classifed_type = 'Local' elif type == 'AMUSE': classifed_type = 'Other' elif type == 'ARCHA': classifed_type = 'Historic' elif type == 'ART': classifed_type = 'Arts' elif type == 'AUTOM': classifed_type = 'Transport' elif type == 'AVIAT': classifed_type = 'Transport' elif type == 'BIOGR': classifed_type = 'Local' elif type == 'ENVIR': classifed_type = 'Local' elif type == 'FASHI': classifed_type = 'Arts' elif type == 'HISTO': classifed_type = 'Historic' elif type == 'INDUS': classifed_type = 'Industrial' elif type == 'LAW E': classifed_type = 'Local' elif type == 'LIVIN': classifed_type = 'Local' elif type == 'LOCAL': classifed_type = 'Local' elif type == 'MARIT': classifed_type = 'Transport' elif type == 'MEDIA': classifed_type = 'Arts' elif type == 'MEDIC': classifed_type = 'Other' elif type == 'MILIT': classifed_type = 'Other' elif type == 'MILL': classifed_type = 'Industrial' elif type == 'MININ': classifed_type = 'Industrial' elif type == 'MULTI': classifed_type = 'Multiple' elif type == 'MUSIC': classifed_type = 'Other' elif type == 'NATUR': classifed_type = 'Other' elif type == 'OPEN ': classifed_type = 'Other' elif type == 'PHILA': classifed_type = 'Other' elif type == 'PHOTO': classifed_type = 'Arts' elif type == 'PRISO': classifed_type = 'Local' elif type == 'RAILW': classifed_type = 'Transport' elif type == 'RELIG': classifed_type = 'Other' elif type == 'RURAL': classifed_type = 'Other' elif type == 'SCIEN': classifed_type = 'Other' elif type == 'SPORT': classifed_type = 'Other' elif type == 'TECHN': classifed_type = 'Other' elif type == 'TEXTI': classifed_type = 'Arts' elif type == 'TOY': classifed_type = 'Arts' elif type == 'TRANS': classifed_type = 'Transport' else: classifed_type = 'Other' return classifed_type
def new_func(message): """ new func :param message: :return: """ def get_message(message): """ get message :param message: :return: """ print('Got a message:{}'.format(message)) return get_message(message)
def is_triangular_matrix(matrix, expected_dim): """ Checks that matrix is actually triangular and well-encoded. :param matrix: the checked matrix :type matrix: list of list :param expected_dim: the expected length of the matrix == number of rows == diagonal size :type expected_dim: """ if type(matrix) is not list: return False current_dim = expected_dim for row in matrix: if (type(row) is not list) or (len(row) != current_dim): return False current_dim = current_dim - 1 # finally testing that number of rows is expected_dim: return current_dim == 0
def get_errno(e): """ Return the errno of an exception, or the first argument if errno is not available. :param Exception e: the exception object """ try: return e.errno except AttributeError: return e.args[0]
def my_round_even(number): """ Simplified version from future """ from decimal import Decimal, ROUND_HALF_EVEN d = Decimal.from_float(number).quantize(1, rounding=ROUND_HALF_EVEN) return int(d)
def ckstr(checksum): """Return a value as e.g. 'FC8E', i.e. an uppercase hex string with no leading '0x' or trailing 'L'. """ return hex(checksum)[2:].rstrip('L').upper()
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 """ new_board = board[1:6] new_lst = [] for els in new_board: new_lst += [els[1:6]] for elo in new_lst: for i in range(5): if elo.count(elo[i]) > 1: return False return True
def decodeServiceStatusFrame(ba, frameLength, reserved_2_24, isDetailed): """Decode a Service Status frame. Args: ba (byte array): Contains all the bytes of the frame. frameLength (int): Holds the current length of this frame. reserved_2_24 (byte): Reserved bits in frame header. isDetailed (bool): ``True`` if a full blown decode is to be done. ``False`` is normal decoding for the usual FIS-B products. Detailed includes those items not normally needed for routine decoding. Returns: dict: Dictionary with decoded data. Raises: ServiceStatusException: Got a service type of 0 which should not happen. """ # Dictionary to store items d = {} # List with planes being followed planeList = [] d['frame_type'] = 15 if isDetailed: d['frameheader_2_24'] = reserved_2_24 # Loop for each plane being followed. Each set of 4 bytes is an # entry. for x in range(0, int(frameLength/4)): x4 = x * 4 byte0 = ba[x4] addr = (ba[x4 + 1] << 16) | \ (ba[x4 + 2] << 8) | \ (ba[x4 + 3]) byte1_1_4 = (byte0 & 0xF0) >> 4 signalType = (byte0 & 0x08) >> 3 addrType = byte0 & 0x07 entry = {} if isDetailed: entry['byte1_1_4'] = byte1_1_4 entry['signal_type'] = signalType # always 1 # See definitions above. This is pretty much always 0. entry['address_type'] = addrType # ICAO address in hex entry['address'] = '{:06x}'.format(addr) planeList.append(entry) d['contents'] = planeList return d
def trim_taxon(taxon: str, int_level: int) -> str: """ taxon_hierarchy: '1|2|3|4|5|6|7' level: 5 output: '1|2|3|4|5' """ return '|'.join(taxon.split('|')[:int_level])
def _set_single_element_or_all_in_list(obj, key, value): """mutates obj, list of dict or dict""" if isinstance(obj, list): for element in obj: element[key] = value else: obj[key] = value return obj
def _M_b_fi_t_Rd(chi_LT_fi, W_y, k_y_theta_com, f_y, gamma_M_fi): """ [Eq. 5.61] :param chi_LT_fi: Reduction factor for lateral-torsion buckling in the fire design situation :param W_y: Sectional modulus (plastic for class 1 steel) :param k_y_theta_com: Reduction factor for yield strength at elevated temperature :param f_y: Steel yield strength :param gamma_M_fi: Partial safety factor :return M_b_fi_t_Rd: The resistant lateral torsion bending moment """ M_b_fi_t_Rd = chi_LT_fi * W_y * k_y_theta_com * f_y / gamma_M_fi return M_b_fi_t_Rd
def get_view_scope_by_dicom_dict(dicom_dict): """ If you set View Scope, the computing time of algorithm will be reduced. But the side effect is that maybe you don't know what the best view scope for each patient's case. There is some patient's case that is not scanned in middle position. So finally, I think return 512x512 is the best value because pixel_array in CT is 512x512 size. :param dicom_dict: :return: """ return (0, 512, 0, 512)
def example_allow(actuator, *extra_args, **extra_kwargs): """ Example target function for example-allow Any parameter of an OpenC2-Command message can be used as an argument [action, actuator, args, id as cmd_id, target] Target will be the contents of the target object :param actuator: the instance of the actuator that called the function :param extra_args: positional arguments passed to the function - list :param extra_kwargs: keyword arguments passed to the function - dict :return: OpenC2 response message - dict """ return dict( status=400, status_text='this is an example action, it returns this message' )
def add_chr_prefix(band): """ Return the band string with chr prefixed """ return ''.join(['chr', band])
def augmented_matrix(A, b): """returns the augmented matrix, assuming A is a square matrix""" aug, n = [], len(A) for i in range(n): t = A[i] t.append(b[i]) aug.append(t) return aug
def hoop_pressure_thin(t, D_o, P_o, sig): """Return the internal pressure [Pa] that induces a stress, sig, in a thin wall pipe of thickness t - PD8010-2 Equation (3). :param float t: Wall thickness [m] :param float D_o: Outside diamter [m] :param float P_o: External pressure [Pa] :param float sig: Stress [Pa] """ return ((sig * 2 * t) / D_o) + P_o
def perm0db(ind, beta=10.): """Perm function 0, D, BETA defined as: $$ f(x) = \sum_{i=1}^n (\sum_{j=1}^n (j+\beta) (x_j^i - \frac{1}{j^i}) )^2$$ with a search domain of $-n < x_i < n, 1 \leq i \leq n$. The global minimum is at $f(x_1, ..., x_n) = f(1, 2, ..., n) = 0. """ return sum(( \ ( sum(( (j+1.+beta) * ((ind[j])**float(i+1) - 1./(float(j+1)**float(i+1))) for j in range(len(ind)) )) )**2. \ for i in range(len(ind)) )),
def space_indentation(s): """The number of leading spaces in a string :param str s: input string :rtype: int :return: number of leading spaces """ return len(s) - len(s.lstrip(" "))
def move_right(board, row): """Move the given row to one position right""" board[row] = board[row][-1:] + board[row][:-1] return board
def uses_all(word, letters): """return True if the word use all the letters""" for letter in letters: if letter not in word: return False return True
def epsilonEffective(epsilon1=0.9, epsilon2=0.9): """ This function simply calculates the epsilon effective if you don't give the value for epsiln one or two it will consider it to be 0.9 by default""" result=1/(1/epsilon1+1/epsilon2-1) return result
def filter_dict(kv, p): """Given a dictionary, returns a new one retaining only pairs satisfying the predicate.""" return { k:v for k,v in kv.items() if p(k,v) }
def from_file(path): """Returns content of file as 'bytes'. """ with open(path, 'rb') as f: content = f.read() return content
def __checkInitdbParams(param): """ function : Check parameter for initdb -D, --pgdata : this has been specified in configuration file -W, --pwprompt: this will block the script --pwfile: it is not safe to read password from file -A, --auth,--auth-local,--auth-host: They will be used with '--pwfile' -c, --enpasswd: this will confuse the default password in script with the password user specified -Z: this has been designated internal -U --username: use the user specified during install step input : String output : Number """ shortInvalidArgs = ("-D", "-W", "-C", "-A", "-Z", "-U", "-X", "-s") longInvalidArgs = ( "--pgdata", "--pwprompt", "--enpasswd", "--pwfile", "--auth", "--auth-host", "--auth-local", "--username", "--xlogdir", "--show") argList = param.split() for arg in shortInvalidArgs: if (arg in argList): return 1 argList = param.split("=") for arg in longInvalidArgs: if (arg in argList): return 1 return 0
def _lz_complexity(binary_string): """Internal Numba implementation of the Lempel-Ziv (LZ) complexity. https://github.com/Naereen/Lempel-Ziv_Complexity/blob/master/src/lziv_complexity.py - Updated with strict integer typing instead of strings - Slight restructuring based on Yacine Mahdid's notebook: https://github.com/BIAPT/Notebooks/blob/master/features/Lempel-Ziv%20Complexity.ipynb """ # Initialize variables complexity = 1 prefix_len = 1 len_substring = 1 max_len_substring = 1 pointer = 0 # Iterate until the entire string has not been parsed while prefix_len + len_substring <= len(binary_string): # Given a prefix length, find the largest substring if ( binary_string[pointer + len_substring - 1] == binary_string[prefix_len + len_substring - 1] ): len_substring += 1 # increase the length of the substring else: max_len_substring = max(len_substring, max_len_substring) pointer += 1 # Since all pointers have been scanned, pick largest as the jump size if pointer == prefix_len: # Increment complexity complexity += 1 # Set prefix length to the max substring size found so far (jump size) prefix_len += max_len_substring # Reset pointer and max substring size pointer = 0 max_len_substring = 1 # Reset length of current substring len_substring = 1 # Check if final iteration occurred in the middle of a substring if len_substring != 1: complexity += 1 return complexity
def det_new_group(i, base=0): """Determine if new_group should be added to pipetting operation. Helper to determine if new_group should be added. Returns true when i matches the base, which defaults to 0. Parameters ---------- i : int The iteration you are on base : int, optional The value at which you want to trigger Returns ------- bool Raises ------ ValueError If i is not of type integer ValueError If base is not of type integer """ assert isinstance(i, int), "Needs an integer." assert isinstance(base, int), "Base has to be an integer" if i == base: new_group = True else: new_group = False return new_group
def next(aList, index): """ Return the index to the next element (compared to the element with index "index") in aList, or 0 if it already is the last one. Useful to make a list of loop. """ return (index+1) % len(aList)
def validate_environment_state(environment_state): """Validate response type :param environment_state: State of the environment :return: The provided value if valid Property: ComputeEnvironment.State """ valid_states = ["ENABLED", "DISABLED"] if environment_state not in valid_states: raise ValueError( "{} is not a valid environment state".format(environment_state) ) return environment_state
def get_odd_flags(odd_flags, blocks, flag_input=False): """Reverse the odd_flag list from the encoder""" odd_list = [flag_input] for odd_block in odd_flags: odd_list += odd_block # reverse odd_list.reverse() odd_de = blocks.copy() i = 0 for m, odd_block in enumerate(odd_de): odd_de[m] = blocks[m].copy() for n, bottle in enumerate(odd_block): odd_de[m][n] = odd_list[i+1] i += 1 return odd_de
def get_relevant_lines(makeoutput): """ Remove everything from make output, that is not a makefile annotation and shell debug output, but leaves the + sign in front of them """ return [line for line in makeoutput.splitlines() if line.startswith("make") or line.startswith("+")]
def binary_to_decimal(binary): """Convert Binary to Decimal. Args: binary (str): Binary. Returns: int: Return decimal value. """ return int(binary, 2)
def intersect(list1, list2) -> bool: """Do list1 and list2 intersect""" if len(set(list1).intersection(set(list2))) == 0: return False return True
def modes(nums): """Returns the most frequently occurring items in the given list, nums""" if len(nums) == 0: return [] # Create a dictionary of numbers to how many times they occur in the list frequencies = {} for num in nums: frequencies[num] = 1 + frequencies.get(num, 0) # How many times each mode occurs in nums: max_occurrences = max(frequencies.values()) return [num for num, frequency in frequencies.items() if frequency == max_occurrences]
def geometric_to_geopotential(z, r0): """Converts from given geometric altitude to geopotential one. Parameters ---------- z: float Geometric altitude. r0: float Planet/Natural satellite radius. Returns ------- h: float Geopotential altitude. """ h = r0 * z / (r0 + z) return h
def _compute_x_crossing( x1: float, y1: float, x2: float, y2: float, y_star: float) -> float: """Approximates the x value at which f(x) == y*. Args: x1: An x value. y1: f(x1). x2: An x value, where x2 > x1. y2: f(x2). y_star: The search value in [y1, y2]. Returns: The x value that gives f(x) = y*, calculated with a linear approximation. """ if y_star < min(y1, y2) or y_star > max(y1, y2): raise ValueError('y_star must be in [y1, y2].') if x1 >= x2: raise ValueError('x2 must be greater than x1.') if y1 == y2: raise ValueError('y1 may not be equal to y2.') alpha = abs((y_star - y1) / (y2 - y1)) return alpha * (x2 - x1) + x1
def _instance_tags(hostname, role): """Create list of AWS tags from manifest.""" tags = [{'Key': 'Name', 'Value': hostname.lower()}, {'Key': 'Role', 'Value': role.lower()}] return [{'ResourceType': 'instance', 'Tags': tags}]
def calc_bmi(mass, height): """Calculates BMI from specified height and mass BMI(kg/m2) = mass(kg) / height(m)2 Arguments: mass {float} -- mass of the person in KG height {float} -- height of the person in meters Returns: bmi {float} -- Body Mass Index of the person from specified mass and height """ bmi = mass/(height**2) bmi = round(bmi, 1) # rounding off to 1 digit after decimal return bmi
def fibonacci_loop(n): """ :param n: F(n) :return: val """ if n == 0: return 0 cache = [0,1] for i in range(n-2): cache[0],cache[1] =cache[1], cache[0] + cache[1] return cache[0] + cache[1]
def non_strict_impl(a, b): """Non-strict implication Arguments: - `a`: a boolean - `b`: a boolean """ if a == False: return True elif a == True: return b elif b == True: return True else: return None
def _parse_to_key_and_indices(key_strings): """given an arg string list, parse out into a dict assumes a format of: key=indices NOTE: this is for smart indexing into tensor dicts (mostly label sets) Returns: list of tuples, where tuple is (dataset_key, indices_list) """ ordered_keys = [] for key_string in key_strings: key_and_indices = key_string.split("=") key = key_and_indices[0] if len(key_and_indices) > 1: indices = [int(i) for i in key_and_indices[1].split(",")] else: indices = [] ordered_keys.append((key, indices)) return ordered_keys
def get_shingles(sentence, n): """ Function to reveal hidden similarity edges between tweet-nodes based on SimHash, an LSH approximation on TF-IDF vectors and a cosine similarity threshold. Args: sentence (str): The sentence (preprocessed text from a tweet-node), from which the shingles will be created. n (int): The size of the shingle. In this case, the size is always set to be three, and it means that all possible tuples with three consecutive words will be created. Returns: A list with all triples made by consecutive words in a sentence. """ s = sentence.lower() return [s[i:i + n] for i in range(max(len(s) - n + 1, 1))]
def station_name_udf(name): """Replaces '/' with '&'.""" return name.replace("/", "&") if name else None
def copy_phrase_target(phrase: str, current_text: str, backspace='<'): """Determine the target for the current CopyPhrase sequence. >>> copy_phrase_target("HELLO_WORLD", "") 'H' >>> copy_phrase_target("HELLO_WORLD", "HE") 'L' >>> copy_phrase_target("HELLO_WORLD", "HELLO_WORL") 'D' >>> copy_phrase_target("HELLO_WORLD", "HEA") '<' >>> copy_phrase_target("HELLO_WORLD", "HEAL") '<' """ try: # if the current_display is not a substring of phrase, there is a mistake # and the backspace should be the next target. phrase.index(current_text) return phrase[len(current_text)] except ValueError: return backspace
def format_configuration(name, value, nearest, path, item_type): """Helper function for formating configuration output :param str name: name of the section being set, eg. paging or log :param str value: new value of the section :param str nearest: value of the nearest set section :param str path: path to the nearest set section :param str item_type: type of the setting, eg. blank, radio or edit :return: dictionary with configuration settings """ name = name.replace('_', ' ') if (name == "paging"): item_type = "radio" elif (name == "type"): item_type = "blank" return { 'name': name, 'value': value, 'nearest': nearest, 'path': path, 'type': item_type, }
def add_file_to_tree(tree, file_path, file_contents, is_executable=False): """Add a file to a tree. Args: tree A list of dicts containing info about each blob in a tree. file_path The path of the new file in the tree. file_contents The (UTF-8 encoded) contents of the new file. is_executable If ``True``, the new file will get executable permissions (0755). Otherwise, it will get 0644 permissions. Returns: The provided tree, but with the new file added. """ record = { "path": file_path, "mode": "100755" if is_executable else "100644", "type": "blob", "content": file_contents, } tree.append(record) return tree
def readonly_safe_field_as_twoline_table_row(field_label, field_value): """See readonly_field_as_table_row(). """ return {'field_label': field_label, 'field_value': field_value}
def convert_result(result, img_metas): """convert the result""" if result is None: return result bboxes = result.get("MxpiObject") for bbox in bboxes: bbox['x0'] = max(min(bbox['x0']/img_metas[3], img_metas[1]-1), 0) bbox['x1'] = max(min(bbox['x1']/img_metas[3], img_metas[1]-1), 0) bbox['y0'] = max(min(bbox['y0']/img_metas[2], img_metas[0]-1), 0) bbox['y1'] = max(min(bbox['y1']/img_metas[2], img_metas[0]-1), 0) mask_height = bbox['imageMask']['shape'][1] mask_width = bbox['imageMask']['shape'][0] print(f'Image_metas:{img_metas}, shape:({mask_height}, {mask_width})') return result
def scale(c, s): """ Scales a cube coord. :param c: A cube coord x, z, y. :param s: The amount to scale the cube coord. :return: The scaled cube coord. """ cx, cz, cy = c return s * cx, s * cz, s * cy
def is_functioncall(reg): """Returns whether a Pozyx register is a Pozyx function.""" if (0xB0 <= reg <= 0xBC) or (0xC0 <= reg < 0xC9): return True return False
def mania_key_fix(objs_each_key, mode=0): """ Remove the 1/4 spaced adjacent notes to make the map perfectly playable. It's a lazy hack for the obvious loophole in the note pattern algorithm. Should set to inactive for low key counts. mode 0: inactive mode 1: remove latter note mode 2: remove former note mode 3: move note to next lane mode 4: mode note to next lane, limiting to no adjacent note in next lane (should be internal use only) """ if mode == 0: return objs_each_key if mode == 1: for k, objs in enumerate(objs_each_key): prev_obj = (-1, -1, -1, -100) filtered_objs = [] for i, obj in enumerate(objs): if obj[3] > prev_obj[3] + 1: filtered_objs.append(obj) prev_obj = obj objs_each_key[k] = filtered_objs return objs_each_key if mode == 2: for k, objs in enumerate(objs_each_key): prev_obj = (-1, -1, -1, 2147483647) filtered_objs = [] for i, obj in reversed(list(enumerate(objs))): if obj[3] < prev_obj[3] - 1: filtered_objs.append(obj) prev_obj = obj objs_each_key[k] = filtered_objs return objs_each_key if mode == 3 or mode == 4: for k in range(len(objs_each_key)): objs = objs_each_key[k] prev_obj = (-1, -1, -1, -100) filtered_objs = [] for i, obj in enumerate(objs): if obj[3] > prev_obj[3] + 1: filtered_objs.append(obj) prev_obj = obj else: target_key = (k+1) % len(objs_each_key) target_key_objs = objs_each_key[target_key] j = 0 while target_key_objs[j][3] <= obj[3]: j += 1 if j == len(target_key_objs): break j -= 1 if mode == 3: # check if target spot is empty if j != len(target_key_objs) - 1: check_next = target_key_objs[j+1] if check_next[0] <= obj[1]: continue if target_key_objs[j][1] + 50 < obj[0]: new_obj = (obj[0], obj[1], target_key, obj[3]) target_key_objs = target_key_objs[:j+1] + [new_obj] + target_key_objs[j+1:] objs_each_key[target_key] = target_key_objs if mode == 4: # check if target spot is empty and has no possible double keys if j != len(target_key_objs) - 1: check_next = target_key_objs[j+1] if check_next[0] <= obj[1] or check_next[3] <= obj[3] + 1: continue if target_key_objs[j][1] + 50 < obj[0] and target_key_objs[j][3] + 1 < obj[3]: new_obj = (obj[0], obj[1], target_key, obj[3]) target_key_objs = target_key_objs[:j+1] + [new_obj] + target_key_objs[j+1:] objs_each_key[target_key] = target_key_objs objs_each_key[k] = filtered_objs if mode == 3: # if mode is 3, do another pass with mode 4 return mania_key_fix(objs_each_key, mode=4) return objs_each_key
def verify_dlg_sdk_proj_env_directory(path): """ Drive letter is not allowed to be project environment. Script checks in parent of 'path': a drive letter like C: doesn't have a parent. """ if(path.find(":\\")+2 >= len(path)): # If no more characters after drive letter (f.e. "C:\\"). return False else: return True
def find_all_children(parent_class): """ Returns list of references to all loaded classes that inherit from parent_class """ import sys, inspect subclasses = [] callers_module = sys._getframe(1).f_globals['__name__'] classes = inspect.getmembers(sys.modules[callers_module], inspect.isclass) for name, obj in classes: if (obj is not parent_class) and (parent_class in inspect.getmro(obj)): subclasses.append((obj, name)) return subclasses
def constraints_to_pretty_strings(constraint_tuples): """ Convert a sequence of constraint tuples as used in PackageMetadata to a list of pretty constraint strings. Parameters ---------- constraint_tuples : tuple of constraint Sequence of constraint tuples, e.g. (("MKL", (("< 11", ">= 10.1"),)),) """ flat_strings = [ "{} {}".format(dist, constraint_string).strip() for dist, disjunction in constraint_tuples for conjunction in disjunction for constraint_string in conjunction ] return flat_strings
def _get_full_name(code_name: str, proj=None) -> str: """ Return the label of an object retrieved by name If a :class:`Project` has been provided, code names can be converted into labels for plotting. This function is different to `framework.get_label()` though, because it supports converting population names to labels as well (this information is in the project's data, not in the framework), and it also supports converting link syntax (e.g. `sus:vac`) into full names as well. Note also that this means that the strings returned by `_get_full_name` can be as specific as necessary for plotting. :param code_name: The code name for a variable (e.g. `'sus'`, `'pris'`, `'sus:vac'`) :param proj: Optionally specify a :class:`Project` instance :return: If a project was provided, returns the full name. Otherwise, just returns the code name """ if proj is None: return code_name if code_name in proj.data.pops: return proj.data.pops[code_name]["label"] # Convert population if ":" in code_name: # We are parsing a link # Handle Links specified with colon syntax output_tokens = code_name.split(":") if len(output_tokens) == 2: output_tokens.append("") src, dest, par = output_tokens # If 'par_name:flow' syntax was used if dest == "flow": if src in proj.framework: return "{0} (flow)".format(proj.framework.get_label(src)) else: return "{0} (flow)".format(src) if src and src in proj.framework: src = proj.framework.get_label(src) if dest and dest in proj.framework: dest = proj.framework.get_label(dest) if par and par in proj.framework: par = proj.framework.get_label(par) full = "Flow" if src: full += " from {}".format(src) if dest: full += " to {}".format(dest) if par: full += " ({})".format(par) return full else: if code_name in proj.framework: return proj.framework.get_label(code_name) else: return code_name
def _create_example(product_id, question, answer): """Create an example dictionary.""" return { 'product_id': product_id, 'context': question, 'response': answer, }
def xml_value_from_key(xml,match,matchNumber=1): """ Given a huge string of XML, find the first match of a given a string, then go to the next value="THIS" and return the THIS as a string. if the match ends in ~2~, return the second value. """ for i in range(1,10): if match.endswith("~%d~"%i): match=match.replace("~%d~"%i,'') matchNumber=i if not match in xml: return False else: val=xml.split(match)[1].split("value=",3)[matchNumber] val=val.split('"')[1] try: val=float(val) except: val=str(val) return val