content
stringlengths
42
6.51k
def find_node(root, query): """ Interprets JSON as tree and finds first node with givens string. """ if not isinstance(root, dict): # skip leaf return None for key, value in root.items(): if key == query: return value if not isinstance(value, list): value ...
def split_list(input_list): """Split input_list into three sub-lists. This function splits the input_list into three, one list containing the inital non-empty items, one list containing items appearing after the string 'Success' in input_list; and the other list containing items appearing after the...
def kill_camels(line): """ Replaces words in the string from m_prefixHelloWorld style to m_prefix_hello_world one. Applies for any words. """ result = '' # finite state machine or alike have_m = False have_delimiter = True have_full_prefix = False for idx, c in enumerate(line): ...
def _find_best_model(fit_result_list, model_list): """[summary] Parameters ---------- fit_result_list : [type] [description] model_list : [type] [description] Returns ------- [type] [description] """ for result_dict in fit_result_list: model...
def find_max(A): """invoke recursive function to find maximum value in A.""" def rmax(lo, hi): """Use recursion to find maximum value in A[lo:hi+1].""" if lo == hi: return A[lo] mid = (lo+hi) // 2 L = rmax(lo, mid) R = rmax(mid+1, hi) return max(L, R) retur...
def get_list_comma_sep_string(input_string): """ This function converts a comma separated string in to a list Eg: "a, b, c, d, e, f" would become ['a', 'b', 'c', 'd', 'e', 'f'] """ final_list = input_string.split(',') for i in range(0, len(final_list)): final_list[i] = final_list[i].st...
def toint(x): """Convert x to interger type""" try: return int(x) except: return 0
def func_demo(a, b): """ doc test demo >>> func_demo(1, 2) 1 >>> func_demo('a', 3) 'aaa' >>> func_demo(3, [1]) [1, 1, 1] >>> func_demo('a', [1]) Traceback (most recent call last): ... ValueError """ try: return a ** b except: raise ValueError
def evalZ(x,y): """value of Z based on values of X and Y Input: x,y: values of x and y Output: res: Z """ if (x >= 2): return x%2 else: return (x+y)%2
def direction_message(prevailing_directions_and_speed_dict): """ Creates a nicely formatted message with all the data. Arguments --------- prevailing_directions_and_speed_dict: dict The output of name_to_data Returns ------- message: str The nicely formatted message. ...
def alnum_prefix(text: str) -> str: """Return the alphanumeric prefix of text, converted to lowercase. That is, return all characters in text from the beginning until the first non-alphanumeric character or until the end of text, if text does not contain any non-alphanumeric characters. >>> aln...
def cmdHasShellSymbols(cmdline): """ Return True if string 'cmdline' contains some specific shell symbols """ return any(s in cmdline for s in ('<', '>', '&&', '||'))
def _is_numeric(x): """Test whether the argument can be serialized as a number (PRIVATE).""" try: float(str(x)) return True except ValueError: return False
def poly_to_box(poly): """Convert a polygon into a tight bounding box.""" x0 = min(min(p[::2]) for p in poly) x1 = max(max(p[::2]) for p in poly) y0 = min(min(p[1::2]) for p in poly) y1 = max(max(p[1::2]) for p in poly) box_from_poly = [x0, y0, x1, y1] return box_from_poly
def from_string(val): """Return simple bool, None, int, and float values contained in a string Useful for converting items in config files parsed by `configparser.RawConfigParser()` or values pulled from Redis """ _val = val if type(val) != str: pass elif val.lower() == 'true': ...
def frequency_to_probability(frequency_map, decorator=lambda f: f): """Transform a ``frequency_map`` into a map of probability using the sum of all frequencies as the total. Example: >>> frequency_to_probability({'a': 2, 'b': 2}) {'a': 0.5, 'b': 0.5} Args: frequency_map (dict): The...
def _get_filters_settings(agg): """ Get the settings for a filters aggregation :param agg: the filter aggregation json data :return: dict of {setting_name: setting_value} """ filter_settings = dict(filters=dict()) settings = agg['settings'] filters = settings['filters'] for _filte...
def _as_list(obj): """Ensure an object is a list.""" if obj is None: return None elif isinstance(obj, str): return [obj] elif isinstance(obj, tuple): return list(obj) elif not hasattr(obj, '__len__'): return [obj] else: return obj
def view_kwargs(check_url): """Return a dict of valid kwargs to pass to SecurityView(**view_kwargs).""" return { "allow_all": False, "allowed_referrers": ["lms.hypothes.is"], "authentication_required": True, "check_url": check_url, }
def get_token_type(string, types): """Match the token with it's type""" # Get the token type from the dictionary token_type = types.get(string) # If there's nothing, it's either an num literal or an identifier if token_type == None: try: float(string) return "NUM_LIT...
def get_buckets_without_key_tag(buckets_data: list, tag_key: str) -> list: """ Returns list of bucket names without specified tag key assigned. """ matching_buckets_names = [] for bucket in buckets_data: bucket_name = bucket['name'] bucket_tags = bucket['tags'] stack_id_tag_p...
def _get_exception_key(exc_info): """ Returns unique string key for exception. Key is filename + lineno of exception raise. """ exc_tb = exc_info[2] if exc_tb is None: return repr(exc_info[1]) return "{}:{}".format(exc_tb.tb_frame.f_code.co_filename, exc_tb.t...
def redefined_index(list_of_tuples,element): """redefine implemented index method for list Parameters ---------- list_of_tuples : list A list containing tuples element : tuple A single tuple whose position in the list is calculated ignoring tuple orientation Returns ...
def _gre_xmin_ ( graph ) : """Get minimal x for the points >>> graph = ... >>> xmin = graph.xmin () """ xmn = None np = len(graph) for ip in range( np ) : x , y = graph[ip] x = x.value() - x.error() if None == xmn or x <= xmn : xmn = x return xmn
def graph_delta_values(y, edge_weights): """ Computes delta values from an arbitrary graph as in the objective function of GSFA. The feature vectors are not normalized to weighted unit variance or weighted zero mean. """ R = 0 deltas = 0 for (i, j) in edge_weights.keys(): w_ij = edge...
def map_diameter(c): """ Compute the diameter """ return 1 / 3 * (c + 1) * (c - 1)
def unflatten_dict(dt, delimiter="/"): """Unflatten dict. Does not support unflattening lists.""" dict_type = type(dt) out = dict_type() for key, val in dt.items(): path = key.split(delimiter) item = out for k in path[:-1]: item = item.setdefault(k, dict_type(...
def get_percentage(a, b) -> str: """Print percentage ratio of a/b.""" return f"{round(100 * a / b, 2)}% ({a}/{b})"
def format_time(seconds, n=5): """Format seconds to std time. note: Args: seconds (int): seconds. n:precision (D,h,m,s,ms) Returns: str: . Example: seconds = 123456.7 format_time(seconds) #output 1D10h17m36s700ms format_time(seconds, n=...
def out2dic(output): """Assign numeric output of a grass command to a dictionary""" split = output.splitlines() d = {} for i in split: key, value = i.split('=') try: d[key] = int(value) except: d[key] = float(value) return(d)
def set_string_length(string: str, length: int) -> str: """Padd- or cut off - the string to make sure it is `length` long""" if len(string) == length: return string elif len(string) < length: return string + ' ' * (length - len(string)) else: # len(string) > length return string...
def answer(input): """ >>> answer("#1 @ 1,3: 4x4\\n#2 @ 3,1: 4x4\\n#3 @ 5,5: 2x2") 4 """ claims = [] for claim in input.split("\n"): b = claim.split(" @ ")[1] r = b.split(": ") x, y = r[0].split(",") w, h = r[1].split("x") claims.append((int(x),int(y),int(...
def is_palindrome(string: str) -> bool: """Checks is given string is palindrome. Examples: >>> assert is_palindrome("abccba") >>> >>> assert is_palindrome("123321") >>> >>> assert not is_palindrome("abccbX") """ if not isinstance(string, str): raise TypeE...
def row_type_name_getter(row): """Returns type name of the row""" return row.__class__.__name__
def ScoreCpuPsnr(target_bitrate, result): """Returns the score relevant to interactive usage. The constraints are: - Stay within the requested bitrate - Encode time needs to stay below clip length - Decode time needs to stay below clip length Otherwise, PSNR rules.""" score = result['psnr'] # We penali...
def overlap(start_1, end_1, start_2, end_2): """Return the `range` covered by two sets of coordinates. The coordinates should be supplied inclusive, that is, the end coordinates are included in the region. The `range` returned will be exclusive, in keeping with the correct usage of that type. Para...
def dict_to_str_sorted(d): """Return a str containing each key and value in dict d. Keys and values are separated by a comma. Key-value pairs are separated by a newline character from each other, and are sorted in ascending order by key. For example, dict_to_str_sorted({1:2, 0:3, 10:5}) should r...
def _is_dunder(name): """Returns True if a __dunder__ name, False otherwise.""" return ( name[:2] == name[-2:] == "__" and name[2:3] != "_" and name[-3:-2] != "_" and len(name) > 4 )
def binary_search(lst, item): """ Perform binary search on a sorted list. Return the index of the element if it is in the list, otherwise return -1. """ low = 0 high = len(lst) - 1 while low < high: middle = (high+low)/2 current = lst[middle] if current == item: ...
def reverse_string_recursive(s): """ Returns the reverse of the input string Time complexity: O(n^2) = O(n) slice * O(n) recursive call stack Space complexity: O(n) """ if len(s) < 2: return s # String slicing is O(n) operation return reverse_string_recursive(s[1:]) + s[0]
def image_location_object_factory(image_id, location_id): """Cook up a fake imagelocation json object from given ids.""" locationimage = { 'image_id': image_id, 'location_id': location_id } return locationimage
def get_api_data_center(api_key): """Determine the Mailchimp API Data Center for `api_key` http://developer.mailchimp.com/documentation/mailchimp/guides/get-started-with-mailchimp-api-3/ """ data_center = api_key.split('-')[1] return data_center
def chrom_transform(chromosome_id): """ convert chromosome id from with or without `chr` suffix """ if chromosome_id.startswith('chr'): if chromosome_id == 'chrM': chrom_id = 'chrM' else: chrom_id = chromosome_id.replace('chr', '') else: if chromosome_...
def url_to_filename(url): """Assume the following URL structure. input: http://www.vsemirnyjbank.org/ru/news/factsheet/2020/02/11/how-the-wo output: '20200211-factsheet-how-the-wo.txt' http://www.worldbank.org/en/news/factsheet/2020/10/15/world-bank-gr Breaks on the following URLs: http://ww...
def extract_channel_platform(url): """Returns last two elements in URL: (channel/platform-arch) """ parts = [x for x in url.split('/')] result = '/'.join(parts[-2:]) return result
def split(content, size): """ Simple split of bytes into two substrings. :param bytes content: string to split :param int size: index to split the string on :returns: two value tuple with the split bytes """ return content[:size], content[size:]
def class_network_unreachable(log): """An error classifier. log the console log text Return None if not recognized, else the error type string. """ if 'Network is unreachable' in log: return 'NETWORK_UNREACHABLE' return None
def align_rows(rows, bbox): """ For every row, align the left and right boundaries to the final table bounding box. """ try: for row in rows: row['bbox'][0] = bbox[0] row['bbox'][2] = bbox[2] except Exception as err: print("Could not align rows: {}".format...
def extract_parent_from_info_field(info): """Helper function to extract parent ID from info string""" for tag in info.split(';'): if tag.startswith('Parent='): return tag[7:]
def list_zip(*lists): """Zip some @p lists, returning the result as a list of lists.""" return list(map(list, zip(*lists)))
def midpoint_point_point_xy(a, b): """Compute the midpoint of two points lying in the XY-plane. Parameters ---------- a : sequence of float XY(Z) coordinates of the first 2D or 3D point (Z will be ignored). b : sequence of float XY(Z) coordinates of the second 2D or 3D point (Z will...
def opcodesToHex(opcodes): """ Converts pairs of chars (opcode bytes) to hex string notation Arguments : opcodes : pairs of chars Return : string with hex """ toreturn = [] opcodes = opcodes.replace(" ","") for cnt in range(0, len(opcodes), 2): thisbyte = opcodes[cnt:cnt+2] toreturn.append("\\x" + th...
def validate_boolean_value(boolean_value_input): """ The purpose of this function is to validate that a boolean value input is valid. """ # Type check. If it is not a boolean value, attempt to change it # into one. if not isinstance(boolean_value_input, bool): try: boo...
def handle(func, *args, **kwargs): """ Handles function callbacks, typically on execution of a class method. :param func: func, callback function :param args: arguments, optional :param kwargs: keyword arguments, optional """ if func is not None: try: return func(*args, *...
def init_actions_(service, args): """ this needs to returns an array of actions representing the depencies between actions. Looks at ACTION_DEPS in this module for an example of what is expected """ # some default logic for simple actions return { 'test': ['install'] }
def lin(pos, goal, x, n_steps): """ Returns the y value of a linear function based which goes from y=pos on x=0 to y=goal on x=n_steps. """ return pos + (1/(n_steps-1) * (goal-pos))*x
def is_ipv4_addr(host): """is_ipv4_addr returns true if host is a valid IPv4 address in dotted quad notation. """ try: d1, d2, d3, d4 = map(int, host.split('.')) except (ValueError, AttributeError): return False if 0 <= d1 <= 255 and 0 <= d2 <= 255 and 0 <= d3 <= 255 and 0 <= d4...
def how_many_derivs(k,n): """How many unique Cartesian derivatives for k atoms at nth order""" val = 1 fact = 1 for i in range(n): val *= 3 * k + i fact *= i + 1; val /= fact return int(val)
def get_parameter(param): """ Convert input parameter to two parameter if they are lists or tuples Mainly used in tb_vis.py and tb_model.py """ if type(param) is list or type(param) is tuple: assert len(param) == 2, "input parameter shoud be either scalar or 2d list or tuple" p1, p2 ...
def win_checker(currBoard): """ Takes in the current board, finds whether or not someone can win and who wins, and returns a tuple with these two parts. """ # This var is all of the locations that need to be checked to look over the 8 possible ways to win # 8 checks - 3 vertical, 3 horizontal...
def remove_empty_sections(lines): """ Mainly relevant for Wikipedia articles, this removes sections without any actual textual content. Notably, we leave in transfer from sections to subsections, subsections to subsubsections, etc. """ new_lines = [] curr_section_depth = "=" curr_section_is...
def xstr(string): """Sane string conversion: return an empty string if string is None.""" return '' if string is None else str(string)
def reward(BG_last_hour): """ Reward function for model: Risk function based on Fermi Risk Function """ b = BG_last_hour[-1] if 20 <= b < 65: return 30-(80-65)*3-(65-b)*10 elif 65 <= b < 80: return 30-(80-b)*3 elif 80 <= b < 100: return 30 elif 100 <= b <...
def map_values(function, dictionary): """Map ``function`` across the values of ``dictionary``. :return: A dict with the same keys as ``dictionary``, where the value of each key ``k`` is ``function(dictionary[k])``. """ return dict((k, function(dictionary[k])) for k in dictionary)
def to_zip_name(name): """ Packages store items with names prefixed with slashes, but zip files prefer them without. This method strips the leading slash. """ return name.lstrip('/')
def compute_bytes_per_voxel(element_type): """Returns number of bytes required to store one voxel for the given metaIO ElementType """ switcher = { 'MET_CHAR': 1, 'MET_UCHAR': 1, 'MET_SHORT': 2, 'MET_USHORT': 2, 'MET_INT': 4, 'MET_UINT': 4, 'MET_LONG'...
def get_word_lengths(s): """ Returns a list of integers representing the word lengths in string s. """ return [len(w) for w in s.split()]
def is_valid_ip_address(ipaddr): """ <Purpose> Determines if ipaddr is a valid IP address. Address 0.0.0.0 is considered valid. <Arguments> ipaddr: String to check for validity. (It will check that this is a string). <Returns> True if a valid IP, False otherwise. """ # Argument must be of ...
def get_abbreviation(text): """ Rename texts to abbreviations in order to fit better to the screen """ if text == "Element": return "Elem" elif text == "Tremolo": return "Tremo" elif text == "Random": return "Rand" elif text == "Sampler": return "Sample" e...
def get_attrib_uri(json_dict, attrib): """ Get the URI for an attribute. """ url = None if type(json_dict[attrib]) == str: url = json_dict[attrib] elif type(json_dict[attrib]) == dict: if json_dict[attrib].get('id', False): url = json_dict[attrib]['id'] elif json...
def suffix_tree(text): """ Build a suffix tree of the string text """ tree = dict() tree[0] = dict() ncount = 1 for s in range(len(text)): current = tree[0] currentText = text[s:] while True: found = False for key in current.keys(): ...
def dic_to_properties(d: dict): """ Takes a dictionary and returns a string amenable to be used in cypher. Parameters ---------- d : dict A dictionary mapping properties to values. Returns ------- out: str A piece of cypher statement specifying properties and values. """ # if the dictionary is not emp...
def process_not_implemented(**kwargs): """ default process function - return not implemented """ ret_dict = { 'function_return': 'not-implemented', 'slack_response': {} } return ret_dict
def flush(hand): """ return True if all the cards have the same suit """ suits = [s for r, s in hand] return len(set(suits)) == 1
def pluralize(x: str) -> str: """Rudimentary pluralization function. It's used to name lists of things.""" if x[-2:] in ["sh", "ch", "ss"]: return x+"es" elif x[-1:] in ["s", "x", "z"]: return x+"es" else: return x+"s"
def is_email(email): """ Simple email validator. A valid email contains only one @ and the @ exists neither at the start nor the end of the string """ # email length - 1 for indexing into the address email_len = len(email) - 1 count = 0 # At least 3 characters are required for a va...
def validate_unit(unit: str) -> str: """ Validates the unit of an object. :param unit: The unit of the object. :return: The validated unit. """ if not unit: raise ValueError("Unit must not be empty.") if len(unit) > 100: raise ValueError("Unit must not be longer than 100 cha...
def removeOuterParentheses(S): """ :type S: str :rtype: str """ r = 0 l = 0 start = 0 ss = "" for i in range(len(S)): if S[i] == "(": r += 1 else: l += 1 if l == r: ss += S[start + 1:i] start = ...
def ret_val(r, params): """Determine the return values.""" rets = [] if 'void' not in r: rets += ['libreturn'] for x in params: if 'out' in x[0]: rets += [x[2]] res_def = '' if len(rets) == 1: res_def = '%s = '%rets[0] elif len(rets) > 1: ...
def _format_results(results: dict): """Return formatted dictionary containing term and relevance. Args: results (dict): JSON dictionary of Google Autocomplete results. Returns: suggestions (dict): Formatted dictionary containing term and relevance. """ if results: suggesti...
def quality_score_to_string(score: int) -> str: """Returns the string representation for the given quality score. We add 33 to the score because this is how the quality score encoding is defined. Source: https://support.illumina.com/help/BaseSpace_OLH_009008/Content/Source/Informatics/BS/QualityScoreEncoding_s...
def make_options(option_list): """Converts a list of two-tuples: (label, value) into a list of dictionaries suitable for use in Dropdown and RadioItems components. """ return [{'label': lbl, 'value': val} for lbl, val in option_list]
def alg2keytype(alg): """ Go from algorithm name to key type. :param alg: The algorithm name :return: The key type """ if not alg or alg.lower() == "none": return "none" elif alg.startswith("RS") or alg.startswith("PS"): return "RSA" elif alg.startswith("HS") or alg.star...
def find_outlier(integers): """ integers: find the outlier in a list of odd or even integers return: the outlier in the integers list """ even_numbers = ([elt for elt in integers if elt%2 == 0]) odd_numbers = ([elt for elt in integers if elt%2 != 0]) if len(even_numbers)>len(odd_numbers): return odd_n...
def absmin(num1, num2): """ Return the value with min aboslute """ num1_abs = abs(num1) num2_abs = abs(num2) num_abs_min = min(num1_abs, num2_abs) if num_abs_min == num1_abs: return num1 else: return num2
def compute_error_for_line_given_points(b, m, points): """ y = mx + b m is slope, b is y-intercept """ totalError = 0 for [x, y] in points: totalError += (y - (m * x + b)) ** 2 return totalError / float(len(points))
def sdm_monomial_divides(A, B): """ Does there exist a (polynomial) monomial X such that XA = B? Examples ======== Positive examples: In the following examples, the monomial is given in terms of x, y and the generator(s), f_1, f_2 etc. The tuple form of that monomial is used in the ca...
def spring1s(ep, ed): """ Compute element force in spring element (spring1e). :param float ep: spring stiffness or analog quantity :param list ed: element displacements [d0, d1] :return float es: element force [N] """ k = ep return k*(ed[1]-ed[0])
def quotes_inner(quoted: str) -> str: """ For a string containing a quoted part returns the inner part """ left_quote = quoted.find('"') right_quote = quoted.rfind('"') if right_quote < 0: right_quote = len(quoted) return quoted[left_quote + 1:right_quote]
def hex_from_64(b64str): """Convert a base64 string to a hex string. Keyword arguments: b64str -- the base64 string we wish to convert """ if b64str == '': return '' B64CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' HEXCHARS = '0123456789abcdef' ## ...
def epoch_time(start_time, end_time): """ Calculate the time spent to train one epoch Args: start_time: (float) training start time end_time: (float) training end time Returns: (int) elapsed_mins and elapsed_sec spent for one epoch """ elapsed_time = end_time - start_tim...
def true_false_converter(value): """ Helper function to convert booleans into 0/1 as SQlite doesn't have a boolean data type. Converting to strings to follow formatting of other values in the input. Relying on later part of pipeline to change to int. """ if value == "True": return '1' ...
def ADD(*expressions): """ Adds numbers together or adds numbers and a date. If one of the arguments is a date, $add treats the other arguments as milliseconds to add to the date. See https://docs.mongodb.com/manual/reference/operator/aggregation/add/ for more details :param expressions: The num...
def peak_power(avg_power, pulse_width, rep_freq): """Compute peak power given average power, pulse width, and rep rate Parameters ---------- avg_power : float The total power of the beam in watts pulse_with : float The FWHM pulse width of the laser in seconds rep_freq: float...
def anySubs(UserDetails): """ Checks if the user has any subscriptions yet """ if('subscriptions' in UserDetails.keys()): return True return False
def getChunks(dsets,nbchunks): """ Splits dataset object into smaller chunks Parameters: * dsets (dict): dataset * nbchunks (int): number of data chunks to be created Returns: * dict: chunks from dataset stored as dictionaries """ ret = [] for ichunk in range(nbchunks): datagrp = {} f...
def get_process_id(process): """Return id attribute of the object if it is process, otherwise return given value.""" return process.id if type(process).__name__ == "Process" else process
def longestConsecutive3(list,missing=1): """ assume list is a list budget missing """ if len(list) == 0: return 0 longest = 0 # print(range(len(list)-1)) starts = [ x for x in range(len(list)) ] # print(starts) for sindex in starts: currentlen = 0 allow = missing ...
def estimate_u_value(d_i): """ Estimate U-value (in W/mK) depending on inner pipe diameter d_i. Estimation based on values by: U-values: C. Beier, S. Bargel, C. Doetsch, LowEx in der Nah- und Fernwaerme. Abschlussbericht, 2010. Parameters ---------- d_i : float Inner diameter of pip...
def calculate_pot_temp(pressure, temperature): """calculate_pot_temp Description: Temp * (1000/Pressure)^0.286 Return potentail temp from pressure and temperature """ return temperature * (1000 / pressure)**(0.286)