content
stringlengths
42
6.51k
def getNextPort(ports, num): """Given a list of open ports, get the next open one from a starting location.""" while True: if any(str(num) in p for p in ports): num += 1 else: return num
def dot(a,b): """ Dot product between two dictionaries. """ keys = set(a.keys()).intersection(set(b.keys())) sum = 0 for i in keys: try: sum += a[i] * b[i]; except KeyError: pass return sum
def check_api_connection(post_data, response) -> list: """ checks connection with api by verifying error codes and number of tasks between post_data/requests and response parameters: post_data: dictionary with requests response: json response form server Returns list of tasks id to be downloade...
def parse_command_num(command_str, end, start = 1): """ start: Starting value of valid integer commands end: Ending value of valid integer commands """ command_int = int(command_str.strip()) if command_int >= start and command_int <= end: return command_int else: raise ValueE...
def get_coords(geojson): """.""" if geojson.get('features') is not None: return geojson.get('features')[0].get('geometry').get('coordinates') elif geojson.get('geometry') is not None: return geojson.get('geometry').get('coordinates') else: return geojson.get('coordinates')
def _members_to_exclude(arg): """Return a set of members to exclude given a comma-delim list them. Exclude none if none are passed. This differs from autodocs' behavior, which excludes all. That seemed useless to me. """ return set(a.strip() for a in (arg or '').split(','))
def _get_pattern_strings(compiled_list): """Returns regex pattern strings from a list of compiled regex pattern objects. Args: compiled_list (list): of regular expression patterns to extract strings from Returns: list: A list of regex pattern strings extracted from compiled list of ...
def bold(string: str) -> str: """Add bold colour codes to string Args: string (str): Input string Returns: str: Bold string """ return "\033[1m" + string + "\033[0m"
def _compose_gpindices(parent_gpindices, child_gpindices): """ Maps `child_gpindices`, which index `parent_gpindices` into a new slice or array of indices that is the subset of parent indices. Essentially: `return parent_gpindices[child_gpindices]` """ if parent_gpindices is None or child_g...
def testSuite(debug: bool = False): """ Function Type: Method Run all test for the class. """ print(debug) # testObj = RegressionUnitTestsCases(debug=debug) # testObj.run() return True
def popCount(v): """Return number of 1 bits (population count) of an integer. If the integer is negative, the number of 1 bits in the twos-complement representation of the integer is returned. i.e. ``popCount(-30) == 28`` because -30 is:: 1111 1111 1111 1111 1111 1111 1110 0010 Uses the a...
def sum_func(n): """ Given an integer, create a function which returns the sum of all the individual digits in that integer. For example: if n = 4321, return 4+3+2+1 """ if n < 10: return n else: return n%10 + sum_func(n//10)
def cb_layer(ctx, param, value): """Let --layer be a name or index.""" if value is None or not value.isdigit(): return value else: return int(value)
def pad(traces, fill=0, end=None): """Pads all the traces signals have the same duration. If ``end`` parameter is not provided the traces are padded to have the same duration as the longest given trace. Parameters ---------- traces : list[list[int]] 2D list of numbers representing the ...
def is_palindrome(x): """ returns True if x is palindrome """ return x == int(str(x)[::-1])
def first_line(doc): """Extract first non-blank line from text, to extract docstring title.""" if doc is not None: for line in doc.splitlines(): striped = line.strip() if striped: return striped return ''
def split_group(group): """ Converts a list of objects splitted by "|" into a list. The complication comes from the fact that we do not want to use other group's "|" to split this one. Meaning (a|(b|c)|e) should be splitted into ['a', '(b|c)', 'e']. Warning, this function supposes that there is...
def attr_bool(s): """Converts an attribute in to a boolean A True value is returned if the string matches 'y', 'yes' or 'true'. The comparison is case-insensitive and whitespace is stripped. All other values are considered False. If None is passed in, then None will be returned. """ if s is No...
def calc_power(cell, serial): """Calculate the power for a single cell """ rack_id = cell[0] + 10 power_level = rack_id * cell[1] power_level += serial power_level *= rack_id hundereds = power_level // 100 if hundereds > 10: hundereds = hundereds % 10 power_level = hundereds ...
def repos_dict(repos): """Returns {"repo1": "branch", "repo2": "pull"}.""" return {r: b or p for (r, (b, p)) in repos.items()}
def add_article(name): """ Returns a string containing the correct indefinite article ('a' or 'an') prefixed to the specified string. """ if name[:1].lower() in "aeiou": return "an " + name return "a " + name
def insertIntoPath(original, insertion='rest'): """ Insert a string after the first block in a path, for example /my/original/path,insertion /my/INSERTION/original/path """ slashIndex = original.index('/',1) newString = '%s/%s%s' % (original[0:slashIndex], insertion, original[slashIndex:len(orig...
def linear_with_memory(A): """ Find single number using hash set using a linear time and linear amount of memory. """ if not A: return None if len(A) == 1: return A[0] seen = dict() for num in A: if num in seen: seen[num] += ...
def align16(address): """ Return the next 16 byte aligned address. """ return (address + 0x10) & 0xFFFFFFF0
def interpretValue(value,*args,**kwargs): """Interprets a passed value. In this order: - If it's callable, call it with the parameters provided - If it's a tuple/list/dict and we have a single, non-kwarg parameter, look up that parameter within the tuple/list/dict - Else, just return it """ ...
def next_char(string, idx): """ Get the next character in a string if it exists otherwise return an empty string Arguments: string (str): idx (idx): Index of the current position in the string Returns: (str): Next character in the string """ if idx >= len(string) - ...
def is_prime(num : int) -> bool: """ Checks if a number is prime or not. Parameters: num: the number to be checked Returns: True if number is prime, otherwise False """ flag : bool = True if num <= 0: raise ValueError("Input argument should be a natural number") ...
def unique_list_order_preserved(seq): """Returns a unique list of items from the sequence while preserving original ordering. The first occurrence of an item is returned in the new sequence: any subsequent occurrences of the same item are ignored. """ seen = set() seen_add = seen.add ret...
def _remove_proper_feature(human_readable: str) -> str: """Removes proper feature from human-readable analysis.""" human_readable = human_readable.replace("+[Proper=False]", "") human_readable = human_readable.replace("+[Proper=True]", "") return human_readable
def remove_item(inventory, item): """ :param inventory: dict - inventory dictionary. :param item: str - item to remove from the inventory. :return: dict - updated inventory dictionary with item removed. """ # inventory.pop(item, None) if item in inventory: del inventory[item] ...
def getThrusterFiringIntervalBefore(tfIndices, minDuration = 10): """Returns range of points between last two thruster firings in input See getThrusterFiringIntervalAfter() for more details. This function does the same job, but returns the last two indices in the array meeting the criteria. """ ...
def flipBit(int_type, offset): """Flips the bit at position offset in the integer int_type.""" mask = 1 << offset return(int_type ^ mask)
def getFeaturePerm(feature): """ Return a list of assets permission of a feature params: feature -> a feature """ return feature["_permissions"]
def is_valid(bo, num, pos): """Returns bollean expresion whether inserting some number in an empty space is valid or not""" #Check whether the number is already in the current row for i in range(len(bo[0])): if bo[pos[0]][i] == num and pos[1] != i: return False #Check whether th...
def areoverlapping(left, right): """Test if the chains represented by left and right are overlapping.""" return right[0] <= left[-1]
def prettyBytes (b): """ Pretty-print bytes """ prefixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB'] while b >= 1024 and len (prefixes) > 1: b /= 1024 prefixes.pop (0) return f'{b:.1f} {prefixes[0]}'
def parse_wallet_data_import(wallet_data): """Parses wallet JSON for import, takes JSON in a supported format and returns a tuple of wallet name, wallet descriptor, and cosigners types (if known, electrum only for now) Supported formats: Specter, Electrum, Account Map (Fully Noded, Gordian, Sparrow etc.) ...
def empty_line(line): """Check if line is emtpy.""" return not bool(line.strip())
def upload_file(body): """accepts file uploads""" # <body> is a simple dictionary of {filename: b'content'} print('body: ', body) return {'filename': list(body.keys()).pop(), 'filesize': len(list(body.values()).pop())}
def stats(ps): """Averages of conflicts at different q rates Parameter --------- ps: list of pairs of rates and conflicts Returns ------- statistics """ s = {} c = {} for p in ps: i,t = p c[i] = c.get(i,0) + 1 s[i] = s.get(i,0) + t r = {} for i i...
def _format_integer_field(field_name, status_information): """Format an integer field. :param field_name: The name of the field :type field_name: str :param status_information: The various fields information :type status_information: :class:`collections.defaultdict` :returns: The updated status...
def get_sidebar_app_legend(title): """Return sidebar link legend HTML""" return '<br />'.join(title.split(' '))
def navigate(obj, attr_path): """get the final attribute, will raise AttributeError when attr not exists >>> navigate(dict(), '__class__.__name__') 'dict' """ attrs = attr_path.split('.') target = obj for attr in attrs: target = getattr(target, attr) return target
def listDiff(lstA, lstB): """ Return a logical of size lstA For each element in lstA, return true if it is not in lstB Therefore, its like lstA-lstB It returns the elements of lstA that are not in lstB """ lstDiffBool = [] # logical for a in lstA: lstDiffBool.append(not a in lst...
def escape_command(cmd: str, needs_enter: bool = True) -> str: """ Escapes a given command for use in tmux shell commands If there is a "C-m" at the end of the command, assume this is already quoted Parameters ---------- cmd : string The command to escape needs_enter : bool ...
def is_scalar(value): """Returns whether the given value is a scalar.""" return isinstance(value, (str, int))
def btc_to_satoshi(btc): """ Converts a value in BTC to satoshi outputs => <int> btc: <Decimal> or <Float> """ value = btc * 100000000 return int(value)
def ravel_multi_index(I, J, shape): """Create an array of flat indices from coordinate arrays. shape is (rows, cols) """ r, c = shape return I * c + J
def get_host_context_for_host_finding(resp_host): """ Prepare host context data as per the Demisto standard. :param resp_host: response from host command. :return: Dictionary representing the Demisto standard host context. """ return { 'ID': resp_host.get('hostId', ''), 'Hostnam...
def jaccard(a, b): """ Jaccard index """ a, b = set(a), set(b) return 1.*len(a.intersection(b))/len(a.union(b))
def make_human_readable_stations(res): """Makes text representation of a search result that is suitable for showing to a user. Returns a string""" ret = [] if not res: ret.append( u"""No stations found""") else: format = u"%%(id)%ds %%(name)s (%%(district)s)" % \ ...
def decode_cp1252(str): """ CSV files look to be in CP-1252 encoding (Western Europe) Decoding to ASCII is normally fine, except when it gets an O umlaut, for example In this case, values must be decoded from cp1252 in order to be added as unicode to the final XML output. This function helps do ...
def ascii_encode(non_compatible_string): """Primarily used for ensuring terminal display compatibility""" if non_compatible_string: return non_compatible_string.encode("ascii", errors="ignore").decode("ascii") else: return ""
def ListJoiner(list): """ Takes in a nested list, returns a list of strings """ temp_list = [] for item in list: i = " ".join(item) temp_list.append(i) return temp_list
def flatten_json_with_key(data, json_key): """ Return a list of tokens from a list of json obj. """ to_return = [] for obj in data: to_return.append(obj[json_key]) return to_return
def get_by_path(root, path): """Access a nested object in root by path sequence.""" for k in path if isinstance(path, list) else path.split("."): root = root[int(k)] if k.isdigit() else root.get(k, "") return root
def jointerms(terms): """String that joins lists of lists of terms as the sum of products.""" return "+".join(["*".join(map(str, t)) for t in terms])
def ReplaceVariables(text, variables): """Returns the |text| with variables replaced with their values. Args: text: A string to be replaced. variables: A list in the form of [(prefix, var_name, values), ...]. Returns: A replaced string. """ for unused_prefix, var_name, value in variables: te...
def isUniqueSeq(objlist): """Check that list contains items only once""" for obj in objlist: if objlist.count(obj) != 1: return False return True
def xor(a, b): """ Compute the xor between two bytes sequences. """ return [x ^ y for x, y in zip(a, b)]
def _nbcols(data): """ retrieve the number of columns of an object Example ------- >>> df = pd.DataFrame({"a":np.arange(10),"b":["aa","bb","cc"]*3+["dd"]}) >>> assert _nbcols(df) == 2 >>> assert _nbcols(df.values) == 2 >>> assert _nbcols(df["a"]) == 1 >>> assert _nbcols(df["a"].valu...
def is_palindrome(x): """ :type x: int :rtype: bool """ if x < 0: return False if x < 10: return True # arr = [n for n in str(x)] # while len(arr) > 1: # a = arr.pop(0) # b = arr.pop() # if a != b: # return False new = 0 while...
def __style_function__(feature): """ Function to define the layer highlight style """ return {"color": "#1167B1", "fillColor": "#476930", "weight": 2, "dashArray": "1, 1"}
def remove_char(string, iterable): """ Return str without given elements from the iterable. More convenient than chaining the built-in replace methods. Parameters ------- string: str String from which the characters from the iterable are removed. iterable: str, list,...
def uri_to_uuid(uri_uuid: str) -> str: """ Standardize a device UUID (MAC address) from URI format (xx_xx_xx_xx_xx_xx) to conventional format (XX:XX:XX:XX:XX:XX) """ return uri_uuid.upper().replace('_', ':')
def extract_counts_double(sentence, pos=False): """Extract the two-edge properties with the same head from a treebank sentence. Args: `Sentence`: A sentence object. pos (boolean): True iff the properties should be PoS-specific. Returns: dict of str:(list of int): Explanation by example: "D#case-det" : [0...
def quicksort_equal_elements(s): """Quicksort from finxter modified to add all elements equal to the pivot directly after the pivot, so that quicksort performs faster for cases where there are many identical elements in the array to be sorted (e.g. there are only 2 values for all elements, or 1 unique v...
def NB_calc(TP, FP, POP, w): """ Calculate Net Benefit (NB). :param TP: true positive :type TP: int :param FP: false positive :type FP: int :param POP: population or total number of samples :type POP: int :param w: weight :type w: float :return: NB as float """ try: ...
def method_already_there(cls, method_name, # type: str this_class_only=False # type: bool ): # type: (...) -> bool """ Returns True if method `method_name` is already implemented by object_type, that is, its implementation...
def func_f(x_i, base, y, p): """ x_(i+1) = func_f(x_i) """ if x_i % 3 == 2: return (y*x_i) % p elif x_i % 3 == 0: return pow(x_i, 2, p) elif x_i % 3 == 1: return base*x_i % p else: print("[-] Something's wrong!") return -1
def get_size(bytes): """ Returns size of bytes in a nice format """ for unit in ['', 'K', 'M', 'G', 'T', 'P']: if bytes < 1024: return f"{bytes:.2f}{unit}B" bytes /= 1024
def coord_to_gtp(coord, board_size): """ From 1d coord (0 for position 0,0 on the board) to A1 """ if coord == board_size ** 2: return "pass" return "{}{}".format("ABCDEFGHJKLMNOPQRSTYVWYZ"[int(coord % board_size)],\ int(board_size - coord // board_size))
def coding_problem_22(dictionary, the_string): """ Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null. Exa...
def GetCaId(settings): """Get ca_id to be used with GetCaParameters(). Args: settings: object with attribute level access to settings parameters. Returns: str like "FOO" or None (use primary parameters) """ return getattr(settings, 'CA_ID', None)
def generate_assembly_id(params): """Generate assembly id for IBM Cloud report.""" return ":".join([str(param) for param in params if param])
def ComputeListDeltas(old_list, new_list): """Given an old and new list, return the items added and removed. Args: old_list: old list of values for comparison. new_list: new list of values for comparison. Returns: Two lists: one with all the values added (in new_list but was not in old_list), an...
def printDictionary( dictio, tabLevel = 0, tabSize = 4, prefix = '', verbose = False ): """ @brief Visualize dictionary contents """ output = '' for k in list(dictio.keys()): if isinstance(dictio[k], dict): output += "%s%s%-20s:\n"%(prefix,tabLevel*tabSize*' ', k) out...
def remove_leading_zeros(num: str) -> str: """ Strips zeros while handling -, M, and empty strings """ if not num: return num if num.startswith("M"): ret = "M" + num[1:].lstrip("0") elif num.startswith("-"): ret = "-" + num[1:].lstrip("0") else: ret = num.lstr...
def classify_turn_direction(relative_azimuth, straight_angle=20): """Classify turn directions based on a relative azimuth """ if (relative_azimuth < straight_angle) or (relative_azimuth > (360 - straight_angle)): return 'straight' elif (relative_azimuth >= straight_angle) and (relative_azim...
def round_price(price: float, exchange_precision: int) -> float: """Round prices to the nearest cent. Args: price (float) exchange_precision (int): number of decimal digits for exchange price Returns: float: The rounded price. """ return round(price, exchange_precision)
def is_device_target(hostname, device_list): """ Check if CV Device is part of devices listed in module inputs. Parameters ---------- hostname : string CV Device hostname device_list : dict Device list provided as module input. Returns ------- boolean True i...
def mirror_mag_d(distance_image,distance_object): """Usage: Find magnification using distance of image and distance of object""" neg_di = (-1) * distance_image return neg_di / distance_object
def get_rotate_order(gimbal_data): """ Based on the gimbal generate the rotate order. Here we can decide whether the Gimbal will be on the twist or on the roll @param gimbal_data: dict which defines what axis are on the bend, roll and twist. Also defines where the gimbal will reside @retur...
def get_tags(misp_attr: dict): """ Tags are attached as list of objects to MISP attributes. Returns a list of all tag names. @param The MISP attribute to get the tag names from @return A list of tag names """ return [ t.get("name", None) for t in misp_attr.get("Tag", []) ...
def getlist(option, sep=',', chars=None): """Return a list from a ConfigParser option. By default, split on a comma and strip whitespaces.""" return [ chunk.strip(chars) for chunk in option.split(sep) ]
def lcs_recursive(s1, s2): """ Given two strings s1 and s2, find their longest common subsequence (lcs). Basic idea of algorithm is to split on whether the first characters of the two strings match, and use recursion. Time complexity: If n1 = len(s1) and n2 = len(s2), the runtime is O(2^(n1+n2...
def pluralize(count, singular, plural): """Return singular or plural based on count""" return singular if count == 1 else plural
def k2e(k, E0): """ Convert from k-space to energy in eV Parameters ---------- k : float k value E0 : float Edge energy in eV Returns ------- out : float Energy value See Also -------- :func:`isstools.conversions.xray.e2k` """ return ((1...
def substitute_rpath(orig_rpath, topdir, new_root_path): """ Replace topdir with new_root_path RPATH list orig_rpath """ new_rpaths = [] for path in orig_rpath: new_rpath = path.replace(topdir, new_root_path) new_rpaths.append(new_rpath) return new_rpaths
def _lookup_option_cost(tier_dict, premium): """ Returns the per share option commission for a given premium. """ if tier_dict is None: return 0.0 for (min_val, max_val) in tier_dict: if min_val <= premium < max_val: return tier_dict[(min_val, max_val)] raise Exceptio...
def pad_items(items, pad_id): """ `items`: a list of lists (each row has different number of elements). Return: padded_items: a converted items where shorter rows are padded by pad_id. lengths: lengths of rows in original items. """ lengths = [len(row) for row in items] max_l = max(lengths) for i...
def file_type(infile): """Return file type after stripping gz or bz2.""" name_parts = infile.split('.') if name_parts[-1] == 'gz' or name_parts[-1] == 'bz2': name_parts.pop() return name_parts[-1]
def should_shard_by_property_range(filters): """Returns whether these filters suggests sharding by property range. Args: filters: user supplied filters. Each filter should be a list or tuple of format (<property_name_as_str>, <query_operator_as_str>, <value_of_certain_type>). Value type is up to th...
def bsearch(list_,value): """Binary search.""" lower = 0 upper = len(list_) - 1 while lower <= upper: if list_[lower] == value: return lower elif list_[upper] == value: return upper else: mid = lower + (upper - lower) / 2 if li...
def vecMul(vec, sca): """Retruns something.""" return tuple([c * sca for c in vec])
def param_str(params): """Helper that turns a param dict in a key=value string""" return ', '.join([f'{key}={value}' for key, value in params.items()])
def get_field_matches(explain, index_fields): """ Iterates over the toString output of the Lucene explain object to parse out which fields generated the current hit. Returns a list containing all fields involved in generating this hit """ match_fields = set() for line in explain.split('\n')...
def workers_and_async_done(workers, async_map): """Returns True if the workers list and asyncore channels are all done. @param workers list of workers (threads/processes). These must adhere to the threading Thread or multiprocessing.Process interface. @param async_map the threading-aware asyncore cha...
def convert_list_to_dict(origin_list): """ convert HAR data list to mapping Args: origin_list (list) [ {"name": "v", "value": "1"}, {"name": "w", "value": "2"} ] Returns: dict: {"v": "1", "w": "2"} """ return {ite...
def predict(list_items): """Returns the double of the items""" return [i*2 for i in list_items]