content
stringlengths
42
6.51k
def create_auto_profile(role_session, user_session, session_name, source_profile_name, role_arn): """Create the profile that'll be stored in the credentials file for autoawsume. Parameters ---------- - role_session - the session credentials from the assume-role api call - user_session - the session...
def player_color(player_name): """Return color of a player given his name """ return { 1 : (0, 255, 0), 2 : (0, 0, 255), 3 : (255, 0, 0), 4 : (255, 255, 0), 5 : (0, 255, 255), 6 : (255, 0, 255), 7 : (224, 224, 224), 8 : (153, 153, 255) }[pl...
def create_keepass_groups(kpo, folders_list): """Create keepass folder structure based on Bitwarden folders """ groups_dict = {} for folder in folders_list: names = folder['name'].split('/') group = None parent = kpo.root_group for name in names: if name ==...
def func_is_even(x): """Returns `True` iff x is divisible by 2.""" return x % 2 == 0
def near_extremes(x, a, b, r): """checks if x is within r of a or b, and between them""" assert a <= b if x >= a and x <= b: if x - a < r or b - x < r: return True return False
def _crimp(color): """ crimps the values between 255 and 0. Required for some other convolutions like emboss where they go out of register. :param color: color to crimp. :return: """ if color > 255: return 255 if color < 0: return 0 return int(color)
def slice_to_list(sl, max_len) -> list: """ Turn a slice object into a list Parameters ---------- sl: slice The slice object max_len: int Max length of the iterable Returns ------- list The converted list """ if sl.start is None: start = 0 ...
def _correct_grd_metadata_key(original_key: str) -> str: """ Change an upper case GRD key to it's SLC metadata equivalent. By default this is uppercasing all keys; otherwise if the value in the `special_keys` dict will be used. Args: original_key: input metadata key special_keys: di...
def get_area_by_player_position(areas, x, y): """ This function checks the area the player is in given its position in the maps """ epsilon = 1 # Variance of 1 block for i, area in areas: if ( area["x1"] - epsilon <= x <= area["x2"] + epsilon and area["y1"] - epsilon...
def outpoint_copy(outpoint): """ Performs a deep-copy of an outpoint """ return { "txid": outpoint["txid"], "output_index": outpoint["output_index"] }
def convert_pattern_to_string(pattern): """ Converts a pattern to explicit format where "-" indicates the beginning of an itemset inside the main pattern and "--" indicates that the next item belongs to that itemset. Each "-" means the begin of a new itemset of length greater than 1. Atributes: ...
def frequency_model_validation_to_text(model_params): """Generate readable text from validation of frequency model. Validates the model type on the input data and parameters and calculate the Mean Absolute Percent Error (MAPE). Args: model_params: Model parameters from the validation. Ret...
def puncend(str1, punctuation): """returns all the punctuation from the end of the string""" # An implementation with regular expressions was slightly slower. newstring = u"" for n in range(len(str1)): c = str1[-1-n] if c in punctuation or c.isspace(): newstring = c + newstr...
def is_int_type_malicious_score(confidence_score, params): """ determine if integer type confidence score is malicious in reputation_params """ return params['override_confidence_score_malicious_threshold'] and isinstance(confidence_score, int) and int( params['override_confidence_score_mali...
def remove_quotes(quoted_values: str) -> str: """Remove Quotes.""" if (len(quoted_values) >= 2 and quoted_values[0] == '"' and quoted_values[-1] == '"'): return quoted_values[1:-1] return quoted_values
def init_config(config, default_config, name=None): """Initialise non-given config values with defaults""" if config is None: config = default_config else: for k in default_config.keys(): if k not in config.keys(): config[k] = default_config[k] if name and con...
def count_values(dictionary): """ """ seen_values = set() for i in dictionary: seen_values.add(dictionary[i]) return len(seen_values)
def normalize_path(path): """ Returns a normalized path from a `path` string. """ return "/" + path.strip("/")
def _next_char(s: str, idx: int): """Returns the character from *s* at the position after *idx* or None, if *idx* is the last position in *s*. """ try: return s[idx + 1] except IndexError: return None
def parse_midi(midi): """Convert a MIDI (3 bytes) to a dictionnary for ease of use.""" return { 'code': midi[0], 'input': midi[1], 'value': midi[2], }
def tcp_received(data=None, data_length=None, id=None): """ Construct a template for TCP incoming data """ tpl = { 'tcp-event': 'received' } if data is not None: tpl['tcp-data'] = data if data_length is not None: tpl['tcp-data-length'] = data_length if id is not None: tpl['client-id'] = str(id) retu...
def get_triangular_matrix(dim, default_value_diag, default_value_other): """ Gets standard matrix for the Correlation: triangular matrix encoded with lists. :param dim: size of the matrix :type dim: int :param default_value_diag: value initialized on the diagonal :type default_value_diag: numbe...
def _build_schema_resource(fields): """Generate a resource fragment for a schema. :type fields: sequence of :class:`SchemaField` :param fields: schema to be dumped :rtype: mapping :returns: a mapping describing the schema of the supplied fields. """ infos = [] for field in fields: ...
def range(first: int, second: int) -> float: """ Returns the range between 2 numbers. Parameters: start (int) : First number end (int) : Second number """ biggest = 0 smallest = 0 if (first < second): biggest = second return biggest - first ret...
def filename_ext(filename): """ Function that returns filename extension """ # Taken from http://flask.pocoo.org/docs/1.0/patterns/fileuploads/ return '.' in filename and filename.rsplit('.', 1)[1].lower()
def _bool_process(item): """Replaces 'true' with True, 'false' with False, otherwise returns the 'item' unchanged """ if item == 'true': return True if item == 'false': return False return item
def del_abbreviation(txt): """ Delete abbreviations Parameters ---------- txt : str Texts with abbreviations. Returns ------- txt : str Texts without abbreviations.. """ while 'mtbi' in txt: txt.remove('mtbi') while 'tbi' in txt: txt.remove(...
def _check_request_fields(dict_datarequest, lst_requiredfields): """ #### Input: - Data request from the HTTP call (Just passed the whole thing in) - List of expected keys. #### Desc: Use set subtraction to figure out if we are missing any fields. """ reqfields = set(lst_requiredfield...
def format_isk_compact(value): """Nicely format an ISK value compactly.""" # Based on humanize.intword(). powers = [10 ** x for x in [3, 6, 9, 12, 15]] letters = ["k", "m", "b", "t", "q"] if value < powers[0]: return "{:,.2f}".format(value) for ordinal, power in enumerate(powers[1:], 1)...
def find_max(a_para_list): """ Take in a list and return its maximum value :param a_para_list: a list of a wanted parameter :return: a_max = a maximum value """ num_lt = [float(i) for i in a_para_list] # Arjun Mehta max_val = max(num_lt) return max_val
def rounded_down (value, granularity) : """Returns `value` rounded down to nearest multiple of `granularity`. >>> rounded_down (3, 5) 0 >>> rounded_down (8, 5) 5 >>> rounded_down (5, 5) 5 >>> rounded_down (-3, 5) -5 >>> rounded_down (-8, 5) -10 ...
def compress_indices(indices, size): """Return compressed indices. The function is used for compressing COO row indices to CSR compressed representation. The input indices must be sorted. """ nse = len(indices) compressed = [0] * (size + 1) k = 1 last_index = 0 for i in range(nse):...
def parse_fulladdress(fulladdress): """ Parses fulladdress into pieces: US format. Returns dict containing address, zip, state, city """ fulladdress = fulladdress.strip() info = dict(address="", zip="", state="", city="") if " " not in fulladdress: info["address"] = fulladdr...
def interpolant(t): """ By Pierre Vigier https://github.com/pvigier/perlin-numpy Licence: MIT """ return t*t*t*(t*(t*6 - 15) + 10)
def chop(seq, size): """Chop a sequence into chunks of the given size.""" chunk = lambda i: seq[i:i+size] return list(map(chunk,range(0,len(seq),size)))
def convert_labels_to_ids(labels): """ Converts labels to integer IDs """ label_to_id = {} counter = 0 id_list = [] for label in labels: if label not in label_to_id.keys(): label_to_id[label] = counter counter += 1 id_list.append(label_to_id[label]) ...
def text_alignment(x, y): """ Align text labels based on the x- and y-axis coordinate values. This function is used for computing the appropriate alignment of the text label. For example, if the text is on the "right" side of the plot, we want it to be left-aligned. If the text is on the "top"...
def clamp(val, min_, max_): """Clamps :val: to the range between :min_: and :max_:""" return min(max(val, min_), max_)
def extract_machine_code(assembly_lines): """ Extract machine code from assembly line dictionaries. Args: assembly_lines (list(dict)): List of assembly line info dictionaries to extract machine code from. See :func:`~.get_assembly_line_template` for details on what ...
def get_symmetric_pos_th_nb(neg_th): """Compute the positive return that is symmetric to a negative one. For example, 50% down requires 100% to go up to the initial level.""" return neg_th / (1 - neg_th)
def mul_with_none(v1,v2): """ Standard mul treating None with zero """ if v1 is None: return None elif v2 is None: return None else: return v1 * v2
def cal_sort_key(cal): """ Sort key for the list of calendars: primary calendar first, then other selected calendars, then unselected calendars. (" " sorts before "X", and tuples are compared piecewise) """ if cal["selected"]: selected_key = " " else: selected_key =...
def split_into_threads(tasks: list, threads_num: int) -> list: """ Splits a 1D list of tasks into a 2D array of iterable threads :param tasks: :param threads_num: :return: """ threads = [] temp = [] for i in range(len(tasks)): temp.append(tasks[i]) if i % threads_num...
def whitespace_tokenize(text): """Splits an input into tokens by whitespace.""" return text.strip().split()
def normalized_bases(classes): """Remove redundant base classes from `classes`""" candidates = [] for m in classes: for n in classes: if issubclass(n, m) and m is not n: break else: # m has no subclasses in 'classes' if m in candidates: ...
def rev_wordpiece(str): """wordpiece function used in cbert""" #print(str) if len(str) > 1: for i in range(len(str)-1, 0, -1): if str[i] == '[PAD]': str.remove(str[i]) elif len(str[i]) > 1 and str[i][0]=='#' and str[i][1]=='#': str[i-1] +=...
def redact_storage_creds(storage): """ Redact storage credentials """ if 'b2drop' in storage: if 'app-username' in storage['b2drop']: storage['b2drop']['app-username'] = '***' if 'app-password' in storage['b2drop']: storage['b2drop']['app-password'] = '***' el...
def sumDigits(s): """ Assumes s is a string Returns the sum of the decimal digits in s For example, if s is 'a2b3c' it returns 5""" sum = 0 letters = 0 for char in s: try: d = int(char) # throws ValueError: invalid literal for int() with base 10: 'a' ...
def truncate_chars(val: str, num: int, end: str = "...") -> str: """Truncates a string if it is longer than the specified number of characters. Truncated strings will end with `end`, an ellipsis by default.""" val_length = len(val) end_length = len(end) if val_length < num: return val ...
def kernel_shape_to_factorization_shape(factorization, kernel_shape): """Returns the shape of the factorized weights to create depending on the factorization """ # For the TT case, the decomposition has a different shape than the kernel. if factorization.lower() == 'tt': kernel_shape = list(...
def get_block_device_mapping(image): """ Retrieves block device mapping from AMI """ bdm_dict = dict() if image is not None and hasattr(image, 'block_device_mapping'): bdm = getattr(image, 'block_device_mapping') for device_name in bdm.keys(): bdm_dict[device_name] = { ...
def _num_steps(total_number, step_size): """ get the number of steps of size `step_size` in a collection of `total_number` items. If `step_size` is not a factor of `total_number`, includes the last smaller-sized step """ return (total_number - 1) // step_size + 1
def any_in_seq(search_vals, seq): """Check if any value in search_vals in the sequence seq""" for v in search_vals: if v in seq: return True return False
def get_thy_info(lvldic): """ convert theory level dictionary to theory information array """ err_msg = '' info = ['program', 'method', 'basis', 'orb_res'] for i, inf in enumerate(info): if inf in lvldic: info[i] = lvldic[inf] else: err_msg = inf if err_ms...
def get_idxs_from_list_of_lists(list_of_lists, idx): """ Returns a list of objects corresponding to index idx from a list of lists. """ return [elem[idx] for elem in list_of_lists]
def which(program): """ Returns the full file path to a command, if found on PATH :param program: program to search for on PATH :return: file path to program if found, else None """ import os def is_exe(path_to_file): return os.path.isfile(path_to_file) and os.access(path_to_file, ...
def compare_model(L1,L2,model_selection): """ Compare two Models L(M1) = L1 and L(M2) = L2. if return True L1 wins; otherwise L2 wins. For Bayes Factor/Odds ratio, it is the log10(L1/L2) being compared. """ if model_selection in ('bic', 'aic'): return L1 <= L2 elif model_selection in ('odds', 'BF','bf')...
def get_local_name(element): """ Just the element name with the schema URI (if any) removed @type element: Element @param element: The XML element @rtype: string @return: the base name of the element or None if it could not be determined """ if element is None: ret...
def elements_of_list_same(iterator): """Check is all elements of an iterator are equal. :param iterator: a iterator :type iterator: ``list`` :rtype: ``bool`` Usage:: >>> from haproxyadmin import utils >>> iterator = ['OK', 'ok'] >>> utils.elements_of_list_same(iterator) Fa...
def reverse_linked_list(ls): """ Question 8.2: Reverse a linked list using O(1) space and O(n) time """ last = None current = ls while current: nxt = current.next current.next = last last = current current = nxt return last
def parse_float(s): """Parse a float and return it. Upon failure, return 0.""" try: return float(s) except ValueError: return 0
def get_avg_price(ph, pl): """Daily average prices calculated as an average of highest and lowest prices""" return (ph + pl)/2
def get_spelling_suggestions(spelling_suggestions): """Returns spelling suggestions from JSON if any """ res = [] if spelling_suggestions and spelling_suggestions[0] and spelling_suggestions[0]['s']: res = spelling_suggestions[0]['s'] return res
def translate(el, onepattern, fourpattern): """With a little bit of help from my reddit friends: https://www.reddit.com/r/adventofcode/comments/rbj87a/comment/hnp38wn/?utm_source=share&utm_medium=web2x&context=3 """ el = set(el) if len(el) == 2: return 1 elif len(el) == 4: retur...
def regex_from_words(words): """Creates a regular expression string that would match one of the words from the list.""" expression = '' # create the core of the expression for w in words: expression += w + '|' # add the endings, while removing the unwanted extra '|' expression = '^.*(' +...
def decimal_to_roman(index): """Converts an int to a roman numerical index""" assert isinstance(index, int) and index > 0 roman = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), ...
def dotproduct(point1, point2): """This is the function used to calculate the dot \ product between two vectors, which will be used as \ numerator for angle calculation""" result = 0 for i in range(len(point1)): result = result + point1[i]*point2[i] return result
def find_index(text, pattern): """Return the starting index of the first occurrence of pattern in text, or None if not found.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) text_index = 0 # start ...
def rk4(y, x, dx, f): """computes 4th order Runge-Kutta for dy/dx. y is the initial value for y x is the initial value for x dx is the difference in x (e.g. the time step) f is a callable function (y, x) that you supply to compute dy/dx for the specified values. """ k1 = dx * f(y, x) ...
def _compose(args, decs): """Helper to apply multiple markers""" if len(args) > 0: f = args[0] for d in reversed(decs): f = d(f) return f return decs
def num_to_list(integer): """changes a number to a list - a quasi inverse of the list_to_num""" result = [0 for _ in range(3)] result[integer] = 1 return result
def are_deeply_linked_synonyms(reference_dict, first_word, second_word): """Takes in two words with a reference dictionary and iteratively checks if the words (with any in between) are synonyms""" if first_word not in reference_dict or second_word not in reference_dict: return False tracker = {} ...
def get_version(version: tuple): """Return a cleaned up version number from :data:`VERSION`.""" return "%s %s.%s.%s" % (version[3], version[0], version[1], version[2])
def getIndexPositionsThatStartWith(listOfElements, item): """ Returns the indexes of all occurrences of give element in the list- listOfElements """ indexPosList = [] for index in range(0, len(listOfElements)): if listOfElements[index].startswith(item): indexPosList.insert(len(indexP...
def binary_to_int(value): """Convert binary number to an integer.""" return int(value, 2)
def _flatten(mylist): """ this is for postprocessing the result of argparse append lists (emulating the expand action) """ if(mylist==None): return mylist elif(type(mylist)==list): if len(mylist)==0: return [] elif len(mylist)==1: return _flatten(mylist[0]) else: return _flatten(mylist[0]) + _flatte...
def list_omit_none(value): """Returns a list of the value, or the empty list if None.""" return [value] if value else []
def serendipity_indices(total, linear, dim, done=[]): """Get the set indices for a serendipity polynomial set.""" if len(done) == dim: if done.count(1) >= linear: return [done] return [] if len(done) == dim - 1: return serendipity_indices(total, linear, dim, done=done + [...
def list2string(list_of_strings): """ Return a string (OUTPUT) from a list of strings (INPUT). E.g., ["I think,", "Therefore, I am."] => "I think. Therefore, I am" """ return " ".join(list_of_strings)
def land(value): """Returns a new trampolined value that lands off the trampoline.""" return ('land', value)
def make_file_name(full_file_path, supported_extensions): """Generate a pure file name for the file.""" chunks = full_file_path.split("/") file_name = chunks[-1] for ext in supported_extensions: # Remove all extensions file_name = file_name.replace(ext, "") return file_name
def get_default_tox21_task_names(): """Get that default tox21 task names and return the bioassays results""" return ['NR-AR', 'NR-AR-LBD', 'NR-AhR', 'NR-Aromatase', 'NR-ER', 'NR-ER-LBD', 'NR-PPAR-gamma', 'SR-ARE', 'SR-ATAD5', 'SR-HSE', 'SR-MMP', 'SR-p53']
def find_middle(arr): """ Gets the middle of an array :param arr: array :return: middle of array, middle index """ middle = float(len(arr))/2 if middle % 2 != 0: return arr[int(middle - .5)], int(middle - .5) return arr[int(middle)], int(middle)
def multiply_even_numbers(nums): """Multiply the even numbers. >>> multiply_even_numbers([2, 3, 4, 5, 6]) 48 >>> multiply_even_numbers([3, 4, 5]) 4 If there are no even numbers, return 1. >>> multiply_even_numbers([1, 3, 5]) 1 """ r = 1 for x in nu...
def compareLists(d1, d2, d3=None, key=None): """ Receives list of data from different sources and compare them. In case a key is passed in, then the input is a dictionary and we validate the value of that key from different sources. """ outcome = 'NOPE' # just to make comparison easier when...
def generate_identifier_for_invenio_iiif(file): """Generate IIIF identifier for 'bucket:version:key'. 'bucket:version:key' is a setting required by invenio-iiif original settings. """ return ":".join([file["bucket"], file["version_id"], file["key"]])
def single_quote(unescaped: object) -> str: """Return a single-quote escaped string from input.""" return "'" + str(unescaped).replace("'", "'\\''") + "'"
def _bisearch(ucs, table): """ Auxiliary function for binary search in interval table. :arg int ucs: Ordinal value of unicode character. :arg list table: List of starting and ending ranges of ordinal values, in form of ``[(start, end), ...]``. :rtype: int :returns: 1 if ordinal value uc...
def cheb_sum(x, coefs): """Evaluates sum(coef * T(k, x) for k, coef in enumerate(coefs, 0)) where T(k, x) is the k:th Chebyshev polynomial.""" if not coefs: return 0 else: # Actually faster than cos_sum because pypy hates slices. x2 = x + x bk = 0 bk1 = 0 for ...
def truncpad(srcline, length, align='l', elipsis=True): """Return srcline truncated and padded to length, aligned as requested.""" ret = srcline[0:length] if length > 6: if len(srcline) > length+2 and elipsis: ret = srcline[0:(length - 3)] + '...' # repl with elipsis? if align == 'l'...
def split_move_notation (move): """ Function: split_move_notation ----------------------------- given a string represneting the fen of a move, this will return (exit_an, enter_an), where exit is the square that was exited and enter was the square that was entered """ return (move[0].upper (), int(move...
def valid_path(path: str) -> bool: """Check if the provided path is valid.""" if len(path) < 4: raise ValueError('File path to short!') extension = path[-3:] if extension != 'csv': raise ValueError('Expects a .csv file!') return True
def replace_underscore(string): """ Replaces an underscore with a space. Return: {string} """ return string.replace('_', ' ')
def sanitize_input(turn, board): """Sanitizes the input and checks for errors.""" ok = False if len(turn) > 1: return turn, board, ok turn = turn.lower() if turn != 'x' and turn != 'o': return turn, board, ok board = [space.lower() if space != "!" else None for space in board...
def sort_mapped(fq_dict, mapped_reads): """ Sort mapped reads from dictionary of fastq reads INPUT: - fq_dict(dict) dictionary with read names as keys, seq and quality as values in a list - mapped_reads(list) list of mapped reads OUTPUT: - mfqd(dict) dictionary with mapped read names...
def normalize_var(var): """Sass defines `foo_bar` and `foo-bar` as being identical, both in variable names and functions/mixins. This normalizes everything to use dashes. """ return var.replace('_', '-')
def arg_parser(argv): """Used for parsing argument passed to the script""" _arg = argv[1] return _arg
def get_reply_message_for_fic_blacklist(data): """to return a simple reply message when fic blacklist cog is used""" if data["resp"] == "404_WRONG_URL": return "Can't add fic to blacklist. Not a valid url or index." elif data["resp"] == "200_VOTE_ADDED": return "Your vote was added." eli...
def es_palindroma(word): """ Retorna falso o verdadero dependiendo si la palabra es palindroma """ return word[::-1] == word
def thousand_sep_filter(val,use_k=False): """Used from the template to produce thousand-separated numbers, optionally with "K" for thousands""" if not use_k: return "{:,}".format(val) else: if val==0: return "-" elif val<1000: return "<1K" else: ...