content
stringlengths
42
6.51k
def capitalize_each_word(s, delimiter): """Capitalize each word seperated by a delimiter Args: s (str): The string to capitalize each word in delimiter (str): The delimeter words are separated by Returns: str: The modified string """ return delimiter.join([w.capitalize() fo...
def _prepend_row_index(rows, index): """Add a left-most index column.""" if index is None or index is False: return rows if len(index) != len(rows): print("index=", index) print("rows=", rows) raise ValueError("index must be as long as the number of data rows") rows = [[v...
def _parse(out, err): """Parses the process output Arguments: out {bytes} -- The stdout of the process err {bytes} -- The stderr of the process Returns: tuple -- (string, string) Both process out and err in string format (utf-8) """ output = out.decode("UTF-8") ...
def get_training_or_validation_split(samples, labels, validation_split, subset): """Potentially restict samples & labels to a training or validation split. Args: samples: List of elements. labels: List of corresponding labels. validation_split: Float, fraction of data to reserve for validatio...
def fix_name(player): """ Get rid of (A) or (C) when a player has it attached to their name :param player: list of player info -> [number, position, name] :return: fixed list """ if player[2].find('(A)') != -1: player[2] = player[2][:player[2].find('(A)')].strip() elif play...
def normalize(*args): """Scale a sequence of occurrences into probabilities that sum up to 1.""" total = sum(args) return [arg / total for arg in args]
def validPair(pair1, pair2): """ Validates that the sets have nothing in common or the pair is unique """ for p1 in pair1: for p2 in pair2: if not p1 & p2: return True return False
def get_coordinates(lines): """Returns list of coordinates. """ coords = [] for l in lines: if l.startswith('] def'): break elif l.startswith('['): coords.append(map(float,l.strip('\n[]').split())) return coords
def sort_list(data_list, index, reverse=True): """ index: int number, according to it to sort data_list""" sorted_data_list = sorted(data_list, key=lambda x: x[index], reverse=reverse) return sorted_data_list
def bicubic_kernel(x, B=1/3., C=1/3.): """https://de.wikipedia.org/wiki/Mitchell-Netravali-Filter""" if abs(x) < 1: return 1/6. * ((12-9*B-6*C)*abs(x)**3 + ((-18+12*B+6*C)*abs(x)**2 + (6-2*B))) elif 1 <= abs(x) and abs(x) < 2: return 1/6. * ((-B-6*C)*abs(x)**3 + (6*B+30*C)*abs(x)**2 + (-12*B-48*...
def _get_mock_tags_dict( sample_name: str = 'sample1', ) -> dict: """Create and return a dictionary of mock tags""" if sample_name == 'sample1': return { 'mock-key-a': 'mock-value-a', 'mock-key-b': 'mock-value-b', } elif sample_name == 'sample2': retur...
def is_leap_year(year): """ returns True for leap year and False otherwise :param int year: calendar year :return bool: """ # return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) return year % 100 != 0 or year % 400 == 0 if year % 4 == 0 else False
def parse_text(raw_text_list: list) -> list: """ Return the parsed text list :param raw_text_list: the raw text list :return: the parsed text list """ text_list: list = [] for raw_text in raw_text_list: text: dict = { 'Data': raw_text.get('_value_1'), 'Type': ...
def fixBadHtml(source): """ Takes bad html lists and puts closing tags on the end of each line with a list tag and no closing tag. """ # process each line on it's own source = source.split('\n') newSource = [] for line in source: line = line.strip() # check if its a...
def numpy_docstring(param1 , param2): """ Summary line. Extended description of function. Parameters ---------- param1 : int The first parameter. param2 : str The second parameter. Returns ------- bool Description of return value See Also -----...
def eea(a, b): """The Extended Euclidean Algorithm. Inputs: a (int) b (int) Returns: gcd (int), c (int), d (int) such that gcd = ac + bd. """ if a == 0: return (b, 0, 1) else: g, y, x = eea(b % a, a) return (g, x - (b // a) * y, y)
def add_field_defaults_to_node(node): """ Since we test using POST, all fields must be present, even if the field will just have the default value set. Rather than manually setting a bunch of default values on every node, we just assign it here. """ node.update( { "license_descri...
def harmonic_mean(l): """ calculate the harmonic mean of a list of classes :param l: a list holding elements :return: """ return len(l) / sum([1 / x for x in l])
def attributes_filter(dataset, attributes, att_names, category): """ Pick up from $dataset only the attributes whose names are in $attributes. Note that, this method assumes that $dataset contains all the attributes from ($name)_data.ATT_NAMES """ #obtain attribute indices is_cat = [] att_i...
def absorp(t, d): """ computes the absorption coefficient for given temperature T and density d """ return 1.984e24 * d / pow(t, 3.5)
def to_bool(value): """ Converts 'something' to boolean. Raises exception for invalid formats Possible True values: 1, True, '1', 'TRue', 'yes', 'y', 't' Possible False values: 0, False, None, [], {}, '', '0', 'faLse', 'no', 'n', 'f', 0.0 """ if type(value) == type(''): if value.lower()...
def check_input(def_list): """Check that all defect structures in list are not None. Args: def_list (list): List of defect structures Returns: True if all defect structures are present. """ for defect in def_list: if not defect: return False return True
def _get_auth_headers(api_key): """Builds up JSON object to authenticate via API. Args: api_key: (str) - A String defining API Key. Returns: A Dictionary with authentication information. """ return {'Content-Type': 'Application/JSON', 'Authorization': api_key}
def dictFlat(l): """Given a list of list of dicts, return just the dicts.""" if type(l) is dict: return [l] if "numpy" in str(type(l)): return l dicts=[] for item in l: if type(item)==dict: dicts.append(item) elif type(item)==list: for item2 in...
def check_policies(policies, policy_check): """ The function takes as an input a list of policies as dicts containing the keys low, high, letter and passwd and a function to check the policies. It checks the password in each dict using the function and adds the key valid = True if the check is ...
def is_link(input_string): """ Takes user input and checks if equal to 'games' Input: string Output: boolean """ if input_string == 'games': return True else: return False
def IsPort(tag): """Returns True iff tag represents a switch port.""" return tag.startswith('switches.')
def float_from_request(params, key, default): """ Get float from request GET, POST, etc :param params: dict POST, GET, etc :param key: key to find :param default: default value :return: float """ value = params.get(key, default) # str if isinstance(value, str): try: ...
def formatTime(t): """ Formats time into the format yyyy/mm/dd. Args: t (tuple): the original date Returns: string: yyyy/mm/dd Examples: 1990/1/1 --> 1990/01/01 """ if t[1] < 10: if t[2] < 10: return '{0}...
def get_hw_boundary(patch_boundary, h, w, pH, sH, pW, sW): """ Calculate height and width of patch """ h_low_ind = max(pH * sH - patch_boundary, 0) h_high_ind = min((pH + 1) * sH + patch_boundary, h) w_low_ind = max(pW * sW - patch_boundary, 0) w_high_ind = min((pW + 1) * sW + patch_boundary...
def get_file_content(filepath: str) -> str: """ `get_file_content` returns the content of the file. """ try: with open(filepath) as f: fc = f.read() return fc except Exception as e: print(e) return ""
def tree_to_list(tree): """ Saves all data in tree in the list. """ lst = [] if tree is not None: if tree.right: lst.extend(tree_to_list(tree.right)) lst.append(tree.entry) if tree.left: lst.extend(tree_to_list(tree.left)) return lst
def find_lcm(first_num: int, second_num: int) -> int: """Find the least common multiple of two numbers. Learn more: https://en.wikipedia.org/wiki/Least_common_multiple >>> find_lcm(5,2) 10 >>> find_lcm(12,76) 228 """ max_num = first_num if first_num >= second_num else se...
def get_path_from_source(source_path): """ Get file path from source Args: source_path (str): relative module path e.g. this.module.Class """ file_path = "/".join(source_path.split('.')[:-1]) + '.py' return file_path
def UBVRI_to_ugriz(V, BmV, UmB, RmI): """ Conversion from Fukugita et al. 1996.""" g = V + 0.56 * BmV - 0.12 r = V - 0.49 * BmV + 0.11 umg = 1.38*UmB + 1.14 u = umg + g #gmr = 1.05*(B-V) - 0.23 if RmI < 1.15: rmi = 0.98* RmI - 0.23 else: rmi = 1.40* RmI - 0.72 i = ...
def copy_dictionary(dictionary: dict) -> dict: """ Create a copy of a dictionary, so that both copies contain the same values, but none of them are modified if elements are included to or excluded from the other dictionary. """ result = {} for key in dictionary: result[key] = dictionary[...
def rescale(ell, X1, X2=None): """ Rescale the input data contained in X1 and X2 with lengthscales ell. Return the tuple of rescaled data, or if X2 is None return (X1, None). """ X1 = (X1 / ell) X2 = (X2 / ell) if (X2 is not None) else None return X1, X2
def str_replace(search, replace, subject, count=-1): """ Replace all occurrences of the search string with the replacement string. This is a wrapper for the PHP str_replace function that returns a string or an array with all occurrences of search in subject replaced with the given replace value. ...
def GetComplimentaryHex(color): """ :param color: """ # strip the # from the beginning color = color[1:] # convert the string into hex color = int(color, 16) # invert the three bytes # as good as substracting each of RGB component by 255(FF) comp_color = 0xFFFFFF ^ ...
def get_age_group(age): """Get age group Done by continuously reducing age and going to previous age group and counting how many times this is done Note that since arrays start with 0, to get the human-readable age group, add 1 """ group = 0 while age >= 22: group += 1 ...
def unquote_string(s_in): """Remove single and double quotes from beginning and end of `s`.""" if isinstance(s_in, bytes): s_in = s_in.decode() if not isinstance(s_in, str): s_in = str(s_in) for quote in ("'", '"'): s_in = s_in.rstrip(quote).lstrip(quote) return s_in
def relu(x): """ :math:`f(x) =` x if x is greater than 0, else 0 (See `<https://en.wikipedia.org/wiki/Rectifier_(neural_networks)>`_ .) """ return x if x > 0.0 else 0.0
def interval2float_m(i: float) -> float: """Convert a time interval to a float or to NA if it is does not have a value Arguments: i: is a number of seconds Returns: the number of minutes represented or NA if i is not a float """ if isinstance(i, float): retu...
def orientation_to_interval(orientation, strict_interval=False): """ Transforms the given orientation value to one of 5 values: -1,-0.5,0,0.5,1 . if the strict_interval argument is set to True, the function only returns -1,0,1 """ if orientation > 0.5: return 1 elif orientation > 0: ...
def _construct_resource_group_name( client: str, user_resource_group_name: str, ) -> str: """Construct a resource group name from deployment context.""" # want the client id as a prefix for easier sorting & grouping in portal. result = "-".join([client, user_resource_group_name]) return result
def find_items(source_data, items, item_pos): """Display all records that contain a specific value in a specific column. Takes a list of lists and for each nested list checks for a specific values in the column specified by item_pos. If an identified value is found, the record is added to the retur...
def empty(region): """ Check if a region is empty or inconsistent :param region: region as an array [xmin, ymin, xmax, ymax] :type region: list of four float :returns: True if the region is considered empty (no pixels inside), False otherwise :rtype: bool""" return region[0] >= regi...
def list_not_matched_source(source_paths, source_paths_matches): """return set""" return set(source_paths).symmetric_difference(set(source_paths_matches))
def _positive_int(integer_string, strict=False, cutoff=None): """ Cast a string to a strictly positive integer. """ ret = int(integer_string) if ret < 0 or (ret == 0 and strict): raise ValueError() if cutoff: ret = min(ret, cutoff) return ret
def get_price_for_market_stateless(result): """Returns the price for the symbols that the API doesnt follow the market state (ETF, Index)""" ## It seems that for ETF symbols it uses REGULAR market fields return { "current": result['regularMarketPrice']['fmt'], "previous": result['regularMark...
def get_unicode_alt(value): """Get alternate Unicode form or return the original.""" return value['code_points']['output']
def sum_all_fields_and_buttons_n_submits(*all_n_clicks): """ Sum the guided search fields and main search field and "Go" button n_submits and n_clicks to a single n_clicks number for the Go button. Thus the user can hit enter on any guided search field or the main box and the app will act like you a...
def scalar_truediv(x, y): """Implementation of `scalar_truediv`.""" return x.__truediv__(y)
def with_end_char_ex(text, char): """ Description: Append an after character to a text. ( Exclusive for core json to html conversion process) :param text: raw text :param char: character to put :return: Appended Text (e.g. with_end_char("Accounts", ":")-> "Accounts:") """ return str("")....
def _GetParentFromFullResourceName(mute_config): """Gets parent from the full resource name.""" mute_config_components = mute_config.split("/") return mute_config_components[0] + "/" + mute_config_components[1]
def consuming_length(iterator): """ Return length of an iterator, consuming its contents. O(1) memory. >>> consuming_length(range(10)) 10 """ cnt = 0 for _ in iterator: cnt += 1 return cnt
def mro_lookup(cls, attr, stop=(), monkey_patched=[]): """Returns the first node by MRO order that defines an attribute. :keyword stop: A list of types that if reached will stop the search. :keyword monkey_patched: Use one of the stop classes if the attr's module origin is not in this list, this to...
def _compute_hms(tot_time): """ Computes hours, minutes, seconds from total time in seconds. """ hrs = tot_time // 3600 mins = (tot_time - hrs * 3600) // 60 secs = (tot_time - hrs * 3600 - mins * 60) return hrs, mins, secs
def unwrap(url): """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" url = url.strip() if url[:1] == '<' and url[-1:] == '>': url = url[1:-1].strip() if url[:4] == 'URL:': url = url[4:].strip() return url
def _parse_cal_product(cal_product): """Split `cal_product` into `cal_stream` and `product_type` parts.""" fields = cal_product.rsplit('.', 1) if len(fields) != 2: raise ValueError(f'Calibration product {cal_product} is not in the format ' '<cal_stream>.<product_type>') ...
def libname_from_dir(dirname): """Reconstruct the library name without it's version""" parts = [] for part in dirname.split('-'): if part[0].isdigit(): break parts.append(part) return '-'.join(parts)
def main(case_data, case): """Here goes the actual code to solve the question """ solution = None return solution
def actual_jaccard(data1, data2): """A util function to get the real 'jaccard similarity' Args: data1: array-like of shape data2: array-like of shape Returns: float: the real jaccard similarity """ s1 = set(data1) s2 = set(data2) actual_jaccard = float(len(s1.i...
def get_time_code(op_time): """Calculate medicare time code from time in theatre. op_time is an int returns time_code as a string""" time_base = "230" time_last = "10" second_last_digit = 1 + op_time // 15 if op_time % 15 == 0: second_last_digit -= 1 if op_time > 15: ...
def dot3D(v1, v2): """Calculates the scalar dot product of two 3D vectors, v1 and v2""" return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
def dms2dd(d, m, s, i): """Convert degrees/minutes/seconds to decimal degrees""" s *= .01 sec = float((m * 60.0) + s) dec = float(sec / 3600.0) deg = float(d + dec) if i.upper() == 'W': deg = deg * -1.0 elif i.upper() == 'S': deg = deg * -1.0 return float(deg)
def byte_to_str(data, data_type=None): """ This function is born for happybase's data. Because happybase's data is all bytes. We should turn it into str(s) which has/have been decode. :param data_type: :param data: generator or other type's data. :return: type of source data """ if ...
def get_request(uri='', method = 'POST'): """ :param uri: :param method: :return: """ return { 'method': method, 'uri': uri, 'params': { }, 'headers': { 'content-type': 'application/json', 'x-cms-token': 'abcdefgABCDEFG0123456789' ...
def analysis_lrn(analysis): """ Returns a dictionary of locals by row. This index can be used to quicky find a local definition by row. Example: (let [a| 1] ...) 'lrn' stands for 'local row name'. """ return analysis.get("lrn", {})
def format_member(member: dict) -> str: """Return the member name and/or login.""" name = member.get("name") or "" login = member.get("login") or "" return f"{name} ({login})" if name and login else name or login
def peterson(number) -> bool: """ Takes a number as input and check whether a given number is Peterson or not. """ n, sum = number, 0 while number > 0: d = number % 10 f = d for i in range(1, d): f *= i sum += f number //= 10 if(sum == n): ...
def code_block(string: str, max_characters=2048): """ Formats text into discord code blocks """ string = string.replace("```", "\u200b`\u200b`\u200b`\u200b") max_characters -= 7 if len(string) > max_characters: return f"```\n{string[:max_characters - 7]} ...```" else: return...
def is_relation(relation): """Return ``True`` if passed object is Relation and ``False`` otherwise.""" return type(relation).__name__ == 'Relation'
def bitwise_not(binary): """Perform a unary NOT operation on the bits of a binary string.""" return ''.join('1' if bit == '0' else '0' for bit in binary)
def duration(t): """ Give a nice short and readable string representation of a given time duration in seconds, e.g. how long it took to render the whole project. Usage ----- >>> timetag = duration(t) Parameters ---------- The time that has passed in seconds (int or float). ...
def _empty(starts, stops, steps): """ Report whether there is an empty range in the triples or not. """ for start, stop, step in zip(starts, stops, steps): if step * (stop - start) <= 0: return True return False
def fibonacci_partial_sum(m: int, n: int): """ Finds the lsat digit of a partial sum of Fibonacci numbers: Fm + Fm+1 + ... + Fn. :param m: starting index in Finacci sequence :param n: end index in Fibonacci sequence :return: the last digit of the partial sum Example: F3 + F4 + F5 + F7 = 2 ...
def get_tri_from_course(course, courses): """ Given a courses dict, return the trimester of the :param course """ for tri in courses: for _course in courses[tri]: if course == _course: return tri.capitalize()
def profile_last_jump_to_step(value): """0 - 99""" return {'step':value}
def luka_implication(x, y): """Performs pairwise the Lukasiewicz implication.""" return min(1, 1 - x + y)
def friendly_worklog_time(seconds): """ https://stackoverflow.com/questions/775049/how-to-convert-seconds-to-hours-minutes-and-seconds :param seconds: :return: """ if not seconds: string = "0m" else: m, s = divmod(int(seconds), 60) h, m = divmod(m, 60) string...
def get_auto_step_size(max_squared_sum, alpha_scaled, loss, fit_intercept): """Compute automatic step size for SAG solver The step size is set to 1 / (alpha_scaled + L + fit_intercept) where L is the max sum of squares for over all samples. Parameters ---------- max_squared_sum : float ...
def grabbedObj(obj, constraints): """ Check if object is grabbed by robot """ return (obj in constraints.keys() and constraints[obj][0] == 'ur5')
def throughput(records_per_sec, mb_per_sec): """Helper method to ensure uniform representation of throughput data""" return { "records_per_sec": records_per_sec, "mb_per_sec": mb_per_sec }
def get_finalization_time(final_transcript, j, partial_transcripts): """ Return the first time such that the first j tokens of the transcript are the same for all following transcripts. """ prefix = final_transcript[:j] partial_time = 0 for partial_time, partial_transcript in reversed(parti...
def isAscii2(b): """ Check if a given hex byte is ascii or not, will not flag newline or carriage return as ascii Argument : the byte Returns : Boolean """ return b >= 0x20 and b <= 0x7e
def exists(iterable): """ Returns True if there is an element in the iterable, False otherwise. """ try: next(iterable) return True except StopIteration: return False
def _check_and_convert_legacy_input_config_key(key): """Checks key and converts legacy input config update to specific update. Args: key: string indicates the target of update operation. Returns: is_valid_input_config_key: A boolean indicating whether the input key is to update input config(s). ...
def _to_unicode_scalar_value(s): """ Helper function for converting a character or surrogate pair into a Unicode scalar value e.g. "\ud800\udc00" -> 0x10000 The algorithm can be found in older versions of the Unicode Standard. https://unicode.org/versions/Unicode3.0.0/ch03.pdf, Section 3.7, D28 ...
def nodes_test_in_train(nodes_list, index): """ Given list of nodes for each time stamp and an index separating between train and test examples, return the nodes in the test set that are also in the training set. :param nodes_list: List of lists of nodes for each time stamp. :param index: Index indi...
def classify(tree, inputs): """classify the input using the given decision tree""" # if this is a leaf node, return its value if tree in [True, False]: return tree # otherwise find the correct subtree attribute, subtree_dict = tree subtree_key = inputs.get(attribute) # None if input ...
def flatten(seq): """given a list of lists, return a new list that concatentes the elements of (seq). This just does one level of flattening; it is not recursive. """ return sum(seq, [])
def _set_default_if_empty_str(tst_str, default=None): """ Return None if str is an empty string or return str. Used to test for general options that reset with value of "" and reset to either None or the default value. Parameters: tst_str (:term:1string): the string to test for value ...
def make_sequential(documents, answers): """ Transform an answer-based dataset (i.e. with a list of documents and a list of keyphrases) to a sequential, ner-like dataset, i.e. where the answer set for each document is composed by the lists of the documents' tokens marked as non-keyphrase (0), be...
def get_n_message_grids(nbits_per_map, ngrids): """ nbits_per_map is list, specifying the number of non-trash bits in each grid if it were a conj_map (given its shape) ngrids is the total number of grids, be they message or conj_map want to find x, the number of message grids, and y, the number of conj...
def vowel_indices(word): """ Find the index of the vowels in a given word, Vowels in this context refers to: a e i o u y (including upper case) This is indexed from [1..n] (not zero indexed!) Some examples: Mmmm => [] Super => [2,4] Apple => [1,5] YoMama -> [1,2,4,6] """ new...
def vector_mult(vector, mult): """ Multiply a vector by a value >>> vector_mult((2,3),4) (8, 12) >>> """ return tuple([l * mult for l in vector])
def get_removed(l_new, l_old, fpatterns): """ Get those labels that are supposed to be removed :param l_new: new labels :param l_old: old labels :param pattern_dict: directory of patterns that are used to match the filenames :type l_new: list :type l_old: list :t...
def sumlist(x, y): """ Sums two lists of the same shape elementwise. Returns the sum. """ z = x for i in range(0, len(z)): if isinstance(x[i], list) and isinstance(y[i], list): z[i] = sumlist(x[i], y[i]) else: z[i] = x[i] + y[i] return z
def get_integrations_list(test_integrations: list) -> list: """ Since test details can have one integration as a string and sometimes a list of integrations- this methods parses the test's integrations into a list of integration names. Args: test_integrations: List of current test's integrations...