content
stringlengths
42
6.51k
def _reverse_list_of_lists(x): """Deep reverse of a list of lists.""" return [sublist[::-1] for sublist in x[::-1]]
def get_free_symbols(s, symbols, free_symbols=None): """ Returns free_symbols present in `s`. """ free_symbols = free_symbols or [] if not isinstance(s, list): if s in symbols: free_symbols.append(s) return free_symbols for i in s: free_symbols = get_free_sym...
def myMax (L): """Maximum. Params: L (list of integers) Returns: (int) max(L) """ # INSERT CODE HERE maxint = L[0] for i in range (1,len(L)): if L[i] > maxint: maxint = L[i] return maxint print(myMax(randList()))
def format_trip_id(number, mode): """formats the ID to be search with the numerical id(number)""" # This functions returns the link to be used to search for trips. # mode refers to whereever the trip is inbound or outbound. # This function is equipped to deal with both # incoming trips and outg...
def not_exonic(variant_class): """Check if SNV is exonic. Args: variant_class: the type of mutation Returns: True for not exonic, False otherwise. """ variant_classes = ["5'Flank", 'Intron', 'RNA', "3'Flank", "3'UTR", "5'UTR", 'IGR'] if variant_class in variant_classes: ...
def flip(c): """ Flip a character's polarity, i.e. a maps to A, B maps to b, etc. :param c: the single character :return: the reversed character wrt case >>> flip('a') 'A' >>> flip('B') 'b' """ return c.upper() if c.islower() else c.lower()
def grounding_dict_to_list(groundings): """Transform the webservice response into a flat list.""" all_grounding_lists = [] for entry in groundings: grounding_list = [] for grounding_dict in entry: gr = grounding_dict['grounding'] # Strip off trailing slashes ...
def formatdevaddr(addr): """ Returns address of a device in usual form e.g. "00:00:00:00:00:00" - addr: address as returned by device.getAddressString() on an IOBluetoothDevice """ # make uppercase cos PyS60 & Linux seem to always return uppercase # addresses # can safely encode to as...
def place_labels(genes, region_start, region_end, num_letters=196): """ Handle the collision between genes' label by placing overlapping labels on different levels :param genes: List of dictionary of genes (gene: [start, end, strand, name]) :param region_start: Region's start position :...
def merge_sort(sequence: list) -> list: """Simple implementation of the merge sort algorithm in Python :param sequence: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending """ if len(sequence) < 2: return sequence ...
def get_subdict_and_remainder(d, list_of_keys): """ :param d: dict :param subset_of_keys: list of keys :return: the subset of key:value pairs of d where key is in list_of_keys """ keys_in = set(d.keys()).intersection(list_of_keys) keys_not_in = set(d.keys()).difference(list_of_keys) retu...
def get_score(score): """ Get the score in the from the csv string """ # If you're having parsing problems I feel bad for you, son. # I got 99 problems, but regex ain't one. remove_these = ["(", "SO", "OT", ")"] for r in remove_these: score = score.replace(r, "") return int(score...
def assemble_flows(currentMods): """ Helper function for building the process diagram, or "biomap" for output to the text file. Parameters ------------- currentMods = dictionary, Current Modular Units of bioprocess Returns ------------- [flows] = a list of the 3 flows shown in the ...
def generous_hire(lambs): """ Generously pay to the henchmen.""" # Edge case: we can pay only to the junior. if (lambs < 1): print ("Generous (special):\n [0]") print (" -> Sum: 0") return 0 # Store payments. payments = [] # Hire first Junior. payments.append(1) ...
def complexMul(complex1, complex2): """This method is used to multiply two complex numbers Arguments: complex1 {tuple} -- tuple of 2 representing the real and imaginary part complex2 {tuple} -- tuple of 2 representing the real and imaginary part Returns: tuple--...
def index_all(elm, lst): """return list[int] all positions where elm appears in lst. Empty list if not found""" if type(list)!=list: lst=list(lst) return [i for i,e in enumerate(lst) if e==elm]
def truncate(formulas, n): """Returns an array of the first n members of formulas.""" if n >= len(formulas): return formulas return formulas[0:n]
def escape_html(text): """Escape &, <, > as well as single and double quotes for HTML.""" return text.replace('&', '&amp;'). \ replace('<', '&lt;'). \ replace('>', '&gt;'). \ replace('"', '&quot;'). \ replace("'", '&#39;')
def filter_list(items_list, indices_to_remove): """Remove list items by their indices. :param items_list: target list :param indices_to_remove: indices of items to be removed from target list """ items_to_remove = list() [items_to_remove.append(items_list[index_to_remove]) for index_to_remove in...
def absolute(value): """ Get the absolute value for "value". This template tag is a wrapper for pythons "abs(...)" method. Usage: >>> absolute(-5) 5 """ try: return abs(value) except: return value
def UniqueLabels(flabels: list, indices: list) -> list: """Unique fingerprint labels.""" return [flabels[x[0]] for x in indices]
def mult1(A, B): """long method """ m = len(A) n = len(B) p = len(B[0]) C = [[0 for _ in range(p)] for _ in range(n)] for i in range(m): for j in range(p): for k in range(n): C[i][j] += A[i][k]*B[k][j] return C
def encrypt(plaintext, cipher, shift): """ Caesar encryption of a plaintext using a shifted cipher. You can specify a positiv shift to rotate the cipher to the right and using a negative shift to rotate the cipher to the left. :param plaintext: the text to encrypt. :param cipher: set of charac...
def combine_bolds(graph): """ Make ID marker bold and remove redundant bold markup between bold elements. """ if graph.startswith('('): graph = graph.replace( ' ', ' ').replace( '(', '**(', 1).replace( ')', ')**', 1).replace( '** **', ' ', 1) ...
def product (*args): """ This function return the product of two number """ tot = 1 for num in args: tot *= num return tot
def get_val(KrigInfo, key, num=None): """Helper function to get values from KrigInfo dictionary. Multiobjective Kriging values are not mapped to single values and need to be extracted using the num parameter. If running multiobjective Kriging, values are stored in a list/dictionary under each key ...
def _update_shape_dtype(shape, dtype, params): """Update shape dtype given params information""" if not params: return shape, dtype shape = shape.copy() shape.update({k : v.shape for k, v in params.items()}) if isinstance(dtype, str): for k, v in params.items(): if v.dtyp...
def set_playback_rate(playbackRate: float) -> dict: """Sets the playback rate of the document timeline. Parameters ---------- playbackRate: float Playback rate for animations on page """ return { "method": "Animation.setPlaybackRate", "params": {"playbackRate": playb...
def _before_each(separator, iterable): """Inserts `separator` before each item in `iterable`. Args: separator: The value to insert before each item in `iterable`. iterable: The list into which to intersperse the separator. Returns: A new list with `separator` before each item in `iterabl...
def shn_abbreviate(word, size=48): """ Abbreviate a string. For use as a .represent see also: vita.truncate(self, text, length=48, nice=True) """ if word: if (len(word) > size): word = "%s..." % word[:size - 4] else: return word else: return wo...
def get_image(default_image, args): """ A function to output a pillar key in JSON. State Example:: {% image = salt['paas_docker.get_image']("nasqueron/mysql", container) %} """ image = default_image if 'image' in args: image = args['image'] if 'version' in args: i...
def output(the_bytes, as_squirrel=True): """ Format the output string. Args: the_bytes (list): The individual integer byte values. as_squirrel (bool): Should we output as Squirrel code? Default: True Returns: str: The formatted output. """ out_str = "local unicodeStr...
def epsilon_decay_schedule(episode_number: int, decay_factor: float, minimum_epsilon: float) -> float: """Decay schedule for the probability that agent chooses an action at random.""" return max(decay_factor**episode_number, minimum_epsilon)
def calculate_route_cost(cost_function, route): """ Calculate cost of a single subroute """ cost = 0.0 for node, next_node in zip(route, route[1:]): cost += cost_function(node, next_node) return cost
def get_human_readable_time(seconds): """Formats seconds as a short human-readable HH:MM:SS string. """ seconds = int(seconds) m, s = divmod(seconds, 60) h, m = divmod(m, 60) return "%d:%02d:%02d" % (h, m, s)
def quick_sort(iter): """Sort the iterable using the merge sort method.""" if not isinstance(iter, (list, tuple)): raise TypeError("Input only a list/tuple of integers") if len(iter) < 2: return iter if not all(isinstance(x, (int, float)) for x in iter): raise ValueError("Input o...
def escape_chars(s): """ Performs character escaping of comma, pipe and equals characters """ return "".join(['\\' + ch if ch in '=|,' else ch for ch in s])
def toStr(b): """ Converts a utf-8 bytes object to a string. """ if type(b) == str: return b else: return b.decode("utf-8")
def pkcs7_pad(plaintext: bytes, block_size: int=0x10) -> bytes: """ Pad a message using the byte padding algorithm described in PKCS#7 This padding scheme appends n bytes with value n, with n the amount of padding bytes. The specification describing the padding algorithm can be found here: http...
def _write_aque(parameters): """Write aqueous species.""" out = [] if not ("aqueous_species" in parameters and parameters["aqueous_species"]): return out for specie in parameters["aqueous_species"]: out += [f"{specie:<20}"] return out
def UniqueSequence(seq): """Returns a list with unique elements. Element order is preserved. @type seq: sequence @param seq: the sequence with the source elements @rtype: list @return: list of unique elements from seq """ seen = set() return [i for i in seq if i not in seen and not seen.add(i)]
def hamming_distance(target, test): """ Calculate the hamming distance between two tuples. Arguments: target (tuple): the target tuple. test (tuple): the test tuple. Must have same length as target Returns: int: the hamming distance """ dist = 0 assert len(target) =...
def _scale_filters(filters, multiplier, base=8): """Scale the filters accordingly to (multiplier, base).""" round_half_up = int(int(filters) * multiplier / base + 0.5) result = int(round_half_up * base) return max(result, base)
def key_to_note(key, octaves=True): """Returns a string representing a note which is (key) keys from A0""" notes = ['a', 'a#', 'b', 'c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#'] octave = (key + 8) // 12 note = notes[(key - 1) % 12] if octaves: return note.upper() + str(octave) else: ...
def merge_taxa_strings_and_scores(master, scores): """Merge taxa strings and their scores, return {id_:(taxa,score)}""" return {k: list(zip(v, scores[k])) for k, v in master.items()}
def mono_block(text: str, syntax: str = "") -> str: """Wrap a String in a Multi-Line block of Monospace text, optionally with Syntax Highlighting. """ return f"```{syntax}\n{text}```"
def workflow_has_secure_parameters(params: list) -> bool: """Returns whether or not a parameter contains sensitive information Arguments: params - the list of parameters to check Returns: Returns True if a known sensitive parameter is detected and False otherwise """ return_value = F...
def text_align(keyword): """``text-align`` property validation.""" return keyword in ('left', 'right', 'center', 'justify')
def get_base_image(version_map, version): """Selects the appropriate base image from the version map. This function takes into account the .NET Core versioning story to determine the appropriate base image for the given version. It will select from within the same major version and only if the mino...
def isSymmetric(root): """ :type root: TreeNode :rtype: bool """ if not root: return True leftPart=[root.left] rightPart=[root.right] while leftPart and rightPart: leftNode=leftPart.pop() rightNode=rightPart.pop() if leftNode and rightNode: if ...
def is_prop(value): """Check whether a field is a property of an object""" return isinstance(value, property)
def shift_within_range(value, min, max, reverse=False): """Shift numeric value within range.""" values = range(min, max + 1) if reverse: index = values.index(value) - 1 else: index = values.index(value) + 1 return values[index % len(values)]
def discount_rate(episode_idx, num_episodes, discount=.95): """[summary] Args: episode_idx (int): The integer encoding for the episode. num_episodes (int): The total number of episodes. discount (float, optional): Discount factor. Defaults to .95. https://tinyurl.com/discou...
def piedPiper(town): """ How many rats are there? See: https://www.codewars.com/kata/598106cb34e205e074000031 Example: ~O~O~O~OP~O~OO~ has 2 deaf rats """ return town.replace(' ', '')[::2].count('O')
def int_to_be_bytes(x): """Convert an integer to an array of four integer values representing the big endian byte encoding.""" return [(x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff]
def try_get_fully_qualified_name(some_object): """ tries to get the fully qualified name of given object. it tries to return `__module__.__name__` for given object. for example: `pyrin.api.services.create_route`. but if it fails to get any of those, it returns the `__str__` for that object. :p...
def hrsize(size): """Return human-readable size from size value""" if size < 1000: return '%d%s' % (size, 'B') for suffix in 'KMGTPEZY': size /= 1024. if size < 10.: return '%.1f%sB' % (size, suffix) if size < 1000.: return '%.0f%sB' % (size, suffix) ...
def reverse(p): """ :type x: int :rtype: int """ if p > 0: x = p else: x = -p y = 0 while x != 0: n = x % 10 y = y * 10 + n x = x // 10 if p > 0: retu = y else: retu = -y if retu > 2147483647 or retu < -2147483648: ...
def nextCol(column): """Return the column letter that comes after column. Returns '' if column 'H'.""" return {'': '', 'A': 'B', 'B': 'C', 'C': 'D', 'D': 'E', 'E': 'F', 'F': 'G', 'G': 'H', 'H': ''}[column]
def addr_to_hex(address): """ convert an address as int or long into a string """ string = hex(address) if string[-1] == 'L': return string[:-1] return string
def get_timetable_with_minimum_departure_datetime_difference(departure_datetime_differences): """ Get the timetable with the minimum departure_datetime difference. :param departure_datetime_differences: [{ 'timetable': timetable_document, 'departure_datetime_difference': float (in seconds)...
def devideContent(span, text): """ @param[in] span a tuple with two elements: the beginning and the end of the text to separate @param[in] text the text to work on @returns an tuple with 3 elements: the text before the beginning, the text to separate and the text after the end """ ...
def filter_ribo_counts(counts, orf_start=None, orf_stop=None): """Filter read counts and return only upstream of orf_start or downstream of orf_stop. Keyword arguments: counts -- Ribo-Seq read counts obtained from get_ribo_counts. orf_start -- Start position of the longest ORF. orf_stop -- Sto...
def cache_to_persistent_dir(a, b, c): """this cache will be persistent across machine restarts if cache_dir is not specified, will instead cache to a tmpdir """ return a * b * c
def move(pos: int, steps: int) -> int: """Move the player's position by the given number of steps. The position is on a disc with labels 1 to 10. After reaching the value 10 the position wraps around to 1. Args: pos: Player's position. steps: Number of steps. Returns: The ...
def write_bash_script_line(cfg): """Write line to bash script to run controller on specified instance.""" return ( f"\necho 'running controller for: {cfg['id']}...'" f"\n{cfg['ctrl_pth']} " f"JAMPR " f"{cfg['data_pth']} " f"{cfg['cpu_mark']} " f"{cfg['time_limit']...
def merge_credentials(config_creds, cli_creds): """merge config file credentials with command line credentials.""" merged_creds = config_creds # do this second to prefer cli creds over config file if cli_creds: if cli_creds["username"]: merged_creds["app_id"] = cli_creds["username"] ...
def add_x(tabuleiro): """ Function that returns a tuple equal to the given one but with x's instead of -1. """ tab_to_print = () for line in tabuleiro: for state in line: if state == -1: tab_to_print += ('x', ) else: tab_to_print += (st...
def parse_metrics(text): """ Parses the Q4S message into the corresponding metrics""" latency = float('nan') jitter = float('nan') bandwidth = float('nan') packetloss = float('nan') text = text.split() for index, word in enumerate(text[:-1]): if word == "Latency:": try: ...
def fibonacci(n): """Get n-th fibonacci number. Uses funny _ notation and range, also swapping values. Args: n: N-th (>=0) fibonacci number Returns: A number that is N-th fibonacci number example: fibonacci(1) = 1 Raises: Exception: because why not. ""...
def subset(dict1, dict2): """ Helper method to find the intersecting subset of key-value pairs contained by two dictionaries. :param dict1: a dictionary :param dict2: another dictionary :return: Tuple of dicts containing the values with identical keys in both dicts """ keys1 = set(dict1.keys...
def intersect(value: list, other: list) -> list: """Intersection of two lists. .. code-block:: yaml - vars: new_list: "{{ [2, 4, 6, 8, 12] | intersect([3, 6, 9, 12, 15]) }}" # -> [6, 12] .. versionadded:: 1.1 """ return list(set(value).intersection(other))
def minutes_to_seconds(minutes: str) -> int: """ Converts minutes to seconds Arguments: minutes: The number of minutes to be converted to seconds. Returns: The number of seconds. """ return int(minutes)*60
def smart_encode(content: str, encoding: str) -> bytes: """Encode `content` using the given `encoding`. Unicode errors are replaced. """ return content.encode(encoding, 'replace')
def distance(x1, y1, z1, x2, y2, z2, round_out=False): """ distance between two points in space for orthogonal axes. >>> distance(1, 1, 1, 2, 2, 2, 4) 1.7321 >>> distance(1, 0, 0, 2, 0, 0, 4) 1.0 """ import math as m d = m.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2) if...
def visitable(coord, maze): """Check if a coordinate is at first sight visitable Args: coord (tuple): tuple of two integers maze (list): maze Returns: bool: is the coordinate in the maze visitable """ x, y = coord n = len(maze) if x >= 0 and x < n and y >= 0 and y <...
def getName(path): """removes ending from path ('/home/robo/Overcast.bag' -> '/home/robo/Overcast')""" parts = path.split('.') if len(parts) > 1: del parts[-1] return ".".join(parts)
def is_abs(field): """ Check if field is absolute value. Parameters ---------- field : str Field name. Returns ------- (bool, str) Whether the field is absolute or not along with the basic field itself. """ if field[:4] == 'ABS(' and field[-1] == ')': r...
def split_word(word, toxic_words): """Function that accounts for toxic words being hidden within normal text. If any of the toxic words are found, it will split the non-toxic text, exposing the toxic word. Arguments: word {string} -- A string containing a toxic word toxic_words {strings...
def is_punctuation(char): """Checks whether `chars` is a punctuation character.""" import unicodedata cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, ...
def is_status_update_request(request_data): """ Returns True if `request_data` contains status update else False. """ return any('status' in update for update in request_data)
def format_to_ext(output_format): """Get a file extension from the output format Args: output_format (str): The target format. Returns: str: The corresponding file extension with '.ext' format. """ if output_format == 'txt': return '.atxt' if output_format == 'braille': ...
def rosenbrock_2d(x): """ The 2 dimensional Rosenbrock function as a toy model The Rosenbrock function is well know in the optimization community and often serves as a toy problem. It can be defined for arbitrary dimensions. The minimium is always at x_i = 1 with a function value of zero. All input ...
def get_custom_kickstart_url(http_url, os_type, server_serial_number): """This function is to generate URL for the custom kickstart file based on the type of OS and server serial number Arguments: http_url {string} -- HTTP server base URL os_type {string} -- Type of...
def is_isogram(string: str) -> bool: """check the given string is a word or phrase without a repeating letter. :param string: :return: """ # noinspection SpellCheckingInspection alphabets = list('abcdefghijklmnopqrstuvwxyz') counts = {} for alphabet in alphabets: counts[alphabet...
def get_subplot_grid(n): """Get a (h, w) arrangement for up to 9 subplots.""" assert 0 <= n <= 9 if n <= 3: return 1, n elif n <= 6: return 2, n - 3 else: return 3, n - 6
def insert_segment(seq, pos, inserted): """Return the sequence with ``inserted`` inserted, starting at index ``pos``.""" return seq[:pos] + inserted + seq[pos:]
def fill(lst, mold, subs): """For every <mold> element in <lst>, substitute for the according <subs> value (indexically). """ nlst = list(lst).copy() j = 0 for i, elem in enumerate(lst): if elem == mold: nlst[i] = subs[j] j += 1 return nlst
def status(level, solved, err): """Calculate status from status and err.""" if solved: if err: status = 'multiple solution' else: status = 'level ' + str(level) else: if err: status = 'no solution' else: status = 'give up' r...
def create_entry(day, opening, closing, notes=None): """Creates a new JSON object representing a single time slot for a single day""" entry = { "day": day, "opens": opening, "closes": closing } if notes: entry["notes"] = notes return entry
def apply_operators(filter_dict, key, resource, count): """ Returns the count for the filters applied on the keys """ split_list = filter_dict[key].split(".") if split_list[0] == 'eq' and str(resource[key]) == str(split_list[1]): count += 1 elif split_list[0] == 'neq' and str(resource[ke...
def sorted_squared_array(arr): """Squares the elements of given array and sorts the squared elements in ascending order. Args: arr (list): given list of elements to be sorted """ squared_list = list(map(lambda x: x*x, arr)) squared_list.sort() return squared_list
def group_tag(group_name): # type: (str) -> str """Marks this field as belonging to a group""" tag = "group:%s" % group_name return tag
def is_insertion(ref, alt): """Is alt an insertion w.r.t. ref? Args: ref: A string of the reference allele. alt: A string of the alternative allele. Returns: True if alt is an insertion w.r.t. ref. """ return len(ref) < len(alt)
def is_subset(x, ref_set): """Return ``True`` if ``x`` is a subset of ``ref_set``.""" if not isinstance(ref_set, set): ref_set = set(ref_set) if isinstance(x, (list, tuple, set)): set_x = set(x) else: set_x = set([x]) return set_x.issubset(ref_set)
def add_ngram(sequences, token_indice, ngram_range=2): """ Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_in...
def dicts_set(a, b, unique_props): """ b has precedence """ def unique_identifier(d): return tuple([d.get(s) for s in unique_props]) d_a = {unique_identifier(d): d for d in a} d_b = {unique_identifier(d): d for d in b} return list({**d_a, **d_b}.values())
def mul_array(arr1, arr2): """ function to multiply arrays """ return [x * y for x, y in zip(arr1, arr2)]
def normalizeGlyphFormatVersion(value): """ Normalizes glyph format version for saving to XML string. * **value** must be a :ref:`type-int-float` of either 1 or 2. * Returned value will be an int. """ if not isinstance(value, (int, float)): raise TypeError("Glyph Format Version must be ...
def cond_interm(row, lang_code): """ Condition for a row to have a word sequence in a given language row : the current row of the dataframe lang_code : "f", "t", "l" or "a" the language identification Return : bool """ return lang_code in row["states"] and row["has_roman_txt"]