content
stringlengths
42
6.51k
def rotate_matrix_90_clk(matrix): """Creates a new rotated matrix. Deos not change the input matrix. Args: A square 2-dim matrix. Returns: Rotated matrix. """ if not matrix: return [] n = len(matrix) if n == 1: return [matrix[0]] rotated_matrix = [[...
def read_coeffiecients_from_file(path): """ Reads a file with path given and returns a list of coefficients. First coefficient is considered to be the coefficient of the largest number (?). :param path: string, representing the path to the file :return coefficients: a list of coefficients from a pol...
def filter_list(l, where): """Returns a list.""" return list(filter(where, l))
def dd_to_dms(dd): """Converts decimal degrees to degrees, minutes and decimal seconds. Example: 41.4034 -> (41, 24, 12.2) :param float dd: decimal degrees :rtype: (int, int, float) """ d = int(dd) m = int((dd - d) * 60) s = (dd - d - m / 60) * 3600 return d, m, s
def xml_entry(phase, rate): """ creates the xml required for tsung (goes between the load tags) requires phase and rate parameters """ entry = """ <arrivalphase phase="{PHASE}" duration="10" unit="minute"> <users interarrival="{RATE}" unit="second"></users> </arrivalphase>""" line = entry...
def _remove_doc(xml_str): """Remove DBus XML documentation from string input """ result = [] do_add = True for line in xml_str.splitlines(): if '<doc:doc>' in line: do_add = False if do_add: result.append(line) if '</doc:doc>' in line: do_...
def _NextMaintenanceToCell(zone): """Returns the start time of the next maintenance or ''.""" maintenance_events = zone.get('maintenanceWindows', []) if maintenance_events: next_event = min(maintenance_events, key=lambda x: x.get('beginTime')) return next_event.get('beginTime') + '--' + next_event.get('en...
def enc(string: str) -> bytes: """"ASCII-encodes a string.""" return bytes(string, "ascii")
def _strbool(data): """ return either the boolean value (if isinstance(text,bool) or True if string is one of True or Yes (case insensitiv) or False""" if isinstance(data, bool): return data else: return data.upper() in ["TRUE", "YES"]
def _adjust_component(val: int) -> int: """ Written by Akshay Vashisht Returns the midpoint of the quadrant in which val is in. val must be between 0 and 255 inclusive. The 4 quadrants are 0 to 63, 64 to 127, 128 to 191, 192 to 255. The repespective midpoints of these quadrants are 31, 9...
def tar_mode(gzip=None, xz=None, is_pipe=None): """Return tarfile.open compatible mode from boolean flags""" if gzip: return ":gz" if xz: return ":xz" if is_pipe: return "|" return ""
def add(a, b): """This program adds two numbers and return the result""" result = a + b return result
def get_domains(options): """ Fetches all domains currently requested :param options: :return: """ domains = [options['common_name']] if options.get('extensions'): for name in options['extensions']['sub_alt_names']['names']: domains.append(name.value) return domains
def lookup_tag(regex_pattern): """ For each @regex_pattern we need a dict so we can lookup the associated string to tag it with. """ lookup = {"[H|h]ello world": "GREETING_TAG"} try: return lookup[regex_pattern] except KeyError: return None
def joinLetterList(hanglist): """Form an easy to read string for the passed hanglist.""" str = '' for ch in hanglist: str += ch str += ' ' return str.strip()
def square_pyramidal_number(num: int) -> int: """ Return the sum of the squares of all numbers up to and including the input number """ # https://en.wikipedia.org/wiki/Square_pyramidal_number return num * (num + 1) * (2 * num + 1) // 6
def maxdistance(paths): """ Returns the longest out of the distances between nodes paths is list(nx.all_pairs_shortest_path(er)) """ maxdist = 0 for k in paths: lastnode = list(k[1])[-1] dist = len(k[1][lastnode]) if dist > maxdist: maxdist = dist return m...
def create_grid(width, height): """ Create a two-dimensional grid of specified size. """ return [[0 for _x in range(width)] for _y in range(height)]
def strides(shape): """Computes ndarray.strides for an array shape.""" result = [] stride = 1 for _, x in reversed(list(enumerate(shape))): result.append(stride) stride *= x return list(reversed(result))
def join_dictionaries(dict1, dict2): """Join two dictionaries. Function to join two input dictionaries. For the pairs with the same keys, the set of values will be stored in a list. Parameters ---------- dict1: dict() or key-value pairs dict2: dict() or key-value pairs """ if not (...
def translater_cidr_netmask(cidr): """ Translate CIDR to netmask notation. :param cidr: :return: netmask as string """ return '.'.join( [str((m >> (3-i)*8) & 0xff) for i, m in enumerate( [-1 << (32-int(cidr))] * 4)] )
def unique_list(arr) -> list: """ returns a unique version of the list while keeping its order :param arr: list | tuple :return: list """ seen = set() seen_add = seen.add return [x for x in arr if not (x in seen or seen_add(x))]
def _is_python_file(filename: str) -> bool: """Check if file is a Python file.""" return filename.endswith(".py")
def odd_primes_below_n(n): """ Returns a list of odd primes less than n. """ sieve = [True] * (n // 2) for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i // 2]: sieve[i * i // 2::i] = [False] * ((n-i*i-1)//(2*i)+1) return [2 * i + 1 for i in range(1, n//2) if sieve[i]]
def getModClass(name): """converts 'xgds_planner.forms.PlanMetaForm' to ['xgds_planner.forms', 'PlanMetaForm']""" try: dot = name.rindex('.') except ValueError: return name, '' return name[:dot], name[dot + 1:]
def PowersOf(logbase, count, lower=0, include_zero=True): """Returns a list of count powers of logbase (from logbase**lower).""" if not include_zero: return [logbase ** i for i in range(lower, count+lower)] else: return [0] + [logbase ** i for i in range(lower, count+lower)]
def upper_hex(input): """ Converts the input to an uppercase hex string. """ if input in [0, "0"]: return "0" elif input <= 0xF: return ("%.x" % (input)).upper() else: return ("%.2x" % (input)).upper()
def getDimensions(array): """ Gets the dimensions for a two-dimensional array. The first dimension is simply the number of items in the list; the second dimension is the length of the shortest row. This ensures that any location (row, col) that is less than the resulting bounds will in fact map to...
def _get_parameters(method, param_name, args, kwargs): """Return the arguments passed to all experimental parameters. All method arguments that are not param_name are treated as experimental parameters. method is assumed to have been called as method(*args, **kwargs). """ from inspect import g...
def flip_string(s): """ flip_string: Flip a string Parameters ---------- s : str String to reverse Returns ------- flipped : str Copy of `s` with characters arranged in reverse order """ flipped = '' # Starting from the last character in `s`, # add...
def find_subsequence(subseq, seq): """ If subsequence exists in sequence, return True. otherwise return False. can be modified to return the appropriate index (useful to test WHERE a chain is converged) """ i, n, m = -1, len(seq), len(subseq) try: while True: i = seq.inde...
def truncate(x, maxlen=1000): """ >>> truncate('1234567890', 8) '1234 ...' >>> truncate('1234567890', 10) '1234567890' """ if len(x) > maxlen: suffix = ' ...' return '%s%s' % (x[:maxlen - len(suffix)], suffix) else: return x
def get_fs_of_path(fs_mntpnt, path): """ tell what is the gpfs filesystem for input path return: either of the following: - filesystem name of given path - False (if path is not under any gpfs filesystem) """ for fs in fs_mntpnt: if path.startswith(fs_mntpnt[fs]): ...
def TO_LOWER(expression): """ Converts a string to lowercase, returning the result. https://docs.mongodb.com/manual/reference/operator/aggregation/toLower/ for more details :param expression: The string or expression of string :return: Aggregation operator """ return {'$toLower': express...
def get_overlap(a, b): """ return the len of overlap between two regions """ q_start = int(a[0]) q_end = int(a[1]) r_start = int(b[0]) r_end = int(b[1]) if q_start == q_end: q_end += 1 # otherwise it doesnt work for SNPs ret = max(0, min(q_end, r_end) - max(q_start, r_start)) return(ret)
def process_excel_cmd(cmd_line): """Process cmd line parameters related to Excel file. filename;table;line line is line number where column names are defined :param cmd_line: [description] :type cmd_line: [type] """ param_dict = {} cmd_line_list = cmd_line.split(';') if len(cmd_...
def _normalize_instancemethod(instance_method): """ wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up; we want the original repr to show up in the logs, therefore we do this trick """ if not hasattr(instance_method, 'im_self'): return instance_met...
def memstr_to_kbytes(text): """ Convert a memory text to it's value in kilobytes. """ kilo = 1024 units = dict(K=1, M=kilo, G=kilo ** 2) try: size = int(units[text[-1]] * float(text[:-1])) except (KeyError, ValueError): raise ValueError( "Invalid literal for size ...
def dictUpdate(original,newer): """Combine two dictionaries. If duplicate keys exist, use the newer values to overwrite the older ones.""" for k in newer.keys(): original[k]=newer[k] return original
def format(cmds, sep=' , '): """Format the alias command""" return sep.join(' '.join(cmd) for cmd in cmds)
def frame2ms(f, frame_rate=30): """Convert a frame number to a time in ms""" return f * 1000 / frame_rate
def migrate_impl_args(argv, migrate_args): """ Given a list of arguments of the form: --foo --bar=baz -- --flim=flam And a list of arguments to migrate, return a list in which the arguments to migrate come before the '--' separator. For example, were we to migrate '--flim', we would return...
def _text_conf_from_tess_dict(data): """From the results of pytesseract data dictionary, return joined text and avg confidence.""" text_chunks = [] confs = [] for conf, text in zip(data["conf"], data["text"]): if float(conf) < 0.0 or not text: continue else: text_...
def as_bytes(value): """ Returns value as bytes """ if not isinstance(value, bytes): return value.encode('UTF-8') return value
def handle_exception(error: Exception): """When an unhandled exception is raised""" message = "Error: " + getattr(error, 'message', str(error)) return {'message': message}, getattr(error, 'code', 500)
def make_new_dict_of_squares(squares, keys_to_keep): """ subsets a dictionary with a list of keys to keep :param squares: dictionary of squares :param keys_to_keep: keys of interest to keep :return: new dictionary only containing key:value pairs from keys_to_keep """ clean_squares_dict = dic...
def all_done_checker(env, obs, rewards, dones, infos): """ Returns True when all agents are reported as done. """ for done in dones.values(): if not done: return False return True
def flatten(variable): """flatten a list of lists """ variable = sum(variable, []) return variable
def _fmt_simple(name, arg): """Format a simple item that consists of a name and argument.""" if arg is None: return None return "%s %s" % (name, arg)
def chronos_parent_str(parentlist): """Returns correct string for parent dependencies. Formatting of returned string depends on number of parents Args: parentlist (list): names of parent jobs Returns: string """ return '"parents": {0}'.format(str(parentlist).replace("'", "\""))
def rule_power_factor(f11, f10, f01, f00): """ Computes the rule power factor (RPF) for a rule `a -> b` based on the contingency table. params: f11 = count a and b appearing together f10 = count of a appearing without b f01 = count of b appearing without a f00 = count of neit...
def get_sentence_at_index(index, resolved_list): """Returns the sentence beginning at the index """ end_of_sentence_punctuation = ['.', '!', '?'] begin_index = index end_index = index while begin_index >= 0: val = resolved_list[begin_index].strip() if val in end_of_sentence_punct...
def printName(name): """takes a name (string) and will print out "Your name is:" along with the name capitalized. Returns the capitalized name. example: printName("julie") will print: Your name is: Lucy """ name = name.capitalize() print("Your name is:", name) return name
def validate_logginglevel(slackchannelconfiguration_logginglevel): """ Validate LoggingLevel for SlackChannelConfiguration Property: SlackChannelConfiguration.LoggingLevel """ VALID_SLACKCHANNELCONFIGURATION_LOGGINGLEVEL = ("ERROR", "INFO", "NODE") if ( slackchannelconfiguration_loggin...
def min_by(f, x, y): """Takes a function and two values, and returns whichever value produces the smaller result when passed to the provided function""" return x if f(x) < f(y) else y
def _parse_attrib(text): """ Parses a string of the form 'key=val'and returns a key, value pair. @type text: C{str} @param text: textual representation of key, value pair @rtype: C{tuple} @return: key, value pair """ key, val = [s.strip() for s in text.split('=')...
def alphabet_index_to_ascii_character(alphabet_index: int): """function that converts alphabetic index to an ascii character""" return chr(alphabet_index + 65)
def nums_only_in_list(lst): """ Takes a list of mixed data types and returns a list containing only the `int` and `float` values in the original list. """ return [num for num in lst if isinstance(num, (int, float))]
def _compute_tolerance(workers): """Computes how many workers can be ignored for one gradient update. These numbers were chosen based on just a few expriments. They are rather arbitrary, feel free to change them. Args: workers: Number of workers used during computations. Returns: int: how many wor...
def get_gran_lvl(intend_lvl, build_latent_class): """Get gran_lvl for each class given specific requied granularity. if intended ganularity is larger than the internal granlarity, take the max """ max_gran_class = [len(build_latent_class[i]) for i in build_latent_class] class_gran_lvl = [min(intend_lvl,...
def _dict_to_list(chrdict): """ Convert a dictionary to an array of tuples """ output = [] for chromosome, values in chrdict.items(): for value in values: output.append((chromosome, ) + value) return output
def strip_suffix(s: str, suffix: str) -> str: """ If ``s`` ends with ``suffix``, return the rest of ``s`` before ``suffix``; otherwise, return ``s`` unchanged. """ # cf. str.removesuffix, introduced in Python 3.9 n = len(suffix) return s[:-n] if s[-n:] == suffix else s
def get_albedo_scaling(inc, albedo=0.12, a=None, b=None, mode="vasavada"): """ Return albedo scaled with solar incidence angle (eq A5; Keihm, 1984). Parameters a and b have been measured since Keihm (1984) and may differ for non-lunar bodies. Optionally supply a and b or select a mode: modes: ...
def char_to_bool(letter): """Transform character (J/N) to Bool.""" if letter.upper() == 'J': return True elif letter.upper() == 'N': return False else: raise ValueError('Ongeldige letter, alleen J of N toegestaan.')
def one_and_none(first, second): """ Check if one element in a pair is None and one isn't. :param first: To return True, this must be None. :type first: str :param second: To return True, this mustbe false. :type second: str """ sentinel = True if first is None and second is not None e...
def parent(i): """ Return an element's parent in relation to a binary tree """ return (i - 1)//2
def _denormalize_mac(mac): """Takes a normalized mac address (all lowercase hex, no separators) and converts it to the Zyxel format. Example:: _denormalize_mac('abcdef123456') == 'ab-cd-ef-12-34-56' """ return '-'.join((mac[i] + mac[i+1] for i in range(0, 12, 2)))
def format_date(value, format="%d.%m.%Y"): """Format a datetime to date (Default) 31.12.2020""" if value is None: return "" return value.strftime(format)
def prepare_nav_data(line_info): """Given a list of tuples from analyze_line, prepares navigation data. Navigation data is a dictionary mapping an id to its children ids, paren id and user ids. It's important for line_info to be in the order gathered from the input. The order is essential for dete...
def calculate_margin(distance): """TOOD: Be permissive in orientation for far people and less for very close ones""" margin = distance * 2 / 5 return margin
def _partition(comparables, lo, hi): """Return index upon partitioning the array pivoting on the first element Arguments: comparables -- an array of which the elements can be compared lo -- lower bound of indices hi -- higher bound of indices After partition, elements to the left of pivot ar...
def getProofFromPredecessors(f, predecessors): """Generate a proof of the formula f. This function generates a proof of the binAd formula f, given a dictionary information about formulas' predecessors i.e. what a given formula could have been derived from using an inference rule. For reasons of pra...
def get_elevated_session_input(response): """Create input for get_elevated_session.""" return { 'aws_access_key_id': response['Credentials']['AccessKeyId'], 'aws_secret_access_key': response['Credentials']['SecretAccessKey'], 'aws_session_token': response['Credentials']['SessionToken'] }
def sorensen(s1,s2) -> float: """ Sorensen similarity. Parameters ---------- s1 : first set. s2 : second set. Returns ------- similarity coefficient (0<=x<=1). """ return 2*len(s1&s2)/(len(s1)+len(s2))
def calc_throughfall_flux(precip, canopyStore, canopyStore_max): """ Calculate the throughfall flux from canopy interception storage Parameters ---------- precip : int or float Precipitation flux [mm day^-1] canopyStore : int or float Canopy Interception storage [mm] ca...
def get_first_word(string): """Get the first word of the line. :param str string: string :rtype str :return: string with the first word """ return string.split(' ', 1)[0]
def factorial(n): """ Return the factorial of a number n. """ f = 1.0 for i in range(0, n): f *= (n - i) return f
def find_diff_in_sentence(original_sentence_tokens: tuple, suspicious_sentence_tokens: tuple, lcs: tuple) -> tuple: """ Finds words not present in lcs. :param original_sentence_tokens: a tuple of tokens :param suspicious_sentence_tokens: a tuple of tokens :param lcs: a longest common subsequence ...
def deg(angle): """Return a plain integer that is simply degrees extracted.""" dms = str(angle).split(':') return int(dms[0])
def additive_extension(additive_func, q, q_max, cache=None, cache_offset=1): """ Additive extension for event models. Any sub- or super- additive function additive_func valid in the domain q \in [0, q_max] is extended and the approximited value f(q) is returned. NOTE: this cannot be directly used with d...
def index(lis, alternatives): """Return index of one of the <alternatives> in <lis>""" for alt in alternatives: try: return lis.index(alt) except ValueError: pass return None
def compute_months_and_offsets(start, count): """ Figure out an array of values """ months = [start] offsets = [0] for i in range(1, count): nextval = start + i if nextval > 12: nextval -= 12 offsets.append(1) else: offsets.append(0) mo...
def format_name(name: str) -> str: """Formats a string for displaying to the user Examples -------- >>> format_name("manage_messages") 'Manage Messages' >>> format_name("some_name") 'Some Name' Parameters ---------- name : str the raw name Returns ------- s...
def _calculateIndex(imageCount : int, downloadIndex : int): """Calculates the download index""" # check if downloadIndex <= 0 if downloadIndex < 0: print("Entered image index must not be less than 1.") return None # check if downloadIndex > imageCount if downloadIndex > imageCount:...
def WeekdayOnFirstAuroran(dekYear): """ Returns the Gregorian week day for the 1 Auroran of a given year """ weekDay = ((1 + 5*((dekYear) % 4) + 4*((dekYear) % 100) + 6*((dekYear) % 400)) % 7) + 1 return weekDay
def ensure(data_type, check_value, default_value=None): """ function to ensure the given check value is in the given data type, if yes, return the check value directly, otherwise return the default value :param data_type: different data type: can be int, str, list, tuple etc, must be python suppo...
def cell_background(val): """Creates the CSS code for a cell with a certain value to create a heatmap effect Args: val (int): the value of the cell Returns: [string]: the css code for the cell """ try: v = abs(val) opacity = 1 if v >100 else v/100 # color = '...
def computeStatistic( benchmarks, field, func ): """ Return the result of func applied to the values of field in benchmarks. Arguments: benchmarks: The list of benchmarks to gather data from. field: The field to gather from the benchmarks. func: The function to apply to the data...
def is_result_group_comparable(grouped, ref_grouped): """Given two nested dictionaries generated by get_dict_from_json, return true if they can be compared. grouped can be compared to ref_grouped if ref_grouped contains all the queries that are in grouped. """ if ref_grouped is None: return False for wo...
def get_omnipresent_at_pos(fragFreqCounters, n, **kwargs): """ Find patterns in fragFreqCounters for which the frequency is n. fragFreqCounters is a dictionary (usually keyed on 'fragments') of whose values are dictionaries mapping positions to frequencies. For example: { ('a', ...
def interaction_truncation_for_Nmax(Nv,Nmax,standardize=True): """ interaction_truncation_for_NMax (Nv, Nmax) -> (N1b,N2b) Identifies (N1b,N2b) truncation needed for interaction to support given many-body run. Nv -- N for valence shell Nmax -- many-body Nmax standardize -- if True, returns a stand...
def unique_irqs(irqs): """ Takes a dictionary containing the list of interrupt lines and filters them to just the unique interrupt sources. This function is made available to the template environment so that interrupt handler declarations and definitions aren't repeated when multiple instances of a...
def LevenshteinCost(a, b): """Cost function for Levenshtein distance with substitutions. Cost function for what is now thought of as the classical Levenshtein distance, which is the minimum number of insertions, deletions, and substitutions required to edit one sequence into another. Returns zero for matche...
def inverse_dic_lookup(dic, item): """Looks up dictionary key using value.""" return next(key for key, value in dic.items() if value == item)
def gcd(a, b): """Greatest common divisor.""" if b == 0: return a return gcd(b, a % b)
def color_print(s, color='green'): """ color str :param s: :param color: :return: """ ct = { 'green': '\033[92m', 'red': '\033[91m', 'none': '\033[0m' } return ''.join([ct[color], s, ct['none']])
def area_or_perimeter(length: int, width: int) -> int: """ This function returns area for a square or perimeter for a rectangle. """ if length == width: return length * width return (2 * length) + (2 * width)
def mixedcase(s, _cache={}): """Convert to MixedCase. >>> mixedcase('res.company') 'ResCompany' """ try: return _cache[s] except KeyError: _cache[s] = s = ''.join([w.capitalize() for w in s.split('.')]) return s
def from_datastore(entity): """Formats data from datastore Datastore typically returns: [Entity{key: (kind, id), prop: val, ...}] This returns: [ name, description, pageCount, author, review ] """ if not entity: return None if isinstance(entity, list): entity = ...
def merge_data_objects(d1, d2, deduplicate_lists=True, merge_dict_in_lists=False): """A very simple function to merge 2 data objects into one recursively Args: d1 (dict or list): Original data object. d2 (dict or list): Data object to merge. Has higher priority in case of conflicting keys. ...