content
stringlengths
42
6.51k
def isSameTree(p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if p and q: return p.val == q.val and isSameTree(p.left, q.left) and isSameTree(p.right, q.right) return p is q
def external_pressure(rho, g, d): """Return the external pressure [Pa] at water depth. :param float rho: Water density [kg/m^3] :param float g: Acceleration of gravity [m/s/s] :param float d: Water depth [m] """ return rho * g * d
def to_aws_tags(tags): """ Convert tags from dictionary to a format expected by AWS: [{'Key': key, 'Value': value}] :param tags :return: """ return [{'Key': k, 'Value': v} for k, v in tags.items()]
def is_valid_mysql_connection(cnx): """Check if it is a valid MySQL connection. """ if cnx is not None and cnx.is_connected(): return True return False
def generate_machine_states(service_configs): """ Generate list of all possible configurations of service and compromised status for a single machine. Config = (compromised, [s0, s1, ..., sn]) where: compromised = True/False sn = True/False """ machine_states = [] for c...
def high(string): """function takes in a string, splits it, and finds one with largest value.""" word_list = string.split() letters = [] word_dict = {} for word in word_list: string_list = [x for x in word] word_sum = 0 for letter in string_list: word_sum += ord(l...
def check_indicators_all_false(indicators): """ Input: indicators: (num_regions,) list Return: True if all indicators are False, False if any indicator is True """ for indicator in indicators: if indicator: return False return True
def IsSubset(l, s): """ Check if list s is a subset of nested list l """ result = False for i in s: if set(i).issubset(set(l)): result = True return result
def dot_product(u, v): """ compute the dot product of u and v """ return sum((a*b for a, b in zip(u, v)));
def insert_sort(data): """Sort a list of unique numbers in ascending order using insert sort. O(n^2). The process includes iterating through a list and ordering elements as they're visited. Args: data: data to sort (list of int) Returns: sorted list """ sorted_data...
def analysis_max(x, y): """Maximum of two integers.""" result = max(x, y) return result
def convert_hex_to_255(hex_color): """ hex_color = '#6A5AFFAF' """ assert hex_color.startswith('#'), 'not a hex string %r' % (hex_color,) parts = hex_color[1:].strip() color255 = tuple(int(parts[i : i + 2], 16) for i in range(0, len(parts), 2)) assert len(color255) in [3, 4], 'must be length...
def merge_partial_elements(element_list): """ Merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list: list List of all the elements. Returns ------- list: List of merged elem...
def prepare_nodelist(lists): """ Combine lists of nodes into a single master list for use by nmf_pathway and other functions that accept a nodelist as input """ set_all = set() for ll in lists: for item in ll: set_all.add(item) rv = sorted(set_all) return rv
def else_while(n, numbers): """ A function illustrating the use of else with a loop. This function will determine if n is in the iterable numbers. :param n: The thing to search for. :param numbers: An iterable to search over. :return: True if the thing is in the iterable, false otherwise. ...
def R(units): """Universal molar gas constant, R Parameters ---------- units : str Units for R. Supported units ============= =============================================== ============ Unit Description Value ...
def int2str(n, length=-1): """Convert an integer to a byte string. @param n: positive integer to convert @param length: minimum length @return: converted bytestring, of at least the minimum length if it was specified """ assert n >= 0 r = bytearray() while length < 0 or len(r) <...
def _extract_contractions(sent): """ Args: sent - a single sentence split up into (word, pos) tuples. Returns: List with the indices in the sentence where the contraction starts. Or None if no contractions are in the sentence. Based on the POS-tags and the existence of a...
def linear(x, a, b): """ Input: x - given point for which background is calculated (floats) a, b - coeffitients for linear background function a * x + b Return: value of function with desired parameters in x (float) Descr.: Calculate linear function for given x and parameters""" ...
def short_version(version): """Get a shorter version, only with the major and minor version. :param version: The version. :type version: str :return 'major.minor' version number. :rtype float """ return float('.'.join(version.split('.')[0:2]))
def translate_version(iana_version: str) -> str: """Translates from an IANA version to a PEP 440 version string. E.g. 2020a -> 2020.1 """ if ( len(iana_version) < 5 or not iana_version[0:4].isdigit() or not iana_version[4:].isalpha() ): raise ValueError( ...
def build_controllers(controller_definitions): """ loop through the list of controller definitions creating them. """ c_list = [] for controller_definition in controller_definitions: c_list.append(controller_definition()) return c_list
def compute_cell_next_state(current, neighbours): """Return the next state of the cell on position (i, j) in alive_matrix. Parameters ---------- current: int The state of the cell, 1 or 0 (live or dead) neighbours: array The number of alive cells around the cell. Returns ...
def slot_by_car_number(parkingLot, number): """ prints the slot number of the cars for the given number ARGS: parkingLot(ParkingLot Object) number(str) - given registration number """ returnString = '' if parkingLot: if not parkingLot.get_parked_cars(): retur...
def value_in_range(rule, value): """ Checks if a value is in range of a given tuple. :param rule: [(a, b), (c, d)] :param value: value :return: boolean """ return value in range(rule[0][0], rule[0][1] + 1) or \ value in range(rule[1][0], rule[1][1] + 1)
def power_law(deg_sep, ALPHA=1.0): """ Applies a power law model. WEIGHT = DEG_SEP^(-ALPHA) ALPHA: Parameter to control power law decay rate. """ return (deg_sep + 1) ** (- ALPHA)
def FilterInteger(param, value): """ Filter: Assert integral number. """ if value.isnumeric () == False: return "parameter --" + param.name + " expectes an integer as value" return None
def action_not_implemented(*args, **kwargs) -> dict: """ Default function if no action function is found :return: OpenC2 response message - dict """ return dict( status=501, status_text="Action not implemented" )
def _get_year(obj): """ Get the year of the entry. :param obj: year string object :return: entry year or none if not valid value """ year = obj[0:4] try: year = int(year) except ValueError: year = None return year
def isxdigit(znak): """Provjerava je li znak hex znamenka""" return znak != '' and (znak.isdigit() or znak in 'ABCDEFabcdef')
def get_heat_required_input(data): """Returns Heat required user input fields.""" heat_params = [] heat_param_dict = data["parameters"] for key, heat_param in heat_param_dict.items(): heat_params.append([key, heat_param.get("type"), heat_pa...
def evaluate_postfix(postfix): """ Evaluates a postfix expression. Precondition: postfix is a valid postfix expression (no extra numbers, extra operators, etc.) :param postfix: Postfix expression to be evaluated :return: Result of the postfix expression, or error if unsupported operators used """ ...
def _get_package_version(package): """Get the version for a package (if any).""" return package["version"] or "None"
def invert_dict(dict_in, append_list=False): """ Invert the key:values of a dict :param dict_in: dict to invert :param append_list: append to a list? (for non-uniqueness) :return: inverted dict """ if not append_list: return {val:key for key,val in dict_in.items()} else: ...
def _grab_newline(position, string, direction): """ Boundary can be preceded by `\r\n` or `\n` and can end with `\r\n` or `\n` this function scans the line to locate these cases. """ while 0 < position < len(string): if string[position] == '\n': if direction < 0: ...
def return_xs_unique(xs, ys): """ merge sorted lists xs and ys. Return only those items that are present in the first list, but not in the second. """ result = [] xi = 0 while True: if xi >= len(xs): # If xs list is finished, return result # We're done. ...
def format_nav_item(url: str, title: str) -> str: """Format a single entry for the navigation bar (navbar).""" return '<li class="nav-item"><a class="nav-link" href="{}">{}</a></li>'.format(url, title)
def select_bucket_region( custom_bucket, hook_region, cfngin_bucket_region, provider_region ): """Return the appropriate region to use when uploading functions. Select the appropriate region for the bucket where lambdas are uploaded in. Args: custom_bucket (Optional[str]): The custom bucket na...
def isleapyear(year): """Given a year as an integer (e.g. 2004) it returns True if the year is a leap year, and False if it isn't.""" if year % 4 != 0: return False elif year % 100 != 0: return True elif year % 400 == 0: return True else: return False
def mpl_process_lbl(lbl, math=False): """ Process a (plotly-compatible) text label `lbl` to matplotlb text. Parameters ---------- lbl : str A text label to process. math : bool, optional Whether math-formatting (latex) should be used. Returns ------- str """ ...
def get_frame(env_observation, info): """Searches for a rendered frame in 'info', fallbacks to the env obs.""" info_frame = info.get('frame') if info_frame is not None: return info_frame return env_observation
def for_each_du_in_mcu(mcu, func): """ Helper function that iterates over all DU's in an MCU and runs "func" on it """ return [map(func, comp) for comp in mcu]
def vrtc_center(viewport_size, cursor_size): """Puts the cursor at the center of the viewport""" return int((viewport_size - cursor_size) / -2)
def calcMemUsage(counters): """ Calculate system memory usage :param counters: dict, output of readMemInfo() :return: system memory usage """ used = counters['total'] - counters['free'] - \ counters['buffers'] - counters['cached'] total = counters['total'] # return used*100 / tot...
def point_not_below_center(p, c): """Return True if a point lies not below (y-value) a circle's center point. Parameters ---------- p : Point that should be checked c : Center point of the circle Returns ------- bool True or False """ return p[1] >= c[1...
def get_environment(health_event): """Get the environment setting from the source event Normalise to prod|test to match index names """ try: event_env = health_event.get("Environment", "prod") except (TypeError): event_env = "prod" env = "prod" if event_env in ("prod", "product...
def _convert(t): """Convert feature and value to appropriate types""" return int(t[0]), float(t[1])
def validate_http_request(request): """Check if request is a valid HTTP request and returns True or False along with the requested URL :param request: The HTTP Request :type request: bytes :return: Whether the request is valid or not and the requested path :rtype: tuple """ headers = [head...
def is_bit_k_set(int_val, k): """Tests if the value of bit at offset k in an integer is set""" return (int_val & (1 << k)) != 0
def dictChoice(invalue, dictionary): """ Return the key of a dictionary designated by a given value, where the value is a ponderation to be consumed. """ value = invalue for key in dictionary.keys(): value -= dictionary[key] if value < 0: return key raise Excepti...
def compare_command(commands): """check if the commands is valid""" if len(commands) < 3: return True if commands[0] != 'sys' or commands[1] != 'undo ip route-static default-bfd' \ or commands[2] != 'commit': return True
def kelvinToFahrenheit(kelvin:float, ndigits = 2)->float: """ Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit """ return round(((float(kelvin)...
def get_dictkey(In, k, dtype): """ returns list of given key (k) from input list of dictionaries (In) in data type dtype. uses command: get_dictkey(In,k,dtype). If dtype =="", data are strings; if "int", data are integers; if "f", data are floats. """ Out = [] for d in In: if...
def lowercase_keys(d: dict): """Map keys to lowercase, e.g. it will map a dict with a MODELS key into {"models": "MODELS"}. This allows for a unified way of naming custom-case keys. """ out = {} for k in d.keys(): out[k.lower()] = k return out
def validate_frequencies(frequencies, p_floor, p_ceil, max_p_factor): """Given a sequence of frequencies, [f1, f2, ..., fn], a minimum period, maximum period, and maximum period factor, first remove all frequencies computed as 0. Then, if periods are the inverse frequencies, this function returns True i...
def an_example_plugin(qrcode): """\ This is a Segno converter plugin used by the next test case. """ assert qrcode return 'works'
def is_eval_epoch(eval_period, cur_epoch, num_epochs): """ Determine if the model should be evaluated at the current epoch. """ return ( cur_epoch + 1 ) % eval_period == 0 or cur_epoch + 1 == num_epochs
def pad(sequences, pad_int, max_length=None): """ ARGUMENTS: sequences : list of sequences (list of word ids) RETURNS: padded_sequences : list with padded sequences """ # if max length is not defined, set length to the longest sequence, # then return the padded sequences if max_length is None: length = max...
def string_rotate(line: str, num_of_symbol: int) -> str: """ Function make left rotate for string :param line: Line to rotate :param num_of_symbol: Number of symbol to rotate :return: Rotating line """ return line[num_of_symbol:] + line[:num_of_symbol]
def update_episodes_per_oracles(episodes_per_oracle, played_policies_indexes): """Updates the current episode count per policy. Args: episodes_per_oracle: List of list of number of episodes played per policy. One list per player. played_policies_indexes: List with structure (player_index, policy_inde...
def get_strawberry_type(name, description, directives): """ Create strawberry type field as a string """ strawberry_type = "" deprecated = [d for d in directives if d.name.value == "deprecated"] deprecated = deprecated[0] if deprecated else None if name or description is not None or directives or de...
def _parse_ports(ports_text): """ Handle the case where the entry represents a range of ports. Parameters ---------- ports_text: str The text of the given port table entry. Returns ------- tuple A tuple of all ports the text represents. """ ports = p...
def prepare_data(data, xn, yn): """Change format from (algo, instance, dict) to (algo, instance, x, y).""" res = [] for algo, algo_name, result in data: res.append((algo, algo_name, result[xn], result[yn])) return res
def ERR_calc(ACC): """ Calculate error rate. :param ACC: accuracy :type ACC: float :return: error rate as float """ try: return 1 - ACC except Exception: return "None"
def grid_search(g, p): """ :type g: list[list[int]] :type p: list[list[int]] :rtype: bool """ pattern_found = False for i in range(0, len(g) - len(p) + 1): for j in range(0, len(g[i]) - len(p[0]) + 1): for p_i in range(len(p)): row_pattern_found = False ...
def mult_mat_vec(a, b): """Multiply matrix times vector for any indexable types.""" return [sum(ae*be for ae, be in zip(a_row, b)) for a_row in a]
def inc(i): """Increments number. Simple types like int, str are passed to function by value (value is copied to new memory slot). Class instances and e.g. lists are passed by reference.""" i += 1 return i
def convert_pyte_buffer_to_colormap(buffer, lines): """ Convert a pyte buffer to a simple colors """ color_map = {} for line_index in lines: # There may be lines outside the buffer after terminal was resized. # These are considered blank. if line_index > len(buffer) - 1: ...
def mod(a,b): """ Function that return the modulus of two numbers (a%b) Takes arguments mod(a,b) """ i = 1 if float(a/b) - int(a/b) != 0.0: while True: if b*i < a: i +=1 else: return a - b * (i-1) break elif b...
def vec_dot(a, b): """Compute the dot product of two vectors given in lists.""" return sum([va * vb for va, vb in zip(a, b)])
def label_decoder(zmin): """figure friendly labels for the redshift bins """ zmax, zs = zmin + 0.1, zmin + 0.2 label = "{0:.1f}< {3:s} <{1:.1f}, {4:s}>{2:.1f}".format(zmin, zmax, zs, r"$z_{\rm H\alpha}$", r"$z_{\rm s}$") return label
def Make_Sequential(sents): """ Make sequential parses (each word simply linked to the next one), to use as baseline """ sequential_parses = [] for sent in sents: parse = [["0", "###LEFT-WALL###", "1", sent[0]]] # include left-wall for i in range(1, len(sent)): ...
def default_dev_objective(metrics): """ Objective used for picking the best model on development sets """ if "eval_mnli/acc" in metrics: return metrics["eval_mnli/acc"] elif "eval_mnli-mm/acc" in metrics: return metrics["eval_mnli-mm/acc"] elif "eval_f1" in metrics: retur...
def init_icon_state_dict(icon_names): """Initialise the icon state for icon_names.""" return {k: False for k in icon_names}
def d2(dx, fc, i): """ second-order centered derivative at index i """ D = fc[i+1] - fc[i-1] D = D/(2.0*dx) return D
def destring(value): """ Strip quotes from string args: value (str) returns: str """ return value.strip('"\'')
def print_path(path): """Assumes path is a list of nodes""" result = '' for i in range(len(path)): result = result + str(path[i]) if i != len(path) - 1: result = result + '->' return result
def baseline_from_names(names_list): """Given a list of ifg names in the form YYYYMMDD_YYYYMMDD, find the temporal baselines in days_elapsed (e.g. 12, 6, 12, 24, 6 etc. ) Inputs: names_list | list | in form YYYYMMDD_YYYYMMDD Returns: baselines | list of ints | baselines in days History:...
def strip_quotes(t): """ Run replace_diacritics first -- this routine only attempts to remove normal quotes ~ ', " """ return t.strip('"').strip("'")
def licor_correction(exp_signal, control_signal): """ """ # Make sure all of the inputs are numbers assert all([type(item) == float or type(item) == int for item in exp_signal]), "Signal should be provided as a float." assert all([type(item) == float or type(item) == int for item in control_signal])...
def parseAlphabetNotation(userInput): """ Replaces any valid coordinate character with a number """ userInput = userInput.lower() userInput = userInput.replace("a", "1") userInput = userInput.replace("b", "2") userInput = userInput.replace("c", "3") userInput = userInput.replace("d", "4") us...
def keys_with_max_val(d): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(d.values()) nbMax = v.count(max(v)) k=list(d.keys()) if nbMax == 1: return k[v.index(max(v))] else: keys = [] for i in range(nbMax): ...
def underline(line, character="-"): """Return the line underlined. """ return line + "\n" + character * len(line)
def compute_exact_R_P(final_patterns, centones_tab): """ Function tha computes Recall and Precision with exact matches """ true = 0 for tab in final_patterns: for centon in centones_tab[tab]: check = False for p in final_patterns[tab]: if centon == p: ...
def split_array(a): """ split a list into two lists :param a: list of integers :return: two sub-list of integers """ n = len(a) if n == 1: return a index = n // 2 b = a[:index] c = a[index:] return b, c
def compare_adapters(adapters): """Part 1""" jolt1 = 0 jolt3 = 0 for i in range(len(adapters) - 1): diff = adapters[i+1] - adapters[i] if diff == 1: jolt1 += 1 if diff == 3: jolt3 += 1 print(f"Found {jolt1} jolt1 and {jolt3} jolt3") return jolt1 * ...
def identify(payload): """If we are here, token verification was successful. Do not load actual user model from mongo, as it's not always required. This can help us save few RPS on mongo reads. """ return payload['identity']
def any_not_none(*args): """ Returns a boolean indicating if any argument is not None. """ return any(arg is not None for arg in args)
def se_beta_formatter(value: str) -> str: """ SE Beta formatter. This formats SE beta values. A valid SE beta values is a positive float. @param value: @return: """ try: se_beta = float(value) if se_beta >= 0: result = str(se_beta) else: ...
def iterative_topological_sort(graph, start): """doesn't return some nodes""" seen = set() stack = [] # path variable is gone, stack and order are new order = [] # order will be in reverse order at first queue = [start] while queue: node = queue.pop() if node not in seen: ...
def flip_nums(text): """ flips numbers on string to the end (so 2019_est --> est_2019)""" if not text: return '' i = 0 s = text + '_' while text[i].isnumeric(): s += text[i] i += 1 if text[i] == '_': i += 1 return s[i:]
def is_json_string(text: str) -> bool: """ Given an input text, is_json_string returns `True` if it is a valid JSON string, or False otherwise. The definition of a valid JSON string is set out in the JSON specification available at https://json.org/. Specifically, the section on strings defines them as: "A string ...
def hex2rgb(h): """ Convert hex colors to RGB tuples Parameters ---------- h : str String hex color value >>> hex2rgb("#ff0033") '255,0,51' """ if not h.startswith('#') or len(h) != 7: raise ValueError("Does not look like a hex color: '{0}'".format(h)) return ',...
def fix_hypenation (foo): """ fix hyphenation in the word list for a parsed sentence """ i = 0 bar = [] while i < len(foo): text, lemma, pos, tag = foo[i] if (tag == "HYPH") and (i > 0) and (i < len(foo) - 1): prev_tok = bar[-1] next_tok = foo[i + 1] ...
def can_reach(adj, start, end): """ Searches in a graph represented by an adjacency list to determine if there is a path from a start vertex to an end vertex. """ vis = [False] * len(adj) def dfs(src): if vis[src]: return False vis[src] = True return src == e...
def paritysort_list(arr): """Move all even numbers to the left and all odd numbers to the right Args: arr (list[int]): a list of integers to be sorted in place Returns: (int): number of exchanges needed to complete the sorting """ larr = len(arr) parr = [[i[0] % 2, i] for i in ...
def sample_b1_fib(x): """Calculate fibonacci numbers.""" if x == 0 or x == 1: return 1 return sample_b1_fib(x - 1) + sample_b1_fib(x - 2)
def single_sort_by(queryset, params): """ Orders and returns the queryset using the GET parameters of a request The function takes care of checking if the "sort_by" key exists in the dict :param queryset queryset: A queryset object from a django model :param dict params: Dict containing the request ...
def calc_angle_speed(omega: float, ang_speed_max: float) -> float: """ Calculation of angular speed :param omega: normalized angular speed [-1 1] :param ang_speed_max: angular speed maximum value, deg/s :return: Angular speed [0 360] grad/s """ if abs(omega) < 0.15: return 0.0 re...
def find_unsaticefied(recipe, likes): """ Find an unsaticefied customer index (0-based). Returns -1 if all customers can be saticefied. """ for i,like in enumerate(likes): for x in like: if recipe[x[0]-1] == x[1]: break else: return i retur...