content
stringlengths
42
6.51k
def match_last_item(items: list) -> bool: """Check if last item matches the rest of the list.""" first_items, last_item = items[:-1], items[-1] first_items = [str(item) for item in first_items] return "".join(first_items) == last_item
def get_rounds(number): """ :param number: int - current round number. :return: list - current round and the two that follow. """ return [i + number for i in range(3)]
def iterative(arr, summation): """ Perform Two Sum by Iterative Method. :param arr: Iterable of elements. :param summation: sum to be searched. :return: returns true if found, else return None. """ hash = set() for i in range(len(arr)): temp = summation-arr[i] if temp>=0...
def get_stub_name(stub): """return stub pkg name""" scope = stub.get('scope', 'device') if scope == 'firmware': return stub['firmware'] dev_fware = stub['firmware'] dev_name = dev_fware['sysname'] name = f"{dev_name}-{dev_fware['name']}-{dev_fware['version']}" return name
def find_S(p): """ Find the S boundary S = <a,b,c,d> where a <= x <= b and c <= y <= d params: p: list of positive training examples """ lx = [e[0] for e in p] a, b = min(lx), max(lx) ly = [e[1] for e in p] c, d = min(ly), max(ly) print(a, b, c, d) return a, b, c, d
def get_value_from_json(dict_data, key): """ usage example {{ your_dict| from_json:your_key }} """ if key: return dict_data.get(key)
def _filter_attrs(attrs, ignored_attrs): """ Return attrs that are not in ignored_attrs """ return dict((k, v) for k, v in attrs.items() if k not in ignored_attrs)
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ # Initial two pointers to beginning and end # Start another pointer to traverse # if list[curr] == 0, then beg++, tra...
def hourangle (lst, ra) : """ Calculate hourangle of specified ra, -12 to +12 args: lst: local sidereal time, in hours ra: ra of object, in degrees returns: hourangle, in hours, -12 to +12 """ return (lst - ra / 15.0 + 12.0) % 24.0 - 12.0
def sum_2_dictionaries(dicta, dictb): """Given two dictionaries of totals, where each total refers to a key in the dictionary, add the totals. E.g.: dicta = { 'a' : 3, 'b' : 1 } dictb = { 'a' : 1, 'c' : 5 } dicta + dictb = { 'a' : 4, 'b' : 1, 'c' : 5 } @param dicta:...
def hyperboloid_params(n_samples): """Generate hyperboloid benchmarking parameters. Parameters ---------- n_samples : int Number of samples to be used. Returns ------- _ : list. List of params. """ manifold = "Hyperboloid" manifold_args = [(3,), (5,)] module...
def strict_forall(l, f): """Takes an iterable of elements, and returns (True, None) if f applied to each element returns True. Otherwise it returns (False, e) where e is the first element for which f returns False. Arguments: - `l`: an iterable of elements - `f`: a function that applies...
def try_get_key(frame, key, default_value=-1): """Return `key` in `frame` if it exists; otherwise return `default_value.""" try: return frame[key] except KeyError: return default_value
def gcd(number1: int, number2: int) -> int: """ gcd: Finds hcf of two numbers. Uses number1 recursive function to find hcf of two numbers. Args: number1 (int): First Number number2 (int): Second Number Returns: int: hcf of number1 and number2 """ if number1 == 0: ...
def merge(novel_adj_dict, full_adj_dict): """ Merges adjective occurrence results from a single novel with results for a larger collection of novels. :param novel_adj_dict: dictionary of adjectives/#occurrences for one novel :param full_adj_dict: dictionary of adjectives/#occurrences for multiple n...
def pgcd_1(a, b): """ Stein algorithm :param a: input 1 :param b: input 2 :return: the PGCD of a and b """ if a == b: return a if (a & 1) == 0 and (b & 1) == 0: return pgcd_1(a >> 1, b >> 1) << 1 elif (a & 1) == 0 and (b & 1) != 0: return pgcd_1(a >> 1, b) ...
def _parse_row(row): """ Returns a two-tuple containing the parsed version of a given row. The first tuple will contain all """ if not row: return (None, None) elif 'DNI' in row: return (None, None) return ([eval(x) for x in row if x.startswith('[')], [x[1:] for x in row if ...
def deep_get(dictionary, keys, previousKey=None): """Search recursively for 'keys' in 'dictionary' and return value, otherwise return None""" value = None if len(keys) > 0: value = dictionary.get(keys[0], None) if isinstance(dictionary, dict) else None if value: # If we are at t...
def addr2dec(instr): """ Turns a string holding either a hex or decimal address into a decimal number """ addr = None try: addr = int(instr) except: pass if addr: return addr try: addr = int(instr, 16); except: pass return addr
def solution(integers): """ Finds the two entries that sum to 2020 and returns their product. Raises `ValueError` if there is no solution. """ inverse = set() for n in integers: if 2020 - n in inverse: return n * (2020 - n) inverse.add(n) raise ValueError('no so...
def pv_fullname(name): """ make sure an Epics PV name ends with .VAL or .SOMETHING! Parameters ---------- pvname: name of PV Returns ------- string with full PV name """ name = str(name) if '.' not in name: name = "%s.VAL" % name return name
def get_name(path): """ Get a file name from its full path. Args: path (str): full path Returns: name (str): just the file name """ splits = path.split("/") if splits[-1] == "": name = splits[-2] else: name = splits[-1] return name
def write_to_log(actual_log_size, max_logsize, value_to_write, log_fp): """ Write down to log the :param actual_log_size: Number of performances samples taken (1 sample = values for one cpu) :param max_logsize: Maximum number of performances samples allowed :param value_to_write: string containing s...
def encodeCaesar(sequence: str, shift: int = 1) -> str: """ Encodes the given string to Caesar Cipher :param sequence: String to encode :param shift: Shift value Example: >>> encodeCaesar("HELLO WORLD", 1) >>> "IFMMP XPSME" """ return ''.join(chr(((ord(c) - 65 + shift) % 26)...
def get_scale_factor(widget): """Returns the scale factor for a Gtk.Widget""" if hasattr(widget, "get_scale_factor"): return widget.get_scale_factor() else: return 1
def u64b(x): """Unpacks a 8-byte string into an integer (big endian)""" import struct return struct.unpack('>Q', x)[0]
def isCircleCrossingSquare(square,circle): """Detect the collision of a square and a circle.""" qx,qy,qr=square cx,cy,cr=circle return abs(qx-cx)<=qr/2+cr and abs(qy-cy)<=qr/2+cr
def fartorank(fahrenheit): """ This function converts fahrenheit to rankine, with fahrenheit as parameter.""" rankine = (fahrenheit + 459.67) return rankine
def generate_pattern_eq_ipv4(value): """ makes a pattern to check an ip address """ return "ipv4-addr:value = '" + value + "'"
def decode_to_text(encoded_list): """Decode an encoded list. Args: encoded_list: Encoded list of code points. Returns: A string of decoded data. """ return ''.join([chr(c) for c in encoded_list])
def eligible_for_account(affiliations): """Returns whether the list of affiliations makes one eligible for an account. """ affiliations = set(affiliations) ALLOWED_AFFILIATES = { 'AFFILIATE-TYPE-CONSULTANT', 'AFFILIATE-TYPE-LBLOP STAFF', 'AFFILIATE-TYPE-VISITING SCHOLAR', ...
def splitjoin(orig, zoek, vervang): """ dit is een routine waarin de binnenkomende string eerst gesplitst wordt in woorden (gescheiden door 1 of meer spaties en/of tabs e.d.); tegelijkertijd worden de scheidende strings ook bepaald. Daarna worden de woorden die vervangen moeten worden vervangen ...
def squared_error(a, b): """Computes the element-wise squared difference between two tensors. .. math:: L = (p - t)^2 Parameters ---------- a, b : Theano tensor The tensors to compute the squared difference between. Returns ------- Theano tensor An expression for the i...
def compact(text): """ Compact whitespace in a string (also trims whitespace from the sides). """ return " ".join(text.split())
def _clip(sid, prefix): """Clips a prefix from the beginning of a string if it exists.""" return sid[len(prefix) :] if sid.startswith(prefix) else sid
def parseBool(v: str) -> bool: """Takes the provided string and converts it to a boolean - 1, 0 - on, off - true, false - yes, no""" return v.lower() in ["true", "1", "yes", "on"]
def remove_duplicates_for_fetch(items: list, last_fetched_ids: list) -> list: """Remove items that were already sent in last fetch. Args: items (list): Items retrieved in this fetch. last_fetched_ids (list): ID's of items from last fetch. Returns: (list) New items wi...
def hierarchyToNumber(digits, b): """ Function to convert an address in the hierarchy to a number. Parameters ---------- digits, tuple of ints: The address in the hierarchy. b, int: The order of the base graph for the hierarcical product. Returns ------- count, int: ...
def get_gain(camcol,band,run=None): """ data.sdss3.org/datamodel/files/BOSS_PHOTOOBJ/frames/RERUN/RUN/CAMCOL/frame.html """ GAIN_CCD = { 0:{"u":1.62, "g":3.32, "r":4.71, "i":5.165,"z":4.745}, 1:{"u":[1.595,1.825],"g":3.855,"r":4.6, "i":6.565,"z":5.15...
def get_git_commit_sha(short=True): """Read the current (short-hand) git commit sha from file written during Docker build stage Args: short (bool): If True, only returns the first seven characters of the SHA """ git_commit_file_name = "/app/.git_commit_sha" try: with open(git_commi...
def angle_dis (a1, a2, factor=1.0) : """ Get distance between angles, around 360-degree bound args: a1: angle 1, scalar or ndarray a2: angle 2, scalar or ndarray, if both a1 and a2 are ndarray, they must have same shape factor: a shrink factor, usually is 1.0/cos(dec) or 1.0/cos(lat) ...
def _nonempty_line_count(src: str) -> int: """Count the number of non-empty lines present in the provided source string.""" return sum(1 for line in src.splitlines() if line.strip())
def get_mac_from_raw_query(request_raw_query: str): """ Get MAC address inside a matchbox "request raw query" /path?<request_raw_query> :param request_raw_query: :return: mac address """ mac = "" raw_query_list = request_raw_query.split("&") for param in raw_query_list: if "m...
def is_unicode(obj): """ Return True if *obj* is a unicode string, False otherwise. """ return isinstance(obj, str)
def normalize_links(raw_links, l_norm_factors, r_norm_factors): """ :param raw_links: :param l_norm_factors: :param r_norm_factors: :return: """ norm_links = dict() # Iterate through reach link for i in raw_links: i_base = i[:-2] norm_links[i] = dict() for ...
def iterable(x): """ Is x iterable? >>> iterable([1, 2, 3]) True >>> iterable('abc') True >>> iterable(5) False """ try: iter(x) return True except TypeError: return False
def make_list(var): """ Convert a variable to a list with one item (the original variable) if it isn't a list already. :param var: the variable to check. if it's already a list, do nothing. else, put it in a list. :return: the variable in a one-item list if it wasnt already a list. """ ...
def get_rpgsnapshot(module, array): """Return iReplicated Snapshot or None""" try: snapname = module.params['name'] + "." + module.params['suffix'] + "." + module.params['restore'] for snap in array.list_volumes(snap=True): if snap['name'] == snapname: return snapname...
def _decode_message(output: bytes, encoding: str) -> str: """Converts bytes to string, stripping white spaces.""" return output.decode(encoding).strip()
def age_to_BP(age, age_unit): """ Convert an age value into the equivalent in time Before Present(BP) where Present is 1950 Returns --------- ageBP : number """ ageBP = -1e9 if age_unit == "Years AD (+/-)" or age_unit == "Years Cal AD (+/-)": if age < 0: age = age+1 ...
def get_applications(input_dict): """Convert Palo Alto query result dict into a list of applications.""" apps = ( input_dict.get("response", {}) .get("result", {}) .get("application", {}) .get("entry", []) ) if not apps: raise RuntimeError( "No applica...
def get_indices(l): """ Description ... Args: l: ... Returns: meta ... For example: ... """ meta = dict({}) for i, k in enumerate(l): if k == 0: continue k_str = str(k) if k_str not in meta.keys(): meta.update({ ...
def extract_start_stop(exon): """Extract start and stop from a chr1,100-200,- tuple Parameters ---------- exon : tuple (chrom, startstop, strand) tuple of strings, e.g. ('chr1', '100-200', '-') Returns ------- extracted : tuple (chrom, start, stop, strand) tuple of ...
def is_in_language(ngram, begin_unicode_range, end_unicode_range): """ Checks if all the characters in the ngram are in the unicode range of the language. """ for character in ngram: if not (begin_unicode_range <= ord(character) <= end_unicode_range): return False return Tru...
def returnSlotNumberForACar(parking_lot, vrn): """Returns the slot number for the vehicle""" if len(vrn) != 13: print("Invalid Vehicle Registration Number!") return -1 if not (vrn[:2].isalpha() and vrn[6:8].isalpha() and vrn[3:5].isdigit() and vrn[10:].isdigit() \ and vrn[2] == '-' an...
def _check_params(params, field_list): """ Helper to validate params. Use this in function definitions if they require specific fields to be present. :param params: structure that contains the fields :type params: ``dict`` :param field_list: list of dict representing the fields ...
def _rhyme(word_a, word_b, phonemes_func): """Return whether two words form a rhyme. This function is just a general version and the shorthands available in the same module should be used instead, except a custom function for extracting phonemes is to be used. :param word_a: first word. :param...
def is_between(val, bound_1, bound_2): """ Return if a value falls between two boundary values """ if val > max([bound_1, bound_2]): print("not between!") return False if val < min([bound_1, bound_2]): print("not between!") return False return True
def relu(x: float) -> float: """ The ReLu activation function Args: x: The input to the function Returns: The output of the function """ if x > 0: return x return 0.1 * x
def get_value(transaction): """ :return: the amount of money of the transaction """ return transaction['value']
def getHeaders(header_raw): """ Gets the request header dictionary from the native request header :param header_raw: {str} headers :return: {dict} headers """ return dict(line.split(": ", 1) for line in header_raw.split("\n") if line != '')
def join_url_parts(*parts): """ Join a URL from a list of parts. See http://stackoverflow.com/questions/24814657 for examples of why urllib.parse.urljoin is insufficient for what we want to do. """ return '/'.join([piece.strip('/') for piece in parts])
def standardize_name(name): """ Converts the given name into a standard Himesis name. @param name: The name of the Himesis graph """ if name.startswith('H'): return name return 'H%s%s' % (name[0].capitalize(), name[1:])
def time_in_words(h, m): """Hackerrank Problem: https://www.hackerrank.com/challenges/the-time-in-words/problem Given the time in numerals we may convert it into words, as shown below: ---------------------------------------------- | 5:00 | -> | five o' clock | | 5:01 | -> | one m...
def near_zero(num, epsilon=0.01): """ :param num: a number (float or integer) :param epsilon: allowable difference between num and zero. :return: True/False value indicating whether num is in tolerance. """ return abs(num) <= epsilon
def calculate_hour_angle(ra, LST): """ Calculate hour angle. Input: ra as float LST as float Output: ha as float """ #Compute the hour angle in range [-12,12] ha = LST - ra #hour angles larger than 12 should be conv...
def get_replacements(cli_args, **kwargs): """ :param cli_args: Dictionary containing all command-line arguments from user :return: Dictionary mapping variables' generic names in template files to those variables' actual values provided by the user """ replacements = {'SUBID': cli_args[...
def decode(in_bytearray): """ Decodes a COBS bytearray. The input should not include the start-of-frame or end-of-frame bytes, it is an error (assertion) if a zero occurs in the sequence. Returns None if an invalid packet was detected. """ assert in_bytearray.find(b'\x00') < 0 out = bytearray() whil...
def year_isnt_int(YEARS): """A funciton to test if years are integers""" return any(type(x) != int for x in YEARS)
def make_it_an_int(stringy_number): """Taks a string and returns and integer. Yes, this is rather nonsensical but its a teaching moment to show you how to centralize common logic across submodules in a module. """ if stringy_number.isdigit(): return int(stringy_number) else: rais...
def is_type_in_list(item_type, items): """ Checks if there is an item of a given type in the list of items. Args: item_type (type): the type of the item. items (list): a list of items. Returns: true if an item of the given type exists in the list, otherwise false. """ r...
def sum_nth_i(seq, n): """ takes a list seq and a number n that is bigger then 0 and takes the sum of the n number """ if n > 0: res = 0 for i in range(n-1, len(seq), n): print(i) res += seq[i] return res else: print("n needs to be bigger then 0 \n...
def pt_segment_dist(A, B, P): """ SUMMARY computes the distance of point P from segment AB PARAMETERS A: endpoint of segment AB B: other endpoint of segment AB P: point at some distance from AB RETURNS float """ x1, y1 = A x2, y2 = B x3, y3 = P ...
def find_peak(list_of_integers): """BRUTE force implementation for question """ max_i = None for ele in list_of_integers: if max_i is None or max_i < ele: max_i = ele return max_i
def int_safe(obj, default=0): """safely convert something to an integer""" try: obj_int = int(obj) except ValueError: obj_int = default return obj_int
def gcd(x, y): """ Calculate greatest common divisor """ while y != 0: t = x % y x, y = y, t return x
def vowel_counter(string): """Counts the number of vowels in a given string""" vowel_count = 0 #iterate over given string for char in string: #check if char is a vowel if char in 'aeiou': vowel_count += 1 return vowel_count
def is_none_or_empty(s: str) -> bool: """judge if a str is None or empty str ''. s: source str. return: True if it's None or empty str, otherwise False.""" if not isinstance(s, str): if s is None or s == "": return True else: return False else: if s is...
def ranges(nums): """ Take a list of numbers (sorted or unsorted) and return all contiguous ranges within the list Ranges should be returned as tuples, where the first value is the start of the range and the last value is the end (inclusive). Single numbers are returned as tuples where both values ...
def trajectory_importance_max_avg(states_importance): """ computes the importance of the trajectory, according to max-avg approach """ max, sum = float("-inf"), 0 for i in range(len(states_importance)): state_importance = states_importance[i] # add to the curr sum for the avg in the future ...
def search_status(term, status): """Searches status for term and returns that line.""" lines = status.split("\n") for line in lines: if term in line: return line return None
def getmtime(pathname): """The last modification time of a file in seconds since Jan 1, 2015""" from os.path import exists,getmtime if not exists(pathname): return 0.0 return getmtime(pathname)
def dungeonlvl(experience): """Calculate the player's catacomb's and classes' lvl""" exp_required = [50, 125, 235, 395, 625, 955, 1425, 2095, 3045, 4385, 6275, 8940, 12700, 17960, 25340, 35640, 50040, 70040, 97640, 135640, 188140, 259640, 356640, 488640, 668640, 911640, 1239640, 1684640, 228...
def _concatenate_shape(input_shape, axis=-1): # pylint: disable=invalid-name """Helper to determine the shape of Concatenate output.""" if isinstance(input_shape, dict): # For named tuples, just use the values. input_shape = list(input_shape.values()) ax = axis % len(input_shape[0]) concat_size = sum(shap...
def get_keys_with_value(dct: dict, value): """Return keys where the value matches the given""" return [k for k, v in dct.items() if v == value]
def utf8_bom(input): """Strips BOM from a utf8 string, because open() leaves it in for some reason.""" output = input.replace('\ufeff', '') return output
def extract_eyeid_diameters(pupil_datum): """Extract data for a given pupil datum Returns: tuple(eye_id, confidence, diameter_2d, and diameter_3d) """ return ( pupil_datum["id"], pupil_datum["confidence"], pupil_datum["diameter"], pupil_datum.get("diameter_3...
def find_options_in_recipes(recipes, choice_search, action_kw, condition_position=0): """ Looks through the master config at recipes and entries to determine if there are place the developer made distince choices, this is used in the inimake script to walk users through makin...
def filter_dict(source, d): """Filter `source` dict to only contain same keys as `d` dict. :param source: dictionary to filter. :param d: dictionary whose keys determine the filtering. """ return {k: source[k] for k in d.keys()}
def _to_float(s): """Converts *s* to a float if possible; if not, returns `False`.""" try: f = float(s) return f except ValueError: return False
def search_in_bst(root, key): """ Search node with given key in the binary search tree :param root: root node of the binary search tree :type root: TreeNode :param key: key to search :type key: Any :return: node with given key :rtype: TreeNode """ if root is None or root.val == ...
def get_strand(orientation): """Convert NCBI Dataset data report orientation to BioPython strand. """ return {'minus':-1, 'plus':+1, None:None}[orientation]
def is_segmentable(partic_id): """ A function that returns True if the participant's interview clip is not in the manually identified set of troubled clips. The clips below were not segmentable do to excessive static, proximity to the virtual interviewer, volume levels, etc. """ troubled = s...
def correct_department(dept_name): """ Correct department names so there aren't apparent duplicates. """ # Create a dictionary for department aliases that we can look up aliases = {"OE": "Ocean Engineering", "ME": "Mechanical Engineering", "Earth Science": "Earth Scienc...
def dict_search_recursive(d, k): """smp_base.common.dict_search_recursive From smp_graphs.common.dict_search_recursive Search for key `k` recursively over nested smp_graph config dicts """ # FIXME: make it generic recursive search over nested graphs and move to smp_base # print "#" * 80 #...
def ldo(bandwidth, spread_factor): """ Calculates the ldo value """ symbol_duration = 1000 / (bandwidth / (1 << spread_factor)) return bool(symbol_duration > 16)
def create_sheets_from_names(names, frows): """ Returns a new sheet for each client. """ new_sheets = [] for name in names: sheet = [] last, first = name.split(', ') for row in frows: if first in row and last in row: sheet.append(row) sheet...
def tolower(lista): """converte os elementos na lista para minusculo.""" list_lower = [] for i in lista: list_lower.append(i.lower()) return list_lower
def name(model): """A repeatable way to get the formatted model name.""" return model.__name__.replace('_', '').lower()
def to_dict(dict_like): """ Converts an object that inherits from dictionary to a plain dictionary. This is useful for CommentedMap objects. :param dict_like: The dictionary like object :returns: A plain dictionary """ d = dict(dict_like) for key in d: if isinstance(d[key]...