content
stringlengths
42
6.51k
def py_strictly_increasing(L): """test series""" return all(x < y for x, y in zip(L[:-1], L[1:]))
def impalad_service_name(i): """Return the name to use for the ith impala daemon in the cluster.""" if i == 0: # The first impalad always logs to impalad.INFO return "impalad" else: return "impalad_node{node_num}".format(node_num=i)
def cartesian(lists): """ Helper function to compute cartesian multiply """ if lists == []: return [()] return [x + (y,) for x in cartesian(lists[:-1]) for y in lists[-1]]
def _retain_from_list(x, exclude): """Returns the features to retain. Used in conjunction with H2OTransformer classes that identify features that should be dropped. Parameters ---------- x : iterable of lists The list from which to exclude exclude : array_like The columns ...
def indice_maximum_liste(t): """ Renvoie l'int max d'une liste Args: t (list): Liste d'int Returns: int: Max """ assert len(t) > 0, "Le tableau est vide" m = 0 for i in range(len(t)): if t[i] > t[m]: m = i return m
def strip_pointy(string): """ Remove leading '<' and trailing '>' from `str` :param string: string :return: cleaned up string """ return string.lstrip('<').rstrip('>')
def valid_parentheses(string): """ Takes a string of parentheses, and determines if the order of the parentheses is valid. :param string: a string of parentheses and characters. :return: true if the string is valid, and false if it's invalid. """ stack = [] for x in string: if x == "...
def distance_max(a, b): """ Chebyshev distance between two 2D vectors (the greatest of their differences along any part). """ return max(abs(x - y) for x, y in zip(a, b))
def transpose(mat): """transpose matrix transpose A[i][j]=A.T[j][i] :param mat: original matrix :return: matrix after transpose """ mat_t = [[0 for y in range(len(mat))] for x in range(len(mat[0]))] for i in range(len(mat)): for j in range(len(mat[0])): mat_t[j][i] = mat[...
def x_label(epoch_axis): """ Get the x axis label depending on the boolean epoch_axis. Arguments: epoch_axis (bool): If true, use Epoch, if false use Minibatch Returns: str: "Epoch" or "Minibatch" """ return "Epoch" if epoch_axis else "Minibatch"
def get_next_actions(measurements, is_discrete_actions): """Get/Update next action, work with way_point based planner. Args: measurements (dict): measurement data. is_discrete_actions (bool): whether use discrete actions Returns: dict: action_dict, dict of len-two integer lists. ...
def digit_in_range(choice, max_val, min_val=1): """ Verifies choice is integer in range 1->max """ if not choice.isdigit(): return False else: val = int(choice) if val < min_val or val > max_val: return False return True
def _get_max_size(x, y, map_info): """ Get the size of the biggest square matrix in the map with first point: (x, y) Arguments: x -- column index y -- line index map_info -- a dict of the map and its information Returns: size -- biggest square matrix size """ x_max ...
def _flatten_yocto_conf(conf): """ Flatten conf entries. While using YAML *entries syntax, we will get list of conf entries inside of other list. To overcome this, we need to move inner list 'up' """ # Problem is conf entries that it is list itself # But we can convert inner lists to tuples, wh...
def bytes_xor(byte_seq1, byte_seq2): """ (bytes, bytes) -> (bytes) Do bit level XOR or two byte arrays. :param byte_seq1: byte sequence (bytes). :param byte_seq2: byte sequence (bytes). :return: XOR of the byte bytes sequences (bytes). """ assert len(byte_seq1) == len(byte_seq2), "Bytes...
def scale_bar_values( bar, top, maxrow ): """ Return a list of bar values aliased to integer values of maxrow. """ return [maxrow - int(float(v) * maxrow / top + 0.5) for v in bar]
def local_part(id_): """nmdc:fk0123 -> fk0123""" return id_.split(":", maxsplit=1)[1]
def is_passphrase_valid(phrase): """ a set can only contain unique values so if the list and the set are the same size, no word was removed """ word_list = phrase.split(" ") return len(word_list) == len(set(word_list))
def _get_from_dictionary(dictionary, key): """ Safely returns the value from a dictionary that has the given key. if the dictionary is None or does not contain the specified key, None is returned :return: a dictionary """ if dictionary and key in dictionary: return dictionary[key] else: return N...
def z_array(s): """ Use Z algorithm (Gusfield theorem 1.4.1) to preprocess s """ assert len(s) > 1 z = [len(s)] + [0] * (len(s)-1) # Initial comparison of s[1:] with prefix for i in range(1, len(s)): if s[i] == s[i-1]: z[1] += 1 else: break r, l = 0, 0 ...
def centre_indices(ndim=2,apron=8): """Returns the centre indices for the correct number of dimension """ return tuple([slice(apron,-apron) for i in range(ndim)])
def make_policy(url, method, query_filter=None, post_filter=None, allowed=True): """ Create a policy dictionary for the given resource and method. :param str url: the resource URL to grant or deny access to :param str method: the HTTP method to allow or deny :param dict query_filter...
def quick_sort(arr): """Sort array of numbers with quicksort.""" if len(arr) == 1: return arr if len(arr) > 1: pivot = arr[0] left = 1 right = len(arr) - 1 while left <= right: if arr[left] > pivot and arr[right] < pivot: arr[left], arr[ri...
def apris_human_alias(x): """ A predefined function for convenience It extracts transcript IDs from the full names of appris genomes. """ return x.split("|")[4]
def shiftl(x: int, bits: int) -> int: """ Why even...? Shifts number to the left by n bits. n can be negative, resulting in a right-shift by n bits. """ return x << bits if bits >= 0 else x >> -bits
def is_list_empty(value): """ Check is a list is empty :param value: :return: """ return len(value) == 0
def ordinal(num : int) -> str: """ Return the ordinal of a number For example, 1 -> 1st , 13 -> 13th , 22 -> 22rd """ remainder = num % 100 if remainder in (11, 12, 13): return str(num) + "th" else: suffixes = ["th", "st", "nd", "rd", "th", "th", "th", "th", "t...
def event_filter(name: str, comparison_operator: str, comparison_value): """ :param name: The name of the item to filter on :param comparison_operator: How to compare values to determine if it is a valid event to send, Expected values: "=", "!=", ">", "<", ">=", "<=", "empty", "exists" :param compariso...
def is_numeric(string: str) -> bool: """ test if a string s is numeric """ for c in string: if c not in "1234567890.": return False return True
def cross(A, B): """Cross product of elements in A and elements in B.""" return [a+b for a in A for b in B]
def nl(*args): """ Adds newlines to the given terms and returns them. This is so that they will eat the newlines after the given args so that the new lines will not affect the rest of the code (would mainly cause paragraph breaks). """ new_terms = [] for term in args: #for en...
def mclag_ka_interval_valid(ka): """Check if the MCLAG Keepalive timer is in acceptable range (between 1 and 60) """ if ka < 1 or ka > 60: return False, "Keepalive %s not in valid range[1-60]" % ka return True, ""
def total_profit(attributes): """ rounds the total profit under the assumption that all inventory was sold. """ return round((attributes['sell_price'] - attributes['cost_price']) * attributes['inventory'])
def mdc_recursivo(a, b): """ Retorna o MDC entre a e b. """ if b == 0: return a r = a % b return mdc_recursivo(b, r)
def grid_traveler_memo(m: int, n: int, memo={}) -> int: """Computes the number of ways of traveling from source to destination. Args: m: The total vertical distance. n: The total horizontal distance. Returns: The number of ways ways you can travel to the goal on a grid with...
def string_contains_surrogates(ustring): """ Check if the unicode string contains surrogate code points on a CPython platform with wide (UCS-4) or narrow (UTF-16) Unicode, i.e. characters that would be spelled as two separate code units on a narrow platform. """ for c in map(ord, ustring): ...
def port(s): """Validate port input""" i = int(s) if i not in range(0, 65536): raise ValueError(s) return i
def section(title, element_list): """ Returns a dictionary representing a new section. Sections contain a list of elements that are displayed separately from the global elements on the page. Args: title: The title of the section to be displayed element_list: The list of elements to...
def analysis_product(x, y): """Product of two integers.""" result = x * y return result
def hash_coord(coord): """ For a dictionary with an x and y key, return a string of the int values of those keys. Lets us use a coordinate for a dictionary key. """ return f"{coord['x']}:{coord['y']}"
def get_origin(tp): """ Simplified getting of the unsubscripted version of a type. Should be replaced with typing.get_origin from Python >= 3.8 """ if hasattr(tp, '__origin__'): return tp.__origin__ return None
def mile_to_km(mile): """ Converts Miles to Kilometers """ try: return float(mile) * 1.609344 except ValueError: return None
def tri_to_dec(n): """ :param n: string representation of a trinary number :returns: decimal number for n """ dec = 0 m = len(n) - 1 for char in n: dec += int(char) * (3 ** m) m -= 1 return dec
def bytesPad(text, size=8, pad=0): """Convert a string to bytes and add pad value if necessary to make the length up to size. """ text_as_bytes = text.encode("utf-8") if len(text_as_bytes) >= size: return text_as_bytes else: return text_as_bytes + bytes([pad] * (size - len(text_as...
def num_to_alnum(integer): """ Transform integer to [a-z], [a0-z0]-[a9-z9] Parameters ---------- integer : int Integer to transform Returns ------- a : str alpha-numeric representation of the integer """ ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' if inte...
def rstrip_lines(text: str) -> str: """Remove trailing whitespace from each line in the text.""" return '\n'.join(line.rstrip() for line in text.split('\n'))
def gcd(a, b): """ Calculates the greatest common divisor of two positive integers. The gcd of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. a, b: two positive integers Returns the greatest common divi...
def read(seq, serial, r=1, data=0): """print fastq record""" seqid = "@M00000-{} {}:0:{}".format(serial, r, data) qual = 'N' * len(seq) return "{}\n{}\n+\n{}".format(seqid, seq, qual)
def getposition(index): """ Return (latitude, longitude) as a tuple from a truble containing the (row, collum) index associated with the numpy matrix meaning (latitudeIndex, longitudeIndex) """ if (index[0] < 0 or index[0] >= 180): raise LookupError('latitude index is out of range') if (index[1] < 0 or index[1] ...
def isthai(text, check_all=False): """ :param str text: input string or list of strings :param bool check_all: checks all character or not :return: A dictionary with the first value as proportional of text that is Thai, and the second value being a tuple of all characters, along with true or false. ...
def insertion_sort(array): """This solution uses one `for` and one `while`.""" for i in range(1, len(array)): key = i j = i - 1 while j >= 0 and key < array[j]: array[j + 1] = array[j] j -= 1 array[j + 1] = key return array
def is_all_char(s, ch): """ All characters in 's' are 'ch'. """ for c in s: if c != ch: return 0 return 1
def get_frame_range(_st, _ed, _duration, _frame_num): """ :param _st: :param _ed: :param _duration: :param _frame_num: :return: """ return int(_st / _duration * _frame_num), int(_ed / _duration * _frame_num)
def _apply_to_first_n(f, x, n): """Helper: apply f to first n elements on the stack x if n > 0.""" if n < 1: return f(x) argument, rest = x[:n], x[n:] if n == 1: argument = argument[0] result = f(argument) if not rest: return result if n == 1: result = [result] result = list(result) + li...
def gift_list(number): """Generates the list of gifts for a given verse Parameters ---------- number: Integer The number of the verse we want the list for Returns ------- string The list of gifts """ gifts = { 1: 'a Partridge in a Pear Tree', 2: 'two...
def logFileCmpFunc(x,y): """ Comparison function for sorting the log file names. """ xNum = int(x.split('_')[1]) yNum = int(y.split('_')[1]) if xNum > yNum: value = 1 elif yNum > xNum: value = -1 else: value = 0 return value
def define_correlation_window(params_acquisition: dict): """Define the window over which the correlation is calculated inside the frame""" params_window = dict({'Elevational size mm': 1, 'Lateral size mm': 1, 'Axial size mm': 1, ...
def generate_csv(fname, fields, trait_list): """ Generate CSV called fname with fields and trait_list """ csv = open(fname, 'w') csv.write(','.join(map(str, fields)) + '\n') csv.write(','.join(map(str, trait_list)) + '\n') csv.close() return fname
def _config_from_cli(cli_args): """Parse command line config settings into more useful types. """ cli_config = dict((k, v) for k, v in cli_args.items() if v is not None) parse = { 'search_paths': lambda x: [path for path in x.split(',')], 'range': lambda x: [int(year) for year in x.spl...
def format_phone(value): """ takes a value with separated by dashes and returns it in the format: (415) 963-4949 """ phone = value.split("-") try: phone = "(%s) %s-%s" % (phone[0],phone[1],phone[2]) except: if value: phone = "(%s) %s-%s" % (value[:3],value[3:6],va...
def temp_to_str(temp, scale): """Prepare the temperature to draw based on the defined scale: Celcius or Fahrenheit""" if scale == 'F': temp = temp * 9/5 + 32 return f"{temp:.1f}"
def kid_rsa_private_key(a, b, A, B): """ Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`, `n = (e d - 1) / M`. The *private key* is `d`, which Bob keeps secret. Examples ======== >>> from sympy.crypto.crypto import kid_rsa_private_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_pri...
def first_n_primes(n): """Compute the first n prime numbers. Parameters ---------- n : int Number of prime numbers to compute. Returns ------- primes : list of int The first n prime numbers. Examples -------- >>> first_n_primes(4) [1, 2, 3, 5] >>> firs...
def shell(numbers): """Shell sort algorithm.""" inc = len(numbers) // 2 while inc: for i, n in enumerate(numbers): while i >= inc and numbers[i - inc] > n: numbers[i] = numbers[i - inc] i -= inc numbers[i] = n inc = 1 if inc == 2 else...
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: ? Space Complexity: ? """ # <-------- NEWMAN CONWAY CONCEPT --------> # P(1) = 1 # P(2) = 1 # for all n > 2 # P(n) = P(P(n - 1)) + P(n - P(n - 1)) # base case -...
def xyz_string_comment(xyz_str): """ Read the comment line of a string of a standard .xyz file. :param xyz_str: string obtained from reading the .xyz file :type xyz_str: str :rtype: str """ return xyz_str.splitlines()[1].strip()
def table(headers, matrix): """return string with markdown table (one-line cells only)""" def line1(string): return string.splitlines()[0] if string.splitlines() else '' def one_line_cells(cells, headers): cells = list(map(lambda s: line1(s).lstrip().rstrip(), cells)) if len(cells) ...
def _sort_cluster_arrays(arrays): """Calculates for the given array which is their natural order: minimum values < ... < maxium values Returns the given array sorted like this. DEPRECATED. Was used before creating sorting cluster dictionary. """ output = arrays for i in range(0, len(output)): for j...
def escape(literal): """ Escape the backtick in table/column name @param literal: name string to escape @type literal: string @return: escaped string @rtype : string """ return literal.replace('`', '``')
def compute_exact_score(predictions, target_lists): """Computes the Exact score (accuracy) of the predictions. Exact score is defined as the percentage of predictions that match at least one of the targets. Args: predictions: List of predictions. target_lists: List ...
def listUpTo(num): """ Returns a lists of integers from 1 up to num """ return list(range(1, num + 1))
def remove_gap_only(alignment): """ Find columns in the alignment where the entire column is '-', replace the '-' with 'P', then remove the '*'. """ if len(alignment) > 0: for entry in alignment: entry['seq'] = list(entry['seq']) for i in range(0,len(alignment[0]['s...
def measurements_available(key): """True if provided measurement key is valid. Parameters ---------- key : string Key to identify measurement type. Check BK984 manual for valid options. """ functions = ["CPD", "CPQ", "CPG", "CPRP", "CSD", "CSQ", "CSRS", "LP...
def mean(num_list): """ Computes the mean of a list of numbers. Parameters --------------- num_list: list List to calculate mean of Returns -------------- list_mean: float Mean of list of numbers """ list_mean = sum(num_list)/len(num_list) return list_mean
def pad_char_sequences(sequences): """ Pads a list of sequences with '0' to the length of the longest sequence """ pad_len = max([len(x) for x in sequences]) sequences = [seq.ljust(pad_len, '0') for seq in sequences] return sequences
def event_evaluation(s1, s2): """ Event-level evaluation of agreement between sequences s1 and s2 :param s1: sequence of decisions s1 :param s2: sequence of decisions s2 :return: event-level f1 metric """ used_1 = [0] * len(s1) found_1 = [0] * len(s1) used_2 = [0] * len(s2) found...
def qrGetRequiredGuides( skeletonParameters ): """ This method returns a list of the guides corresponding to the given skeleton parameters. It should be in sync with the output of: - qrGetGuidesFromEmbedding( ) """ guides = [ 'Reference' , 'Hips' , 'Head' , ...
def set_string_(bytearray_: bytearray, byte_index: int, value: str, max_size: int): """Set string value Args: bytearray_: buffer to write to. byte_index: byte index to start writing from. value: string to write. max_size: maximum possible string size. Raises: :obj:`Ty...
def twoStrings(s1, s2): """Compares two strings to find matching substring.""" for i in s1: if i in s2: return "YES" return "NO"
def space(string, cnt=1, pad=" "): """returns the blank-delimited words in string with cnt pad characters between each word. If you specify cnt, it must be a positive whole number or zero. If it is 0, all blanks are removed. Leading and trailing blanks are always removed. The default for cnt is 1, a...
def make_training_sample(relev_articles, irrel_articles): """ Builds the training sample Args: relev_articles: a list of relevant articles irrel_articles: a list of irrelevant articles """ all_articles = relev_articles + irrel_articles training_sample = "" for article in all_...
def remove_from(message, keyword): """ Strip the message from the keyword """ message = message.replace(keyword, '').strip() return message
def interpolate(curr_x, x_init, x_end, y_init, y_end): """ Compute an intermediate value between two points by linear interpolation """ m = (y_end - y_init)/(x_end - x_init) n = y_end - x_end * m return m * curr_x + n
def sort_string(s, key=None, reverse=False): """Returns a string.""" return u''.join(sorted(s, key=key, reverse=reverse))
def _shallow_dict_copy_without_key(table, key_to_omit): """Returns a shallow copy of dict with key_to_omit omitted.""" return {key: table[key] for key in table if key != key_to_omit}
def record(eventname, from_state): """ Returns a pre-formatted log line to save on the boilerplate """ return { '@version': '1', 'eventname': eventname, 'from_state': from_state, 'groupname': 'messages', 'level': 'INFO', 'logger_name': 'supervisor', ...
def _get_and_map_code_owner(row, owner_map): """ From a csv row, takes the theme and squad, update ownership maps, and return the code_owner. Will also warn if the squad appears in multiple themes. Arguments: row: A csv row that should have 'owner.theme' and 'owner.squad'. owner_map: A...
def handle_extend_type_attr(data): """ Validate and handle data_point type attribute """ extend_type_attr: dict = data['extendTypeAttr'] if data.get('extendTypeAttr') else {} point_data_type = data.get('pointDataType') if point_data_type == 1: # number point_data_type required_extend_at...
def _split_joins(join_string, only_join=False): """ Split a string into the field and it's joins, separated by __ as per Django convention """ split = join_string.split('__') field = split.pop(0) # the first field join = '__'.join(split) # the rest of the fields # return single join o...
def order_by_index(seq, index, iter=False): """\ Order a given sequence by an index sequence. The output of `index_natsorted` and `index_versorted` is a sequence of integers (index) that correspond to how its input sequence **would** be sorted. The idea is that this index can be used to reorder...
def tuple32(data): """ A helper to split a concatenated merkle proof into its individual elements. """ start = 0 end = 8 result = [] while end <= len(data): pair = (data[start:end - 4], data[end - 4:end]) result.append(pair) start = end end += 8 return r...
def _is_extension(data): """Detect if a package is an extension using its metadata. """ if 'jupyterlab' not in data: return False if not isinstance(data['jupyterlab'], dict): return False is_extension = data['jupyterlab'].get('extension', False) is_mime_extension = data['jupyterl...
def _str(s): """ Convert PTB tokens to normal tokens """ if s.lower() == "-lrb-": s = "(" elif s.lower() == "-rrb-": s = ")" elif s.lower() == "-lsb-": s = "[" elif s.lower() == "-rsb-": s = "]" elif s.lower() == "-lcb-": s = "{" elif s.lower() == "-rc...
def items_list(mapping, items): """Return a list of values from `mapping` in order of the given `items`.""" return [mapping[item] for item in items]
def isOK(http_response): """ return True for successful http_status codes """ if http_response < 300: return True return False
def combination(n: int, r: int) -> int: """ Returns the combination i.e nCr of given n and r >>> combination(5,3) 10 """ # If either n or r is 0, nCr = 1 if n == 0 or r == 0: return 1 # Initializing variables nFac = 1 rFac = 1 nrFac = 1 # A single for loop t...
def num_to_note(note_int: int, custom_map=None) -> str: """ Convert a musical pitch from integer representation to a string. "Merge" enharmonic equivalents, e.g. the integers for 'F#' and 'Gb' just become the string 'F#'. Args: note_int: The integer representation of a musical pitch. ...
def trim_link(url): """Remove unnessecary parts from the url.""" return url.split('?')[0]
def granules_to_urls(granules_idxs, urls): """ Takes an array of granules indexes granules_idx and urls array 'urls' and returns a list of urls that correspond to the indices. """ results = [] for idx in granules_idxs: results.append(urls[idx]) return results
def createGeoJSON(features):# [[coord1,cord2,cord3,...], row, column] """ createGeoJSON(features) From structure as [[coord1,cord2,cord3,...], row, column] creates a new geoJSON used for Surface Unit Parameters ---------- features : List Structure as [[coord1,cord2,cord3,...], row, ...