content
stringlengths
42
6.51k
def get_class(d): """Get class name from the whole dictionary E.g., '{'index': 'data/Deploy/KLAC/KLAC0570/KLAC0570_12.jpg', 'prediction': ..., 'label': ...}' ==> (str) 'KLAC' """ return d['index'].split('/')[2]
def encode_utf8(u): """ Encode a UTF-8 string to a sequence of bytes. Args: u (str) : the string to encode Returns: bytes """ import sys if sys.version_info[0] == 2: u = u.encode('utf-8') return u
def generate_file_name(report_file): """Generates a report file name based on the file metadata.""" # If no filename is specified, use the file ID instead. file_name = report_file['fileName'] or report_file['id'] extension = '.csv' if report_file['format'] == 'CSV' else '.xml' return file_name + extension
def doubleslash(text): """Replaces / with // Args: text (str): location Returns: str: formatted location """ return text.replace('\\' , '\\\\')
def get_args (indata, prefix=''): """ Slightly esoteric function to build a tuple to be used as argument to constructor calls. Python dicts are not ordered, so we have to look at the number in the parameter's name and insert items appropriately into an ordered list """ ident=prefix+'arg' # need to pregenerat...
def add_notebook_volume(notebook, volume): """ Add the provided podvolume (dict V1Volume) to the Notebook's PodSpec. notebook: Notebook CR dict volume: Podvolume dict """ podspec = notebook["spec"]["template"]["spec"] if "volumes" not in podspec: podspec["volumes"] = [] podspec...
def inject_function_id(gw_config, function_id, title="yappa gateway"): """ accepts gw config as dict, finds where to put function_id, returns new dict """ gw_config["info"].update(title=title) for path, methods in gw_config["paths"].items(): for method, description in methods.items(): ...
def validate_comma_separated(ctx, param, value): """ Validate multiple string input values are comma-separated. Each of the value is put into a list, which is returned after validation. """ if value is None: return return value.split(',')
def is_number(s): """ Is s a number? True if 'tis so. False otherwise. """ try: float(s) return True except ValueError: return False
def _find_traces_for_automation(traces, item_id): """Find traces for an automation.""" return [trace for trace in traces if trace["item_id"] == item_id]
def clipstr(s, size, fill=" "): """Clips a string to a specific length, with an optional fill character.""" if len(s) > size: s = s[:size] if len(s) < size: s = fill * (size - len(s)) + s return s
def default_kernel_config(defn): """Creates a default kernel configuration suitable for general purpose inference. Parameters ---------- defn : hmm definition """ return [('beam', {}), ('hypers', { 'alpha_a': 4.0, 'alpha_b'...
def standardize_template_names(t): """Standardize names of templates for matching purposes.""" return t.strip().lower().replace(" ", "_")
def standardize_tag(tag): """Convert tag to a uniform string.""" return tag.lower().replace(" ", "_")
def pre_order_traversal(tree, path=[]): """Visit curr -> left -> right""" if tree: path.append(tree.value) pre_order_traversal(tree.left, path) pre_order_traversal(tree.right, path) return path
def alpha_vals(a,n): """ This function generates the values of \alpha to be used for cross validation. """ itrs=[] for i in range(0,n): itrs.append(a*0.9**i) itrs.reverse() return itrs
def read_data_line(line): """Process a line from data file. Assumes the following format: WORD W ER D i.e. word tab separated with pronunciation where pronunciation has space separated phonemes Args: line: string representing the one line of the data file Returns: chars:...
def format_number(number): """ Formats a number to a more readable format; 10000 -> 10,000 """ if isinstance(number, int): return '{:,d}'.format(number) if number is None: return 'Unknown' return '{:3.2f}'.format(number)
def merge_sort(arr): """ Merge sort repeatedly divides the arr then recombines the parts in sorted order """ l = len(arr) if l > 1: mid = l//2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < le...
def map_key(key) -> str: """Funcion para mapear las claves""" lookup = { "volume_level": "volume", "title": "title", "subtitle": "subtitle", "series_title": "series", "season": "season", "episode": "episode", "artist": "artist", "album_name": "albu...
def _sourcenames(short=False): """Return a list with the source names. :param short: True for shorter names, defaults to False :type short: bool, optional :return: Source names. :rtype: dict [list [str]] """ if short is False: sources = ["psicov", "ccmpred", "deepmetapsicov"] e...
def time_sync(time1, time2): """ finds the row index to time sync the collected data and returns start and end index """ ref = time2[1] ind = 0 while abs(ref - time1[ind]) > 5: ind += 1 start = time1[ind] return ind, ind+len(time2) # return 3580, 1157
def parse_sexp(sexp_iter): """ Transforms a sequence of s-expression tokens (given in string form) into a corresponding tree of strings. The given sequence is interpreted as the elements of an enclosing list expression, i.e. with a prepended "(" token and an appended ")" token. Example: parse_sexp...
def line_with_jacoco_test_header(line): """Check if the given string represents JaCoCo unit test header.""" return line == "Code coverage report BEGIN"
def multQuatLists(q0, q1): """Multiply two quaternions that are represented as lists.""" x0, y0, z0, w0 = q0 x1, y1, z1, w1 = q1 return [ w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1, w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1, w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1, w0 * w1 - x0 * x...
def getSquareDistance(p1, p2): """ Square distance between two points """ dx = p1[0] - p2[0] dy = p1[1] - p2[1] return dx * dx + dy * dy
def validation(size, training): """ Obtain the validation set corresponding to the given training set """ result = [] for i in range(0, size): if i not in training: result.append(i) return result
def mean_and_error(_data): """A helper for creating error bar""" import numpy as np _data = np.array(_data) _two_sigma = 2*np.std(_data) _mean = np.mean(_data) print(f"{_mean:.0f} +- {_two_sigma:.0f}") return _mean, _two_sigma
def isclose(float_a, float_b, rel_tol=1e-9, abs_tol=0.0): """ Once Python3.5 is applicable this function can be replaced by math.isclose """ return (abs(float_a - float_b) <= max(rel_tol * max(abs(float_a), abs(float_b)), abs_tol))
def Dic_Subset_Begin(indic,end_num): """ subset a dictionary by retaining only the beginning "end_num" elements. Note: 1. Test has been done for only the case that indic[key] is 1D ndarray. """ outdic={} for key,value in indic.items(): try: newvalue=value[0:end_num] ...
def inline_product(factors, seed): """Computes a product, using the __imul__ operator. Args: seed (T): The starting total. The unit value. factors (iterable[T]): Values to multiply (with *=) into the total. Returns: T: The result of multiplying all the factors into the unit value. ...
def _careful_add(a, b): """Return the sum `a + b`, else whichever is not `None`, else `None`.""" if a is None: return b if b is None: return a return a + b
def image_directive(image, width=None, align=None, alt=None): """Generate an RST Image directive.""" if width is None: width = '300' if align is None: align = 'center' if alt is None: alt = image return (".. image:: %s\n :width: %s\n :align: %s\n" " :alt:...
def read_label_file(file_path): """ Function to read labels from text files. Args: file_path: File path to labels. Returns: list of labels """ with open(file_path, "r") as f: lines = f.readlines() ret = {} for line in lines: pair = line.strip().split(maxsplit...
def partition(data): """ Partitions a list of data into three sections which are lower, equal, and equal to the pivot which is selected to be the last element in the list. """ pivot = len(data) -1 lower, equal, upper = [], [], [] for i in range(0, len(data), 1): if data[i] >...
def createLineSegment(sequence, maxLineSegmentLength, sequenceStringIndex): """ Creates a segment of the pyramid on one line. Params: sequence - Full string representing the sequence. maxLineSegmentLength - Maximum length of one line segment sequenceStringIndex - A reference to an index for fet...
def _merge_dict(a, b): """ Given two dicts, merge them into a new dict as a shallow copy. Keys on dictionary b will overwrite keys on dictionary a. :param a: a dictionary, may be None :type a: None | dict :param b: a dictionary, may be None :type b: None | dict :return: the result o...
def get_num_from_curr(raw_val): """ strips the random currency generation and returns a value """ op_str = raw_val.strip('+').strip(',').strip(' ').strip('$') return float(op_str)
def ntyped(var, types): """ Ensure that the "var" argument is among the types passed as the "types" argument, or is None. @param var: The argument to be typed. @param types: A tuple of types to check. @type types: tuple @returns: The var argument. >>> a = ntyped('abc', str) >>> type(...
def flatten(l): """ inefficiently flattens a list l: an arbitrary list """ if not l: return list(l) if isinstance(l[0], (list, tuple)): return flatten(l[0]) + flatten(l[1:]) return [l[0]] + flatten(l[1:])
def conv_output_length(input_size, conv_size, stride, pad): """ calculates the output size along a single axis for a conv operation """ if input_size is None: return None without_stride = input_size + 2 * pad - conv_size + 1 # equivalent to np.ceil(without_stride / stride) output_siz...
def normalized_total_time(p, max_time=3600000): # by default 1 h (in ms) """If time was longer than max_time, then return max_time, otherwise return time.""" if p["result.totalTimeSystem"] == "3600.0": v = 3600000 # convert to ms (error in logging) else: v = int(float(p["result.totalTimeSys...
def get_columns(table_name): """ It gets the content from any file with data in it(auto generated) and returns in list """ lines = [] try: with open(f"{table_name}/{table_name}_data.txt",encoding='UTF-8') as file: for line in file: line = line.strip() ...
def get_valid_place(place): """ Return valid place. Strip spaces and check for empty value.""" place = place.strip() if not place: raise ValueError('empty string') return place
def reciprocal(attrs, inputs, proto_obj): """Returns the reciprocal of the argument, element-wise.""" return 'reciprocal', attrs, inputs
def schema(): """Get record schema.""" return { 'allOf': [{ 'type': 'object', 'properties': { 'title_statement': { 'type': 'object', 'properties': { 'title': {'type': 'string'} } ...
def dict_from_list(keyfunc, l): """ Generate a dictionary from a list where the keys for each element are generated based off of keyfunc. """ result = dict() for item in l: result[keyfunc(item)] = item return result
def write_file(filename, content, mode="w"): """ Write content to a filename """ with open(filename, mode) as filey: filey.writelines(content) return filename
def make_content_url(url, category=None): """ Returns URL with appropriate path appended if Skype shared content URL, e.g. "https://api.asm.skype.com/v1/objects/0-weu-d11-../views/imgpsh_fullsize" for "https://api.asm.skype.com/v1/objects/0-weu-d11-..". @param category type of content, e.g. "av...
def verify_metadata_version(metadata, version=None): """ Utility function to verify that the metadata has the correct version number. If no version number is passed, it will just extract the version number and return it. :param metadata: the content of an export archive metadata.json file :para...
def _parse_gcs_path(path: str): """Parses the provided GCS path into bucket name and blob name Args: path (str): Path to the GCS object Returns: bucket_name, blob_name: Strings denoting the bucket name and blob name """ header, rest = path.strip().split('//') if header != '...
def find_spaces(string_to_check): """Returns a list of string indexes for each string this finds. Args: string_to_check; string: The string to scan. Returns: A list of string indexes. """ spaces = list() for index, character in enumerate(string_to_check): if character == ' ': spaces.ap...
def clean_float(num): """ Pasa de string a float """ ntmp = num.replace('.', '').replace(',', '.') return float(ntmp)
def teamid(runid): """ SF_UMass_IESL1 -> UMass_IESL """ return runid.split("_", 1)[-1][:-1]
def find_lca(node, n1, n2): """Finds LCA of 2 numbers by recursively searching in left and right subtree input args : current node, the numbers whose lca is to be found, isFound list telling if the particular element is found returns : lca if found else None Time complexity : O(n), Space complexity ...
def evaluate(h,x): """evaluate an instance x with an hypothesis h, that is a function X->{Yes,No}""" for i,feature in enumerate(h): if feature=="0": return "No" if feature!="?" and feature!=x[i]: return "No" return "Yes"
def _parse_display(display): """Parse an X11 display value""" try: host, dpynum = display.rsplit(':', 1) if host.startswith('[') and host.endswith(']'): host = host[1:-1] idx = dpynum.find('.') if idx >= 0: screen = int(dpynum[idx+1:]) dpynu...
def pluralize(count, singular, plural): """Return singular or plural depending on count""" if count == 1: return singular return plural
def dsigmoid(y): """Derivative function of the function represented in :py:func:`sigmoid`. * If :math:`y = tanh(x)`, then :math:`Dy = 1 - y^2`, * if :math:`y = s(x)`, then :math:`Ds = y - y^2`. * There are infinite sigmoid functions. Just put here the derivative of the ``sigmoid`` fun...
def sigmoid(x): """sigmoid A sigmoid-like function. """ return x / (1 + abs(x))
def is_empty_line(line): """Checks whether a line is empty. A line is empty is has only whitespace or consists only of a carriage return. """ return (line.split == '') or (line in ['\n', '\n\r'])
def number_format(num, places=0): """Format a number with grouped thousands and given decimal places""" places = max(0,places) tmp = "%.*f" % (places, num) point = tmp.find(".") integer = (point == -1) and tmp or tmp[:point] decimal = (point != -1) and tmp[point:] or "" count = 0 forma...
def clean_ponctuation(text, activated=True): """Remove non alphanumeric characters from text (except spaces)""" if activated: text = ''.join(c if c.isalnum() else " " for c in text) return text
def multifilter(filters, result): """ Applies multiple filters to `result` . Returns: list: result, reduced by each filter. """ if not filters: return result for f in filters: result = filter(f, result) return result
def is_string(value: str): """Return true if given value is a string""" return isinstance(value, str)
def get_ordinal_indicator(number: int) -> str: """ Returns the ordinal indicator for an integer. Args: number (int): An integer for which the ordinal indicator will be determined. Returns: str The integer's ordinal indicator. """ ordinal_dict = {1: 'st', 2: 'nd', 3: 'rd'} i...
def getGbLen(str): """get length""" return len(str.encode('gb2312'))
def convert_dico(dico) : """Gets the average age for every genre""" def normalize(dic) : """converts one of nested dictionaries from dico_average_age function in an integer age average in years""" average_in_days = (dic['nb_days'].days/dic['nb_people']) average_age = int(average_in_days/...
def flat_result_2_row(predictions): """ flat the mitosis prediction result into rows Args: predictions: a tuple of (slide_id, ROI, mitosis_num, mitosis_location_scores), where mitosis_location_scores is a list of tuples (r, c, score) Return: a list of tuples(slide_id, ROI, mitosis_num, r, c, ...
def clip_and_integer_coordinates(quad, im_dimentions): """ quad(list[list]): [[x1, y1], [x2, y2], ....] im_dimentions(tuple): w,h """ w, h = im_dimentions clip_x = lambda p: max(0, min(p, w)) clip_y = lambda p: max(0, min(p, h)) quad = [(int(clip_x(quad[i][0])), int(clip_y(quad[i][1])))...
def build_condition_pairs(conditions): """ Return the list of parameter pairs in a form of strings Inputs ------ conditions : dict dictionary with arguments Outputs ------- condition_pairs : list of str parameter pairs in strings """ condition_pairs = [] for key in conditions.keys(): ...
def fs_to_string(fs: float) -> str: """ Convert sampling frequency into a string for filenames Parameters ---------- fs : float The sampling frequency Returns ------- str Sample frequency converted to string for the purposes of a filename Examples -------- ...
def eta_p(ranking, Ep, Vp): """Return the (normalised) eta_p measure. Parameters ---------- ranking : list or array-like ranking Ep : list or array-like comparison matrix. Ensure that it satisfies Ep[x][y] == 1 - Ep[y][x] and 0 <= Ep[x][y] <= 1. Vp : list or array-like ...
def dualzahl(integer): """rechnet eine "normale" Zahl (Basis 10) in eine Dualzahl (Basis 2) um""" bases = [1] base = 2 i = 1 while bases[-1]*2 <= integer: bases.append(2**i) i = i+1 bases.reverse() ziffern = "" for i in bases: ziffern = ziffern + str(int(integer/i...
def splitImageFrames(image_in): """Splits an image (or multiple images as a list) to its different frames, and returns a list containing the images. """ # Determine if images in are a list or a single image if isinstance(image_in, list): full_images = [] # Iterate through images, creating a sublist of frames fo...
def validate_byr(birth_year: str) -> bool: """byr (Birth Year) - four digits; at least 1920 and at most 2002.""" return len(birth_year) == 4 and int(birth_year) >= 1920 and int(birth_year) <= 2002
def get_api_url(method): """ Returns API URL for the given method. :param method: Method name :type method: str :returns: API URL for the given method :rtype: str """ return 'https://slack.com/api/{}'.format(method)
def get_conv_fname(fname: str, dest_ext: str, output_dir=None) -> str: """Returns the filename and path of the file after conversion Arguments: fname -- the original filename dest_ext -- the extension of the destination file output_dir -- the output directory of the operation """ if output...
def vaporViscosity(T, vVP): """ vaporViscosity(T, vVP) vaporViscosity (micropoise) = A + B*T + C*T^2 Parameters T, temperature in Kelvin vVP, A=vVP[0], B=vVP[1], C=vVP[2] A, B, and C are regression coefficients Returns vapor viscosity in micropoise at T """ r...
def convert_8_int_to_tuple(int_date): """ Converts an 8-digit integer date (e.g. 20161231) to a date tuple (Y,M,D). """ return (int(str(int_date)[0:4]), int(str(int_date)[4:6]), int(str(int_date)[6:8]))
def filter_json(in_list): """ filters and returns the list of unique sensors found""" found_list = [] for device in in_list: for key, val in device.items(): if key == "sensor": for k, v in val.items(): if k == "id": found_list....
def bounded_binary_search(generator, length, target, lower_bound, upper_bound): """ efficient binary search for a <target> value within bounds [<lower_bound>, <upper_bound>] - converges to a locally optimal result within the bounds - instead of indexing an iterable, lazy evaluate a functor for performan...
def preorder_traversal_recursive(root): """ Return the preorder traversal of nodes' values. - Worst Time complexity: O(n) - Worst Space complexity: O(n) :param root: root node of given binary tree :type root: TreeNode or None :return: preorder traversal of nodes' values :rtype: list[in...
def api_card(text: str, color: str) -> str: """Create a HTML Card for API display""" html = f""" <div class='demo_card' style='background-color:{color}'> <span>{text}</span> </div> """ return html
def get_group(items, group_size, group_id): """Get the items from the passed in group based on group size.""" start = group_size * (group_id - 1) end = start + group_size if start >= len(items) or start < 0: raise ValueError("Invalid test-group argument") return items[start:end]
def modname(name): """Get a stylized version of module name""" return "[\x032{}\x0f]".format(name)
def get_continious(objects_l): """ just to fix the list of list of list to finally make it one list to keep track of images and qs per timestep """ # print(len(objects_l)) fixed_objs = [] for obj in objects_l: # print(img) if obj: # print("img = ", img) for _obj i...
def _get_url(env, endpoint): """ This function returns the http url """ return '{}/{}'.format(env['SERVER_URL'], endpoint)
def derivative(f, x, eps=1e-6): """ Computes a numerical approximation of the first derivative of a function. f -- Function to find the first derivative of x -- The value to calculate the first derivative for eps -- The value of epsilon in the equation, default = 1e-6 returns approximation of ...
def make_memoryview(obj, offset=-1, size=-1): """Uses Python2 buffer syntax to make memoryview""" if offset < 0: return memoryview(obj) elif size < 0: return memoryview(obj)[offset:] else: return memoryview(obj)[offset:offset+size]
def _filter_nones(centers_list): """ Filters out `None` from input list Parameters ---------- centers_list : list List potentially containing `None` elements Returns ------- new_list : list List without any `None` elements """ return [c for c in centers_list if...
def bbox_for_points(coords): """ Return bbox for a sequence of points. """ bbox = min(coords), max(coords) return bbox
def transfer(i_list,target): """ Return all the consecutive element in i_list equal to target and copy it into the Out list1, all the remaining element will be put into the Out list2. :param i_list: The source list :param target: The target element :return: (Out_list1,Out_lis...
def create_bcs(fields, **namespace): """ Return a dict of DirichletBCs. """ return dict((field, []) for field in fields)
def _filter_similarity(mols, distance, generator, query_fps, cutoff): """Filter molecules by a certain distance to the reference fingerprints. User must supply distance funtion, FP generator, query FPs and cutoff.""" return list(filter( lambda q: any(distance(generator(q), q_fp) >= float(cutoff) ...
def binary_search(arr, elem): """Return the index of the given element within a sorted array.""" low = 0 high = len(arr) - 1 mid = 0 while low < high: mid = (high + low) // 2 # Check if elem is present at mid if arr[mid] < elem: low = mid + 1 # If elem...
def sec2days(seconds): """Seconds to number of days""" return seconds / (24.0 * 3600)
def play_opposite_corner(computer_piece, board_state): """Play on the corner opposite of the user's last move""" # All the possible corner pairs in Tic-Tac-Toe corner_pairs = [[1, 9], [3, 7]] squares_played = [] last_square_played = int(board_state[-1][1]) # Get all the squares from the board...
def efficientnet_params(model_name): """Map EfficientNet model name to parameter coefficients. Args: model_name (str): Model name to be queried. Returns: params_dict[model_name]: A (width,depth,res,dropout) tuple. """ params_dict = { # Coefficients: width,depth,res,dropou...
def filter_manifest_definition(manifest_definition, name_filter): """ Filters the manifest to only include functions that partially match the specified filter. :param manifest_definition: Dictionary of the manifest :param name_filter: A function name specified in the manifest :return: Filtered m...