content
stringlengths
42
6.51k
def islist(val): """ check if the entry is a list or is a string of list Parameters ---------- val an entry of any type Returns ------- bool True if the input is either a list or a string of list, False otherwise """ text = str(val) if text[0] == '[' and te...
def nb_predicates(self): """Get the number of predicates in the database""" # return self._hdt.nb_predicates return 0
def extract_feature_sequence(extracted_results, frame_idx, causal, seq_len, step=1): """Extract the target frame from person results, and pad the sequence to a fixed length. Args: ext...
def _match(property): """Triggered for match event type :@param property: string :@return event_type: string """ event_mapper = { "ForkEvent": "forked", "WatchEvent": "started", "CheckRunEvent": "checked run", "CommitCommentEvent": "committed comment", "Create...
def cleanhtml(txt): """Remove html tags from a string""" import re clean = re.compile('<.*?>') return re.sub(clean, '', txt)
def b_f_general(graph_array, current_node): """Runs the Bellman-Ford algorithm to find shortest paths.""" distance = [] predecessor = [] ## Step 1: Initialize graph: for _ in range(len(graph_array)): distance.append(float('inf')) predecessor.append(None) distance[current_node] =...
def _end_of_encoding(encoding: bytes, start: int) -> int: """Find the end index of the encoding starting at index start. The encoding is not validated very extensively. There are no guarantees what happens for invalid encodings; an error may be raised, or a bogus end index may be returned. Callers are expected ...
def convert_genre(genre: str) -> str: """Return the HTML code to include for the genre of a word.""" return f" <i>{genre}.</i>" if genre else ""
def get_lighter_color(color): """Generates a lighter color. Keyword arguments: color -- color you want to change, touple with 3 elements (Doesn't matter if it is RGB or BGR) Return: Return a lighter version of the provided color """ add = 255 - max(color) add = min(add,30)...
def parCondense(form, tar): """ Performs paranthesis reduction at a particular depth. Parameters ---------- form : string Formula. tar : int Target depth for paranthesis condensation. Returns ------- ans : string The condensed paranthesis form of the given f...
def l(a: float, b: float) -> float: """ l = b * b / a :param a: semi-major axis :type a: float :param b: semi-minor axis :type b: float :return: semi-latus rectum :rtype: float """ return b * b / a
def bitarray2fasm(bitarray): """ Convert array of bits ('0', '1') into FASM value. Note: index 0 is the LSB. """ bitstr = ''.join(bitarray[::-1]) return "{}'b{}".format(len(bitstr), bitstr)
def update_transmission_parameters(parameters, compartments_to_update): """ Update parameters with transmission rates for each compartment with altered immunity/sucseptibility to infection """ for compartment in compartments_to_update: parameters.update( { "contact_ra...
def stripNamespace(name): """ Method used to remove any colon characters from the supplied name. :type name: str :rtype: str """ return name.split(':')[-1]
def dict_to_string(input_dict: dict, separator=", ") -> str: """ :param input_dict: :param separator: :return: """ combined_list = list() for key, value in input_dict.items(): individual = "{} : {:.5f}".format(key, value) combined_list.append(individual) retur...
def mclag_ka_session_dep_check(ka, session_tmout): """Check if the MCLAG Keepalive timer and session timeout values are multiples of each other and keepalive is < session timeout value """ if not session_tmout >= ( 3 * ka): return False, "MCLAG Keepalive:{} Session_timeout:{} values not satisfying ...
def _get_function_name(func, aliases): """Returns the associated name of a function.""" try: return aliases[func] except KeyError: # Has to be a different branch because not every function has a # __name__ attribute. So we cannot simply use the dictionaries `get` # with defau...
def add3(a, b): """Adds two 3D vectors c=a+b""" return [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
def normalize_typename(typename): """ Drops the namespace from a type name and converts to lower case. e.g. 'tows:parks' -> 'parks' """ normalized = typename if ":" in typename: normalized = typename.split(":")[1] return normalized.lower()
def discount_with_dones(rewards, dones, gamma): """ Apply the discount value to the reward, where the environment is not done :param rewards: ([float]) The rewards :param dones: ([bool]) Whether an environment is done or not :param gamma: (float) The discount value :return: ([float]) The discou...
def time_taken(elapsed): """To format time taken in hh:mm:ss. Use with time.monotic()""" m, s = divmod(elapsed, 60) h, m = divmod(m, 60) return "%d:%02d:%02d" % (h, m, s)
def factorial(n): """Return n * (n - 1) * (n - 2) * ... * 1. >>> factorial(5) 120 """ if n == 0: return 1 else: return n * factorial(n-1)
def area(region): """Returns the area of the specified region. Args: region (dict): A dictionary containing {x1, y1, x2, y2} arguments. Returns: float: The area of the region. """ w = region["x2"] - region["x1"] h = region["y2"] - region["y1"] return w * h
def partition(array, first, last): """helper for quick_sort""" pivot_value = array[first] left_mark = first + 1 right_mark = last done = False while not done: while left_mark <= right_mark and array[left_mark] <= pivot_value: left_mark = left_mark + 1 while array[righ...
def score_time_cost(event, attributes): """ Score based on indicators of time cost (WIP) Key indicators of resource cost will be numbers of targets and analysis effort """ score = 0 for attribute in attributes: if attribute["category"] == "Network activity": ty = attribute[...
def keyify_value(value): """ :type value: str :return: """ return value.lower().replace(' ', '-').replace("'", "-")
def ensure_operators_are_strings(value, criteria_pattern): """ This function ensures that both value and criteria_pattern arguments are unicode (string) values if the input value type is bytes. If a value is of types bytes and not a unicode, it's converted to unicode. This way we ensure all the ope...
def update_tuple(origin_tuple, update_value, update_index): """Update tuple/namedtuple for specified update_index and update_value.""" # Namedtuple is inherit from tuple. if not isinstance(origin_tuple, tuple): raise ValueError("Only tuple/namedtuple supported. Origin_tuple type: " "%s." ...
def sort_by_priority_list(values, priority): """ Sorts a list of parameter dictionaries by a list of priority. Useful when setting up parameters automatically. """ # priority_dict = {k: i for i, k in enumerate(priority)} # try to get a value from priority_dict using priority_dict.get(value). ...
def coerce_to_strict(const): """ This is used to ultimately *encode* into strict JSON, see `encode` """ # before python 2.7, 'true', 'false', 'null', were include here. if const in ("Infinity", "-Infinity", "NaN"): return None else: return const
def rm_spaces_and_chars_from_str(input_str, remove_slashes=True, replace_brackets=True, replace_quotes=True, replace_dots=True, remove_plus=True, swap_pcent=True, replace_braces=True): """ remove the spaces and extra ...
def splitFilename(filename): """ Pass in a standard style rpm fullname Return a name, version, release, epoch, arch, e.g.:: foo-1.0-1.i386.rpm returns foo, 1.0, 1, i386 1:bar-9-123a.ia64.rpm returns bar, 9, 123a, 1, ia64 """ if filename[-4:] == '.rpm': filename = fi...
def bind_method(value, instance): # good with this """ Return a bound method if value is callable, or value otherwise """ if callable(value): def method(*args): return value(instance, *args) return method else: return value
def write_values(value): """Write a `*values` line in an LTA file. Parameters ---------- value : [sequence of] int or float or str Returns ------- str """ if isinstance(value, (str, int, float)): return str(value) else: return ' '.join([str(v) for v in value])
def combine(*styles): """Combine multiple style specifications into one. Parameters ---------- styles: sequence of :class:`dict` instances A collection of dicts containing CSS-compatible name-value pairs. Returns ------- styles: :class:`dict` containing CSS-compatible name-value pa...
def isa(obj, types): """an alias for python built-in ``isinstance``.""" if types is callable: return callable(obj) return isinstance(obj, types)
def short_to_full_git_sha(short, refs): """Converts a short git sha to a full sha :param short: A short git sha represented as a string :param refs: A list of refs in the git repository :return: The full git sha or None if one can't be found """ return [sha for sha in set(refs.values()) if sha....
def getHeight(root): """ Start with 0 height and recurse going down, increasing the levels """ if not root: return 0 return 1 + max(getHeight(root.left), getHeight(root.right))
def check_line_start(line_breaks, char_count): """ Determines whether the current word is the start of a line. line_breaks: dict The words split across a line in the current page char_count: int The number of characters examined so far in the current line Retur...
def parse_course_info(course): """ Parse information of a course that is retrieved from Moodle. :param course: A json statement, received as response on a Moodle call. :type course: dict(str, list(dict(str, int))) :return: The name of a course. :rtype: str """ course_name = course['cour...
def string_reverser(our_string): """ Reverse the input string Args: our_string(string): String to be reversed Returns: string: The reversed string """ return our_string[::-1]
def convert_empty_sets_to_none(config_dict): """Convert empty lists to None type objects in configuration dictionary. :param config_dict: dict, CAZy classes and families to be scraped Return dictionary with no empty lists. """ for key in config_dict: if config_dict[key] is not None: ...
def resolve_time(delta: int, sep: str = "") -> str: """ Converts an int to its human-friendly representation :param delta: time in seconds :param sep: string separator :return: string """ if type(delta) is not int: delta = int(delta) years, days, hours, minutes = 0, 0, 0, 0 ...
def get_dotted_attr(obj, attr_name): """ Get the value of the attribute. Unlike getattr this accepts nested or 'dotted' attributes. """ if '.' not in attr_name: return getattr(obj, attr_name) else: L = attr_name.split('.', 1) return get_dotted_attr(getattr(obj, L[0]), L[1])
def normalize_tuple(value, n, name): """Transforms an integer or iterable of integers into an integer tuple. A copy of tensorflow.python.keras.util. Args: value: The value to validate and convert. Could an int, or any iterable of ints. n: The size of the tuple to be returned. nam...
def flatten(x): """ Flatten list of lists """ import itertools flatted_list = list(itertools.chain(*x)) return flatted_list
def fib_matrix(n): """Efficient algorithm to return F(n) via matrix multiplication. """ if (n <= 1): return n v1, v2, v3 = 1, 1, 0 for rec in bin(n)[3:]: calc = v2 * v2 v1, v2, v3 = v1 * v1 + calc, (v1 + v3) * v2, calc + v3 * v3 if rec == '1': v1, v2, v3 =...
def get_capitalized_words(text): """Finds individual capitalized words and return in a list""" s = [] if isinstance(text, list): text = " ".join(text) for t in text.split(): if len(t) > 1: if t[0].isupper() and t[1:].islower(): s.append(t) return s
def getToPlane(p, shape): """Convert coordonnates in the plane coordonnates system.""" x, y = p h, w = shape[:2] m = max(w, h) return (x / m, -y / m)
def convert_byte_to( n , from_unit, to , block_size=1024 ): """ This function converts filesize between different units. By default, it assumes that 1MB = 1024KB. Modified from https://github.com/mlibre/byte_to_humanity/blob/master/byte_to_humanity/bth.py. The mods let this transform units of any ty...
def cut_rod_bottom_up(p, n): """ Only difference from book is p[i-1] instead of p[i] due to indexing, also create to arrays to n+1 since range doesn't include end bound. """ r = [0 for k in range(n+1)] for j in range(1, n+1): q = -100000 for i in range(1, j+1): q = ma...
def get_top_header(table, field_idx): """ Return top header by field header index. :param table: Rendered table (dict) :param field_idx: Field header index (int) :return: dict or None """ tc = 0 for th in table['top_header']: tc += th['colspan'] if tc > field_idx: ...
def inner_product(D1, D2): """ Take the inner product of the frequency maps. """ result = 0. for key in D1: if key in D2: result += D1[key] * D2[key] return result
def bubble_sort(array): """Bubble sort in Python >>> bubble_sort([]) [] >>> bubble_sort([2,1]) [1, 2] >>> bubble_sort([6,1,4,2,3,5]) [1, 2, 3, 4, 5, 6] """ is_sorted = False while not is_sorted: is_sorted = True for i in range(len(array)-1): if arr...
def get_paths_threshold(plist, decreasing_factor): """ Get end attributes cutting threshold Parameters ---------- plist List of paths ordered by number of occurrences decreasing_factor Decreasing factor of the algorithm Returns --------- threshold Paths cutt...
def parsed_path(path): """ message=hello&user=yoo { 'message': 'hello', 'user': 'yoo', } """ index = path.find('?') if index == -1: return path, {} else: path, query_str = path.split('?', 1) args = query_str.split('&') query = {} fo...
def is_parallel_ui_tests(args): """ This function checks for coverage args exists in command line args :return: boolean """ if "parallel" in args and args["parallel"]: return True return False
def regex_split(original_output, regex_split_cmd): """ Takes in a regex string and output, returns a list of output split :param original_output: :param regex_split_cmd: :return: """ def _regex_split(): return original_output.split(regex_split_cmd) return _regex_split()
def rotate_axes(xs, ys, zs, zdir): """ Reorder coordinates so that the axes are rotated with zdir along the original z axis. Prepending the axis with a '-' does the inverse transform, so zdir can be x, -x, y, -y, z or -z """ if zdir == 'x': return ys, zs, xs elif zdir == '-x'...
def estimate_arpu(x): """ Allocate consumption category given a specific luminosity. """ arpu = 0 if x['mean_luminosity_km2'] > 5: # #10 year time horizon # for i in range(0, 10): # #discounted_arpu = (arpu*months) / (1 + discount_rate) ** year # arpu += ( ...
def sub_test_noiser(new_bots, old_bots, turn, should_noise, test_other): """ sub test function to check if noiser worked Parameters ---------- new_bots: bots after noising old_bots: bots before noising turn: which turn is it now? 0,1,2,3 should_noise: should the noiser do something right no...
def _get_versioned_config(config, version = ""): """select version from config Args: config: config version: specified version, default is "". Returns: updated config with specified version """ versioned_config = {} versioned_config.update(config) used_version = co...
def mode_assignment(arg): """ Translates arg to enforce proper assignment """ arg = arg.upper() stream_args = ('STREAM', 'CONSOLE', 'STDOUT') try: if arg in stream_args: return 'STREAM' else: return arg except Exception: return None
def sum_even_fibonaccis(limit): """Find the sum of all even terms in the Fibonacci sequence whose values do not exceed the provided limit. """ # Fibonacci seed values are 0 and 1. previous, current, even_fibonacci_sum = 0, 1, 0 while previous + current <= limit: # This is a memoized cal...
def calculate_average(result): """Calculates the average package size""" vals = result.values() if len(vals) == 0: raise ValueError("Cannot calculate average on empty dictionary.") return sum(vals)/float(len(vals))
def filter_positive_even_numbers(numbers): """Receives a list of numbers, and filters out numbers that are both positive and even (divisible by 2), try to use a list comprehension""" return [x for x in numbers if x > 0 and x % 2 == 0]
def group_metrics(metrics): """ Groups metrics with the same name but different label values. Takes metrics as a list of tuples containing: * metric name, * metric documentation, * dict of label key -> label value, * metric value. The metrics are grouped by metric name. All metrics wit...
def proglen(s): """ Program length is measured in characters, but in order to keep the values in a similar range to that of compressibility, DTW and Levenshtein, we divide by 100. This is a bit arbitrary. :param s: A string of a program phenotype. :return: The length of the program divided ...
def str_to_dec(string): """Converts fractions in the form of strings to decimals """ tokens = string.split() if string == None: return 0 elif string == "a" or string == "an" or string == "the": return 1 elif tokens and tokens[-1] == "eighth": return 0.125 elif tokens[-2:]...
def interval_class( pitch1: int, pitch2: int, ) -> int: """Finds the interval class between two pitches or pitch-classes. """ diff_mod_12 = abs(pitch1 - pitch2) % 12 if diff_mod_12 > 6: diff_mod_12 = 12 - diff_mod_12 return diff_mod_12
def compute_weighted_percentiles(weighted_values, number_of_percentiles, key=lambda x: x): """ Compute weighted percentiles from a list of values and weights. number_of_percentiles evenly distributed percentiles values will be returned, including the 0th (minimal value) and the 100th (maximal value). ...
def _is_surf(config): """Returns True iff we are on the surface""" return "surface_file" in config and config["surface_file"]
def _list_union_inter_diff(*lists): """Return 3 lists: intersection, union and differences of lists """ union = set(lists[0]) inter = set(lists[0]) for l in lists[1:]: s = set(l) union = union | s inter = inter & s diff = union - inter return list(union), list(inter),...
def __control_dict(v): """ Wrap a control field value in a dict. """ return {"type": "control", "value": v}
def arg_process(number): """Fake function for pytest""" number_added = number + 1 return number_added
def wait_for_line(input_string): """ Should the intepreter wait for another line of input or try to evaluate the current line as is. """ trailing_ops = ['+', '-', '/', '*', '^', '=', '>', '<', '/;', '/:', '/.', '&&', '||'] if any(input_string.rstrip().endswith(op) for op in t...
def tuple_factor(tuple1, factor): """ returns the tuple multiplied with the factor """ return tuple1[0] * factor, tuple1[1] * factor
def find_all_indexes(text, pattern): """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found. Time Complexity: O(p * t) -- p being length of pattern and t being length of text """ assert isinstance(text, str), 'text is not a string: {}'.format(text) ...
def unique_name(name, all_names): """Make the name unique by appending "#n" at the end.""" if not isinstance(all_names, set): all_names = set(all_names) if name not in all_names: return name i = 1 head, sep, tail = name.rpartition('#') if sep: try: i = int(...
def _check_handle(handle): """Checks if provided file handle is valid.""" return handle is not None and handle.fileno() >= 0
def build_vocab(posts): """ Given the training set of posts, constructs the vocabulary dictionary, `tok_to_ix`, that maps unique tokens to their index in the vocabulary. """ tok_to_ix = {} for post in posts: tokens = post.split(' ') for token in tokens: tok_to_ix.setd...
def order_steps(steps): """Return order steps must be taken given their requirements.""" num_steps = len(steps) order = '' while num_steps: ready_steps = [] for step, requirements in steps.items(): if step in order: continue ready = True ...
def neatify_string_to_list(input_string): """Gets me my actual list of items to query""" clean_brackets = input_string.replace('[', '')\ .replace(']', '') print(clean_brackets) return clean_brackets.split(' ')
def get_table_name(table_name): """Get table name from full table name.""" parts = table_name.split('.', 1) return parts[-1]
def Get(x, start, end=None, step=None): """ iterable >> Get(start, end, step) Extract elements from iterable. Equivalent to slicing [start:end:step] but per element of the iterable. >>> from nutsflow import Collect >>> [(1, 2, 3), (4, 5, 6)] >> Get(1) >> Collect() [2, 5] >>> [(1, 2, ...
def wmode(x: bytes) -> str: """ Wireless mode decoding Args: x: byte encoded representation of wireless mode Returns: String representation of wireless mode """ if x == b"\x02": return "sta" elif x == b"\x03": return "ap" return ""
def is_int(string): """ Checks if a string can be converted to an int :param str string: a string of any kind :return: True if possible, False if not :rtype: bool """ try: int(string) return True except ValueError: return False
def _tgrep_parens_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node from a parenthetical notation. """ assert len(tokens) == 3 assert tokens[0] == "(" assert tokens[2] == ")" return tokens[1]
def StartsWithBuiltinMessages(messages): """Whether the message list starts with the vim built in messages.""" return len(messages) >= 2 and not messages[0] and messages[1] == ( 'Messages maintainer: Bram Moolenaar <Bram@vim.org>')
def utm_isNorthern(latitude): """Determine if a latitude coordinate is in the northern hemisphere. Arguments --------- latitude: float latitude coordinate (Deg.decimal degrees) Returns ------- out: bool ``True`` if `latitude` is in the northern hemisphere, ``False`` ...
def isMultiline(s): """ Returns C{True} if this string has a newline in it. """ return (s.find('\n') != -1)
def choose_file_location(default=True): """ Created for user's choice of directory. None -> list Usage: (suggested) > choose_file_location() """ choice = ['docs/locations.list', 'docs/locations.csv', 'docs/info.csv', 'docs/countries.csv'] if default: return choice else: while True: choi...
def format_number(n, accuracy=6): """Formats a number in a friendly manner (removes trailing zeros and unneccesary point.""" fs = "%."+str(accuracy)+"f" str_n = fs%float(n) if '.' in str_n: str_n = str_n.rstrip('0').rstrip('.') if str_n == "-0": str_n = "0" #str_n = str_n.re...
def num_to_s8(num): """Convert signed number to 8bit (unsigned)""" assert -0x80 <= num < 0x80, '{} out of range'.format(num) return num & 0xff
def makepath(path): """ creates missing directories for the given path and returns a normalized absolute version of the path. - if the given path already exists in the filesystem the filesystem is not modified. - otherwise makepath creates directories along the given path using the di...
def classify_design_space(action: str) -> int: """ The returning index corresponds to the list stored in "count": [sketching, 3D features, mating, visualizing, browsing, other organizing] Formulas for each design space action: sketching = "Add or modify a sketch" + "Copy paste sketch" 3...
def add_at_idx(seq, k, val): """ Add (subtract) a value in the tuple at position k """ list_seq = list(seq) list_seq[k] += val return tuple(list_seq)
def sort_dictionary_to_list_by_keys(dictionary): """ Extract a list of paired tuples with each tuple being a key, value pair from the input dictionary and the order of the list according to the order of the keys of the dictionary. Args: dictionary: Input dictionary with keys that have an inher...
def _CheckUploadStatus(status_code): """Validates that HTTP status for upload is 2xx.""" return status_code / 100 == 2
def len_eq(node, length): """Return whether the match lengths of 2 nodes are equal. Makes tests shorter and lets them omit positional stuff they don't care about. """ node_length = None if node is None else node.end - node.start return node_length == length