content
stringlengths
42
6.51k
def _create_path(directory, filename): """ Returns the full path for the given directory and filename. """ return f'{directory}/{filename}'
def get_only_updated_values(instance, data): """ """ new_data = dict() for key, value in data.items(): current_value = instance.__getattribute__(key) if value != current_value: new_data[key] = value return new_data
def check_data(data): """ Check the *data* argument and make sure it's a tuple. If the data is a single array, return it as a tuple with a single element. This is the default format accepted and used by all gridders and processing functions. Examples -------- >>> check_data([1, 2, 3]) ([1, 2, 3],) >>> check_data(([1, 2], [3, 4])) ([1, 2], [3, 4]) """ if not isinstance(data, tuple): data = (data,) return data
def recall(TP, FN): """Sensitivity, hit rate, recall, or true positive rate""" return (TP) / (TP + FN)
def swap_column(content, col_index, col_info=[]): """ Swap column position into the table Arguments: - the table content, a list of list of strings: - First dimension: the columns - Second dimensions: the column's content - cursor index for col - optional information to append from command line Returns: - the table content, a list of list of strings: - First dimension: the columns - Second dimensions: the column's content """ nb_col = len(content) if col_index == nb_col: to_swap = col_index - 2 else: to_swap = col_index col_saved = content[to_swap] del content[to_swap] content.insert(col_index - 1, col_saved) return content
def custom_dict_chunking(basedict, field, how_many): """ splits a dict value based on comma x amount of times :param basedict: a dict with keys and messy values :param field: what key to split in the dict :param how_many: how many fields should remain after splitting :return: clean dict (hopefully) """ new_dict_list = [] for v in basedict[field]: new_dict_list.append(v.split(",", how_many)) basedict[field] = new_dict_list return basedict
def modulus(intf, ints): """ overpython.modulus(intf, ints) Calculate the modulus of intf and ints. Raises ValueError if intf/ints is a string. """ try: return float(intf) % float(ints) except ValueError: raise ValueError("%s/%s is not a number" % (intf, ints))
def orfs(dna,frame=0) : """ This function outputs a list of all ORFs found in string 'dna', using triplet boundaries defined by frame position 'frame' dna is the dna sequence to be analysed frame is the offset (0,1 or 2) from start of the sequence to scan triplets """ orfs=[] orf='' start_codons=['atg'] stop_codons=['tga','tag','taa'] start_codon_active = False for i in range(frame, len(dna),3): codon=dna[i:i+3].lower() if start_codon_active == False and codon in start_codons : start_codon_active = True if start_codon_active and codon in stop_codons : orfs.append(orf+codon) orf='' start_codon_active = False else: if start_codon_active: orf=orf+codon return orfs
def isUnmarked(s): """If string s is unmarked returns True otherwise False. """ if len(s) > 0: return s[0] != '*' else: return False
def fibonacci(n): """ assumes n an int != 0 returns Fibonacci of n """ assert type(n) == int and n >= 0 if n == 0 or n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2)
def split_line_num(line): """Split each line into line number and remaining line text Args: line (str): Text of each line to split Returns: tuple consisting of: line number (int): Line number split from the beginning of line remaining text (str): Text for remainder of line with whitespace stripped """ line = line.lstrip() acc = [] while line and line[0].isdigit(): acc.append(line[0]) line = line[1:] return (int(''.join(acc)), line.lstrip())
def pv_f(fv,r,n): """Objective: estimate present value fv: fture value r : discount period rate n : number of periods formula : fv/(1+r)**n e.g., >>>pv_f(100,0.1,1) 90.9090909090909 >>>pv_f(r=0.1,fv=100,n=1) 90.9090909090909 >>>pv_f(n=1,fv=100,r=0.1) 90.9090909090909 """ return fv/(1+r)**n
def decompress(x, slen, n): """ Take as input an encoding x, a bytelength slen and a length n, and return a list of integers v of length n such that x encode v. If such a list does not exist, the encoding is invalid and we output False. """ if (len(x) > slen): print("Too long") return False w = list(x) u = "" for elt in w: u += bin((1 << 8) ^ elt)[3:] v = [] # Remove the last bits while u[-1] == "0": u = u[:-1] try: while (u != "") and (len(v) < n): # Recover the sign of coef sign = -1 if u[0] == "1" else 1 # Recover the 7 low bits of abs(coef) low = int(u[1:8], 2) i, high = 8, 0 # Recover the high bits of abs(coef) while (u[i] == "0"): i += 1 high += 1 # Compute coef coef = sign * (low + (high << 7)) # Enforce a unique encoding for coef = 0 if (coef == 0) and (sign == -1): return False # Store intermediate results v += [coef] u = u[i + 1:] # In this case, the encoding is invalid if (len(v) != n): return False return v # IndexError is raised if indices are read outside the table bounds except IndexError: return False
def _is_acyclic(edges: set): """ Use the number of nodes (NN) and the number of edges (NE) to determine whether an undirected graph has a ring: NE >= NN: has a ring NE < NN: does not have a ring Args: edges: a set of Edge. """ NE = len(edges) nodes = set() for edge in edges: node1, node2 = edge.get_nodes() nodes.add(node1) nodes.add(node2) NN = len(nodes) return True if NE >= NN else False
def parse_boundary(text): """Parse a string which represents the boundary of a value. :param str text: the input string. :return tuple: (lower boundary, upper boundary). Examples: parse_boundary("1, 2") == (1, 2) """ msg = "Input lower and upper boundaries separated by comma." try: if "," not in text: raise ValueError(msg) # float('Inf') = inf ret = [float(x) for x in text.split(",")] if len(ret) != 2: raise ValueError(msg) if ret[0] >= ret[1]: raise ValueError("lower boundary >= upper boundary") except Exception as e: raise ValueError(str(e)) return ret[0], ret[1]
def assert_repr_reproduces(object_): """ The second assertion assumes that __eq__ checks actual equality. In fact - it skips docstring. """ assert repr(eval(repr(object_))) == repr(object_) assert eval(repr(object_)) == object_ return True
def cur_mkt_score(ds, fs): """ Given a bunch of participants' open-interests and fees, calculate the total current market score. """ total = 0 for d, f in zip(ds, fs): total += (d**.3) * (f**.7) return total
def get_word2vector(wordsense, word2vecDic = dict()): """ :param wordsense: :param word2vecDic: :return: """ wd = wordsense.split('.')[0] if wd in word2vecDic: return word2vecDic[wd] elif wordsense.split('.')[0] in word2vecDic: return word2vecDic[wordsense.split('.')[0]]
def difference_of(lhs, rhs): """ Computes the difference of two posting lists, that is, the elements in the first list which are not elements in the second list. """ i = 0 j = 0 answer = [] while (i < len(lhs)): if (j == len(rhs) or lhs[i] < rhs[j]): answer.append(lhs[i]) i += 1 elif (rhs[j] < lhs[i]): j += 1 else: i += 1 return answer
def fermat_test(n): """Statistically test the primality of a number using the Fermat algorithm. """ return (2**(n - 1) % n) == 1
def dimensions(data, array=False): """Takes in a string map and returns a 2D list map and map dimensions""" if not array: data = [[col for col in row] for row in data.split('\n')] height = len(data) width = max(len(col) for col in data) return data, height, width
def binary_search_recursive(arr, val, start, end): """searches arr for val between and including the indices start and end. Parameters: arr (array): array to search. val (type used in array): value to search for in arr. start (int): start index to search for val in arr. end (int): end index to search for val in arr. Returns: (int) : index of val in arr if val is found. Otherwise returns -1 if val cannot be found in arr. """ #base case, we've searched the entire array if end < start: return -1 mid = ((end - start) // 2) + start #we found the value we want. Hurray! if arr[mid] == val: return mid elif arr[mid] > val: #search lower half of the array return binary_search_recursive(arr, val, start, mid - 1) elif arr[mid] < val: #search upper half of the array return binary_search_recursive(arr, val, mid + 1, end)
def convert_to_float(string): """Convert a string to a float, if possible """ return float(string) if string else 0.0
def _check_weights(weights): """Check to make sure weights are valid""" if weights not in (None, "uniform", "distance") and not callable(weights): raise ValueError( "weights not recognized: should be 'uniform', " "'distance', or a callable function" ) return weights
def getinfo(segment, spec): """ Method to get basic information about a spectral line that was only detected by segment detection. Calculates the peak intensity, the sigma of the peak, and the very rough FWHM of the line. Parameters ---------- segment : list List of two points (the start and end of the segement) spec : a single admit.util.Spectrum or list of admit.util.Spectrum. If a list, the Spectrum with the highest peak (or lowest in case of absorption spectrum) will be used. Returns ------- Tuple containing the peak intensity, sigma, and FHWM in km/s of the line """ if spec is None: return None,None,None peak = 0.0 ratio = 0.0 rms = 0.0 fwhm = 0.0 end = 0 start = 0 if type(spec) is list: pkloc = 0 # find the strongest peak from all input spectra for i in range(len(spec)): tmp = spec[i].peak(segment) if tmp > peak: pkloc = i peak = tmp thespectrum = spec[pkloc] else: thespectrum = spec if len(thespectrum) > 0: rms = thespectrum.rms() #print("Specinfo nchan=%d, rms = %f" % (segment[1]-segment[0],rms)) peak = thespectrum.peak(segment) if (rms > 0): ratio = peak/rms else: ratio = 0.0 fwhm = thespectrum.fwhm(segment) else: return None, None, None return peak, ratio, fwhm
def remove_dir_from_path(path: str, directory: str): """Remove a directory form a string representing a path Args: path: String resembling path directory: String resembling directory to be removed from path Returns: String resembling input path with directory removed """ return path.replace(directory, "")
def getSymbols(equation): """Return a set of symbols present in the equation""" stopchars=['(',')','*','/','+','-',','] symbols=set() pos=0 symbol="" for i, c in enumerate(equation,1): if c in stopchars: pos=i if(len(symbol)!=0): if not all(i.isdigit() for i in symbol): if not '.' in symbol: symbols.add(symbol) symbol="" else: symbol+=c if(len(symbol)!=0): if not all(i.isdigit() for i in symbol): if not '.' in symbol: symbols.add(symbol) symbols.discard('complex') return symbols
def runge_kutta(y, x, dx, f): """ y is the initial value for y x is the initial value for x dx is the time step in x f is derivative of function y(t) """ k1 = dx * f(y, x) k2 = dx * f(y + 0.5 * k1, x + 0.5 * dx) k3 = dx * f(y + 0.5 * k2, x + 0.5 * dx) k4 = dx * f(y + k3, x + dx) return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6.
def as_valid_fraction(x): """Ensure that x is between 0 and 1.""" if x < 0.: x = 0. elif x > 1.: x = 1. return x
def _find_minimum_alignment(offset: int, base_alignment: int, prev_end: int) -> int: """ Returns the minimum alignment that must be set for a field with ``base_alignment`` (the one inherent to the type), so that the compiler positioned it at ``offset`` given that the previous field ends at the position ``prev_end``. """ # Essentially, we need to find the minimum k such that: # 1) offset = m * base_alignment * 2**k, where m > 0 and k >= 0; # (by definition of alignment) # 2) offset - prev_offset < base_alignment * 2**k # (otherwise the compiler can just as well take m' = m - 1). if offset % base_alignment != 0: raise ValueError( f"Field offset ({offset}) must be a multiple of the base alignment ({base_alignment}).") alignment = base_alignment while offset % alignment == 0: if offset - prev_end < alignment: return alignment alignment *= 2 raise ValueError( f"Could not find a suitable alignment for the field at offset {offset}; " "consider adding explicit padding.")
def magnitude(vector_1, vector_2): """ This just-in-time compiled CUDA kernel is a device function for calculating the distance between vectors. """ total = 0 for i in range(0, 3): total += (vector_1[i] - vector_2[i]) ** 2 return total ** 0.5
def is_function(func_var): """ Check if a variable is a callable function object. """ import inspect import types if not func_var: return False can_call = callable(func_var) chk_type = isinstance(func_var, ( types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType)) positive = inspect.isfunction(func_var) return can_call or chk_type or positive
def convert_masks(seq): """Converts # masking to the [MASK] symbol used by BERT.""" seq = list(seq) for i, c in enumerate(seq): if c == "#": seq[i] = "[MASK]" return "".join(seq)
def kernel_primitive_zhao(x, s0=0.08333, theta=0.242): """ Calculates the primitive of the Zhao kernel for given values. :param x: point to evaluate :param s0: initial reaction time :param theta: empirically determined constant :return: primitive evaluated at x """ c0 = 1.0 / s0 / (1 - 1.0 / -theta) if x < 0: return 0 elif x <= s0: return c0 * x else: return c0 * (s0 + (s0 * (1 - (x / s0) ** -theta)) / theta)
def naka_rushton_allow_decreasing(c, a, b, c50, n): """ Naka-Rushton equation for modeling contrast-response functions. Taken from Dan to allow for decreasing contrast responses (eg. VIP cells). If bounded, returns the same as naka_rushton. (?) Where: c = contrast a = Rmax (max firing rate) b = baseline firing rate c50 = contrast response at 50% n = exponent """ return (a*(c/c50)**n + b)/((c/c50)**n + 1)
def weighted_precision(relationships, run_rules, run_confidences, threshold=0.0, allow_reverse=False): """ From a list of rules and confidences, calculates the proportion of those rules that match relationships injected into the data, weighted by confidence. """ wrong_relationship_weight = 0 total_relationship_weight = 0 for j, rule in enumerate(run_rules): # Skip rules with confidence below threshold if run_confidences[j] < threshold or rule[0] in rule[1]: continue total_relationship_weight += run_confidences[j] # Check if rule is correct if rule[0] in relationships: if relationships[rule[0]] == rule[1]: continue if len(rule[1]) == 1: body_pred = list(rule[1])[0] # If learning reverse rule is acceptable, check for reverse rule for rules with only one body predicate if allow_reverse and body_pred in relationships and relationships[body_pred] == {rule[0]}: continue # Learning x-->x is not wrong, technically elif len(rule) == 2 and rule[0] == body_pred: continue wrong_relationship_weight += run_confidences[j] if total_relationship_weight != 0: return (total_relationship_weight - wrong_relationship_weight) / total_relationship_weight else: return 0
def split_string0(buf): """split a list of zero-terminated strings into python not-zero-terminated bytes""" if isinstance(buf, bytearray): buf = bytes(buf) # use a bytes object, so we return a list of bytes objects return buf.split(b'\0')[:-1]
def calculate_appointments(new_set, old_set): """ Calculate different appointment types. Used for making useful distinctions in the email message. new_set will be the fresh set of all available appointments at a given interval old_set will the previous appointments variable getting passed in. Ex1: Addition of HONEOYE new_set = {'LIVERPOOL', 'BROOKLYN', 'HONEOYE', 'KINGSTON'} old_set = {'LIVERPOOL', 'BROOKLYN', 'KINGSTON'} returns ->-> new_appointments = {'HONEOYE'} all_appointments = {'LIVERPOOL', 'BROOKLYN', 'KINGSTON', HONEOYE} Ex2: No Changes new_set = {'LIVERPOOL', 'BROOKLYN', 'HONEOYE', 'KINGSTON'} old_set = {'LIVERPOOL', 'BROOKLYN', 'HONEOYE', 'KINGSTON'} returns ->-> new_appointments = set() (empty set) all_appointments = {'LIVERPOOL', 'BROOKLYN', 'HONEOYE', 'KINGSTON'} """ new_appointments = new_set.difference(old_set) # set of All appointments minus set of Old appointments yields the set of New appointments old_appointments = new_set.intersection(old_set) # New intersect Old. yields those appointments that (intersect is equivalent the overlap in a venn diagram) return new_appointments, old_appointments # Return new sets
def numtomaxn2(n): """This function rearranges the digits of a number to its maximum value possible """ if type(n) is not int: raise TypeError("Input an integer only") digits = list(str(n)) digits.sort(reverse=True) return int(''.join(digits))
def extract_data_from_str_lst(str_lst, tag, num_args=1): """ General purpose routine to extract any static from a log (text) file Args: file_name (str): file name or path to the file, can either be absolute or relative tag (str): string at the beginning of the line num_args (int): number of arguments separated by ' ' or ',' to extract after the tag Returns: list: List of arguments extracted as strings """ def multiple_delimiter_split(s, seps): res = [s] for sep in seps: s, res = res, [] for seq in s: res += seq.split(sep) while "" in res: res.remove("") return res collector = [] ind_start = len(tag.split()) for line_in_file in str_lst: if line_in_file.startswith(tag): collector = [] vals = multiple_delimiter_split(line_in_file, (" ", ",")) if num_args == 1: collector.append(vals[ind_start]) else: collector.append(vals[ind_start : num_args + ind_start]) return collector
def keep_numeric(s: str) -> str: """ Keeps only numeric characters in a string ------ PARAMS ------ 1. 's' -> input string """ return "".join(c for c in list(s) if c.isnumeric())
def fast_sum_ternary(J, s): """Helper function for calculating energy in calc_e(). Iterates couplings J.""" assert len(J)==(len(s)*(len(s)-1)//2) e = 0 k = 0 for i in range(len(s)-1): for j in range(i+1,len(s)): if s[i]==s[j]: e += J[k] k += 1 return e
def wheel(pos): """ Helper to create a colorwheel. :param pos: int 0-255 of color value to return :return: tuple of RGB values """ # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if pos < 0 or pos > 255: return 0, 0, 0 if pos < 85: return 255 - pos * 3, pos * 3, 0 if pos < 170: pos -= 85 return 0, 255 - pos * 3, pos * 3 pos -= 170 return pos * 3, 0, 255 - pos * 3
def GetDimensions(line): """ Parse and extract X, Y and Z dimensions from string Parameters ---------- line: string Line containing x, y, z dimensions Returns ------- (nx,ny,nz): (int,int,int) The dimensions on x, y, and z coordinate respectively Raises ------ ValueError: In case we try to parse a string to an int/float but the file is not in the expected format, this error will be raised """ try: split = line.split(" ") split = [x for x in split if x] # remove empty lines nx = int(split[0]) ny = int(split[1]) nz = int(split[2]) return (nx, ny, nz) except ValueError: raise ValueError('Invalid file format')
def _conditional_links(assembled_specs, app_name): """ Given the assembled specs and app_name, this function will return all apps and services specified in 'conditional_links' if they are specified in 'apps' or 'services' in assembled_specs. That means that some other part of the system has declared them as necessary, so they should be linked to this app """ link_to_apps = [] potential_links = assembled_specs['apps'][app_name]['conditional_links'] for potential_link in potential_links['apps']: if potential_link in assembled_specs['apps']: link_to_apps.append(potential_link) for potential_link in potential_links['services']: if potential_link in assembled_specs['services']: link_to_apps.append(potential_link) return link_to_apps
def atom_dict_to_atom_dict(d, aniso_dict): """Turns an .mmcif atom dictionary into an atomium atom data dictionary. :param dict d: the .mmcif atom dictionary. :param dict d: the mapping of atom IDs to anisotropy. :rtype: ``dict``""" charge = "pdbx_formal_charge" atom = { "x": d["Cartn_x"], "y": d["Cartn_y"], "z": d["Cartn_z"], "element": d["type_symbol"], "name": d.get("label_atom_id"), "occupancy": d.get("occupancy", 1), "bvalue": d.get("B_iso_or_equiv"), "charge": d.get(charge, 0) if d.get(charge) != "?" else 0, "alt_loc": d.get("label_alt_id") if d.get("label_alt_id") != "." else None, "anisotropy": aniso_dict.get(int(d["id"]), [0, 0, 0, 0, 0, 0]), "is_hetatm": False } for key in ["x", "y", "z", "charge", "bvalue", "occupancy"]: if atom[key] is not None: atom[key] = float(atom[key]) return atom
def _ragged_eof(exc): """Return True if the OpenSSL.SSL.SysCallError is a ragged EOF.""" return exc.args == (-1, 'Unexpected EOF')
def checksum16(payload): """ Calculates checksum of packet. :param payload: Bytearray, data to which the checksum is going to be applied. :return: Int, checksum result given as a number. """ chk_32b = 0 # accumulates short integers to calculate checksum j = 1 # iterates through payload # make odd length packet, even if len(payload) % 2 == 1: payload.append(0x00) while j < len(payload): # extract short integer, in little endian, from payload num_16b = payload[j - 1] + (payload[j] << 8) # accumulate chk_32b += num_16b j += 2 # increment pointer by 2 bytes # adds the two first bytes to the other two bytes chk_32b = (chk_32b & 0xFFFF) + ((chk_32b & 0xFFFF0000) >> 16) # ones complement to get final checksum chk_16b = chk_32b ^ 0xFFFF return chk_16b
def full_path(csv): """Path to the csv_files. Used mainly for raw data.""" # Make sure we have the file ending if csv[-4:] != '.csv': csv = csv + '.csv' return f'csv_files\\{csv}'
def calculate_accuracy(test_tags, model_tags): """ Function to calculate the accuracy of the Viterbi algorithm by comparing the output of the POS tagger to the actual tags provided in the test set. """ num_correct = 0 total = 0 for test_taglist, model_taglist in zip(test_tags, model_tags): for test_pos, model_pos in zip(test_taglist, model_taglist): if test_pos == model_pos: num_correct += 1 total += 1 accuracy = round(num_correct/float(total), 3) * 100 return accuracy
def map_range_constrained(x, in_min, in_max, out_min, out_max): """Map value from one range to another - constrain input range.""" if x < in_min: x = in_min elif x > in_max: x = in_max return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def mock_run_applescript(script): """Don't actually run any applescript in the unit tests, ya dingbat. This function should return whatever type of object dialogs._run_applescript returns. Returns: tuple """ return (1, "", "")
def greet(person): """ Return a greeting, given a person. Args: person (str): The person's name. Returns: str. The greeting. Example: >>> greet('Matt') Hello Matt! """ return "Hello {}!".format(person)
def count_set_bits(n): """ Returns the number of set bits in the input. """ count = 0 while n != 0: last_bit = n & 1 if last_bit == 1: count += 1 n = n >> 1 return count
def is_libris_edition_id(identifier): """ Check if identifier is old-format Libris ID. @param identifier: ID to check @type identifier: string """ if len(identifier) <= 9 and identifier.isdigit(): return True return False
def InStrRev(text, subtext, start=None, compare=None): """Return the location of one string in another starting from the end""" assert compare is None, "Compare modes not allowed for InStrRev" if start is None: start = len(text) if subtext == "": return len(text) elif start > len(text): return 0 else: return text[:start].rfind(subtext)+1
def parseName(lines): """ Args: lines: all information on all identified molecular lines. nested list Returns: list of names of identified elements. Str list """ result = [] for line in lines: name = line["name"] result.append(name) return result
def listify_dict(dict_): """ turn each element that is not a list into a one-element list """ if not isinstance(dict_, dict): return dict_ def listify_sub(key): """ actual worker """ value = dict_[key] if isinstance(value, dict): return [listify_dict(value)] elif isinstance(value, list): return [listify_dict(el) for el in value] else: return [value] keys = dict_.keys() values = [listify_sub(key) for key in keys] return dict(zip(keys, values))
def is_crack(x, y): """Determine whether a pair of particles define the crack.""" output = 0 crack_length = 0.3 p1 = x p2 = y if x[0] > y[0]: p2 = x p1 = y # 1e-6 makes it fall one side of central line of particles if p1[0] < 0.5 + 1e-6 and p2[0] > 0.5 + 1e-6: # draw a straight line between them m = (p2[1] - p1[1]) / (p2[0] - p1[0]) c = p1[1] - m * p1[0] # height a x = 0.5 height = m * 0.5 + c if (height > 0.5 * (1 - crack_length) and height < 0.5 * (1 + crack_length)): output = 1 return output
def get_product_linear_fair(sets, bound): """ Return the product of the input sets (1-D combinatorial) in breadth-first order. @param sets: Input sets @type sets: List @param bound: Max number of the product @type bound: Int @return: Product (partial) of the input sets @rtype: List """ for s in sets: if not s: return [] product = [[s[0] for s in sets]] cnt = 1 ptrs = [1] * len(sets) while (cnt < bound) or (bound < 0): done = True for idx, si in enumerate(sets): # pre pre = [s[0] for s in sets[:idx]] # post post = [s[0] for s in sets[idx + 1:]] # pivot if ptrs[idx] < len(si): pivot = si[ptrs[idx]] ptrs[idx] += 1 cnt += 1 product.append(pre + [pivot] + post) if ptrs[idx] < len(si): done = False if done: break if (bound > 0) and (len(product) > bound): return product[:bound] return product
def mod_inverse(X, MOD): """ return X^-1 mod MOD """ return pow(X, MOD - 2, MOD)
def smartsplit(t, s, e): """ smartsplit(text, start_position, end_position) Splits a string into parts according to the number of characters. If there is a space between the start and end positions, split before a space, the word will not end in the middle. If there are no spaces in the specified range, divide as is, by the finite number of characters. """ t = t.replace("\r\n", "\n").replace("\r", "\n") if(e >= len(t)): return [t] l = [] tmp="" i=0 for sim in t: i = i + 1 tmp = tmp + sim if(i<s): continue if(i==e): l.append(tmp) tmp="" i=0 continue if((i > s and i < e) and (sim == chr(160) or sim == chr(9) or sim == chr(10) or sim == chr(32))): l.append(tmp) tmp="" i=0 continue if(len(tmp)>0): l.append(tmp) return l
def ensure_evidence(badge_data: dict) -> dict: """Given badge_data, ensure 'evidence' key exists with list value""" if 'evidence' not in badge_data: badge_data['evidence'] = [{}] return badge_data
def fitness_function(items, m): """Return sum of cost for child if weight < m otherwise return 0.""" cost = 0 weight = 0 for key, is_selected in items.items(): if is_selected: weight += key[1] cost += key[0] res = cost if weight <= m else 0 return res
def cloudfront_origin_request_query_string_behavior(query_string_behavior): """ Property: OriginRequestQueryStringsConfig.QueryStringBehavior """ valid_values = ["none", "whitelist", "all"] if query_string_behavior not in valid_values: raise ValueError( 'QueryStringBehavior must be one of: "%s"' % (", ".join(valid_values)) ) return query_string_behavior
def get_bit(value, n): """ :param value: :param n: :return: """ if value & (1 << n): return 1 else: return 0
def remove_or_ingredients(string: str) -> str: """Removes any 'or' ingredients. Example: >>> 1/2 small eggplant or a few mushrooms or half a small zucchini or half a pepper 1/2 small eggplant """ or_index = string.find(" or ") if or_index != -1: return string[:or_index] return string
def topleft2corner(topleft): """ convert (x, y, w, h) to (x1, y1, x2, y2) Args: center: np.array (4 * N) Return: np.array (4 * N) """ x, y, w, h = topleft[0], topleft[1], topleft[2], topleft[3] x1 = x y1 = y x2 = x + w y2 = y + h return x1, y1, x2, y2
def text_to_markdownv2(text: str) -> str: """Helper function to convert plaintext into MarkdownV2-friendly plaintext. This method is based on the fastest method available in: https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string :param text: The text to convert. :return: The MarkdownV2-friendly plaintext. """ for ch in ('_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'): if ch in text: text = text.replace(ch, "\\" + ch) return text
def isPrime(n): """Returns True if n is prime.""" if n == 2:return True if n == 3:return True if n % 2 == 0:return False if n % 3 == 0:return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True
def convert_lx_to_qx(lx_list: list): """ Converts a list of lx values to a qx list. """ q_values = [] for i, l in enumerate(lx_list[:-1]): q_values.append(1 - lx_list[i + 1] / l) return q_values
def parse_problems(lines): """ Given a list of lines, parses them and returns a list of problems. """ res = [list(map(int, ln.split(" "))) for ln in lines] return res
def int2str(val, max_dec=1024): """Make string from int. Hexademical representaion will be used if input value greater that 'max_dec'.""" if val > max_dec: return "0x%x" % val else: return "%d" % val
def decreasing_strict(args): """ Ensure that the values in args are strict decreasing. """ return [args[i-1] >= args[i] for i in range(1,len(args))]
def normalize_wiki_text(text): """ Normalizes a text such as a wikipedia title. @param text text to normalize @return normalized text """ return text.replace("_", " ").replace("''", '"')
def solve(string): """ Capitalizing function """ list_strings = string.rstrip().split(" ") result = "" for item in list_strings: if item[0].isalpha(): item = item.title() result += item + " " return result.strip()
def next_permutation(a): """Generate the lexicographically next permutation inplace. https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order Return false if there is no next permutation. """ # Find the largest index i such that a[i] < a[i + 1]. If no such # index exists, the permutation is the last permutation for i in reversed(range(len(a) - 1)): if a[i] < a[i + 1]: break # found else: # no break: not found a.reverse() return False # no next permutation # Find the largest index j greater than i such that a[i] < a[j] j = next(j for j in reversed(range(i + 1, len(a))) if a[i] < a[j]) # Swap the value of a[i] with that of a[j] a[i], a[j] = a[j], a[i] # Reverse sequence from a[i + 1] up to and including the final element a[n] a[i + 1:] = reversed(a[i + 1:]) return True
def is_digit(s): """ Return True if given str is a digit or a dot(in float), which means it is in `0,1,2,3,4,5,6,7,8,9,.`, False otherwise. @param --- `s` A symbol in string """ return s in "1234567890."
def guess_platform(product_id): """Guess platform of a product according to its identifier.""" if len(product_id) == 40 and product_id.startswith('L'): return 'Landsat' if product_id.startswith('ASA'): return 'Envisat' if product_id.startswith('SAR'): return 'ERS' if product_id.startswith('S1'): return 'Sentinel-1' raise ValueError('Unrecognized product ID.')
def scorefun(x, threshold=70): """ Score function used by `finalgrade` """ if x['total'] >= threshold: return 100 else: return x['total']
def moveTime(time, start): """ Move the given time to the given start time. Example: print moveTime((15, 35), 5) # 5, 20 :type time: (int, int) :type start: int :rtype: (int, int) """ srcStartTime, srcEndTime = time duration = srcEndTime - srcStartTime if start is None: startTime = srcStartTime else: startTime = start endTime = startTime + duration if startTime == endTime: endTime = startTime + 1 return startTime, endTime
def implyGate(argumentValues): """ Method that evaluates the IMPLY gate Note that this gate requires a specific definition of the two inputs. This definition is specifed in the order of the events provided in the input file As an example, BE1->BE2 is translated as: <define-gate name="TOP"> <imply> <basic-event name="BE1"/> <basic-event name="BE2"/> </imply> </define-gate> @ In, argumentValues, list, list of values @ Out, outcome, float, calculated outcome of the gate """ keys = list(argumentValues.keys()) if argumentValues[keys[0]]==1 and argumentValues[keys[1]]==0: outcome = 0 else: outcome = 1 return outcome
def plur(word, n, plural=lambda n: n != 1, convert=lambda w, p: w + 's' if p else w): """ Pluralize word based on number of items. This function provides rudimentary pluralization support. It is quite flexible, but not a replacement for functions like ``ngettext``. This function takes two optional arguments, ``plural()`` and ``convert()``, which can be customized to change the way plural form is derived from the original string. The default implementation is a naive version of English language plural, which uses plural form if number is not 1, and derives the plural form by simply adding 's' to the word. While this works in most cases, it doesn't always work even for English. The ``plural(n)`` function takes the value of the ``n`` argument and its return value is fed into the ``convert()`` function. The latter takes the source word as first argument, and return value of ``plural()`` call as second argument, and returns a string representing the pluralized word. Return value of the ``convert(w, p)`` call is returned from this function. Here are some simple examples:: >>> plur('book', 1) 'book' >>> plur('book', 2) 'books' # But it's a bit naive >>> plur('box', 2) 'boxs' The latter can be fixed like this:: >>> exceptions = ['box'] >>> def pluralize(word, is_plural): ... if not is_plural: ... return word ... if word in exceptions: ... return word + 'es' ... return word + 's' >>> plur('book', 2) 'books' >>> plur('box', 2, convert=pluralize) 'boxes' """ return convert(word, plural(n))
def is_valid_payload(payload): """Validates search query size""" if ( len(payload["cards"]) < 1 or len(payload["cards"]) > 15 or any(not card.strip() or len(card) < 3 for card in payload["cards"]) ): return False return True
def get_serialized_obj_from_param(page, param): """ Get content of a param that contains a java serialized object (base64 gziped or only base64 of raw) :param page: The page source code for search in it :param param: The param that will be searched :return: Param content with java serialized object or None """ page = str(page).replace("\\n", "\n") full_param = "name=\""+param+"\"" for i in page.strip().split('\n'): tokens = i.strip().split(" ") for t in tokens: # get param value if full_param in t: index = tokens.index(full_param) if 'value=\"' in tokens[index+1]: obj = tokens[index+1].split("\"")[1] if obj.startswith("H4sI") or obj.startswith("rO0"): #return last_link, obj return obj elif tokens[index+2]: obj = tokens[index+2].split("\"")[1] if obj.startswith("H4sI") or obj.startswith("rO0"): #return last_link, obj return obj return None
def find_f_index(x, col): """find feature index giving matrix index""" return x[0] * col + x[1] + 1
def __assign_if_set(old_val, json, key): """ Helper method for returning the value of a dictionary entry if it exists, and returning a default value if not :param old_val: The default to return if key is not found in json. Typically the current assignment of the variable this function is being used against. :param json: :param key: :return: """ if key in json and json[key] is not None: return json[key] else: return old_val
def reorder_acq_dict(acq_dict): """ Re-order the dictionary of files associated with an acquisition to a format that is better suited for multi-raft outputs. """ d_out = {} for raft, v in acq_dict.items(): for sensor, vv in v.items(): for image_type, fits_file in vv.items(): if image_type not in d_out: d_out[image_type] = {} if raft not in d_out[image_type]: d_out[image_type][raft] = {} d_out[image_type][raft][sensor] = fits_file return d_out
def get_fpn_config(base_reduction=8): """BiFPN config with sum.""" p = { 'nodes': [ {'reduction': base_reduction << 3, 'inputs_offsets': [3, 4]}, {'reduction': base_reduction << 2, 'inputs_offsets': [2, 5]}, {'reduction': base_reduction << 1, 'inputs_offsets': [1, 6]}, {'reduction': base_reduction, 'inputs_offsets': [0, 7]}, {'reduction': base_reduction << 1, 'inputs_offsets': [1, 7, 8]}, {'reduction': base_reduction << 2, 'inputs_offsets': [2, 6, 9]}, {'reduction': base_reduction << 3, 'inputs_offsets': [3, 5, 10]}, {'reduction': base_reduction << 4, 'inputs_offsets': [4, 11]}, ], 'weight_method': 'fastattn', } return p
def process_wav(wav_rxfilename, process): """Return preprocessed wav_rxfilename. Args: wav_rxfilename: input process: command which can be connected via pipe, use stdin and stdout Returns: wav_rxfilename: output piped command """ if wav_rxfilename.endswith("|"): # input piped command return wav_rxfilename + process + "|" else: # stdin "-" or normal file return "cat {} | {} |".format(wav_rxfilename, process)
def stdr_val(val_freqv, mean, std): """Make data zero mean and with unit variance with given mean and standard deviation.""" return (val_freqv - mean) / std
def pack_address(value, *, is_reg=False, is_deref=False): """Pack an address into an integer.""" return value | is_reg << 15 | is_deref << 14
def get_string_event_attribute_succession_rep(event1, event2, event_attribute): """ Get a representation of the feature name associated to a string event attribute value Parameters ------------ event1 First event of the succession event2 Second event of the succession event_attribute Event attribute to consider Returns ------------ rep Representation of the feature name associated to a string event attribute value """ return "succession:" + str(event_attribute) + "@" + str(event1[event_attribute]) + "#" + str( event2[event_attribute])
def map_recommendations(recommendations, inv_user_index, inv_doc_index, mode='usr2doc'): """ Map internal IDs to real IDs. Supports three modes depending on the recommendations shape. Args: recommendations: A list of tuples to be mapped from internal IDs to real IDs. The tuples can have one of the following shapes. (userID,docID,value),(userID,userID,value)or (docID,docID,value). inv_user_index: A dictionary with the userID -> user index. inv_doc_index: A dictionary with the docID -> doc index. mode: One of (usr2doc,usr2usr,doc2doc). This depends on the shape of the recommendations. Returns: recommendations: A list of tuples mapped from internal IDs to real IDs. """ if mode == 'usr2usr': recommendations = [(inv_user_index[rec[0]], inv_user_index[rec[1]], rec[2]) for rec in recommendations] elif mode == 'doc2doc': recommendations = [(inv_doc_index[rec[0]], inv_doc_index[rec[1]], rec[2]) for rec in recommendations] else: recommendations = [(inv_user_index[rec[0]], inv_doc_index[rec[1]], rec[2]) for rec in recommendations] return recommendations
def get_fil_int(col) -> str: """ Integer based filter conditions :param col: :return: """ return """ if %s is not None: data = data[data["%s"] == int(%s)] """ % (col, col, col)
def argdef(*args): """Return the first non-None value from a list of arguments. Parameters ---------- value0 First potential value. If None, try value 1 value1 Second potential value. If None, try value 2 ... valueN Last potential value Returns ------- value First non-None value """ args = list(args) arg = args.pop(0) while arg is None and len(args) > 0: arg = args.pop(0) return arg
def scope_vars(var_list, scope): """ Args: var_list: list of `tf.Variable`s. Contains all variables that should be searched scope: str. Scope of the variables that should be selected """ return [v for v in var_list if scope in v.name]
def interseccion(m1,b1,m2,b2): """Da la interseccion entre dos rectas""" if m1 != m2: return False x = (b2-b1) / (m1 - m2) y = m1* x + b1 return (x,y)
def get_diagnosis(case): """Returns site and diagnosis.""" site = 'unknown' diagnosis = 'unknown' if 'diagnoses' in case: for d in case['diagnoses']: _site = d.get('site', None) if _site: site = _site _diagnosis = d.get('diagnosis', None) if _diagnosis: diagnosis = _diagnosis return site, diagnosis
def erb_bandwidth(fc): """Bandwitdh of an Equivalent Rectangular Bandwidth (ERB). Parameters ---------- fc : ndarray Center frequency, or center frequencies, of the filter. Returns ------- ndarray or float Equivalent rectangular bandwidth of the filter(s). """ # In Hz, according to Glasberg and Moore (1990) return 24.7 + fc / 9.265