content
stringlengths
42
6.51k
def parse_word(word, s): """Parses the word and counts the number of digits, lowercase letters, uppercase letters, and symbols. Returns a dictionary with the results. If any character in the word is not in the set of digits, lowercase letters, uppercase letters, or symbols it is marked as a bad character. Words with bad characters are not output.""" count = {'d': 0, 'l': 0, 'u': 0, 's': 0, 'x':0} d = '0123456789' l = 'abcdefghijklmnopqrstuvwxyz' u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for c in word: if c in d: count['d'] += 1 elif c in l: count['l'] += 1 elif c in u: count['u'] += 1 elif c in s: count['s'] += 1 else: count['x'] += 1 return count
def invmod(a,b): """ Return modular inverse using a version Euclid's Algorithm Code by Andrew Kuchling in Python Journal: http://www.pythonjournal.com/volume1/issue1/art-algorithms/ -- in turn also based on Knuth, vol 2. """ a1, a2, a3 = 1, 0, a b1, b2, b3 = 0, 1, b while b3 != 0: # The following division will drop decimals. q = a3 / b3 t = a1 - b1*q, a2 - b2*q, a3 - b3*q a1, a2, a3 = b1, b2, b3 b1, b2, b3 = t while a2<0: a2 = a2 + a return a2
def get_bit_values(number, size=32): """ Get bit values as a list for a given number >>> get_bit_values(1) == [0]*31 + [1] True >>> get_bit_values(0xDEADBEEF) [1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, \ 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1] You may override the default word size of 32-bits to match your actual application. >>> get_bit_values(0x3, 2) [1, 1] >>> get_bit_values(0x3, 4) [0, 0, 1, 1] """ number += 2 ** size return list(map(int, bin(number)[-size:]))
def get_array_prepare(*args): """Find the wrapper for the array with the highest priority. In case of ties, leftmost wins. If no wrapper is found, return None """ wrappers = sorted((getattr(x, '__array_priority__', 0), -i, x.__array_prepare__) for i, x in enumerate(args) if hasattr(x, '__array_prepare__')) if wrappers: return wrappers[-1][-1] return None
def re_escape(string: str) -> str: """ Escape literal backslashes for use with :mod:`re`. .. seealso:: :func:`re.escape`, which escapes all characters treated specially be :mod:`re`. :param string: """ return string.replace('\\', "\\\\")
def _makeDefValues(keys): """Returns a dictionary containing None for all keys.""" return dict(( (k, None) for k in keys ))
def to_usd(my_price): """ Converts a numeric value to usd-formatted string, for printing and display purposes. Param: my_price (int or float) like 4000.444444 Example: to_usd(4000.444444) Returns: $4,000.44 """ return f"${my_price:,.2f}"
def get_subset_tasks(all_tasks, ratio): """Select a subset of tasks from all_tasks, keeping some % from each temp. Args: all_tasks: List of tasks like ['00001:001', ...] ratio: A number between 0-1, specifying how many of the tasks to keep. Returns: tasks: An updated list, with the ratio number of tasks. """ if len(all_tasks) == 0: return all_tasks assert 0.0 <= ratio <= 1.0 all_tasks = sorted(all_tasks) samples_to_keep = int(len(all_tasks) * ratio) return all_tasks[::(len(all_tasks) // samples_to_keep)][:samples_to_keep]
def extract_user_text(info): """ Extract known information from info['user_text']. Current known info is + 'Calibration data for frame %d' """ user_text = info['user_text'] if b'Calibration data for' in user_text[:20]: texts = user_text.split(b'\n') for i in range(info['NumberOfFrames']): key = 'Calibration_data_for_frame_{:d}'.format(i+1) coefs = texts[i][len(key)+2:].strip().split(b',') info[key] = [float(c) for c in coefs] # Calibration data should be None for this case info['Calibration_data'] = None else: coefs = info['Calibration_data'].strip().split() try: info['Calibration_data'] = [float(c) for c in coefs] except ValueError: del info['Calibration_data'] del info['user_text'] return info
def reverse_dict_partial(dict_obj): """Reverse a dict, so each value in it maps to one of its keys. Parameters ---------- dict_obj : dict A key-value dict. Returns ------- dict A dict where each value maps to the key that mapped to it. Example ------- >>> dicti = {'a': 1, 'b': 3} >>> reverse_dict_partial(dicti) {1: 'a', 3: 'b'} """ new_dict = {} for key in dict_obj: new_dict[dict_obj[key]] = key return new_dict
def generate_error(source: str, error: str): """Generate error message""" return { 'source': source, 'error': error, }
def _read24(arr): """Parse an unsigned 24-bit value as a floating point and return it.""" ret = 0.0 for b in arr: ret *= 256.0 ret += float(b & 0xFF) return ret
def validate_threshold(threshold, sim_measure_type): """Check if the threshold is valid for the sim_measure_type.""" if sim_measure_type == 'EDIT_DISTANCE': if threshold < 0: raise AssertionError('threshold for ' + sim_measure_type + \ ' should be greater than or equal to 0') elif sim_measure_type == 'OVERLAP': if threshold <= 0: raise AssertionError('threshold for ' + sim_measure_type + \ ' should be greater than 0') else: if threshold <= 0 or threshold > 1: raise AssertionError('threshold for ' + sim_measure_type + \ ' should be in (0, 1]') return True
def problem_2_try2(limit=4000000): """ attempted optimize for not checking even, but actually marginally slower? """ f_1 = 0 f_2 = 1 even_sum = 0 while f_1 < limit: # at start of iter, f_1 should always be even even_sum += f_1 for _ in range(3): f_1, f_2 = f_2, f_2 + f_1 return even_sum
def get_mzi_delta_length(m, neff=2.4, wavelength=1.55): """ m*wavelength = neff * delta_length """ return m * wavelength / neff
def get_dict_of_struct(connection, host): """ Transform SDK Host Struct type to Python dictionary. """ if host is None: return dict() hosts_service = connection.system_service().hosts_service() host_service = hosts_service.host_service(host.id) clusters_service = connection.system_service().clusters_service() devices = host_service.devices_service().list() tags = host_service.tags_service().list() stats = host_service.statistics_service().list() labels = host_service.affinity_labels_service().list() groups = clusters_service.cluster_service( host.cluster.id ).affinity_groups_service().list() return { 'id': host.id, 'name': host.name, 'address': host.address, 'cluster': connection.follow_link(host.cluster).name, 'status': str(host.status), 'description': host.description, 'os_type': host.os.type, 'os_version': host.os.version.full_version, 'libvirt_version': host.libvirt_version.full_version, 'vdsm_version': host.version.full_version, 'tags': [tag.name for tag in tags], 'affinity_labels': [label.name for label in labels], 'affinity_groups': [ group.name for group in groups if ( connection.is_link(group.hosts) and host.name in [ h.name for h in connection.follow_link(group.hosts) ] ) ], 'statistics': dict( (stat.name, stat.values[0].datum) for stat in stats ), 'devices': [device.name for device in devices], 'ansible_host': host.address, }
def to_set(list): """Crappy implementation of creating a Set from a List. To cope with older Python versions""" temp_dict = {} for entry in list: temp_dict[entry] = "dummy" return temp_dict.keys()
def generate_latex_error(error_msg): """ generate_latex_error(error_msg: str) -> str this generates a piece of latex code with an error message. """ error_msg = error_msg.replace("\n", "\\MessageBreak ") s = """\\PackageError{vistrails}{ An error occurred when executing vistrails. \\MessageBreak %s }{}""" % error_msg return s
def maximum_difference_sort_value(contributions): """ Auxiliary function to sort the contributions for the compare_plot. Returns the value of the maximum difference between values in contributions[0]. Parameters ---------- contributions: list list containing 2 elements: a Numpy.ndarray of contributions of the indexes compared, and the features' names. Returns ------- value_max_difference : float Value of the maximum difference contribution. """ if len(contributions[0]) <= 1: max_difference = contributions[0][0] else: max_difference = max( [ abs(contrib_i - contrib_j) for i, contrib_i in enumerate(contributions[0]) for j, contrib_j in enumerate(contributions[0]) if i <= j ] ) return max_difference
def color565(r, g=0, b=0): """Convert red, green and blue values (0-255) into a 16-bit 565 encoding. As a convenience this is also available in the parent adafruit_rgb_display package namespace.""" try: r, g, b = r # see if the first var is a tuple/list except TypeError: pass return (r & 0xf8) << 8 | (g & 0xfc) << 3 | b >> 3
def find_match_brackets(search, opening='<', closing='>'): """Returns the index of the closing bracket that matches the first opening bracket. Returns -1 if no last matching bracket is found, i.e. not a template. Example: 'Foo<T>::iterator<U>'' returns 5 """ index = search.find(opening) if index == -1: return -1 start = index + 1 count = 1 str_len = len(search) for index in range(start, str_len): c = search[index] if c == opening: count += 1 elif c == closing: count -= 1 if count == 0: return index return -1
def fib(n): """ a pure recursive fib """ if n < 2: return 1 else: return fib(n-1) + fib(n-2)
def get_graph_element_name(elem): """Obtain the name or string representation of a graph element. If the graph element has the attribute "name", return name. Otherwise, return a __str__ representation of the graph element. Certain graph elements, such as `SparseTensor`s, do not have the attribute "name". Args: elem: The graph element in question. Returns: If the attribute 'name' is available, return the name. Otherwise, return str(fetch). """ if hasattr(elem, "attr"): val = elem.attr("name") else: val = elem.name if hasattr(elem, "name") else str(elem) return val
def check_for_lower_adj_height(arr, index_row, index_col) -> bool: """ Args: arr: heightmap array index_row: row index of location to check adjacent locations for lower or equally low height index_col: column index of location to check adjacent locations for lower or equally low height Returns: True if check location is lower than all adjacent locations, else False """ if index_row >= 1: if arr[index_row][index_col] >= arr[index_row-1][index_col]: return False if index_row < len(arr) - 1: if arr[index_row][index_col] >= arr[index_row+1][index_col]: return False if index_col >= 1: if arr[index_row][index_col] >= arr[index_row][index_col-1]: return False if index_col < len(arr[index_row]) - 1: if arr[index_row][index_col] >= arr[index_row][index_col+1]: return False return True
def scalar_in_sequence(x, y): """Determine whether the scalar in the sequence.""" if x is None: raise ValueError("Judge scalar in tuple or list require scalar and sequence should be constant, " "but the scalar is not.") if y is None: raise ValueError("Judge scalar in tuple or list require scalar and sequence should be constant, " "but the sequence is not.") if x in y: return True return False
def _inFilesystemNamespace(path): """ Determine whether the given unix socket path is in a filesystem namespace. While most PF_UNIX sockets are entries in the filesystem, Linux 2.2 and above support PF_UNIX sockets in an "abstract namespace" that does not correspond to any path. This function returns C{True} if the given socket path is stored in the filesystem and C{False} if the path is in this abstract namespace. """ return path[:1] not in (b"\0", u"\0")
def convertOrfToGenomic(start, end, strand, orfStart): """Convert domain coordinates in ORF to genomic. @param start: Domain start coord @param end: Domain end coord @param strand: Strand @param orfStart: ORF start coord @return: (gStart, gEnd) """ if strand=='+': gStart = orfStart + 3*(start-1) gEnd = orfStart + 3*(end-1) + 2 else: gStart = orfStart - 3*(start-1) gEnd = orfStart - 3*(end-1) - 2 return gStart, gEnd
def create_nc_dimension(nc_file, shape): """ Cria as dimensoes do arquivo (x, y, z, w) time = UNLIMITED ; level = UNLIMITED ; latitude = shape[0] ; longitude = shape[1] ; Parameters ---------- nc_file : netCDF4.Dataset Dataset file to create the dimensions. shape : tuple Shape of the grid, shape=(latitude.size, longitude.size). Returns ------- : bool Returns True if the dimensions are created correctly, else returns False. """ try: nc_file.createDimension("latitude", shape[0]) nc_file.createDimension("longitude", shape[1]) nc_file.createDimension("level") nc_file.createDimension("time") return True except: return False
def sumofDigits(n): """calculate the sum of the digits of an input integer""" assert n >= 0 and int(n) == n, 'The number has to be positive integers only' if n == 0: return 0 else: return int(n%10) + sumofDigits(int(n/10))
def MID(text, start_num, num_chars): """ Returns a segment of a string, starting at start_num. The first character in text has start_num 1. >>> MID("Fluid Flow", 1, 5) 'Fluid' >>> MID("Fluid Flow", 7, 20) 'Flow' >>> MID("Fluid Flow", 20, 5) '' >>> MID("Fluid Flow", 0, 5) Traceback (most recent call last): ... ValueError: start_num invalid """ if start_num < 1: raise ValueError("start_num invalid") return text[start_num - 1 : start_num - 1 + num_chars]
def convert_bytes(num): """ this function will convert bytes to MB.... GB... etc """ if num < 1024.0: return "%3.0f bytes" % (num) num /= 1024.0 for x in ['KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 1024.0
def chunks(seq, n) : """ Description ---------- Split list seq into n list Parameters ---------- seq : input list n : number of elements to split seq into Returns ------- list of n list """ return [seq[i::n] for i in range(n)]
def toggle_popover(n, is_open): """ Shows/hides informance on toggle click :param n: num clicks on toggle button :param is_open: open state of class warnings :return: negated open state if click, else open state """ if n: return not is_open return is_open
def reference(api, line): """ day on day line :param api: plugin api object, select is not implement during init. :param line: tuple-like ((timestamp, value)), the timestamp and value is const :return: (reference_name, [[timestamp, value]]), tuple is not recommended """ res = [] if len(line) > 0: offset = api.DAY / api.get_period() res = [] for idx in range(len(line) - 1, -1, -1): if idx - offset > -1: res.append([line[idx][0], line[idx - offset][1]]) else: res.append([line[idx][0]]) return 'Day on Day', res
def bar(x, greeting='hello'): """bar greets its input""" return f'{greeting} {x}'
def badhash(x): """ Just a quick and dirty hash function for doing a deterministic shuffle based on image_id. Source: https://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key """ x = (((x >> 16) ^ x) * 0x045d9f3b) & 0xFFFFFFFF x = (((x >> 16) ^ x) * 0x045d9f3b) & 0xFFFFFFFF x = ((x >> 16) ^ x) & 0xFFFFFFFF return x
def _mask_token(token: str) -> str: """Mask a PAT token for display.""" if len(token) <= 8: # it's not valid anyway, just show the entire thing return token else: return "%s%s%s" % (token[0:4], len(token[4:-4]) * "*", token[-4:])
def coupling_list2dict(couplinglist): """Convert coupling map list into dictionary. Example list format: [[0, 1], [0, 2], [1, 2]] Example dictionary format: {0: [1, 2], 1: [2]} We do not do any checking of the input. Return coupling map in dict format. """ if not couplinglist: return None couplingdict = {} for pair in couplinglist: if pair[0] in couplingdict: couplingdict[pair[0]].append(pair[1]) else: couplingdict[pair[0]] = [pair[1]] return couplingdict
def will_reciprocate(data_dict, index): """Searches the text of the request for phrases that suggest a promise to give pizza to someone else. data_dict is a dictionary of lists,and any given index in the lists corresponds to the same post for different keys. """ title = data_dict["title"][index] body = data_dict["body"][index] phrases = ["pay it forward", "return the favor", "reciprocate"] for p in phrases: if p in title or p in body: return True return False
def setDefaultOptionIfMissing(options,defaultOptions): """ If options is none or empty, return defaultOptions directly; Otherwise set option in options if option exist in defaultOptions but does not exist in options. """ if not defaultOptions: return {} if options is None else options if not options: return dict(defaultOptions) for key,value in defaultOptions.iteritems(): if key not in options: options[key] = value return options
def create_row(*fields): """ generate aligned row """ row = "" for field in fields: value, width, padding, alignment = \ field[0], field[1], field[2], field[3] value = value[:(width - padding)] + ".." \ if len(value) > width - padding else value if alignment == 'right': row += (value + (width - len(value)) * ' ') else: row += ((width - len(value) - padding) * ' ' + value + padding * ' ') return row
def convert_composition_string_to_dict( X ): """ Converts a composition string of style "CH4:0.02, N2:0.01, O2:0.45" into a dict, a la composition['CH4'] = 0.02 """ results = {} for sp in X.split(","): st = sp.strip() try: results[ st.split(":")[0].strip() ] = float( st.split(":")[1].strip() ) except IndexError: # X is probably not a list # (why would we run split on a list?) # or is empty err = "ERROR: CanteraGasUtils: your X is probably specified incorrectly. Expected type list, got type "+type(X) raise Exception(err) # normalize results_sum = sum( [results[k] for k in results.keys()] ) for k in results.keys(): results[k] = results[k]/results_sum return results
def is_ignored_file(f): """Check if this file has to be ignored. Ignored files includes: - .gitignore - OS generated files - text editor backup files - XCF image files (Gimp) """ return f == '.gitignore' or f == '.DS_Store' or f == '.DS_Store?' or \ f == '.Spotlight-V100' or f == '.Trashes' or f == 'ehthumbs.db' or f == 'Thumbs.db' or \ f.startswith("._") or f.endswith(".swp") or f.endswith(".bak") or f.endswith("~") or \ f.endswith(".xcf")
def tick(price: float, tick_size: float = 0.05) -> float: """ round the given price to the nearest tick >>> tick(100.03) 100.05 >>> tick(101.31, 0.5) 101.5 >>> tick(101.04, 0.1) 101.0 >>> tick(100.01,0.1) 100.0 """ return round(round(price / tick_size) * tick_size, 2)
def uint16_tag(name, value): """Create a DMAP tag with uint16 data.""" return name.encode('utf-8') + \ b'\x00\x00\x00\x02' + \ value.to_bytes(2, byteorder='big')
def is_power_of_2(num): """ Check if the input number is a power of 2. """ return num != 0 and ((num & (num - 1)) == 0)
def get_year_filename(file): """Get the year from the datestr part of a file.""" date_parts = [int(d) for d in file.split('.')[-2].split('-')] return date_parts[0]
def h5str(obj): """strings stored in an HDF5 from Python2 may look like "b'xxx'", that is containg "b". strip these out here """ out = str(obj) if out.startswith("b'") and out.endswith("'"): out = out[2:-1] return out
def filename(tmpdir): """Use this filename for the tests.""" return f"{tmpdir}/test.mp4"
def set_whole_node_entry(entry_information): """Set whole node entry Args: entry_information (dict): a dictionary of entry information from white list file Returns: dict: a dictionary of entry information from white list file with whole node settings """ if "submit_attrs" in entry_information: if "+xcount" not in entry_information["submit_attrs"]: entry_information["submit_attrs"]["+xcount"] = None if "+maxMemory" not in entry_information["submit_attrs"]: entry_information["submit_attrs"]["+maxMemory"] = None if "attrs" not in entry_information: entry_information["attrs"] = {} if "GLIDEIN_CPUS" not in entry_information["attrs"]: entry_information["attrs"]["GLIDEIN_CPUS"] = {"value": "auto"} if "GLIDEIN_ESTIMATED_CPUS" not in entry_information["attrs"]: entry_information["attrs"]["GLIDEIN_ESTIMATED_CPUS"] = {"value": 32} if "GLIDEIN_MaxMemMBs" not in entry_information["attrs"]: entry_information["attrs"]["GLIDEIN_MaxMemMBs"] = {"type": "string", "value": ""} if "GLIDEIN_MaxMemMBs_Estimate" not in entry_information["attrs"]: entry_information["attrs"]["GLIDEIN_MaxMemMBs_Estimate"] = {"value": "True"} return entry_information
def flip(board): """Returns horizontal mirror image of board with inverted colors.""" flipped_board = dict() for square, piece in board.items(): flipped_board[(7 - square[0], square[1])] = piece.swapcase() return flipped_board
def unzip(l): """ Returns the inverse operation of `zip` on `list`. Args: l (list): the list to unzip """ return list(map(list, zip(*l)))
def tanh_derivative(x): """ Actual derivative: tanh'(x) = 1 - (tanh(x))^2 but logic same as sigmoid derivative """ return 1 - x ** 2
def _get_short_lang_code(lang: str) -> str: """Returns an alternative short lang code""" return lang if "zh" in lang else lang.split("-")[0]
def changed_keys(a, b): """Compares two dictionaries and returns list of keys where values are different""" # Note! This function disregards keys that don't appear in both dictionaries keys = [] if a is not None and b is not None: for k, _ in b.items(): if k in a and a[k] != b[k]: keys.append(k) return keys
def filter_duplicates(donors, acceptors): """ Filter out duplicate donor acceptor atom pairs """ pairs = sorted(list(set([(d, acceptors[idx]) for idx, d in enumerate(donors)]))) new_donors, new_acceptors = [], [] for d, a in pairs: new_donors.append(d) new_acceptors.append(a) return new_donors, new_acceptors
def index_in_str(text, substring, starting=0): """ Gets index of text in string :arg text: text to search through :arg substring: text to search for :arg starting: offset :return position """ search_in = text[starting:] if substring in search_in: return search_in.index(substring) else: return -1
def getHeaderObj(relationname, attribute_conf): """Generate header of ARFF file in JSON format Args: relationname (string): relation name, can be understood as name of dataset attribute_conf (dict): attribute configuration load from file Returns: dict: header JSON object of ARFF format """ print("Generating header...") def getAttrObj(attr_info): attr_obj = { "name": attr_info['name'], "type": attr_info["type"], "class": False, "weight": 1.0 } if attr_info['type'] == 'nominal': attr_obj['labels'] = attr_info['labels'] return attr_obj return { "relation": relationname, "attributes": list(map(getAttrObj, attribute_conf)) }
def convert_to_camel(data): """ Convert snake case (foo_bar_bat) to camel case (fooBarBat). This is not pythonic, but needed for certain situations. """ components = data.split("_") capital_components = "".join(x.title() for x in components[1:]) return f"{components[0]}{capital_components}"
def i2n(i): """ip to number """ ip = [int(x) for x in i.split('.')] return ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3]
def heuristic_function_1(game_state, move): """Give a heuristic evaluation in form of a number of how good it would be to make "move" to "game_state". The value is higher the better the move, regardless of the player to make it. This function give higher values to more central columns. """ return -abs(3 - move)
def hsv2rgb(c): """Convert an hsv color to rgb.""" h,s,v = c h = h%360 h = 6*((h/360)%1) i = int(h) f = h-i p = v*(1-s) q = v*(1-s*f) t = v*(1-s*(1-f)) if (i==6) or (i==0): return (v,t,p) elif i == 1: return (q,v,p) elif i == 2: return (p,v,t) elif i == 3: return (p,q,v) elif i == 4: return (t,p,v) elif i == 5: return (v,p,q) else: return i
def has_more_results(response): """ Checks the `exceededTransferLimit` flag of the REST API response. If set, this flag indicates that there are more rows after the page offset than could be returned in the response, which means that we need to continue paging. """ return response.get('exceededTransferLimit', False)
def calculate_posterior(bayes_factor, prior_prob): """ Calculate the posterior probability of association from the bayes factor and prior probability of association. """ if bayes_factor == float('inf'): return 1.0 posterior_odds = bayes_factor * prior_prob / (1.0 - prior_prob) return posterior_odds / (1.0 + posterior_odds)
def Val(text): """Return the value of a string This function finds the longest leftmost number in the string and returns it. If there are no valid numbers then it returns 0. The method chosen here is very poor - we just keep trying to convert the string to a float and just use the last successful as we increase the size of the string. A Regular expression approach is probably quicker. """ best = 0 for idx in range(len(text)): try: best = float(text[:idx + 1]) except ValueError: pass return best
def tuple_to_bool(value): """ Converts a value triplet to boolean2 values From a triplet: concentration, decay, threshold Truth value = conc > threshold/decay """ return value[0] > value[2] / value[1]
def u8(x: int) -> bytes: """ Encode an 8-bit unsigned integer. """ assert 0 <= x < 256 return x.to_bytes(1, byteorder='little')
def valfilter(predicate, d, factory=dict): """ Filter items in dictionary by value >>> iseven = lambda x: x % 2 == 0 >>> d = {1: 2, 2: 3, 3: 4, 4: 5} >>> valfilter(iseven, d) {1: 2, 3: 4} See Also: keyfilter itemfilter valmap """ rv = factory() for k, v in d.items(): if predicate(v): rv[k] = v return rv
def get_color_index(name_index, color_arr): """ examine color index due to the name index value :param name_index: baby name index :param color_arr: color array :return: color index """ if name_index > len(color_arr): color_index = name_index % len(color_arr) else: color_index = name_index return color_index
def concat_multi_expr(*expr_args): """Concatenates multiple expressions into a single expression by using the barrier operator. """ me = None for e in expr_args: me = me | e if me else e return me
def _get_sub_dict(d, *names): """ get sub dictionary recursive. """ for name in names: d = d.get(name, None) if d is None: return dict() return d
def DefficiencyBound(D, k, k2): """ Calculate the D-efficiency bound of an array extension Args: D (float): D-efficiency of the design k (int): numbers of columns k2 (int): numbers of columns Returns: float: bound on the D-efficiency of extensions of a design with k columns to k2 columns """ m = 1. + k + k * (k - 1) / 2 m2 = 1. + k2 + k2 * (k2 - 1) / 2 Dbound = D**(m / m2) return Dbound
def residue_vs_water_hbonds(hbonds, solvent_resn): """ Split hbonds into those involving residues only and those mediated by water. """ residue_hbonds, water_hbonds = [], [] for hbond in hbonds: frame_idx, atom1_label, atom2_label, itype = hbond if solvent_resn in atom1_label or solvent_resn in atom2_label: water_hbonds.append(hbond) else: residue_hbonds.append(hbond) return residue_hbonds, water_hbonds
def format_prio_list(prio_list): """Format a list of prios into a string of unique prios with count. Args: prio_list (list): a list of PrioEvent objects. Returns: The formatted string containing the unique priorities and their count if they occurred more than once. """ prio_count = {} prio_str = None for prio_event in prio_list: prio = prio_event.prio if prio not in prio_count: prio_count[prio] = 0 prio_count[prio] += 1 for prio in sorted(prio_count.keys()): count = prio_count[prio] if count > 1: count_str = ' ({} times)'.format(count) else: count_str = '' if prio_str is None: prio_str = '[{}{}'.format(prio, count_str) else: prio_str += ', {}{}'.format(prio, count_str) if prio_str is None: prio_str = '[]' else: prio_str += ']' return prio_str
def otp(data, password, encodeFlag=True): """ do one time pad encoding on a sequence of chars """ pwLen = len(password) if pwLen < 1: return data out = [] for index, char in enumerate(data): pwPart = ord(password[index % pwLen]) newChar = char + pwPart if encodeFlag else char - pwPart newChar = newChar + 256 if newChar < 0 else newChar newChar = newChar - 256 if newChar >= 256 else newChar out.append(newChar) return bytes(out)
def list_of_strings_has_substring(list_of_strings, string): """Check if any of the strings in `list_of_strings` is a substrings of `string`""" return any([elem.lower() in string.lower() for elem in list_of_strings])
def normalize_starting_slash(path_info): """Removes a trailing slash from the given path, if any.""" # Ensure the path at least contains a slash if not path_info: return '/' # Ensure the path starts with a slash elif path_info[0] != '/': return '/' + path_info # No need to change anything else: return path_info
def get_namespace(namespace, view=None): """ Get the contents of the given 'namespace', returning a dictionary of choices (appropriate for folders) and a list of items (appropriate for messages). """ d = {} l = [] # First try looking for folders. Then look for items. And so on. for properties in (("Folders", "Name"), ("Items", None)): # Look for objects of the current type: folders, items, etc. object_name = properties[0] try: subobject = getattr(namespace, object_name) except AttributeError: # Ignore the rest of the loop body and start # the next iteration. continue # Index the retrieved items by storing them by name in a dictionary. # Cannot slice items, and they always seem to start at index 1. total_number = len(subobject) for i in range(1, total_number + 1): try: field_name = properties[1] # Store in the dictionary using the specified property, if # specified. l.append(subobject[i]) if field_name is not None: d[getattr(subobject[i], field_name)] = subobject[i] except AttributeError: pass # Crude status indicator. if view: view.update_status(i, total_number) return d, l
def _get_keyed_rule_indices(rules): """returns {frozesent((par_name, edge1, edge2, ..)): index}""" new = {} for i, rule in enumerate(rules): edges = rule.get("edges", rule.get("edge", None)) or [] edges = [edges] if type(edges) == str else edges par_name = rule["par_name"] key = frozenset([par_name] + edges) new[key] = i return new
def has_prefix(x: list): """Returns "True" if some value in the list is a prefix for another value in this list.""" for val in x: if len(list(filter(val.startswith, x))) > 1: return True return False
def _field_post(field): """Add sqlalchemy conversion helper info Convert aggregation -> _aggregation_fn, as -> _cast_to_datatype and default -> _coalesce_to_value""" if "as" in field: field["_cast_to_datatype"] = field.pop("as") if "default" in field: field["_coalesce_to_value"] = field.pop("default") return field
def _check_validity_specie_tag_in_reaction_dict(k): """Validate key in database reaction entry""" return not ( k == "type" or k == "id_db" or k == "log_K25" or k == "log_K_coefs" or k == "deltah" or k == "phase_name" or k == "Omega" or k == "T_c" or k == "P_c" or k == "Vm" )
def format_properties(event): """Formats the user input for a password policy.""" event_properties = event["ResourceProperties"] allowed_properties_bool = [ "RequireSymbols", "RequireNumbers", "RequireUppercaseCharacters", "RequireLowercaseCharacters", "AllowUsersToChangePassword", "HardExpiry" ] for i in allowed_properties_bool: if event_properties[i] == "true": event_properties[i] = True elif event_properties[i] == "false": event_properties[i] = False else: raise Exception("Resource property values not supported. Values must be boolean.") allowed_properties_int = [ "MinimumPasswordLength", "MaxPasswordAge", "PasswordReusePrevention" ] for j in allowed_properties_int: event_properties[j] = int(event['ResourceProperties'][j]) return event
def multiply_with_positional_args(*args): """ :param args: a tuple with arbitrary number of positional arguments :return: """ foo = args[0] bar = args[1] return foo * bar
def rm(x, l): """List l without element x.""" return [y for y in l if x != y]
def rsa_decrypt(c: int, d: int, n: int) -> int: """ Implements RSA Decryption via the mathematical formula. The formula is m=(c**d) % N Returns the plain "text" really integer representation of the value. :param c: Ciphertext integer. :param d: the private key exponent. :param n: the modulus. :return: the plaintext integer M. """ m=pow(c, d, n) return m
def ConvertIregName(iregname): """ On Python 2.3 and higher, converts the given ireg-name component of an IRI to a string suitable for use as a URI reg-name in pre- rfc2396bis schemes and resolvers. Returns the ireg-name unmodified on Python 2.2. """ try: # I have not yet verified that the default IDNA encoding # matches the algorithm required by the IRI spec, but it # does work on the one simple example in the spec. iregname = iregname.encode('idna') except: pass return iregname
def spliter(line, _len=len): """ Credits to https://stackoverflow.com/users/1235039/aquavitae Return a list of words and their indexes in a string. """ words = line.split(' ') index = line.index offsets = [] append = offsets.append running_offset = 0 for word in words: word_offset = index(word, running_offset) word_len = _len(word) running_offset = word_offset + word_len append((word, word_offset, running_offset)) return offsets
def removeDuplicatesList(value): """ remove duplicates """ print(value) return list(dict.fromkeys(value))
def q2p(q): """ Convert MAPQ to Pr(incorrect). """ return 10**(q/-10)
def calculateSensitivity(tn, fp, fn, tp): """ return the Sensitivity based on the confusion matrix values :param tn: Quantity of True negative :param fp: Quantity of False positive :param fn: Quantity of False negative :param tp: Quantity of True positive :type tn: int - required :type fp: int - required :type fn: int - required :type tp: int - required :return: The sensitivity value :rtype: Float """ sen = tp / (tp + fn) return sen
def un_unicode(d): """ transform unicode keys to normal """ return dict((str(k), v) for (k,v) in d.items())
def IsRefsTags(value): """Return True if the given value looks like a tag. Currently this is identified via refs/tags/ prefixing.""" return value.startswith("refs/tags/")
def calc_max_num_clones(walker_weight, min_weight, max_num_walkers): """ Parameters ---------- walker_weight : min_weight : max_num_walkers : Returns ------- """ # initialize it to no more clones max_n_clones = 0 # start with a two splitting n_splits = 2 # then increase it every time it passes or until we get to the # max number of walkers while ((walker_weight / n_splits) >= min_weight) and \ (n_splits <= max_num_walkers): n_splits += 1 # the last step failed so the number of splits is one less # then we counted n_splits -= 1 # we want the number of clones so we subtract one from the # number of splits to get that, and we save this for this # walker max_n_clones = n_splits - 1 return max_n_clones
def _EdgeStyle(data): """Helper callback to set default edge styles.""" flow = data.get("flow") if flow in {"backward_control", "backward_data", "backward_call"}: return "dashed" else: return "solid"
def percentage(fraction, total): """ Calculate the percentage without risk of division by zero Arguments: fraction -- the size of the subset of samples total -- the total size of samples Returns: fraction as a percentage of total """ p = 0 if total == 0 else 100.0 * fraction / total return "%.2f%%" % p
def _replica_results_dedup(queries): """This method deduplicates data object results within a query, so that ls displays data objects one time, instead of once for every replica.""" deduplicated_queries = [] for query in queries: new_query = query.copy() if "results" in query: objects_seen = {} dedup_results = [] results = query["results"] for result in results: if result["type"] == "dataobject": full_name = result["full_name"] if full_name not in objects_seen: objects_seen[full_name] = 1 dedup_results.append(result) else: dedup_results.append(result) new_query["results"] = dedup_results deduplicated_queries.append(new_query) return deduplicated_queries
def is_fully_unmeth(methfreq, eps=1e-5): """ Check if the freq is unmethylated, means 0.0 (almost) :param methfreq: :param eps: :return: """ if methfreq > 1.0 + eps or methfreq < 0: raise Exception(f'detect error value for freq={methfreq}') if methfreq < eps: # near 0 return True return False
def split_accn(accn): """ Split accession into prefix and number, leaving suffix as text and converting the type prefix to uppercase. :param str accn: ordinary accession identifier. :return str, str: prefix and integral suffix """ typename, number_text = accn[:3], accn[3:] return typename.upper(), number_text
def get_lambda_path_from_event(event) -> str: """Builds the lambda function url based on event data""" lambda_path = event["requestContext"]["path"] lambda_domain = event["requestContext"]["domainName"] return f"https://{lambda_domain}{lambda_path}"