content
stringlengths
42
6.51k
def get_key_paths(d, key_paths=None, param_lists=None, acc=None): """Used to traverse a config and identify where multiple parameters are given. Args: d (dict): Config dictionary. key_paths (list): The list of keys to the relevant part of the config. param_lists (list): The list of multiple parameters specified in the config. acc (list): Tracker for the keys. """ # Avoid mutable default argument issue for first call if key_paths is None: key_paths = [] if param_lists is None: param_lists = [] if acc is None: acc = [] # Loop over the items for k, v in d.items(): if isinstance(v, dict): get_key_paths(v, key_paths, param_lists, acc=acc + [k]) elif isinstance(v, list): key_paths.append(acc + [k]) param_lists.append(v) return key_paths, param_lists
def parseReviewsCount(textIn, replaceStr): """ """ if not textIn:return None _text=textIn.replace(replaceStr, "") return int(_text.strip())
def _resource_name_package(name): """ pkg/typeName -> pkg, typeName -> None :param name: package resource name, e.g. 'std_msgs/String', ``str`` :returns: package name of resource, ``str`` """ if not '/' in name: return None return name[:name.find('/')]
def opt_pol_1(state) -> int: """'100 or bust' policy. Bet the maximum stake required to (possibly) get to 100 in one go. """ return min(state, 100 - state)
def isValidOpts(opts): """ Check if the required options are sane to be accepted - Check if the provided files exist - Check if two sections (additional data) exist - Read all target libraries to be debloated from the provided list :param opts: :return: """ # if not options.perfpath: # parser.error("All options -e, -p and -l and should be provided.") # return False return True
def flatten_nested(nested_dicts): """ Flattens dicts and sequences into one dict with tuples of keys representing the nested keys. Example >>> dd = { \ 'dict1': {'name': 'Jon', 'id': 42}, \ 'dict2': {'name': 'Sam', 'id': 41}, \ 'seq1': [{'one': 1, 'two': 2}] \ } >>> flatten_nested(dd) == { \ ('dict1', 'name'): 'Jon', ('dict1', 'id'): 42, \ ('dict2', 'name'): 'Sam', ('dict2', 'id'): 41, \ ('seq1', 0, 'one'): 1, ('seq1', 0, 'two'): 2, \ } True """ assert isinstance(nested_dicts, (dict, list, tuple)), 'Only works with a collection parameter' def items(c): if isinstance(c, dict): return c.items() elif isinstance(c, (list, tuple)): return enumerate(c) else: raise RuntimeError('c must be a collection') def flatten(dd): output = {} for k, v in items(dd): if isinstance(v, (dict, list, tuple)): for child_key, child_value in flatten(v).items(): output[(k,) + child_key] = child_value else: output[(k,)] = v return output return flatten(nested_dicts)
def luhn_algorthm_check(card_num: int) -> bool: """Checks that a user entered card num corresponds with the luhn algorithm""" card_num_lst = [int(x) for x in str(card_num)] last_digit = card_num_lst[-1] card_num_lst[-1] = 0 # Mutiplying odd digits by two for index, value in enumerate(card_num_lst): if index == 0 or index % 2 == 0: card_num_lst[index] *= 2 if card_num_lst[index] > 9: card_num_lst[index] -= 9 if (sum(card_num_lst) + last_digit) % 10 == 0: return True else: return False
def __x_product_aux (property_sets, seen_features): """Returns non-conflicting combinations of property sets. property_sets is a list of PropertySet instances. seen_features is a set of Property instances. Returns a tuple of: - list of lists of Property instances, such that within each list, no two Property instance have the same feature, and no Property is for feature in seen_features. - set of features we saw in property_sets """ if not property_sets: return ([], set()) properties = property_sets[0].all() these_features = set() for p in property_sets[0].non_free(): these_features.add(p.feature()) # Note: the algorithm as implemented here, as in original Jam code, appears to # detect conflicts based on features, not properties. For example, if command # line build request say: # # <a>1/<b>1 c<1>/<b>1 # # It will decide that those two property sets conflict, because they both specify # a value for 'b' and will not try building "<a>1 <c1> <b1>", but rather two # different property sets. This is a topic for future fixing, maybe. if these_features & seen_features: (inner_result, inner_seen) = __x_product_aux(property_sets[1:], seen_features) return (inner_result, inner_seen | these_features) else: result = [] (inner_result, inner_seen) = __x_product_aux(property_sets[1:], seen_features | these_features) if inner_result: for inner in inner_result: result.append(properties + inner) else: result.append(properties) if inner_seen & these_features: # Some of elements in property_sets[1:] conflict with elements of property_sets[0], # Try again, this time omitting elements of property_sets[0] (inner_result2, inner_seen2) = __x_product_aux(property_sets[1:], seen_features) result.extend(inner_result2) return (result, inner_seen | these_features)
def cipher(text, shift, encrypt=True): """ Encrypts and decrypts phrases by moving each alphabetical character a given number of index units. Parameters ---------- text: A string to be encrypted or decrypted. Can include alphabetical or other characters shift: The number of index units to shift each alphabetical character. An integer encrypt: If True, alphabetical characters will be shifted by the given value for the shift argument. If false, the alphabetical characters will be shifted by the negative of the given value for the shift argument. Returns ---------- string The encrypted or decrypted string. Examples ---------- >>> import cipher_ajm2314 >>> cipher('Mr. Smith Goes to Washington',1) 'Ns. Tnjui Hpft up Xbtijohupo' >>> cipher('Mr. Smith Goes to Washington',-3) 'Jo. Pjfqe Dlbp ql TXpefkdqlk' >>> cipher('Mr. Smith Goes to Washington',3,encrypt=False) 'Jo. Pjfqe Dlbp ql TXpefkdqlk' """ alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' new_text = '' for c in text: index = alphabet.find(c) if index == -1: new_text += c else: new_index = index + shift if encrypt == True else index - shift new_index %= len(alphabet) new_text += alphabet[new_index:new_index+1] return new_text
def pluck(n): """New pluck. It's longer! """ rval = n - 2 return rval
def comment_out_magics(source): """ Utility used to make sure AST parser does not choke on unrecognized magics. """ filtered = [] for line in source.splitlines(): if line.strip().startswith('%'): filtered.append('# ' + line) else: filtered.append(line) return '\n'.join(filtered)
def check_orientation(orientation): """Check ``orientation`` parameter and return as `bool`. Parameters ---------- orientaion : {'vertical', 'horizontal'} Returns ------- is_vertical : bool Raises ------ ValueError """ if orientation == "vertical": is_vertical = True elif orientation == "horizontal": is_vertical = False else: raise ValueError("'orientation' must be 'vertical' or 'horizontal'") return is_vertical
def rank_simple(vector ): """given a list, return the ranks of its elements when sorted.""" return sorted(range(len(vector)), key=vector.__getitem__)
def gen_profile_id(profile_id): """ Generates the Elasticsearch document id for a profile Args: profile_id (str): The username of a Profile object Returns: str: The Elasticsearch document id for this object """ return "u_{}".format(profile_id)
def rankAnomalousPoint(sampleErrors: list, rankingMap: dict) -> dict: """Adds a new list of sample errors to the majority voting map. Args: sampleErrors: A list of `(name, distance)` tuples. rankingMap: A mapping between counter names and vote count lists. Returns: A updated rankingMap. """ sampleErrors.sort(key=lambda tup: tup[1], reverse=True) for index, errorTuple in enumerate(sampleErrors): rankingMap[errorTuple[0]][index] += 1 return rankingMap
def wlist_to_dict_parenthesis(words): """Converts a list of strings in the format: ['(', '(', 'n1', 'v1', ')', ..., '(', 'nk', 'vk', ')', ')'] to a dictionary {n1:v1, ..., nk:vk}.""" res = {} i = 1 while True: if words[i] == '(': res[words[i+1]] = words[i+2] i += 4 else: break return res
def rep01(s): """REGEX: build repeat 0 or 1.""" return s + '?'
def snake_to_camel_case(text: str, dontformat: bool = False) -> str: """Convert a snake_case string into camelCase format if needed. This function doesnt check that passed text is in snake_case. If dontformat is True, return text. """ if dontformat: return text first, *others = text.split("_") return first + "".join(map(str.capitalize, others))
def is_private_env_name(env_name): """ Examples: >>> is_private_env_name("_conda") False >>> is_private_env_name("_conda_") True """ return env_name and env_name[0] == env_name[-1] == "_"
def __get_tp(rank_query_taxids, rank_truth_taxids): """ Returns true positive >>> __get_tp(test_rank_query_taxids, test_rank_truth_taxids) 2 """ return len(rank_query_taxids.intersection(rank_truth_taxids))
def rel_to_abs_ages(rel_ages, gestation=19): """Convert sample names to ages. Args: rel_ages (List[str]): Sequence of strings in the format, ``[stage][relative_age_in_days]``, where stage is either "E" = "embryonic" or "P" = "postnatal", such as "E3.5" for 3.5 days after conception, or "P10" for 10 days after birth. gestation (int): Number of days from conception until birth. Returns: Dictionary of ``{name: age_in_days}``. """ ages = {} for val in rel_ages: age = float(val[1:]) if val[0].lower() == "p": age += gestation ages[val] = age return ages
def compare(reference, tested): """ Compare the two outputs according to a specific logic :return: True iff both input are equal """ epsilon = 0.01 for k,v in reference.items(): tested_vals = tested[k] ok = all (map( lambda x: (abs(x[1] - x[0])) <= epsilon, zip(v,tested_vals))) if not ok: return False return True
def _reverse_bytes(mac): """ Helper method to reverse bytes order. mac -- bytes to reverse """ ba = bytearray(mac) ba.reverse() return bytes(ba)
def skipPunctuation(word): """ skip punctuation in word """ if "'" in word: split = word.split("'") word = split[0] # define punctuation punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' # remove punctuation from the string wordWithoutPunctuation = "" for char in word: if char not in punctuations: wordWithoutPunctuation = wordWithoutPunctuation + char # display the un-punctuated string return wordWithoutPunctuation
def group(list_, size): """Separate list into sublists of size size""" return [list_[i:i + size] for i in range(0, len(list_), size)]
def lower_bound_index(desired_capacity, capacity_data): """Determines the index of the lower capacity value that defines a price segment. Useful for accessing the prices associated with capacity values that aren't explicitly stated in the capacity lists that are generated by the build_supply_curve() function. Needed for ks_test(). :param float/int desired_capacity: Capacity value for which you want to determine the index of the lowest capacity value in a price segment. :param list capacity_data: List of capacity values used to generate a supply curve. :return: (*int*) -- Index of a price segment's capacity lower bound. """ # Check that the list is not empty and that the capacity falls within the list range if not capacity_data or capacity_data[0] > desired_capacity: return None # Get the index of the capacity that is immediately less than the desired capacity for i, j in enumerate(capacity_data): if j > desired_capacity: return i - 1
def redM(m1, m2): """The reduced mass shows up in Kepler formulae, m1*m2/(m1+m2) """ return( m1*m2/(m1+m2) )
def marge_ranges(range_1, range_2): """Return merged range.""" return min(range_1[0], range_2[0]), max(range_1[1], range_2[1])
def permute(nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) == 0: return [] if len(nums) == 1: return [[nums[0]]] element = nums.pop() result_curr = permute(nums) result_next = [] for i in range(len(result_curr)): for j in range(len(result_curr[0]) + 1): result = list(result_curr[i]) result.insert(j, element) result_next.append(result) return result_next
def get_f1_score_for_each_label(pre_lines, gold_lines, label): """ Get F1 score for each label. Args: pre_lines: listed label info from pre_file. gold_lines: listed label info from gold_file. label: Returns: F1 score for this label. """ TP = 0 FP = 0 FN = 0 index = 0 while index < len(pre_lines): pre_line = pre_lines[index].get(label, {}) gold_line = gold_lines[index].get(label, {}) for sample in pre_line: if sample in gold_line: TP += 1 else: FP += 1 for sample in gold_line: if sample not in pre_line: FN += 1 index += 1 f1 = 2 * TP / (2 * TP + FP + FN) return f1
def normalize_mode(mode): """ Return a mode value, normalized to a string and containing a leading zero if it does not have one. Allow "keep" as a valid mode (used by file state/module to preserve mode from the Salt fileserver in file states). """ if mode is None: return None if not isinstance(mode, str): mode = str(mode) mode = mode.replace("0o", "0") # Strip any quotes any initial zeroes, then though zero-pad it up to 4. # This ensures that somethign like '00644' is normalized to '0644' return mode.strip('"').strip("'").lstrip("0").zfill(4)
def parse_record2(raw_record): """Parse raw record and return it as a set of common symbols""" common_symbols = set("abcdefghijklmnopqrstuvwxyz") for person in raw_record.split(): common_symbols.intersection_update(set(person)) return common_symbols
def create_candidates(dataset, verbose=False): """Creates a list of candidate 1-itemsets from a list of transactions. Parameters ---------- dataset : list The dataset (a list of transactions) from which to generate candidate itemsets. Returns ------- The list of candidate itemsets (c1) passed as a frozenset (a set that is immutable and hashable). """ c1 = [] # list of all items in the database of transactions for transaction in dataset: for item in transaction: if not [item] in c1: c1.append([item]) c1.sort() if verbose: # Print a list of all the candidate items. print(("" \ + "{" \ + "".join(str(i[0]) + ", " for i in iter(c1)).rstrip(', ') \ + "}")) # Map c1 to a frozenset because it will be the key of a dictionary. return list(map(frozenset, c1))
def has_property(property_set, property): """"Checks whether given property set has the given property.""" positive = True if property.startswith("NOT "): property = property[4:] positive = False if property == "TRUE": return True if property == "FALSE": return False return (property in property_set) == positive
def grid_to_surface(x, y, w, h, tw, th): """ Converts grid coordinates to screen coordinates with 0,0 on the top corner of the topmost tile in the map """ return ( ((tw * (h-1)) + ((x-y)*tw)) / 2 ,((x+y)*th) / 2 )
def ComputeRho(A, nr, A_tot): """ Compute the ratio of area of a reinforcement to area of a section. @param A (float): Area of reinforcement. @param nr (float): Number of reinforcement (allow float for computing ratio with different area; just convert the other areas to one and compute the equivalent n). @param A_tot (float): Area of the concrete. @returns float: Ratio. """ return nr * A / A_tot
def lasso(number: complex, unit: str = '') -> str: """ Make a large number more readable by inserting commas before every third power of 10 and adding units """ return f'{number:,} {unit}'.strip()
def clean_euler_path(eulerian_path: list) -> list: """Cleans a Eulerian path so that each edge (not directed) appears only once in the list. If a edge appears more than once, only the first occurrence is kept. Arguments: eulerian_path {list} -- Eulerian path Returns: list -- cleaned Eulerian path """ # noqa path = [] for edge in eulerian_path: if edge not in path and edge[::-1] not in path: path.append(edge) return path
def stamp_tuple_to_secs(stamp): """ Converts a stamp tuple (secs,nsecs) to seconds. """ return stamp[0] + stamp[1]*1.0e-9
def time_interpolation(array0, array1, date0, date, date1): """ Time interpolation at date 'date' of two arrays with dates 'date0' (before') and 'date1' (after). Returns the interpolated array. """ w = (date-date0)/(date1-date0) #Weights array = (1 - w ) * array0 + w * array1 return array
def g_iter(n): """Return the value of G(n), computed iteratively. >>> g_iter(1) 1 >>> g_iter(2) 2 >>> g_iter(3) 3 >>> g_iter(4) 10 >>> g_iter(5) 22 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion']) True """ "*** YOUR CODE HERE ***" glist = [1, 2, 3] for i in range(3, n): atom = glist[i - 1] + 2 * glist[i - 2] + 3 * glist[i - 3] glist.append(atom) return glist[n - 1]
def check_new_value(new_value: str, definition) -> bool: """ checks with definition if new value is a valid input :param new_value: input to set as new value :param definition: valid options for new value :return: true if valid, false if not """ if type(definition) is list: if new_value in definition: return True else: return False elif definition is bool: if new_value == "true" or new_value == "false": return True else: return False elif definition is int: try: int(new_value) return True except ValueError: return False elif definition is float: try: float(new_value) return True except ValueError: return False elif definition is str: return True else: # We could not validate the type or values so we assume it is incorrect return False
def filter_broker_list(brokers, filter_by): """Returns sorted list, a subset of elements from brokers in the form [(id, host)]. Passing empty list for filter_by will return empty list. :param brokers: list of brokers to filter, assumes the data is in so`rted order :type brokers: list of (id, host) :param filter_by: the list of ids of brokers to keep :type filter_by: list of integers """ filter_by_set = set(filter_by) return [(id, host) for id, host in brokers if id in filter_by_set]
def tabs(num): """ Compute a blank tab """ return " " * num
def module_to_str(obj): """ Return the string representation of `obj`s __module__ attribute, or an empty string if there is no such attribute. """ if hasattr(obj, '__module__'): return str(obj.__module__) else: return ''
def int_with_commas(number): """helper to pretty format a number""" try: number = int(number) if number < 0: return '-' + int_with_commas(-number) result = '' while number >= 1000: number, number2 = divmod(number, 1000) result = ",%03d%s" % (number2, result) return "%d%s" % (number, result) except Exception: return ""
def round_list(x, n = 2): """Auxiliary function to round elements of a list to n decimal places. Parameters ---------- x : list List of float values. n : int Number of decmial places to round the elements of list. Returns ------- list List with elements rounded to n decimal places. """ try: return [round(i,n) for i in x] except: return x
def parse_structure(node): """Turn a collapsed node in an OverlayGraph into a heirchaical grpah structure.""" if node is None: return None structure = node.sub_structure if structure is None: return node.name elif structure.structure_type == "Sequence": return {"Sequence" : [parse_structure(n) for n in structure.structure["sequence"]]} elif structure.structure_type == "HeadBranch": return {"Sequence" : [ {"Branch" : [parse_structure(n) for n in structure.structure["branches"]] }, parse_structure(structure.structure["head"]) ]} elif structure.structure_type == "TailBranch": return {"Sequence" : [ parse_structure(structure.structure["tail"]), {"Branch" : [parse_structure(n) for n in structure.structure["branches"]] }, ]} else: data = {} for k in structure.structure: if isinstance(structure.structure[k], list): data[k] = [parse_structure(n) for n in structure.structure[k]] else: data[k] = parse_structure(structure.structure[k]) return {structure.structure_type : data}
def isAlreadyInArchive(archive, x): """ Check to see if the candidate is already in the archive. """ already = False for xi in archive: if tuple(xi) == tuple(x): already=True return (already)
def separate_list(inlist, rule): """ Separates a list in two based on the rule. The rule is a string that is mached for last characters of list elements. """ lrule = len(rule) list1 = [] list2 = [] for item in inlist: if (item[-lrule:] == rule): list1.append(item) else: list2.append(item) return list1, list2
def calculate_reward(state, l_gap=0.25, road_length=200): """ Calculate reward for the given state. Notice that this function doesnt account for status inconsistency, but it gets covered in the state_transition function. :param road_length: segment length :param l_gap: minimum safety gap :param state: given state :return: reward for this state """ # First get the number of valid vehicles: num_valid_vehs = 0 for veh in state: if veh[5] != 2: num_valid_vehs += 1 # Initialize reward for this step reward = -1 # Initialize collision indicator: has_collision = False # Initialize process completed: has_done = True # For the new state: # First, we want to check collision: for i in range(num_valid_vehs): for j in range(i + 1, num_valid_vehs): # Determine which vehicle is the leading vehicle by their front position: if state[i][0] >= state[j][0]: leading_veh = state[i] following_veh = state[j] else: leading_veh = state[j] following_veh = state[i] # Find out the back of leading vehicle and front of following vehicle: back_pos = leading_veh[0] - leading_veh[3] front_pos = following_veh[0] # Collision check: 1. both vehicles are on the same lane, 2: two vehicles have overlapped with minimum # safety gap. if (back_pos < 200) and (leading_veh[1] != 2) and (following_veh[1] != 2) and (leading_veh[1] == following_veh[1]) \ and (back_pos - l_gap < front_pos): has_collision = True # # If any vehicle is on lane 0 and vehicle position has not exceed the roadway length: # for veh in state[:num_valid_vehs - 1]: # if veh[1] == 0 and veh[0] - veh[3] <= road_length: # has_cleared = False # Summarize reward: # If there is collision, apply collision penalty and end the process: if not has_collision: vehs_left_counter = 0 for veh in state: if (veh[1] == 0) and (veh[0] - veh[3]) < road_length: vehs_left_counter += 1 has_done = False reward -= vehs_left_counter else: reward -= 2000 has_done = True return has_done, reward
def bb_intersection_over_union(box_a, box_b): """Thank you pyimagesearch! https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/ :param box_a: Rect :param box_b: Rect """ # determine the (x, y)-coordinates of the intersection rectangle xA = max(box_a[0], box_b[0]) yA = max(box_a[1], box_b[1]) xB = min(box_a[2], box_b[2]) yB = min(box_a[3], box_b[3]) # compute the area of intersection rectangle inter_area = max(0, xB - xA + 1) * max(0, yB - yA + 1) # compute the area of both the prediction and ground-truth # rectangles bbox_a_area = (box_a[2] - box_a[0] + 1) * (box_a[3] - box_a[1] + 1) bbox_b_area = (box_b[2] - box_b[0] + 1) * (box_b[3] - box_b[1] + 1) # compute the intersection over union by taking the intersection # area and dividing it by the sum of prediction + ground-truth # areas - the interesection area iou = inter_area / float(bbox_a_area + bbox_b_area - inter_area) # return the intersection over union value return iou
def average_above_zero(tab): """ Brief: computes of the avrage of the positive value sended Arg: a list of numeric values, except on positive value, else it will raise an Error Return: a list with the computed average as a float value and the max value Raise: ValueError if no positive value is found ValueError if input tab is not a list """ if not(isinstance(tab,list)): raise ValueError("Expected a list as input") return_vals=[] average=0.0 nPositiveValue=0 valSum=0.0 maxi=0 #NMAX = len(tab) #for idx in range(NMAX) for value in tab: if value>0: valSum=valSum+float(value) nPositiveValue=nPositiveValue+1 if (maxi<value): maxi=value if nPositiveValue<=0: raise ValueError("No positive value found") average=valSum/nPositiveValue return_vals=[average,maxi] #return return_vals return return_vals[0]
def dict_differs_from_spec(expected, actual): """ Returns whether all props in "expected" are matching in "actual" Note that "actual" could contain extra properties not in expected """ for k, v in enumerate(expected.items()): if not k in actual: return False if actual[k] != v: return False return True
def delete_multi( keys, retries=None, timeout=None, deadline=None, use_cache=None, use_global_cache=None, global_cache_timeout=None, use_datastore=None, use_memcache=None, memcache_timeout=None, max_memcache_items=None, force_writes=None, _options=None, ): """Deletes a sequence of keys. Args: keys (Sequence[:class:`~google.cloud.ndb.key.Key`]): A sequence of keys. retries (int): Number of times to retry this operation in the case of transient server errors. Operation will potentially be tried up to ``retries`` + 1 times. Set to ``0`` to try operation only once, with no retries. timeout (float): Override the gRPC timeout, in seconds. deadline (float): DEPRECATED: Synonym for ``timeout``. use_cache (bool): Specifies whether to store entities in in-process cache; overrides in-process cache policy for this operation. use_global_cache (bool): Specifies whether to store entities in global cache; overrides global cache policy for this operation. use_datastore (bool): Specifies whether to store entities in Datastore; overrides Datastore policy for this operation. global_cache_timeout (int): Maximum lifetime for entities in global cache; overrides global cache timeout policy for this operation. use_memcache (bool): DEPRECATED: Synonym for ``use_global_cache``. memcache_timeout (int): DEPRECATED: Synonym for ``global_cache_timeout``. max_memcache_items (int): No longer supported. force_writes (bool): No longer supported. Returns: List[:data:`None`]: A list whose items are all None, one per deleted key. """ futures = [key.delete_async(_options=_options) for key in keys] return [future.result() for future in futures]
def tone(n, base_freq=440.0): """Return the frequency of the nth interval from base_freq (in 12-TET).""" # -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12 # G G# A A# B C C# D D# E F F# G G# A # G Ab A Bb B C Db D Eb E F Gb G Ab A return base_freq * 2 ** (n/12)
def truth(exp) -> str: """ Converts return of expression from 1,0 to corresponding bool """ return '[FALSE]' if (exp == 0) else '[TRUE]'
def consecutive_pairs(list): """ Utility function to return each consecutive pair from a list >>> consecutive_pairs([1,2,3,4,5]) [(1, 2), (2, 3), (3, 4), (4, 5)] >>> consecutive_pairs(['a', 'b', 'c']) [('a', 'b'), ('b', 'c')] >>> consecutive_pairs([2]) [] """ return [(list[i], list[i+1]) for i in range(len(list) - 1)]
def masternode_status(status): """Get a human-friendly representation of status. Returns a 3-tuple of (enabled, one_word_description, description). """ statuses = { 'ACTIVE': (False, ('ACTIVE'), ('Waiting network to allow Masternode.')), 'PRE_ENABLED': (True, ('PRE_ENABLED'), ('Waiting for masternode to enable itself.')), 'ENABLED': (True, ('ENABLED'), ('Masternode is enabled.')), 'EXPIRED': (False, ('EXPIRED'), ('Masternode failed to ping the network and was disabled.')), 'NEW_START_REQUIRED': (False, ('NEW_START_REQUIRED'), ('Must start masternode again.')), 'UPDATE_REQUIRED': (False, ('UPDATE_REQUIRED'), ('Masternode failed to ping the network and was disabled.')), 'POSE_BAN': (False, ('POSE_BAN'), ('Masternode failed to ping the network and was disabled.')), 'OUTPOINT_SPENT': (False, ('OUTPOINT_SPENT'), ('Collateral payment has been spent.')) } if (status): if statuses.get(status): return statuses[status] elif status is False: return (False, ('MISSING'), ('Masternode has not been seen on the network.')) return (False, (' '), ('Masternode status not loaded yet'))
def decryptlist(d, n, dalist): """ >>> decryptlist(257, 377, [341, 287, 202, 99, 96, 69, 116, 69]) [100, 105, 115, 99, 5, 101, 116, 101] >>> decryptlist(257, 377, [56, 287, 556, 235, 22, 45, 354, 78]) [374, 105, 225, 40, 42, 197, 178, 169] >>> decryptlist(257, 377, [256, 35, 456, 543, 32, 56, 667, 245]) [94, 120, 118, 147, 301, 374, 348, 267] """ return [x ** d % n for x in dalist]
def CleanParties(column): """Removes any text within parentheses.""" parties = column.replace("(",";(").split(";") party = [] for i in range (0,len(parties)): if parties[i].find("(") == -1: party.append(parties[i]) i+=1 preposition = ", between " if len(party) == 2 else ", among " parties = "" for i in range (0,len(party)-1): parties = parties + party[i].strip() + ", " parties = parties + "and " + party[len(party)-1].strip() return parties, preposition
def numberList(listItems): """Convert a string list into number @param listItems (list) list of numbers @return list of number list """ return [float(node) for node in listItems]
def bin2hexstr(binbytes): """ Converts bytes to a string with hex Arguments: binbytes - the input to convert to hex Return : string with hex """ return ''.join('\\x%02x' % ord(c) for c in binbytes)
def str_splitword(chars, count=1): """Return the leading whitespace and words, split from the remaining chars""" tail = chars if count >= 1: counted_words = chars.split()[:count] for word in counted_words: tail = tail[tail.index(word) :][len(word) :] if not tail: return (chars, "") head = chars[: -len(tail)] return (head, tail)
def is_stochastic_matrix(m, ep=1e-8) -> bool: """Checks that the matrix m (a list of lists) is a stochastic matrix.""" for i in range(len(m)): for j in range(len(m[i])): if (m[i][j] < 0) or (m[i][j] > 1): return False s = sum(m[i]) if abs(1.0 - s) > ep: return False return True
def twos_comp(val, bits=8): """compute the 2's complement of int value val""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val # return positive value as is
def is_file_readable(file, strict=False): """Check if a file exists and is readable. Parameters ---------- file : :class:`str` The file to check. strict : :class:`bool`, optional Whether to raise the exception (if one occurs). Returns ------- :class:`bool` Whether the file exists and is readable. """ try: with open(file, mode='rb'): return True except: if strict: raise return False
def pentagonal(n: int) -> int: """ Pentagonal Number Conditions: 1) n >= 0 :param n: non-negative integer :return: nth pentagonal number """ if not n >= 0: raise ValueError return (3*n**2 - n)//2
def zone_url_to_name(zone_url): """Sanitize DNS zone for terraform resource names zone_url_to_name("mydomain.com.") >>> "mydomain-com" """ return zone_url.rstrip(".").replace(".", "-")
def delleadingoff(process_list): """ if the first input of the process list is 'off' delete it""" if (process_list[0][0] == 'off'): del process_list[0] return process_list
def data_type_transfer(data): """ Transfer string fields in submitted json data if necessary """ if isinstance(data['is_active'], str): data['is_active'] = data['is_active'] in ["true", "True", "1"] if data['like_count']: data['like_count'] = int(data['like_count']) if isinstance(data['products'], str): if data['products']: data['products'] = [int(i) for i in data['products'].split(',') if i] else: data['products'] = [] if data['rating']: data['rating'] = float(data['rating']) return data
def fibonacci_two(n): """ Return the n-th fibonacci number""" if n in (0, 1): return n return (fibonacci_two(n - 2) + fibonacci_two(n - 1))
def _to_camel(snake_str: str) -> str: """Convert a string from snake_case to JSON-style camelCase Args: snake_str (str): Input string Returns: str: Camel case formatted string """ components = snake_str.split("_") return components[0] + "".join(x.title() for x in components[1:])
def fibonacci(n): """ Returns the n-th number in the Fibonacci sequence. Parameters ---------- n: int The n-th number in the Fibonacci sequence. """ if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2)
def path_parts(path): """Returns a list of all the prefixes for this document's [snoop.data.digests.full_path][]. This is set on the Digest as field `path-parts` to create path buckets in Elasticsearch. """ elements = path.split('/')[1:] result = [] prev = None for e in elements: if prev: prev = prev + '/' + e else: prev = '/' + e result.append(prev) return result
def header(time_type=float): """ Return a header that describes the fields of an example record in a table of example definitions. time_type: Constructor for type of time / date found in example records: time_type<T>(str) -> T. An example record describes a span of time where a subject has a particular label, treatment status, and classification. It also has fields for storing a weight and a number of events. Specifically, the fields of an example record are: id: int Subject ID. lo: time_type Start of example period. hi: time_type End of example period. lbl: str Semantic label for the example period. trt: str Treatment / Control status. cls: str Classification. wgt: float Example weight. Perhaps the length of the period. n_evs: int Number of events during the example period. jsn: str Any extra information in JSON format. The fields of an example record are defined by how you use them. For example, patient 123456789 took drug A from 2005-11-22 to 2006-08-16. Since this study compares drug A to drug B, they are a control. However, they were diagnosed with X during this period, which makes them positive for outcome X. Thus, their record might be: 123456789|2005-11-22|2006-08-16|rx-A:dx-X|c|+|267.0|13|{"age": 50} """ return ( ('id', int), ('lo', time_type), ('hi', time_type), ('lbl', str), ('trt', str), ('cls', str), ('wgt', float), ('n_evs', int), ('jsn', str), )
def obtain_header(line_lexems): """ get an included file name from provided lexems :param line_lexems: a list of lexems :return: file name is include construction exists, None otherwise """ control_stack = [] include_words = [] for lex in line_lexems: if lex == '//': break if lex == '/*': control_stack.append(lex) if lex == '*/': if control_stack[-1] == '/*': del control_stack[-1] else: return None if len(control_stack) > 0 and control_stack[-1] == '/*': continue include_words.append(lex) i = 1 while i < len(include_words)-1: if include_words[i] == '/': include_words[i-1] = include_words[i-1] + include_words[i] + include_words[i+1] del include_words[i:i+2] i += 1 if len(include_words) >= 5 and \ include_words[-5:-2] == ['#', 'include', '<'] and \ include_words[-1] == '>': return include_words[-2] if len(include_words) >= 5 and \ include_words[-5:-2] == ['#', 'include', '"'] and \ include_words[-1] == '"': return include_words[-2]
def sort_by(dict_list, key): """ Returns a List of dictionaries, sorted by a specific key """ return sorted(dict_list, key=lambda k: k[key])
def strip_suffix(filename): """Returns a filename minus it's extension.""" dotidx = filename.rfind(".") return filename[:dotidx] if dotidx != -1 else filename
def chunks(l, n, truncate=False): """Yield successive n-sized chunks from l.""" batches = [] for i in range(0, len(l), n): if truncate and len(l[i:i + n]) < n: continue batches.append(l[i:i + n]) return batches
def bigramSuggest(world, word, invert=False): """ world format: { word1 : { word2 : count } } """ ret=[] word=word.lower() if(word in world): items=world[word] invertedList={} vals=[] for item in items.keys(): vals.append(items[item]) if (not (items[item] in invertedList)): invertedList[items[item]]=[] invertedList[items[item]].append(item) vals=list(set(vals)) vals.sort() for val in vals: ret.extend(invertedList[val]) if(invert): ret.reverse() return ret
def proof_of_euler(big_number): """ proof euler number using exponential growth """ return (1 + 1/big_number) ** big_number
def _build_task_dependency(tasks): """ Fill the task list with all the needed modules. Parameters ---------- tasks : list list of strings, containing initially only the last module required. For instance, to recover all the modules, the input should be ``['fourier']``. Returns ------- tasks : list Complete task list. """ if not isinstance(tasks, (tuple, list)): tasks = [tasks] tasks = set(tasks) if 'thermodynamics' in tasks: tasks.discard('background') # if 'lensing' in tasks: # tasks.add('harmonic') if 'harmonic' in tasks: tasks.add('fourier') if 'fourier' in tasks: tasks.add('transfer') return list(tasks)
def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2): """ returns a (x, y) tuple or None if there is no intersection """ d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1) if d: uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d else: return if not(0 <= uA <= 1 and 0 <= uB <= 1): return x = Ax1 + uA * (Ax2 - Ax1) y = Ay1 + uA * (Ay2 - Ay1) return x, y
def title_case(sentence): """ convert a string to a title case. Parameters __________ sentence: string string to be converted to title case Returns _______ title_case_sentence : string String converted to title case Example _______ >>> title_case('This Is A String To Be Converted.') 'This Is A String To Be Converted.' """ # check that input is a string if not isinstance(sentence, str): raise TypeError('Invalid input %s - Input must be string type' %(sentence)) # error if empty string if len(sentence) == 0: raise ValueError('cannot apply title funtion to empty string') ret = sentence[0].upper() for i in range(1, len(sentence)): if sentence[i - 1] == ' ': ret += sentence[i].upper() else: ret +=sentence[i].lower() return ret
def quadratic_equation(a, b, c, rnd=4): """Solving quadratic equations""" if a == 0: if b == 0: if c == 0: return 'any numbers' else: return 'No solutions' else: return -c / b elif b == 0: if c <= 0: return c**0.5 else: x1 = (-c)**0.5 x1 = complex(f'{round(x1.imag, rnd)}j') + round(x1.real, rnd) return x1 dD = b**2 - 4 * a * c if dD >= 0: x1 = (-b + dD**0.5) / (2 * a) if dD == 0: return x1 x2 = (-b - dD**0.5) / (2 * a) return x1, x2 else: sqrtD = dD**0.5 x1 = (-b + sqrtD**0.5) / (2 * a) x2 = (-b - sqrtD**0.5) / (2 * a) x1 = complex(f'{round(x1.imag, rnd)}j') + round(x1.real, rnd) x2 = complex(f'{round(x2.imag, rnd)}j') + round(x2.real, rnd) # print(f'x1 = {x1}, x2 = {x2}') return x1, x2
def parse_gender(gender_codeName_str): """ parse user gender :param gender_codeName_str: :return: """ dict_gender_mapping = {'0': 'male', '1': 'female', '2': "unknown"} if isinstance(gender_codeName_str, str): return dict_gender_mapping[gender_codeName_str]
def check_arg_type(arg_name: str, arg_value: str): """ Checks that RST Threat Feed API parameters are valid. Args: arg_name (str): paramater name arg_value (str): paramater value to verify Returns: (str): a null string means OK while any text is an error """ output = '' try: isinstance(int(arg_value), int) value = int(arg_value) if 'threshold' in arg_name: if value < 0 or value > 100: output = str(arg_name) + ': the value must be between 0 and 100; ' if 'indicator_expiration' in arg_name: if value < 0: output = str(arg_name) + ': the value must be positive (>0); ' except Exception: return str(arg_name) + ': bad format, must be a number; ' return output
def my_sum(x_val: int, y_val: int) -> int: """Sum 2 integers. Args: x_val (int): integer to sum. y_val (int): integer to sum. Returns: int: result of the summation. """ assert isinstance(x_val, int) and isinstance( y_val, int ), "Input parameters should be integers." return x_val + y_val
def _as_inline_code(text): """Apply inline code markdown to text Wrap text in backticks, escaping any embedded backticks first. E.g: >>> print(_as_inline_code("foo [`']* bar")) `foo [\\`']* bar` """ escaped = text.replace("`", r"\`") return f"`{escaped}`"
def human_readable_size(size): """Show size information human readable""" symbols = ["Ei", "Ti", "Gi", "Mi", "Ki"] symbol_values = { "Ei": 1125899906842624, "Ti": 1099511627776, "Gi": 1073741824, "Mi": 1048576, "Ki": 1024 } if size < 1024: return "%d" % int(size) for ele in symbols: if size >= symbol_values[ele]: return "%d %s" % (int(size / symbol_values[ele]), ele) return "%d" % int(size)
def is_onehotencoder(feat_name): """ Parameters ---------- feat_name : string Contains the name of the attribute Returns ------- Returns a boolean value that states whether OneHotEncoder has been applied or not """ if "oneHotEncoder" in feat_name: return True else: return False
def get_atom_table(topology): """Convert the atom information to a dictionary.""" if 'atoms' not in topology: return None atoms = {} for atom in topology['atoms']: atoms[atom[0]] = atom return atoms
def _string_merge_wildcard(s1: str, s2: str, wildcard: str) -> str: """Takes a "union" of two equal-length strings `s1` and `s2`. Whenever one has a symbol `wildcard` and the other does not, the result has the non-wildcard symbol. Raises :py:class:`ValueError` if `s1` and `s2` are not the same length or do not agree on non-wildcard symbols at any position.""" if len(s1) != len(s2): raise ValueError(f'\ns1={s1} and\ns2={s2}\nare not the same length.') union_builder = [] for i in range(len(s1)): c1, c2 = s1[i], s2[i] if c1 == wildcard: union_builder.append(c2) elif c2 == wildcard: union_builder.append(c1) elif c1 != c2: raise ValueError(f's1={s1} and s2={s2} have unequal symbols {c1} and {c2} at position {i}.') elif c1 == c2: union_builder.append(c1) else: raise AssertionError('should be unreachable') return ''.join(union_builder)
def dms_to_deg(degrees: int, minutes: int, seconds: float) -> float: """Converts degrees minutes seconds to dgrees in a float point format. Args: degrees (int): Number of degrees minutes (int): Number of minutes seconds (float): Number of seconds Returns: float: The degrees of lattitude or longitude in flaoting point format """ # Calculates total minutes form minutes and seconds mins: float = float(minutes) + (seconds / 60) # Calculates total degrees from mins and degrees degs: float = degrees + (mins / 60) return degs
def chop(s): """Chop off the last bit of a file object repr, which is the address of the raw file pointer. """ return ' '.join(s.split()[:-1])
def bytes_to_int(byte): """Takes some Bytes and returns an Integer.""" return int.from_bytes(byte, 'little')
def build_response_card_attachment(title, subtitle, image_url, link_url, options = None): """ Build a responseCard attachment with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.append(options[i]) if len(title) > 80: title = title[:77] + '...' if len(subtitle) > 80: subtitle = subtitle[:77] + '...' return { 'title': title, 'subTitle': subtitle, 'imageUrl': image_url, 'attachmentLinkUrl': link_url, 'buttons': buttons }
def partition (ar, left, right, pivotIndex, comparator): """ In linear time, group an array into two parts, those less than a certain value (left), and those greater than or equal to a certain value (right). left and right are inclusive. """ pivot = ar[pivotIndex] # move pivot to the end of the array ar[right],ar[pivotIndex] = ar[pivotIndex],ar[right] store = left for idx in range(left, right): if comparator(ar[idx], pivot) <= 0: ar[idx],ar[store] = ar[store],ar[idx] store += 1 # move pivot to its final place ar[right],ar[store] = ar[store],ar[right] return store
def _is_float(value): """Use casting to check if value can convert to a `float`.""" try: float(value) except ValueError: return False else: return True