content
stringlengths
42
6.51k
def exists_key_in_dicts_list(dict_list, key): """From a list of dicts, checks if a certain key is in one of the dicts in the list. See also https://stackoverflow.com/questions/14790980/how-can-i-check-if-key-exists-in-list-of-dicts-in-python Parameters ---------- dict_list: list A list of...
def intcode_seven(parameter_list, code_list): """If first parameter is less than second parameter, stores 1 in third parameter. Else stores 0 in third parameter. Returns True""" if parameter_list[0] < parameter_list[1]: code_list[parameter_list[2]] = 1 else: code_list[parameter_list[2]] = ...
def invert_keyword(keyword): """Takes in a keyword e.g. [3, 1, 0, 2], which describes the mapping of abcd to dbac, and returns the keyword that returns dbac to abcd. So if you have a keyword that encrypts a text, the decrypting keyword woud be its inverse and vice versa """ # for each in...
def dtype_to_pandas_dtype(dtype: str) -> str: """ Matches the given dtype to its pandas equivalent, if one exists Args: dtype (str): The type to attempt to match Returns: The pandas version of the dtype if one exists, otherwise the original """ if dtype == "integer": dtype ...
def str_is_int(s): """Checks if a string can be converted to int.""" if not isinstance(s, str): raise TypeError('str_is_int function only accepts strings.') try: int(s) return True except ValueError as e: if 'invalid literal' in str(e): return False el...
def bold(text): """ Function to return text as bold :param text: str to bold :type text: str :return: str in bold """ return '\x1b[1;30m'+text+'\x1b[0m' if text else '\x1b[1;30m'+'\x1b[0m'
def _exit_with_general_warning(exc): """ :param exc: exception """ if isinstance(exc, SystemExit): return exc print("WARNING - General JbossAS warning:", exc) return 1
def nameSanitize(inString): """ Convert a string to a more file name (and web) friendly format. Parameters ---------- inString : str The input string to be sanitized. Typically these are combinations of metric names and metadata. Returns ------- str The string after rem...
def _backticks(line, in_string): """ Replace double quotes by backticks outside (multiline) strings. >>> _backticks('''INSERT INTO "table" VALUES ('"string"');''', False) ('INSERT INTO `table` VALUES (\\'"string"\\');', False) >>> _backticks('''INSERT INTO "table" VALUES ('"Heading''', False) ...
def get_alphabet_from_dict(dictionary): """ `get_alphabet_from_dict()` gets the alphabet from the dictionary by adding each used letter. * **dictionary** (*list*) : the input dictionary (before processing) * **return** (*list*) : the alphabet based on the letters used in the dictionary """ ...
def diff(first, second): """ compute the difference between two lists """ second = set(second) return [item for item in first if item not in second]
def map_rows_to_cols(rows, cols): """ Returns a list of dictionaries. Each dictionary is the column name to its corresponding row value. """ mapped_rows = [] for row in rows: mapped_rows.append({cols[i]: row[i] for i in range(len(cols))}) return mapped_rows
def reorderOddEvent(nums): """[1,2,3,4,5,6,7]""" def event(num): return (num % 2) == 0 leftIndex, rightIndex = 0, len(nums) - 1 while leftIndex < rightIndex: while leftIndex < rightIndex and not event(nums[leftIndex]): leftIndex += 1 while leftIndex < rightIndex an...
def recvall(sock, size: int): """Receive data of a specific size from socket. If 'size' number of bytes are not received, None is returned. """ buf = b"" while size: newbuf = sock.recv(size) if not newbuf: return None buf += newbuf size -= len(newbuf) ...
def load_secret(name, default=None): """Check for and load a secret value mounted by Docker in /run/secrets.""" try: with open(f"/run/secrets/{name}") as f: return f.read().strip() except Exception: return default
def leapyear(year): """Judge year is leap year or not.""" return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
def discrete_time_approx(rate, timestep): """ :param rate: daily rate :param timestep: timesteps per day :return: rate rescaled by time step """ return 1. - (1. - rate)**(1. / timestep)
def xor(a: bytes, b: bytes) -> bytes: """Return a xor b. :param a: Some bytes. :param b: Some bytes. :returns: a xor b """ assert len(a) == len(b), \ "Arguments must have same length." a, b = bytearray(a), bytearray(b) return bytes(map(lambda i: a[i] ^ b[i], range(len(a))))
def interpolation_search(to_be_searched, searching_for): """ Improvement over binary search when the data is uniformly distributed... :param to_be_searched: :param searching_for: :return: """ if to_be_searched: low = 0 high = len(to_be_searched) - 1 while low <= hig...
def __firstMatch(matches, string): """ Takes in a list of Match objects and returns the minimal start point among them. If there aren't any successful matches it returns the length of the searched string. """ starts = map(lambda m: len(string) if m is None else m.start(), matches) return min(starts)
def get_item(dictionary, key): """ For getting an item from a dictionary in a template using a variable. Use like: {{ mydict|get_item:my_var }} """ return dictionary.get(key)
def get_abs_sum(lst): """ Get absolute sum of list """ sum = 0 for x in lst: if x < 0: sum += (x * -1) else: sum += x return sum
def _function_to_name(name): """Returns the name of a CMD function.""" return name[3:].replace('_', '-')
def update_bathrooms_slider(area): """ Update bathrooms slider to sensible values. """ return [1, min(int(area / 40) + 1, 5)]
def getMonthString(my_list): """Given a list of months creates the string representing the sequence""" if not isinstance(my_list, (list, tuple)): my_list = [my_list, ] dic = { 1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY', 6: 'JUNE', 7: 'JULY', 8: 'AUGUST', 9:...
def process_channel_names(channel_names): """Process to obtain the electrode name from the channel name. Parameters ---------- channel_names : list Channel names in the EEG. Returns ------- channel_names : list Proccessed channel names, containing only the name of the el...
def safe_divide(x, y): """Compute x / y, but return 0 if y is zero.""" if y == 0: return 0 else: return x / y
def dataRange(data): """ This is used to find the range of a set of data. The range is the difference between the lowest and highest valued digits in a given set of data.""" data = data data.sort() return data[len(data)-1] - data[0]
def _attr_key(attr): """Return an appropriate key for an attribute for sorting Attributes have a namespace that can be either ``None`` or a string. We can't compare the two because they're different types, so we convert ``None`` to an empty string first. """ return (attr[0][0] or ''), ...
def min_blocks(length, block): """ Returns minimum number of blocks with length ``block`` necessary to cover the array with length ``length``. """ return (length - 1) // block + 1
def calc_t_int(n_group, t_frame, n_frame, n_skip): """Calculates the integration time. Parameters ---------- n_group : int Groups per integration. t_frame : float Frame time (in seconds). n_frame : int Frames per group -- always 1 except maybe brown dwarves. n_sk...
def greet(name: str): """ Create a simple greeting. Parameters ---------- name: str, required Name of person to greet. Returns ------- greeting: str String with a simple greeting. """ # Return greeting return f"Hello, {name}!"
def format_stats(stats): """Format statistics for printing to a table""" result = '' for key, value in stats.items(): result += f'{key} - {value}\n' return result[:-1]
def get_div(value, start): """Returns the maximum divider for `value` starting from `start` value""" div = 1 for d in range(start, 0, -1): if (value % d) == 0: div = d break return div
def get_name(layer_name, counters): """ utlity for keeping track of layer names """ if not layer_name in counters: counters[layer_name] = 0 name = layer_name + "_" + str(counters[layer_name]) counters[layer_name] += 1 return name
def GetTMIndex(iRes, posTM):# {{{ """Get index of TM helix given a residue position Return -1 if iRes is not within TM region """ for i in range(len(posTM)): (b, e) = posTM[i] if iRes >= b and iRes < e: return i return -1 # }}}
def square_root(mu, c, i0=1.0): """ Calculates the intensity of a given cell in the stellar surface using a square-root limb-darkening law. Parameters ---------- mu (``float`` or ``numpy.ndarray``): Cosine of the angle between a line normal to the stellar surface and the line of...
def metadata_filter_as_dict(metadata_config): """Return the metadata filter represented as either None (no filter), or a dictionary with at most two keys: 'additional' and 'excluded', which contain either a list of metadata names, or the string 'all'""" if metadata_config is None: return {} ...
def _timeline_from_nodestats(nodestats, device_name): """Return sorted memory allocation records from list of nodestats.""" if not nodestats: return [] lines = [] peak_mem = 0 for node in nodestats: for mem in node.memory: try: records = mem.allocation_records except: # pylint: di...
def set_users(username): """Returns screen names from command line or file.""" users = [] if username: users = [u for u in username] else: with open('userlist.txt', 'r') as f: users = [u.strip() for u in f.readlines()] if not users: raise ValueErr...
def pretty_size(size: int, precision: int = 2) -> str: """ Returns human-readable size from bytes. Args: size: Size in bytes. precision: Precision for the result. """ if size >= 1 << 40: return f"{size / (1 << 40):.{precision}f} TB" if size >= 1 << 30: return f"{...
def clean_word(word): """ converts every special character into a separate token """ cleaned_words = [] temp = "" for char in word: if (ord(char)>=33 and ord(char)<=47) or (ord(char)>=58 and ord(char)<=64): # if (ord(char)>=33 and ord(char)<=47 and ord(char)!=39) or (ord(char)>=5...
def calc_energy_consumption(hvac_kwh_per_day, lights_kwh_per_day, misc_kwh_per_day): """ Energy Consumption Notes ------ Energy consumption for different time periods """ farm_kwh_per_day = hvac_kwh_per_day + lights_kwh_per_day + misc_kwh_per_day farm_kwh_per_week = f...
def user_master_name(mdir, input_name): """ Convert user-input filename for master into full name Mainly used to append MasterFrame directory Parameters ---------- mdir : str input_name : str Returns ------- full_name : str """ islash = input_name.find('/') if islash >...
def joined_list(items, element): """Return a list with element added between each item. Similar to str.join() except returns a list. >>>joined_list(['a', 'b', 'c'], '@') ['a', '@', 'b', '@', 'c'] Args: items: list element: anything that can be an element of a list, """...
def parse_teams(competitors): """Parse a competitors object from Bovada and return the home and away teams, respectively""" if len(competitors) > 2: raise Exception("Unexpected objects in competitors") home_team = "" away_team = "" for team in competitors: if team["home"]: ...
def create_stream_size_map(stream_indices): """ Creates a map from stream name to stream size from the indices table. :param stream_indices: The stream indices table. :return: The map. """ return {pair[0]: len(pair[1]) for pair in stream_indices}
def normalize(x, min, max): """ Data min-max normalization: """ return (x - min) / (max - min)
def escape_html(text): """ For an HTML text, escapes characters that would be read as markup Adds in a line break after '>' to make reading the text easier """ edited_text = str(text).replace("<", "&lt;").replace(">", "&gt;<br>") return edited_text
def lpol_sdiff(s): """return coefficients for seasonal difference (1-L^s) just a trivial convenience function Parameters ---------- s : int number of periods in season Returns ------- sdiff : list, length s+1 """ return [1] + [0] * (s - 1) + [-1]
def format_makehelp(target, detail): """ return "{target}:\t{detail}" """ return '{}:\t{}'.format(target, detail)
def merge_total_time_dict(a, b): """Merge two total-time dictionaries by adding the amount of collected time in each hierarchical element. Parameters ---------- a, b : total-time dict A total-time dict is a dictionary with the keys being the name of the timer and the value being a p...
def middle(t): """ Return a new list that doesn't include the first or last elements from the original. """ res = t del(res[0]) del(res[-1]) return res
def bolt_min_dist(d_0): """ Minimum bolt spacing. :param d_0: :return: """ e_1 = 1.2 * d_0 e_2 = 1.2 * d_0 e_3 = 1.5 * d_0 p_1 = 2.2 * d_0 p_2 = 2.4 * d_0 return e_1, e_2, e_3, p_1, p_2
def select_headers(headers, include_headers): """Select message header fields to be signed/verified. >>> h = [('from','biz'),('foo','bar'),('from','baz'),('subject','boring')] >>> i = ['from','subject','to','from'] >>> select_headers(h,i) [('from', 'baz'), ('subject', 'boring'), ('from', 'biz')] ...
def quaternion_multiply(q, r): """ Computes quaternion multiplication :param q: Quaternion :param r: Quaternion :return: """ q_w = q[0] q_x = q[1] q_y = q[2] q_z = q[3] r_w = r[0] r_x = r[1] r_y = r[2] r_z = r[3] return [ q_w * r_w - q_x * r_x - q_y * ...
def call_in_transaction(func, *args, **kwargs): """Call a function with the supplied arguments, inside a database transaction.""" return func(*args, **kwargs)
def schema_highlight(turn): """ Highlight some slot values in the utterance. Args: turn(dict): A dictionary of the dialogue turn. Returns: highlight_text(str): The dialogue utterance after highlighting. """ highlight_slots = ("name",) span_info = sorted(turn["span_info"], k...
def is_nonempty(pot): """ Determine if the potential has any values """ return any(val is not None for val in pot.values())
def partition_helper(a, first, last): """ A left_mark index are initiated at the leftmost index available (ie not the pivot) and a right_mark at the rightmost. The left_mark is shifted right as long as a[left_mark] < pivot and the right_mark left as long as a[right_mark] > pivot. If left_mark < righ...
def as_int(x, default=0): """Convert a thing to an integer. Args: x (object): Thing to convert. default (int, optional): Default value to return in case the conversion fails. Returns: int: `x` as an integer. """ try: return int(x) except ValueError: retu...
def histogram(ratings, min_rating=None, max_rating=None): """ Generates a frequency count of each rating on the scale ratings is a list of scores Returns a list of frequencies """ ratings = [int(r) for r in ratings] if min_rating is None: min_rating = min(ratings) if max_rating i...
def isAnagram(s1, s2): """ Checks if s1 and s2 are anagrams by counting the number of occurrences of each letter in s1 and s2. """ set1 = set(s1) set2 = set(s2) if set1 == set2: for char in set1: if s1.count(char) != s2.count(char): return False else: ...
def name_sort_key(name): """ Gets sort key for the given name, when sorting attribute, method, or such names. Parameters ---------- name : `str` Name of an attribute, method or class. Returns ------- key : `tuple` (`int`, `str`) The generated key. """ ...
def extend_path(start_el, block, queue, is_lateral): """Extends path through block and returns true if the way is blocked""" next_el = start_el h = len(block) w = len(block[0]) while next_el is not None: current = next_el next_el = None for i in range(-1, 2): add...
def get_id_of_referenced_submission(user_note): """Extracts the id of the submission referenced by the usernote""" link_code_segments = user_note['l'].split(',') if len(link_code_segments) > 1: return link_code_segments[1] else: return None
def doc_label_name(context_type): """ Takes a string `context_type` and makes that a standard 'label' string. This functions is useful for figuring out the specific label name in metadata given the context_type. :param context_type: A type of tokenization. :type context_type: string :retu...
def convert_twos_compliment(bin_str): """ Converts a string of binary numbers to their two's compliment integer representation """ length = len(bin_str) if(bin_str[0] == '0'): return int(bin_str, 2) else: return int(bin_str, 2) - (1 << length)
def sol(a, b): """ Follows the standard DP approach of finding common subsequence. The common length can be >=1 so if we find a common character in both the strings, it does the job """ m = len(a) n = len(b) dp = [[0 for _ in range(n+1)] for _ in range(m+1)] for i in range(1, m+...
def color_float_to_hex(r, g, b): """Convert RGB to hex.""" def clamp(x): x = round(x*255) return max(0, min(x, 255)) return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
def base64_decode(decvalue): """ Base64 decode the specified value. Example Format: SGVsbG8gV29ybGQ= """ msg = """ There was an error. Most likely this isn't a valid Base64 value and Python choked on it """ try: base64dec = decvalue.decode("Base64") return(base64dec) ex...
def simplerep(obj): """ """ return "{}(...)".format(obj.__class__.__name__)
def delete_spaces(s): """Deletes all the spaces of a string Parameters: ----------- s : str Returns ----------- The corresponding string """ s = ''.join(i for i in s if i != ' ') return s
def calculate_okta(percentage): """ Calculate okta based on the provided percentage :param percentage: percentage between 0 and 100 :type percentage: float :return: an integer between 0 and 8 :rtype: int """ if percentage == 0: return 0 elif 0 < percentage < 18.75: re...
def int_list_from_string(s): """ creates a list of integers from a string (counterpart to list_as_string(l)) :param s: string :return: """ if s == "None": return None l = [] for element in s.split(":"): l.append(int(element)) return l
def calcrange(data, log=False): """Return the range (min, max) of a dataset, excluding any NANs.""" xmin, xmax = None, None for x in data: if not log or x > 0.: if xmin is None or x < xmin: xmin = x if xmax is None or x > xmax: xmax = x if xmin is None and xmax is None: ...
def autoname(index, sizes): """ Given an index and list of sizes, return a name for the layer. >>> autoname(0, sizes=4) 'input' >>> autoname(1, sizes=4) 'hidden1' >>> autoname(2, sizes=4) 'hidden2' >>> autoname(3, sizes=4) 'output' """ if index == 0: n = "inp...
def columns_matching_pattern(row, starts_with, does_not_match=[]): """ Takes in a json "row" and filters the keys to match the `starts_with` parameter. In addition, it will remove any match that is included in the `does_not_match` parameter. :param dict row: A dictionary with string keys to be fil...
def AverageGrade(adjList): """Calculates the average grade of a graph""" size = len(adjList) averageGrade = 0 for i in range(size): averageGrade += len(adjList[i]) averageGrade /= size return averageGrade
def getColor(cnvtype, pathOrBen): """Return the shade of the item according to it's variant type.""" if cnvtype not in ["copy_number_loss","copy_number_gain"] or pathOrBen not in ["Benign", "Pathogenic"]: return "0,0,0" if cnvtype == "copy_number_loss": if pathOrBen == "Pathogenic": ...
def GT(x=None, y=None): """ Compares two values and returns: true when the first value is greater than the second value. false when the first value is less than or equivalent to the second value. See https://docs.mongodb.com/manual/reference/operator/aggregation/gt/ for more details ...
def find_one_possible_value(sorted_values, all_matching_indices): """Return the value that has only one element.""" for key, value in all_matching_indices.items(): if len(value) == 1: sorted_values[key] = value[0] return value[0]
def _address_set_in_column_map(address_set: tuple, column_map: list): """Determines if all elements of the address set are in the column map""" for element in address_set: if element not in column_map: return False return True
def get_user_mapping(config): """ Invert the definition in the config (group -> user) so can ask which group a user belongs to """ user_map = {} for group, users in config['groups'].items(): if group == 'default_group': continue for user in users: if user...
def limit(min_, num, max_): """limit a number within a specific range""" return max(min(num,max_),min_)
def binner(min_size, max_size, bin_no): """ :param min_size lower bound of the interval to divide into bins :param max_size upper bound of the interval to divide into bins :param bin_no the interval will be divided into that many bins :returns list of tuples, representing the lower and upper limits ...
def get_scenario_name(cases): """ This function filters the test cases from list of test cases and returns the test cases list :param cases: test cases :type cases: dict :return: test cases in dict :rtype: dict """ test_cases_dict = {} test_cases_dict_json = {} for class_name...
def to_nbsphinx(s): """Use the sphinx naming style for anchors of headings""" s = s.replace(" ", "-").lower() return "".join(filter(lambda c : c not in "()", s))
def is_triangular(k): """ k, a positive integer returns True if k is triangular and False if not """ it = 1 sum = 0 while sum <= k: if sum != k: sum = sum + it it += 1 else: return True return False
def validate_asn_ranges(ranges): """ Validate ASN ranges provided are valid and properly formatted :param ranges: list :return: bool """ errors = [] for asn_range in ranges: if not isinstance(asn_range, list): errors.append("Invalid range: must be a list") elif l...
def fit_func(freqs, intercept, slope): """A fit function to use for fitting IRASA separated 1/f power spectra components.""" return slope * freqs + intercept
def normalize_arr(arr): """ Normalizes a normal python list. Probably works with numpy arrays too. """ total = sum(arr) if total == 0: print("Arr is empty/All numbers are zero, returning [1], This is a warning") return [1] return [i / total for i in arr]
def clock_sec(value): """ 2 bytes: seconds: 0 to 59 """ return {'seconds': value}
def rm_backslash(params): """ A '-' at the beginning of a line is a special charter in YAML, used backslash to escape, need to remove the added backslash for local run. """ return {k.strip('\\'): v for k, v in params.items()}
def dialog_username_extractor(buttons): """ Extract username of a follow button from a dialog box """ if not isinstance(buttons, list): buttons = [buttons] person_list = [] for person in buttons: if person and hasattr(person, 'text') and person.text: try: pe...
def getattr_recursive(variable, attribute): """ Get attributes recursively. """ if '.' in attribute: top, remaining = attribute.split('.', 1) return getattr_recursive(getattr(variable, top), remaining) else: return getattr(variable, attribute)
def _is_visible(idx_row, idx_col, lengths) -> bool: """ Index -> {(idx_row, idx_col): bool}). """ return (idx_col, idx_row) in lengths
def inclusive_range(start, end, stride=1): """ Returns a range that includes the start and end. """ temp_range = list(range(start, end, stride)) if(end not in temp_range): temp_range.append(end) return temp_range
def parse_cigar(cigarlist, ope): """ for a specific operation (mismach, match, insertion, deletion... see above) return occurences and index in the alignment """ tlength = 0 coordinate = [] # count matches, indels and mismatches oplist = (0, 1, 2, 7, 8) for operation, length in cigarlist: if operation...
def _prepname(str): """custom string formatting function for creating a legible label from a parm name takes an incoming label, and sets it to title case unless the 'word' is all caps""" parts = () for part in str.split(" "): if not part.isupper(): parts += (part.capitalize(),)...