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]: ...
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])/...
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_a...
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): ...
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, rem...
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 ...
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 ...
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: ...
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(...
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...
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 no...
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 al...
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_lis...
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, Assertio...
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 s...
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: ...
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 co...
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: ...
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 na...
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 ...
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...
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_s...
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...
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.value...
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.) ...
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)...
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: valu...
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 stri...
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 te...
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....
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 ...
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 Tr...
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()...
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 '...
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 i...
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.sp...
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. ...
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 ...
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...
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 to...
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 ove...
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]...
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.pseudoForma...
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 z...
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', '...
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...
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...
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. "...
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: ...
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 f...
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 th...
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...
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...
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 ...
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_si...
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 T...