content
stringlengths
42
6.51k
def dB_to_amp(dB): """ :: Convert decibels to amplitude """ return 10**(dB/20.)
def _is_shorthand_ip(ip_str): """Determine if the address is shortened. Args: ip_str: A string, the IPv6 address. Returns: A boolean, True if the address is shortened. """ if ip_str.count('::') == 1: return True if [x for x in ip_str.split(':') if len(x) < 4]: return True return False
def momentum(vector): """ Computes the momentum of a vector. Parameters: - `vector` : :class:`list` of :class:`floats` Moentum is computed as follow: - momentum = 100*(new - old)/old Returns the momentum of the vector (:class:`float`) """ return 100*((vector[0] - vector[-1])/vector[-1])
def lower(value): # Only one argument. """Converts a string into all lowercase""" return value.lower()
def swap(puzzle, pos_0, new_pos): """ swap pos_0 and pos_to_move """ temp = puzzle[pos_0[0]][pos_0[1]] puzzle[pos_0[0]][pos_0[1]] = puzzle[new_pos[0]][new_pos[1]] puzzle[new_pos[0]][new_pos[1]] = temp return puzzle
def get_filename(fd): """ Helper function to get to file name from a file descriptor or filename. :param fd: file descriptor or filename. :returns: the filename. """ if hasattr(fd, 'name'): # fd object return fd.name # fd is a filename return fd
def get_numbers_activitychurn_timebin_status(l_sets_activity_timebin_status): """ Convert list of sets to actual numbers only version tracking changes overtime. :param l_sets_activity_timebin_status: :return: """ qty_ips_down = len(l_sets_activity_timebin_status[0]) qty_ips_up = len(l_sets_activity_timebin_status[1]) qty_bgpprefix_down = len(l_sets_activity_timebin_status[2]) qty_bgpprefix_up = len(l_sets_activity_timebin_status[3]) qty_same_ips = len(l_sets_activity_timebin_status[4]) qty_same_bgpprefixes = len(l_sets_activity_timebin_status[5]) traffic_volume_diff = l_sets_activity_timebin_status[6] qty_packets_diff = l_sets_activity_timebin_status[7] return [qty_ips_down, qty_ips_up, qty_bgpprefix_down, qty_bgpprefix_up, qty_same_ips, qty_same_bgpprefixes, traffic_volume_diff, qty_packets_diff]
def scc(graph): """ Finds what strongly connected components each node is a part of in a directed graph, it also finds a weak topological ordering of the nodes """ n = len(graph) comp = [-1] * n top_order = [] Q = [] stack = [] new_node = None for root in range(n): if comp[root] >= 0: continue # Do a dfs while keeping track of depth Q.append(root) root_depth = len(top_order) while Q: node = Q.pop() if node >= 0: if comp[node] >= 0: continue # First time # Index the node comp[node] = len(top_order) + len(stack) stack.append(node) # Do a dfs Q.append(~node) Q += graph[node] else: # Second time node = ~node # calc low link low = index = comp[node] for nei in graph[node]: if root_depth <= comp[nei]: low = min(low, comp[nei]) # low link same as index, so create SCC if low == index: while new_node != node: new_node = stack.pop() comp[new_node] = index top_order.append(new_node) else: comp[node] = low top_order.reverse() return comp, top_order
def is_int(thing): """Returns True when thing is an integer type.""" return isinstance(thing, int)
def extended_gcd(aa, bb): """Extended Euclidean Algorithm, from https://rosettacode.org/wiki/Modular_inverse#Python """ lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
def set_difference(dependent,independent): """ This function compares two lists, and takes their set-theoretical difference: dependent - independent arguments: dependent, independent """ return list(set(dependent)-set(independent))
def check_for_tree(x, y, trees, max_x): """ Checks to see if a tree exists in the given location, taking into account the infinite repeating pattern. >>> check_for_tree(0, 0, {(0, 0)}, 1) True >>> check_for_tree(0, 0, {(0, 1)}, 1) False >>> check_for_tree(15, 0, {(0, 0)}, 5) True :param x: :param y: :param trees: :param max_x: :return: """ while x >= max_x: x -= max_x return (x, y) in trees
def om_values(values, year): """ Return a list of values for an observation model parameter. :param values: Values may be scalar, a list of scalars, or a dictionary that maps years to a scalar or list of scalars. :param year: The calendar year of the simulation. :raises ValueError: If the values are a dictionary and the year is not a valid key, or if there are duplicate values. :raises TypeError: If the values are not one of the types defined above. """ if isinstance(values, dict): # The values are stored in a dictionary and are indexed by year. if year in values: values = values[year] else: raise ValueError('Invalid year {}'.format(year)) try: # Try treating the values as a list of values. values = list(values) except TypeError: # If that fails, assume we have a scalar value. return [values] # Detect duplicate values. if len(set(values)) == len(values): return values else: raise ValueError("Duplicate values in {}".format(values))
def irange(start, end): """ Inclusive range from start to end (vs. Python insanity.) irange(1,5) -> 1, 2, 3, 4, 5 Credit: Mininet's util library. """ return range(start, end + 1)
def get_string_between_tags(string, opening_tag, closing_tag): """ Return the substring between two tags. The substring will begins at the first occurrence of the opening tag and will finishes at the last occurrence of the closing tag. :param string: String in which are the tags :param opening_tag: Tag opening the substring :param closing_tag: Tag closing the substring :return: The substring between the opening tag and the closing tag """ try: start = string.index(opening_tag) + len(opening_tag) end = string.rindex(closing_tag, start) return string[start:end] except ValueError: return ""
def valid_string_hook_function(arg1, context, kwarg1='kwarg1'): """A valid hook function used in testing""" return 'foobar ' + arg1 + ' ' + kwarg1
def get_proportion(part, whole): """ Get proportion between part and whole, if whole is zero, returns 0 to be used as 0% """ if whole == 0: return 0 return float(part)/float(whole)
def _compare_attributes(obj, other, key_attributes): """Object comparison helper """ if not isinstance(obj, other.__class__): return NotImplemented try: return all(getattr(obj, a) == getattr(obj, a) for a in key_attributes) except AttributeError: return False
def calc_table_variable_volumes(line, table_vols): """ Calculates the table volumes. :param line: :param table_vols: :return: table_vols """ varVolDict = {} l = line.split('::') table_var = l[0].strip().split('.') table, var, vol = table_var[0], table_var[1], float(l[-1].strip().strip('Tb')) varVolDict[var] = vol if not table in table_vols.keys(): table_vols[table] = [varVolDict] else: table_vols[table].append(varVolDict) return table_vols
def replace_dict_value(dictionary, old_value, new_value): """ Selectively replaces values in a dictionary Parameters: :dictionary(dict): input dictionary :old_value: value to be replaced :new_value: value to replace Returns: :output_dictionary (dict): dictionary with replaced values""" for key, value in dictionary.items(): if value == old_value: dictionary[key] = new_value return dictionary
def append_write(filename="", text=""): """ Appends a string at the end of a text file and Returns the number of characters added """ with open(filename, 'a', encoding='utf-8') as f: return f.write(text)
def filename_parse(fstr): """ parses a filepath string into it's path, name, and suffix """ split = fstr.split('\\') if len(split) == 1: file_path = None else: file_path = '\\'.join(split[0:-1]) split2 = split[-1].split('.') # try and guess whether a suffix is there or not # my current guess is based on the length of the final split string # suffix is either 3 or 4 characters if len(split2[-1]) == 3 or len(split2[-1]) == 4: file_name = '.'.join(split2[0:-1]) file_suffix = split2[-1] else: file_name = split[-1] file_suffix = None return file_path, file_name, file_suffix
def partition(A, p, r): """ Particiona o vetor. """ x = A[r] i = p - 1 for j in range(p, r): # de p a r-1 if A[j] <= x: i += 1 A[i], A[j] = A[j], A[i] # troca valores A[i+1], A[r] = A[r], A[i+1] # troca valores return i + 1
def rrl(n,dn=1,amu=1.007825,Z=1): """ compute Radio Recomb Line freqs in GHz from Brown, Lockman & Knapp ARAA 1978 16 445 UPDATED: Gordon & Sorochenko 2009, eqn A6 Parameters ---------- n : int The number of the lower level of the recombination line (H1a is Lyman alpha, for example) dn : int The delta-N of the transition. alpha=1, beta=2, etc. amu : float The mass of the central atom Z : int The ionization parameter for the atom. Z=1 is neutral, Z=2 is singly ionized, etc. For hydrogen, only z=1 makes sense, since ionized hydrogen has no electrons and therefore cannot have recombination lines. Returns ------- frequency in GHz """ nu = 3.289842e6*(1-5.48593e-4/amu)*(1/float(n)**2 - 1/float(n+dn)**2) nu = 3.28984196e6 * Z**2 * (amu-5.48579911e-4*(Z+1))/(amu-5.48579911e-4*Z) * (1/float(n)**2 - 1/float(n+dn)**2) return nu
def relativ_Fehler(wert, erwartet): """Relativer Fehler von 'wert' bezueglich einer Referenz 'erwartet'.""" return abs((wert - erwartet) / erwartet)
def reverseWord(a_sentence): """assumes a_sentence is a string of characters and spaces treats spaces as delimeters between "words" (not checked to be "real" words) returns a string, with the same "words" in reverse order e.g. reverseWord("cats are purrfect") -> "purrfect are cats" """ words_list = a_sentence.split(" ") return " ".join(words_list[::-1])
def get_name_ARPS_simulation(degree, simulation): """Get short name of ARPS files""" [topo_or_wind, N, dx, xi, sigma, ext] = simulation.split('_') name = str(degree) + 'degree' + '_' + xi + '_' + ext return (name)
def centerify(text, width=-1): """Center multiline text.""" lines = text.split(" ") width = max(map(len, lines)) if width == -1 else width return "\n".join(line.center(width) for line in lines)
def check_port(port, _used_ports=()): """ Check that a port is well formated and not already taken""" try: port = int(port) assert 1 <= port <= 65535 if port in _used_ports: ValueError("Port '%s' is already in used" % port) return port except (ValueError, AssertionError): msg = 'Port must be a number between 1 and 65535 not "%s"' raise ValueError(msg % port)
def header(text, color='black', gen_text=None): """Create an HTML header""" if gen_text: raw_html = f'<h1 style="margin-top:16px;color: {color};font-size:54px"><center>' + str( text) + '<span style="color: red">' + str(gen_text) + '</center></h1>' else: raw_html = f'<h1 style="margin-top:12px;color: {color};font-size:54px"><center>' + str( text) + '</center></h1>' return raw_html
def remove_restricted(list): """ Remove restricted (system) Amazon tags from list of tags """ clean_list = [] try: for dict in list: if 'aws' not in dict['Key']: clean_list.append(dict) except Exception: return -1 return clean_list
def only_t1t2(src, names): """ This function... :param src: :param names: :return: """ if src.endswith("TissueClassify"): # print "Keeping T1/T2!" try: names.remove("t1_average_BRAINSABC.nii.gz") except ValueError: pass try: names.remove("t2_average_BRAINSABC.nii.gz") except ValueError: pass else: names.remove("TissueClassify") # print "Ignoring these files..." # for name in names: # print "\t" + name return names
def Qout_computing2(V_t0,V_t1,b,alpha): """ Compute the output flows Qout from the computed water volumes: Returns ------- Qout : scalar The outflow rate from the water store during the time-step (:math:`m^3/s`) """ Qout=b/2.*(V_t1**alpha+V_t0**alpha) return Qout
def mod_temp_deriv(heat_coeff: float, mass_mod: float, heat_cap_mod: float, mass_flow: float, temp_fuel: float, temp_mod: float, temp_in: float) -> float: """Compute time derivative of moderator temperature, $\frac{dT_mod}{dt}(t)$ Args: heat_coeff: float, heat transfer coefficient of fuel and moderator [J/K/sec] mass_mod: float, mass of moderator [kg] heat_cap_mod: float, specific Heat capacity of moderator [J/kg/K] mass_flow: float, total moderator/coolant mass flow rate [kg/sec] temp_fuel: float, temperature of fuel [K] temp_mod: float, temperature of moderator [K] temp_in: float, temperature of inlet coolant [K] """ return (heat_coeff / (mass_mod * heat_cap_mod)) * (temp_fuel - temp_mod) - (2 * mass_flow / mass_mod) * (temp_mod - temp_in)
def optiC2(R,s,tau,w): """Compute the optimal consumption of old generation Args: tau (float): percentage of contribution of the wage of the young agent w (float): wage s (float): savings R (float): gross return on saving Returns: (float): optimal consumption of old generation """ return R*s+tau*w
def __validate_for_scanners(address, port, domain): """ Validates that the address, port, and domain are of the correct types Pulled here since the code was the same Args: address (str) : string type address port (int) : port number that should be an int domain (str) : domain name that should be a string """ if not isinstance(address, str): raise TypeError(f"{address} is not of type str") if not isinstance(port, int): raise TypeError(f"{port} is not of type int") if domain is not None and not isinstance(domain, str): raise TypeError(f"{domain} is not a string") return True
def random_string (length, char_range = 127, char_offset = 128) : """Returns a string of `length` random characters in the interval (`char_offset`, `char_offset + char_range`). """ from random import random return "".join \ ( chr (int (random () * char_range + char_offset)) for c in range (length) )
def hash_function(num_row, a, b, m): """Hash function for calculating signature matrix :return hash number for each row number """ return (a * num_row + b) % m
def _uwsgi_args(host, port): """uWSGI""" return ( 'uwsgi', '--http', '{}:{}'.format(host, port), '--wsgi-file', '_wsgi_test_app.py', )
def add_dicts(dict1, dict2) -> dict: """ Return a dictionary with the sum of the values for each key in both dicts. """ return {x: dict1.get(x, 0) + dict2.get(x, 0) for x in set(dict1).union(dict2)}
def asymmetry_index(volume_left, volume_right): """It calculates the asymetry index of volumes of hippocampus.""" return 100*(volume_left - volume_right)/(volume_right + volume_left)
def cp_stations_adjoint2structure(py, stations_adjoint_directory, base_directory): """ copy the stations adjoint file to the structure. """ script = f"ibrun -n 1 {py} -m seisflow.scripts.shared.cp_stations_adjoint2structure --stations_adjoint_directory {stations_adjoint_directory} --base_directory {base_directory}; \n" return script
def version(libname): """ Returns library version """ try: _module = __import__(str(libname)) except ImportError: return None if hasattr(_module, '__version__'): return _module.__version__ else: return None
def get_byte_width(value_to_store, max_byte_width): """ Return the minimum number of bytes needed to store a given value as an unsigned integer. If the byte width needed exceeds max_byte_width, raise ValueError.""" for byte_width in range(max_byte_width): if 0x100 ** byte_width <= value_to_store < 0x100 ** (byte_width + 1): return byte_width + 1 raise ValueError
def haslinearpathRs(Rs_in, l_out, p_out): """ :param Rs_in: list of triplet (multiplicity, representation order, parity) :return: if there is a linear operation between them """ for mul_in, l_in, p_in in Rs_in: if mul_in == 0: continue for l in range(abs(l_in - l_out), l_in + l_out + 1): if p_out == 0 or p_in * (-1) ** l == p_out: return True return False
def sub_tracks(tracks_a, tracks_b): """ :param tracks_a: :param tracks_b: :return: """ tracks = {} for t in tracks_a: tracks[t.track_id] = t for t in tracks_b: tr_id = t.track_id if tracks.get(tr_id, 0): del tracks[tr_id] return list(tracks.values())
def q_conjugate(q): """ quarternion conjugate """ w, x, y, z = q return (w, -x, -y, -z)
def per_hurst_measure(measure): """Hurst computation parameter from periodogram slope fit. Parameters ---------- measure: float the slope of the fit using per method. Returns ------- H: float the Hurst parameter. """ # Compute measure H = float((1-measure)/2.) return H
def get_prefix_dict(form_dict): """Returns a tag prefix dictionary from a form dictionary. Parameters ---------- form_dict: dict The dictionary returned from a form that contains a column prefix table Returns ------- dict A dictionary whose keys names (or COLUMN_XX) and values are tag prefixes to prepend. """ tag_columns = [] prefix_dict = {} keys = form_dict.keys() for key in keys: if not key.startswith('column') or key.endswith('check'): continue pieces = key.split('_') check = 'column_' + pieces[1] + '_check' if form_dict.get(check, None) != 'on': continue if form_dict[key]: prefix_dict[int(pieces[1])] = form_dict[key] else: tag_columns.append(int(pieces[1])) return tag_columns, prefix_dict
def _get_sequence(value, n, channel_index, name): """Formats a value input for gen_nn_ops.""" if value is None: value = [1] else: value = [value] # elif not isinstance(value, collections_abc.Sized): # value = [value] current_n = len(value) if current_n == n + 2: return value elif current_n == 1: value = list((value[0],) * n) elif current_n == n: value = list(value) else: raise ValueError("{} should be of length 1, {} or {} but was {}".format( name, n, n + 2, current_n)) if channel_index == 1: return [1, 1] + value else: return [1] + value + [1]
def remove_prefix(string: str, prefix: str): """ Removes a prefix from a string if present. Args: string (`str`): The string to remove the prefix from. prefix (`str`): The prefix to remove. Returns: The string without the prefix. """ return string[len(prefix) :] if string.startswith(prefix) else string[:]
def meta_text(region: str, stage: str) -> str: """Construct a piece of text based on the region and fit stage. Parameters ---------- region : str TRExFitter Region to use. stage : str Fitting stage (`"pre"` or `"post"`). Returns ------- str Resulting metadata text """ if stage == "pre": stage = "Pre-fit" elif stage == "post": stage = "Post-fit" else: raise ValueError("stage can be 'pre' or 'post'") if "1j1b" in region: region = "1j1b" elif "2j1b" in region: region = "2j1b" elif "2j2b" in region: region = "2j2b" else: raise ValueError("region must contain '1j1b', '2j1b', or '2j2b'") return f"$tW$ Dilepton, {region}, {stage}"
def example_madmps_for_invenio_requiring_users(example_madmps_for_invenio): """Only those example maDMPs that have datasets and contributors.""" madmps = {} for name, madmp in example_madmps_for_invenio.items(): dmp = madmp["dmp"] for ds in dmp.get("dataset", []): for dist in ds.get("distribution", []): if dist.get("host") is not None: madmps[name] = madmp return madmps
def check_invalid(string,*invalids,defaults=True): """Checks if input string matches an invalid value""" # Checks string against inputted invalid values for v in invalids: if string == v: return True # Checks string against default invalid values, if defaults=True if defaults == True: default_invalids = ['INC','inc','incomplete','NaN','nan','N/A','n/a','missing'] for v in default_invalids: if string == v: return True # For valid strings return False
def toExport4F12(op): """Converts number to exportable 4.12 signed fixed point number.""" return int(round(op * 4096.0))
def divide(nmbr1, nmbr2): """Divide Function""" if nmbr2 == 0: raise ValueError('Can not divide bnmbr2 zero!') return nmbr1 / nmbr2
def attending_info_detect(in_data): """Detect if the email address is validate or not See if the email address include the @ sign to determine if it is a valid email address Args: in_data (dict): The dictionary that includes the attending's email address Returns: str or True: Indicate if it is a valid email address """ good_email = "@" in in_data["attending_email"] if good_email is not True: return "You entered a invalid email address, " return True
def norm_mean_dict(dict1): """ Mean normalization for whole dictonary :param dict1: input dictonary :return: mean normalized dictionary values """ for key, value in dict1.items(): dict1[key] = (dict1[key] - sum(dict1.values()) / len(dict1.values())) / ( max(dict1.values()) - min(dict1.values())) return dict1
def flux_f(energy, norm, index): """Flux function :param energy: Energy to evaluate :param norm: Flux normalisation at 100 TeV :param index: Spectral index :return: Flux at given energy """ return norm * (energy**-index) * (10.0**5) ** index
def parse_cookie_string(cookie, cookie_string): """ Parse cookies as strings. Args: cookie: Response cookie object. cookie_string: e.g. "cookie['SESSION']" e.g. "cookie" """ queue_val = '' if 'cookie' in cookie_string: # split cookie if '[' in cookie_string: # e.g. "cookie['SESSION']" => SESSION cookie_key = cookie_string.split("[")[1][1:-2] try: cookie_val = eval(cookie_string) except (TypeError, ValueError, NameError, SyntaxError): cookie_val = cookie_string queue_val = '{}={}'.format(cookie_key, cookie_val) else: temp_list = [] for ky, vak in cookie.items(): temp_list.append('{}={}'.format(ky, vak)) queue_val = '; '.join(temp_list) return queue_val
def distance_pure_python(ps, p1): """ Distance calculation using numpy with jit(nopython=True) """ distances = [] x1 = p1[0] y1 = p1[1] for x0, y0 in ps: distance_squared = (x0 - x1) ** 2 + (y0 - y1) ** 2 distances.append(distance_squared) return distances
def _new_format(template, variables): """Format a string that follows the {}-based syntax. """ return template.format(**variables)
def split_mailbox(mailbox, return_extension=False): """Try to split an address into parts (local part and domain name). If return_extension is True, we also look for an address extension (something foo+bar). :return: a tuple (local part, domain<, extension>) """ domain = None if "@" not in mailbox: localpart = mailbox else: parts = mailbox.split("@") if len(parts) == 2: localpart = parts[0] domain = parts[1] else: domain = parts[-1] localpart = "@".join(parts[:-1]) if not return_extension: return (localpart, domain) extension = None if "+" in localpart: localpart, extension = localpart.split("+", 1) return (localpart, domain, extension)
def heading4(text): """Formats text as heading 4 in Markdown format. Args: text(string): Text to format Return: string: Formatted text. """ return '#### {0:s}'.format(text.strip())
def create_callsign(raw_callsign): """ Creates callsign-as-dict from callsign-as-string. :param raw_callsign: Callsign-as-string (with or without ssid). :type raw_callsign: str :return: Callsign-as-dict. :rtype: dict """ if '-' in raw_callsign: call_sign, ssid = raw_callsign.split('-') else: call_sign = raw_callsign ssid = 0 return {'callsign': call_sign, 'ssid': int(ssid)}
def update_timer_interval(acq_state, seconds_per_sample): """ A callback function to update the timer interval. The timer interval is set to one day when idle. Args: acq_state (str): The application state of "idle", "configured", "running" or "error" - triggers the callback. seconds_per_sample (float): The user specified sample rate value in seconds per sample. Returns: float: Timer interval value in ms. """ interval = 1000*60*60*24 # 1 day if acq_state == 'running': interval = seconds_per_sample * 1000 # Convert to ms return interval
def version_is_compatible(imp_version, version): """Determine whether versions are compatible. :param imp_version: The version implemented :param version: The version requested by an incoming message. """ if imp_version is None: return True if version is None: return False version_parts = version.split('.') imp_version_parts = imp_version.split('.') try: rev = version_parts[2] except IndexError: rev = 0 try: imp_rev = imp_version_parts[2] except IndexError: imp_rev = 0 if int(version_parts[0]) != int(imp_version_parts[0]): # Major return False if int(version_parts[1]) > int(imp_version_parts[1]): # Minor return False if (int(version_parts[1]) == int(imp_version_parts[1]) and int(rev) > int(imp_rev)): # Revision return False return True
def other_p(msg, lst): """ (Player, list) -> Player Function returnes other player from list of 2 """ if msg == lst[0]: return lst[1] return lst[0]
def _indent( txt: str ) -> str: """return the text with all lines indented one indent step """ return "".join( map( lambda s: "" if s.strip() == "" else " " + s + "\n", txt.split( "\n" ) ))
def get_goal_object(mission): """ Interpret agent observations in terms relative object location. Currently only works for levels GoToObj, GoToLocal, GoToObjMaze and GoTo :param mission: :return: """ COLOR_TO_IDX = { 'red': 0, 'green': 1, 'blue': 2, 'purple': 3, 'yellow': 4, 'grey': 5 } OBJECT_TO_IDX = { 'unseen': 0, 'empty': 1, 'wall': 2, 'floor': 3, 'door': 4, 'locked_door': 5, 'key': 6, 'ball': 7, 'box': 8, 'goal': 9, 'lava': 10 } goal_object = mission.split()[-2:] encoded_goal = [OBJECT_TO_IDX[goal_object[1]], COLOR_TO_IDX[goal_object[0]]] return(encoded_goal)
def _link_stats_are_zero(statistics, keys): """ Verify that all statistics whose keys are present are zero """ for key in keys: if statistics.get(key) != 0: return False return True
def mean(data): """Return the sample arithmetic mean of data.""" n = len(data) if n < 1: raise ValueError('len < 1') return sum(data) / float(n)
def extractBigrams(sentence): """ Extracts the bigrams from a tokenized sentence. Applies some filters to remove bad bigrams """ bigrams = [(stem(tok1.lower()), stem(tok2.lower())) for tok1, tok2 in zip(sentence, sentence[1:])] # filter bigrams bigrams = [(tok1, tok2) for tok1, tok2 in bigrams if not (tok1 in nltk.corpus.stopwords.words('english') and tok2 in nltk.corpus.stopwords.words('english')) and tok1 not in string.punctuation and tok2 not in string.punctuation] return bigrams
def filter_by_overlap(regions): """ Iterate all regions and remove those that overlap more than 25% with a better region :param regions: Dictionary of regions (key: chrm, value: list of regions [start, end, reads, bin_start sd]) :return: """ # For each chromosome, we look if some regions are overlapping more than 25% for chrm, reg_lst in regions.items(): regions2 = [] if len(reg_lst) > 1: # List of regions to skip because they are overlapping a better region to_skip = [] for i, r1 in enumerate(reg_lst): if i in to_skip: continue # Add the region regions2.append(r1) resolution = r1[1] - r1[0] start_limit = r1[0] + 0.25 * resolution end_limit = r1[1] - 0.25 * resolution # Compare it with region not as good (since sorted) for j, r2 in enumerate(reg_lst): if j > i: if start_limit < r2[0] < end_limit or start_limit < r2[1] < end_limit: # r2 is overlapping with r1, so we're going to discard it to_skip.append(j) regions[chrm] = regions2 return regions
def identical(obj, other, bs=4096): """Takes two file-like objects and return whether they are identical or not.""" s, t = obj.tell(), other.tell() while True: a, b = obj.read(bs), other.read(bs) if not a or not b or a != b: break obj.seek(s), other.seek(t) return a == b
def tokenize_sentence(untokenized_str): """ Returns a tokenized string Args: untokenized_str : a given sentence Returns: list of words from the given sentence """ return [word for word in untokenized_str.split(" ")]
def fib_clean(n): """ Calcuate the nth Fibonacci number, without unnecesarry work""" if n == 2: return 1, 1 else: tmp, b = fib_clean(n-1) a = b b = b + tmp return a, b
def maximum_sum_subarray(a): """returns subarray [l, r) with maximal sum s""" s = 0 # prefix sum min_s, min_i = 0, -1 # minimum on s[0..r - 1] l, r, max_s = 0, 1, a[0] for i, e in enumerate(a): s += e # suppose i is right boundary, # then l - 1 is the minimum on s[0..r - 1] if s - min_s > max_s: l = min_i + 1 r = i + 1 max_s = s - min_s if s < min_s: min_i = i min_s = s return l, r, max_s
def flattenEmailAddresses(addresses): """ Turn a list of email addresses into a comma-delimited string of properly formatted, non MIME-encoded email addresses, suitable for use as an RFC 822 header @param addresses: sequence of L{EmailAddress} instances """ return ', '.join(addr.pseudoFormat() for addr in addresses)
def monomial_divides(A, B): """ Does there exist a monomial X such that XA == B? Examples ======== >>> from sympy.polys.monomials import monomial_divides >>> monomial_divides((1, 2), (3, 4)) True >>> monomial_divides((1, 2), (0, 2)) False """ return all(a <= b for a, b in zip(A, B))
def lzw_compression(string) -> str: """ compression using the Lempel-Ziv-Welch algorithm (LZW). """ dictionary = {'+':'0', '/':'1', '0':'2', '1':'3', '2':'4', '3':'5', '4':'6', '5':'7', '6':'8', '7':'9', '8':'10', '9':'11', '=':'12', 'A':'13', 'B':'14', 'C':'15', 'D':'16', 'E':'17', 'F':'18', 'G':'19', 'H':'20', 'I':'21', 'J':'22', 'K':'23', 'L':'24', 'M':'25', 'N':'26', 'O':'27', 'P':'28', 'Q':'29', 'R':'30', 'S':'31', 'T':'32', 'U':'33', 'V':'34', 'W':'35', 'X':'36', 'Y':'37', 'Z':'38', 'a':'39', 'b':'40', 'c':'41', 'd':'42', 'e':'43', 'f':'44', 'g':'45', 'h':'46', 'i':'47', 'j':'48', 'k':'49', 'l':'50', 'm':'51', 'n':'52', 'o':'53', 'p':'54', 'q':'55', 'r':'56', 's':'57', 't':'58', 'u':'59', 'v':'60', 'w':'61', 'x':'62', 'y':'63', 'z':'64', '\n':65} dict_size = 66 sequence = "" compressed_im = [] for char in string: sequence_char = sequence + char if sequence_char in dictionary: sequence = sequence_char else: compressed_im.append(dictionary[sequence]) dictionary[sequence_char] = str(dict_size) dict_size += 1 sequence = char # Output the code for sequence. if sequence: compressed_im.append(dictionary[sequence]) return ' '.join(compressed_im)
def dec2bin(decimal, bits) -> str: """ Converts a decimal number to it's 2nd complement binary representation :param decimal: decimal to be converted :param bits: number of bits for binary representation :return: string containing binary representation of decimal number """ binary = bin(decimal & int("1" * bits, 2))[2:] return ("{0:0>%s}" % bits).format(binary)
def ref_to_model_name(s): """Take the '#/definitions/...' string in a $ref: statement, and return the name of the model referenced""" return s.split('/')[-1].replace("'", "").replace('"', '').strip()
def overflow(c): """overflow""" v = "c.o" return v
def optional_apply(f, value): """ If `value` is not None, return `f(value)`, otherwise return None. >>> optional_apply(int, None) is None True >>> optional_apply(int, '123') 123 Args: f: The function to apply on `value`. value: The value, maybe None. """ if value is not None: return f(value)
def rename_sls_hostnames(sls_variables): """Parse and rename SLS switch names. The operation needs to be done in two passes to prevent naming conflicts. Args: sls_variables: Dictionary containing SLS variables. Returns: sls_variables: Dictionary containing renamed SLS variables. """ # First pass rename leaf ==> leaf-bmc for key, value in sls_variables["HMN_IPs"].copy().items(): new_name = key.replace("-leaf-", "-leaf-bmc-") sls_variables["HMN_IPs"].pop(key) sls_variables["HMN_IPs"][new_name] = value for key, value in sls_variables["MTL_IPs"].copy().items(): new_name = key.replace("-leaf-", "-leaf-bmc-") sls_variables["MTL_IPs"].pop(key) sls_variables["MTL_IPs"][new_name] = value for key, value in sls_variables["NMN_IPs"].copy().items(): new_name = key.replace("-leaf-", "-leaf-bmc-") sls_variables["NMN_IPs"].pop(key) sls_variables["NMN_IPs"][new_name] = value # Second pass rename agg ==> leaf for key, value in sls_variables["HMN_IPs"].copy().items(): new_name = key.replace("-agg-", "-leaf-") sls_variables["HMN_IPs"].pop(key) sls_variables["HMN_IPs"][new_name] = value for key, value in sls_variables["MTL_IPs"].copy().items(): new_name = key.replace("-agg-", "-leaf-") sls_variables["MTL_IPs"].pop(key) sls_variables["MTL_IPs"][new_name] = value for key, value in sls_variables["NMN_IPs"].copy().items(): new_name = key.replace("-agg-", "-leaf-") sls_variables["NMN_IPs"].pop(key) sls_variables["NMN_IPs"][new_name] = value return sls_variables
def is_mole(c: str) -> bool: """Evaluate whether this character a mole.""" return c == "o"
def bids_add_run_number(bids_suffix, run_no, run_mult): """ Safely add run number to BIDS suffix Handle prior existence of run-* in BIDS filename template from protocol translator :param bids_suffix, str :param run_no, int :return: new_bids_suffix, str """ if "run-" in bids_suffix: # Preserve existing run-* value in suffix print(' * BIDS suffix already contains run number - skipping') new_bids_suffix = bids_suffix else: if run_mult > 0: if '_' in bids_suffix: # Add '_run-xx' before final suffix bmain, bseq = bids_suffix.rsplit('_', 1) new_bids_suffix = '%s_run-%02d_%s' % (bmain, run_no, bseq) else: # Isolated final suffix - just add 'run-xx_' as a prefix new_bids_suffix = 'run-%02d_%s' % (run_no, bids_suffix) else: new_bids_suffix = bids_suffix return new_bids_suffix
def normalizeStrongPadding(strong, strong_template='000000'): """ Normalizes the padding on a strong number so it matches the template :param strong: :param strong_template: :return: """ return (strong + '0000000000')[:len(strong_template)]
def bbox_vert_aligned_left(box1, box2): """ Returns true if the left boundary of both boxes is within 2 pts """ if not (box1 and box2): return False return abs(box1.left - box2.left) <= 2
def filesystem_safe(name): """Returns a filesystem safe version of a test name. Args: * name (str) - The name of a test case, as provided to `api.test` inside a GenTests generator. Returns a str which is nominally safe for use as a file name. """ return ''.join('_' if c in '<>:"\\/|?*\0' else c for c in name)
def is_palindrome_dict(head): """ Returns true if the linked list is a palindrome, false otherwise Creates a dictionary of with the node's value as the key, and the list of positions of where this value occurs in the linked list as the value. Iterates through the list of values and checks that their indexes sum up to the length of the list - 1 (ie same value at index 0 and l -1, same at 2 and l - 3 etc) >>> linked_list = LinkedList() >>> is_palindrome_dict(linked_list.head) True >>> linked_list.insert(20) >>> linked_list.insert(11) >>> linked_list.insert(20) >>> is_palindrome_dict(linked_list.head) True >>> linked_list = LinkedList() >>> linked_list.insert(20) >>> linked_list.insert(11) >>> linked_list.insert(11) >>> linked_list.insert(20) >>> is_palindrome_dict(linked_list.head) True >>> linked_list.insert(20) >>> linked_list.insert(11) >>> linked_list.insert(20) >>> linked_list.insert(20) >>> is_palindrome_dict(linked_list.head) False >>> linked_list = LinkedList() >>> linked_list.insert(12) >>> linked_list.insert(11) >>> linked_list.insert(20) >>> is_palindrome_dict(linked_list.head) False """ if not head or not head.next: return True d = {} pos = 0 while head: if head.val in d.keys(): d[head.val].append(pos) else: d[head.val] = [pos] head = head.next pos += 1 checksum = pos - 1 middle = 0 for v in d.values(): if len(v) % 2 != 0: middle += 1 else: step = 0 for i in range(0, len(v)): if v[i] + v[len(v) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
def _make_divisible(v, divisor, min_value=None): """https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py """ if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v
def check_if_intersected(coord_a, coord_b): """ Check if the rectangular b is not intersected with a :param coord_a: dict with {y_min, x_min, y_max, x_max} :param coord_b: same as coord_a :return: true if intersected, false instead """ return \ coord_a['x_max'] > coord_b['x_min'] and \ coord_a['x_min'] < coord_b['x_max'] and \ coord_a['y_max'] > coord_b['y_min'] and \ coord_a['y_min'] < coord_b['x_max']
def fixIoU(bb1, bb2): """ Calculate the fix Intersection over Union (IoU) of two bounding boxes. fixiou = intersection_area / min(bb1_area, bb2_area) Parameters ---------- bb1 : set Keys: ('x1', 'y1', 'x2', 'y2') The (x1, y1) position is at the top left corner, the (x2, y2) position is at the bottom right corner bb2 : set Keys: ('x1', 'y1', 'x2', 'y2') Returns ------- float in [0, 1] """ assert bb1[0] < bb1[2] and bb1[1] < bb1[3], print(bb1) assert bb2[0] < bb2[2] and bb2[1] < bb2[3], print(bb2) # determine the coordinates of the intersection rectangle x_left = max(bb1[0], bb2[0]); y_top = max(bb1[1], bb2[1]) x_right = min(bb1[2], bb2[2]); y_bottom = min(bb1[3], bb2[3]) if x_right < x_left or y_bottom < y_top: return 0.0 # The intersection of two axis-aligned bounding boxes is always an # axis-aligned bounding box intersection_area = (x_right - x_left) * (y_bottom - y_top) # compute the area of both AABBs bb1_area = (bb1[2] - bb1[0]) * (bb1[3] - bb1[1]) bb2_area = (bb2[2] - bb2[0]) * (bb2[3] - bb2[1]) # compute the fix intersection over union by taking the intersection fixiou = intersection_area / min(bb1_area, bb2_area) assert fixiou >= 0.0 and fixiou <= 1.0 return fixiou
def _prod(iterable): """ Product of a list of numbers. Faster than cp.prod for short lists like array shapes. """ product = 1 for x in iterable: product *= x return product
def serialize_ap_features(apdict): """serialize ap features to add to database""" out = {} out["fname"] = apdict["fname"] out["fpath"] = apdict["fpath"] out["mouse_id"] = apdict["mouse_id"] out["sweep"] = apdict["sweep"] out["treatment"] = apdict["treatment"].lower().strip() out["cell_side"] = apdict["cell_side"].lower().strip() out["cell_n"] = apdict["cell_n"] if not apdict["peak_index"]: out["ap_max_voltage"] = None out["max_dydx"] = None out["firing_threshold_voltage"] = None out["ap_amplitude"] = None out["AHP_amplitude"] = None out["FWHM"] = None return out out["ap_max_voltage"] = float(apdict["ap_max_voltage"][0]) out["max_dydx"] = float(apdict["max_dydx"][0]) out["firing_threshold_voltage"] = float(apdict["firing_threshold_voltage"]) out["ap_amplitude"] = float(apdict["ap_amplitude"]) out["AHP_amplitude"] = float(apdict["AHP_amplitude"]) out["FWHM"] = float(apdict["fwhm"]) return out
def as_array(value): """ Checks whether or not the given value is a list. If not, the value is wrapped in a list. :param value: List or Other. The value to wrap in a list if it isn't already one. :return: The value as a lit. """ if not isinstance(value, list): return [value] return value
def num(value): """Parse number as float or int.""" value_float = float(value) try: value_int = int(value) except ValueError: return value_float return value_int if value_int == value_float else value_float
def check_waypoints_correct(waypoints, goal_point): """ checks if final waypoint matches with the goal point has a built in try catch to see if waypoints is empty or not """ #waypoints = waypoint_array.tolist() try: if waypoints[-1] == tuple(goal_point): return True else: #print("not correct", waypoints[-1], goal_point) return False except IndexError: #print("no waypoints", waypoints) return False