content
stringlengths
42
6.51k
def maybe_ansi(text: str, level: int, use_ansi: bool = True): """ Adds an ANSI highlight corresponding to the level, if enabled """ return f"\u001b[{(level % 6) + 31}m{text}\u001b[0m" if use_ansi else text
def clean_path(path): """ Add ws:///@user/ prefix if necessary """ if path[0:3] != "ws:": while path and path[0] == "/": path = path[1:] path = "ws:///@user/" + path return path
def default_flist_reader(root, flist): """ flist format: impath label\nimpath label\n ...(same to caffe's filelist) """ imlist = [] with open(flist, 'r') as rf: for line in rf.readlines(): splitted = line.strip().split() if len(splitted) == 2: impath, ...
def _coco_category_name_id_dict_from_list(category_list): """Extract ``{category_name: category_id}`` from a list.""" # check if this is a full annotation json or just the categories category_dict = {category['name']: category['id'] for category in category_list} return category_dic...
def station_name(f): """ From the file name (f), extract the station name. Gets the data from the file name directly and assumes the file name is formatted as Data/Station_info.csv. """ return f.split('/')[1].split('_')[0]
def _format_key(key): """Format table key `key` to a string.""" schema, table = key table = table or "(FACT)" if schema: return "{}.{}".format(schema, table) else: return table
def set_verbose(amount=1): """ Set the current global verbosity level Parameters: amount (int): the new level Returns: int: the new level """ global VERBOSE VERBOSE = amount return VERBOSE
def matrix_get(main: list, pos: int): """ Get a subset of a matrix. """ n = len(main) if n % 2 != 0: print("ERROR: Cannot split matrix with odd num of cols/rows. Stop.") return None mid = n // 2 sub = [] if pos == 0: for col in range(mid): column = [...
def get_domain_concept_id(domain_table): """ A helper function to create the domain_concept_id field :param domain_table: the cdm domain table :return: the domain_concept_id """ return domain_table.split('_')[0] + '_concept_id'
def handle_arg(arg_index, arg_key, arg_value, args, kwargs): """ Replace an argument with a specified value if it does not appear in :samp:`{args}` or :samp:`{kwargs}` argument list. :type arg_index: :obj:`int` :param arg_index: Index of argument in :samp:`{args}` :type arg_key: :obj:`str` ...
def tidy_gene(tcr_gene): """ :param tcr_gene: The named TCR gene as read in the data file :return: A properly IMGT-recognised TCR gene name """ # Remove leading zeroes and inappropriate 'C' in 'TRXY' tcr_gene = tcr_gene.replace('TCR', 'TR').replace('V0', 'V').replace('J0', 'J').replace('D0', 'D...
def getForecastRun(cycle, times): """ Get the latest forecast run (list of objects) from all all cycles and times returned from DataAccessLayer "grid" response. Args: cycle: Forecast cycle reference time times: All available times/cycles Returns: DataTime ar...
def remove_point(vector, element): """ Returns a copy of vector without the given element """ vector.pop(vector.index(element)) return vector
def get_otpauth_url(user, domain, secret_key): """Generate otpauth url from secret key. Arguments: .. csv-table:: :header: "argument", "type", "value" :widths: 7, 7, 40 "*user*", "string", "User." "*domain*", "string", "Domain." "*secret_key*", "string", "Base 32 s...
def init_defaults(*sections): """ Returns a standard dictionary object to use for application defaults. If sections are given, it will create a nested dict for each section name. This is sometimes more useful, or cleaner than creating an entire dict set (often used in testing). Args: se...
def bgr_to_rgb(ims): """Convert a list of images from BGR format to RGB format.""" out = [] for im in ims: out.append(im[:,:,::-1]) return out
def neg(effect): """ Makes the given effect a negative (delete) effect, like 'not' in PDDL. """ return (-1, effect)
def cmyk2rgb(c, m, y, k): """ Convert cmyk color to rbg color. """ r = 1.0 - min(1.0, c + k) g = 1.0 - min(1.0, m + k) b = 1.0 - min(1.0, y + k) return r, g, b
def approx_second_derivative(f,x,h): """ Numerical differentiation by finite differences. Uses central point formula to approximate second derivative of function. Args: f (function): function definition. x (float): point where second derivative will be approximated h (float): ste...
def longestCommonSubsequence(text1: str, text2: str) -> int: """ Time: O(mn) Space: O(mn) """ dp = [[0 for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)] for i in range(len(text1)): for j in range(len(text2)): if text1[i] == text2[j]: dp[i + ...
def ascii_to_string(s): """ Convert the array s of ascii values into the corresponding string. """ return ''.join(chr(i) for i in s)
def str2int(s): """ Returns integer representation of product state. Parameters ---------- s : str """ return int(s, 2)
def color_prob(prob): """Generates a purple shade which is darker for higher probs""" return (f"rgb({240 - 120*prob:0.0f}, {240 - 130*prob:0.0f}, " f"{240 - 70*prob:0.0f})")
def get_urls(doc_names: list) -> list: """ :param doc_names: list of wiki url (the key word) :return: """ urls = [] for doc_name in doc_names: url = "https://en.wikipedia.org/wiki/" + doc_name urls.append(url) return urls
def to_seconds(hours, minutes, seconds): """Return the amount of seconds in the given hours, minutes, seconds.""" return hours * 3600 + minutes * 60 + seconds
def series_char(series,header): """Uses interquartile range to estimate amplitude of a time series.""" series=[float(s) for s in series[1:] if s!="NA"] head = [header[i] for i,s in enumerate(series) if s!="NA"] if series!=[]: mmax = max(series) mmaxloc = head[series.index(mmax)] ...
def rgbsplit(image): """ Converts an RGB image to a 3-element list of grayscale images, one for each color channel""" return [[[pixel[i] for pixel in row] for row in image] for i in (0,1,2)]
def check_command_format(command): """Check command format """ if len(command[0].split(' ')) != 2: return True for twocell in command[1].split(';'): if len(twocell.split(' ')) != 2: return True for cell in twocell.split(' '): if len(cell.split(',')) != 2: ...
def compute_CIs(data, alpha=0.95): """ compute confidence interval for a bootstrapped set of data... """ n = len(data) data = sorted(data) lower_bound, upper_bound = int(n*(1-alpha)/2), int(n*(1+alpha)/2) return data[lower_bound], data[upper_bound]
def goa_criterion_1_check(x1_list, x2_list): """ function Calculate the difference between the current and previous x_list if the difference between each pair in the same index of the current and previous x_list is less than 1%: the x_list is good enough to be returned :param ...
def run_intcode(memory): """Run an Intcode program from memory and return the result""" instr_ptr = 0 while instr_ptr < len(memory): opcode = memory[instr_ptr] if opcode == 99: return memory[0] if opcode == 1: store = memory[instr_ptr + 3] num1 = m...
def exponent(numbers): """Raises the 0th number to the 1..Nth numbers as powers""" result = numbers[0] for number in numbers[1:]: result *= number return result
def is_bool(element): """True if boolean else False""" check = isinstance(element, bool) return check
def generate_set_l2_general(ident,size=13): """ return list of page numbers that collide in L2 TLB, likely independent of addressing function """ assert ident >= 0 assert ident < 256 l=[] k=0 for x in range(size): k+=1 l.append(k * 2**16 + ident) assert len(l) == size...
def centroid_points(points): """Compute the centroid of a set of points. Warning ------- Duplicate points are **NOT** removed. If there are duplicates in the sequence, they should be there intentionally. Parameters ---------- points : sequence A sequence of XYZ coordinates. ...
def get_nested_value(d, key): """Return a dictionary item given a dictionary `d` and a flattened key from `get_column_names`. Example: d = { 'a': { 'b': 2, 'c': 3, }, } key = 'a.b' will return: 2 """ if '.' n...
def sunday(text, pattern): """sunday string match Args: text, pattern Returns: int: match index, -1: not match """ # get index from right char_right_idx_dict = dict() for i in range(len(pattern)): # right pos char will replace left char_right_idx_dict[patter...
def percent_to_str(percent): """ Return a nice string given a percentage. """ s = "" if percent < 0: return "Unknown" return str(int(percent)) + "%"
def coverage(seq, seq_len): """ Return coverage of the sequence in the alignment. >>> coverage("AAAA----", 8) 50.0 """ res = len(seq.replace('-', '')) return 100.0 * res / seq_len
def operation(d, i, r): """Get operation from item. :param d: Report definition :type d: Dict :param i: Item definition :type i: Dict :param r: Meter reading :type r: usage.reading.Reading :return: operation :rtype: String """ return i.get('operation', '')
def get_string_index(strings, substrings, exact=False): """ Search for the first index in list of strings that contains substr string anywhere or, if exact=True, contains an exact match. Args: ----- strings : List of strings to be searched substrings : List of strings to be...
def sbox_inv(block): """Bitsliced implementation of the inverse s-box >>> x = [1, 2, 3, 4] >>> sbox_inv(sbox(x)) [1, 2, 3, 4] """ b = (block[2] & block[3]) ^ block[1] d = (block[0] | b) ^ block[2] a = (d & block[0]) ^ block[3] c = (a & b) ^ block[0] return [a, b, c, d]
def sum_even_fib_below(n): """ Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... :param n: :return: the sum of the even-valued terms """ ans ...
def get_exception_message(exception: Exception) -> str: """Returns the message part of an exception as string""" return str(exception).strip()
def mb(x): """Represent as MB""" return x / 10**6
def red(text): """ Shameless hack-up of the 'termcolor' python package by Konstantin Lepa - <https://pypi.python.org/pypi/termcolor> to reduce rependencies and only make red text. """ s = '\033[%dm%s\033[0m' % (31, text) return s
def make_filename(params, run): """Generate a filename based on params and run. params: (net, seed, freq, weight)""" nets = ['net_tunedrev', 'net_nofeedbackrev', 'net_disinhibitedrev'] return (f"population_vectors_{nets[int(params[0])]}" f".TunedNetwork_{params[1]}_{...
def moyenne(liste): """ calculer la moyenne """ print ( locals()) print ( globals()) return sum(liste)/len(liste)
def clean_output_string(s): """Cleans up an output string for comparison""" return s.replace("\r\n", "\n").strip()
def foo1(x): """ Returns x+1 Parameter x: The number to add to Precondition: x is a number (int or float) """ assert type(x) in [int,float], repr(x)+' is not a number' return x+1
def id_ee(value): """generate id""" return f"execution_environment={value}"
def collect_defaults(config_spec): """Extract the default values from config_spec as a dict of param_name:value. Inputs: config_spec: list of tuples of format (param_name, conversion_function, default), where default = None means no default. Outputs: defaults: d...
def _map_mdast(node): """ Walk a MDAST and return a "map" that includes just the hierarchy and types of nodes, but none of the inner content of those nodes. Can be used to easily compare, for example, two trees which represent the same basic content in two different languages, and verify that they p...
def truediv_operator(): """/: Division operator.""" class _Operand: def __truediv__(self, other): return "hipster R&B" return _Operand() / 0
def applyConstraint(data, constraint_func): """Return a subset of data that satisfies constraint_function If constraint_func is None, return back entire data Args: data: constraint_func: Returns: """ if constraint_func is None: return data else: outdata = ...
def size (N): """size(N:long) : int Returns the size of the number N in bits. """ bits = 0 while N >> bits: bits += 1 return bits
def partition(arr, left, right, pivot): """Partition function inplace Args: arr ([type]): [description] left ([type]): [description] right ([type]): [description] pivot ([type]): [description] """ sorted_i = left # Move pivot to the end pivot_value = arr[pivot] ...
def associate(keys, values, multiValues=False, allowDuplicates=False, shift=0, logger=None, verbose=True, sortKeys=True, sortValues=True): """ This function associate keys to values. If you set multiValues as True, multiple values can ba associated to each key, so the structure will be a dic...
def substitute(expr, d): """ Using a dictionary of substitutions ``d`` try and explicitly evaluate as much of ``expr`` as possible. :param Expression expr: The expression whose parameters are substituted. :param Dict[Parameter,Union[int,float]] d: Numerical substitutions for parameters. :return...
def calculate_derivative(x_value, c0, c1, c2, c3): """Get the first derivative value according to x_value and curve analysis formula y = c3 * x**3 + c2 * x**2 + c1 * x + c0 Args: x_value: value of x c3: curvature_derivative c2: curvature c1: heading_angle ...
def sane_fname(mbox): """ sanitise the mailbox name for notification """ ret = str(mbox) if "." in ret: ret = ret.split(".")[-1] return ret
def getFormat( self ) : """Checks if self has a getFormat method. If it does not, then None is returned. If it does then: 1) if getFormat returns a string or None then it is returned else getFormat must return an integer, n1. If n1 is 12 (default for legacy ENDL) then None is returned else returns string ...
def _GetBinnedHotlistViews(visible_hotlist_views, involved_users): """Bins into (logged-in user's, issue-involved users', others') hotlists""" user_issue_hotlist_views = [] involved_users_issue_hotlist_views = [] remaining_issue_hotlist_views = [] for view in visible_hotlist_views: if view.role_name in (...
def getgwinfo(alist): """Picks off the basic information from an input dictionary list (such as that returned by readGridworld) and returns it""" height = alist.get('height') width = alist.get('width') startsquare = alist.get('startsquare') goalsquare = alist.get('goalsquare') barrierp = ...
def fixture_real_base_context(real_spring_api, real_cram_api) -> dict: """context to use in cli""" return { "spring_api": real_spring_api, "cram_api": real_cram_api, }
def cowsay(msg: str) -> str: """ Generate ASCII picture of a cow saying something provided by the user. Refers to the true and original: https://en.wikipedia.org/wiki/Cowsay """ speech_bubble_border = len(msg) * '#' cow_speech_bubble = ( f'\n' f'##{speech_bubble_border}##\n' ...
def dfs(graph, source, path=None, explored=None): """Depth-First Search Recursive""" if not path: path = [] if not explored: explored = set() explored.add(source) path.append(source) for node in graph[source]: if node not in explored: dfs(graph, node, path...
def list_of_str(seq): """ Converting sequence of integers to list of strings. :param seq: any sequence :return: list of string """ return [str(el) for el in seq]
def str_list(input_Str): """convert string to list""" temp=input_Str.split(' ') #define temp list to save the result for i in range(len(temp)): temp[i]=float(temp[i]) return temp
def get_first_duplicate_freq(changes: list): """Find the first duplicate frequency. Args: changes: frequency changes Returns: first duplicate frequency """ cur_freq = 0 visited_freqs = set() while True: for change in changes: if cur_freq in visited_freq...
def _apply_colon_set(snode): """helper method for parse_patran_syntax""" ssnode = snode.split(':') if len(ssnode) == 2: nmin = int(ssnode[0]) nmax = int(ssnode[1]) new_set = list(range(nmin, nmax + 1)) elif len(ssnode) == 3: nmin = int(ssnode[0]) nmax = int(ssnode...
def reverse(dafsa): """Generates a new DAFSA that is reversed, so that the old sink node becomes the new source node. """ sink = [] nodemap = {} def dfs(node, parent): """Creates reverse nodes. A new reverse node will be created for each old node. The new node will get a reversed label and the...
def leastCommonMuliply(m:int, n:int) ->int: """ Return a least common multiply of a given two numbers param: int, int return LCM """ large = max(m,n) small = min(m,n) # if large is divisible by small returns large if large % small == 0: return large lcm = la...
def remove_none_tags(xml_string: str) -> str: """ Function for removing tags with None values. """ xml_string_splitted = xml_string.split("\n") xml_string_cleaned = [] for line in xml_string_splitted: if not line.strip() or ">None</" in line: continue xml_string_clean...
def get_ratios(L1, L2): """ Assume L1 and L2 as lists of equal lengths Return list of containing L1[i]/L2[i] """ ratios = [] for i in range(len(L1)): try: ratios.append(L1[i]/float(L2[i])) except ZeroDivisionError: ratios.append(float('NaN')) # Appends n...
def label_filter(label_key, label_value): """Return a valid label filter for operations.list().""" return 'labels."{}" = "{}"'.format(label_key, label_value)
def min_path(path): """ this function recives a path of a file and will find lightest path from point the upper left corner to the bottom right corner :param path: Sting a path that contains the Matrix :return: the weight of the minimum path """ # parses the file into a matrix matrix_l...
def get_valid_extension(extension_string): """ Convert an extension string into a tuple that can be used on an hdulist. Transform an extension string obtained from the command line into a valid extension that can be used on an hdulist. If the extension string is just the extension version, con...
def f(stack, k): """ Fake tail recursive function """ if k == 1: return stack stack = 0.5 * (stack + 2/stack) return f(stack, k-1)
def sqrt(a, m): """Compute two possible square roots of a mod m.""" assert m & 0b11 == 0b11 t = pow(a, (m + 1) >> 2, m) if t % 2 == 0: return t, m - t else: return m - t, t
def intlist(tensor): """ A slow and stupid way to turn a tensor into an iterable over ints :param tensor: :return: """ if type(tensor) is list: return tensor tensor = tensor.squeeze() assert len(tensor.size()) == 1 s = tensor.size()[0] l = [None] * s for i in rang...
def decrypt_letter(letter): """ (str) -> str Precondition: len(letter) == 1 and letter.isupper() Return letter decrypted by shifting 3 places to the left. >>> decrypt_letter('Y') 'V' """ # Translate to a number. ord_diff = ord(letter) - ord('A') # Apply the left shift. new_c...
def is_float3(items): """Verify that the sequence contains 3 :obj:`float`. Parameters ---------- items : iterable The sequence of items. Returns ------- bool """ return len(items) == 3 and all(isinstance(item, float) for item in items)
def invert_mapping(kvp): """Inverts the mapping given by a dictionary. :param kvp: mapping to be inverted :returns: inverted mapping :rtype: dictionary """ return {v: k for k, v in list(kvp.items())}
def user_model(role): """Return a user model""" return { "email": "user@email.com", "id": 99, "name": "User Name", "profile": { "institution": "User Institute", "occupation": "User occupation" }, "roles": [ f"jupyter:{role}" ...
def la_tamgiac(a,b,c): """Cho biet tam giac gi""" if a+b <= c or b+c <= a or c+a <= b: return 'Khong phai tam giac' else: if a == b or b == c or a == b: if a == b and b == c: return 'Tam giac deu' elif a*a+b*b==c*c or b*b+c*c==a*a or c*c+a*a==b...
def is_string_environment_variable(string): """Determines if string being sent in without the $ is a valid environmnet variable""" if len(string) == 0: return False return string[0].isalpha()
def cga_signature(b): """+-(...+)""" return 1 if b == 0 else (-1 if b == 1 else 1)
def sizes(ranges): """Get a list with the size of the ranges""" sizes = [] for r in ranges: sizes.append(r[1] - r[0]) # 1: end, 0: start return sizes
def argument(*name_or_flags, **kwargs): """Convenience function to properly format arguments to pass to the subcommand decorator. """ return list(name_or_flags), kwargs
def select_first(*args): """Return the first argument that's not None.""" for arg in args: if arg is not None: return arg return None
def create_error_message(message='Error was happened.'): """Create a error message dict for JSON :param message: error message :return: dict contain a error message """ return {'error': message}
def filter_null(item, keep_null=False, null_vals=None): """Function that returns or doesn't return the inputted item if its first value is either a False value or is in the inputted null_vals list. This function first determines if the item's first value is equivalent to False using bool(), with one exception;...
def read_binary(filepath): """return bytes read from filepath""" with open(filepath, "rb") as file: return file.read()
def mem_profile(func): """Profile memory usage of `func`. """ import tracemalloc tracemalloc.start() success = func() snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('lineno') print("[ Top 20 ]") for stat in top_stats[:20]: print(stat) return succes...
def robot_move(current, direction): """Moves robot one square, depending on current direction it is facing. Returns new current.""" if direction == 0: current = (current[0] - 1, current[1]) elif direction == 1: current = (current[0], current[1] + 1) elif direction == 2: current ...
def pad_right(string, chars, filler="0"): """ Should be called to pad string to expected length """ numchars = chars - len(string) tail = "" if numchars > 0: tail = filler * numchars return string + tail
def dict_count_to_freq(d): """Turns dictionary of counts to dictionary of frequencies""" tot_d = sum(d.values()) for val in d: d[val] /= float(tot_d) return d
def pa_test(a, b, c, d, e = None, f = None): """ ============ DOCTEST FOOD ============ >>> pa_test(1, 2, 3, 4, 5) (1, 2, 3, 4, 5, None) >>> pa = pa_test(_1, 2, 3, 4, 5) >>> pa(1) (1, 2, 3, 4, 5, None) """ return (a, b, c, d, e, f)
def annualYield(r, c): """Annual yield Returns: Simple interest rate necessary to yield the same amount of dollars yielded by the annual rate r compounded c times for one year Input values: r : interest rate c : number of compounding periods in a year """ y = ((1 + (r / c))...