content
stringlengths
42
6.51k
def is_number(s): """ Check if a string s represents a number Parameters ---------- s : `str` String to check Returns ------- `bool` ``True`` if a string represents an integer or floating point number """ try: int(s) is_int = True exc...
def action_of(origin: str, destination: str) -> int: """Finds which action was taken from origin to destination. If the states origin and destination are separated by one action, it returns the numeric value of the action taken (0 = up, 1 = right, 2 = down, 3 = left). It returns -1 if they are separate...
def shortest_equivalent_path(path): """ Question 9.4: Normalize relative pathnames """ elts = path.split('/') realpath = [] for elt in elts: if not len(elt) or elt == '.': continue elif elt == '..': realpath.pop() else: realpath.append(...
def create_word_inds_dicts(words_counted, specials=None, min_occurences=0): """ creates lookup dicts from word to index and back. returns the lookup dicts and an array of words that were not used, due to rare occurence. """ missing_words ...
def h2i(a): """Decode hex string to int""" return int(a, 16)
def truncate(text: str, max_length: int) -> str: """Return text truncated to the max_length character if needed.""" if len(text) > max_length: return text[: max_length - 3] + "..." return text
def clean_bibtex_authors(author_str): """Convert author names to `firstname(s) lastname` format.""" authors = [] for s in author_str: s = s.strip() if len(s) < 1: continue if "," in s: split_names = s.split(",", 1) last_name = split_names[0].strip(...
def recursive_unicode(obj): """Walks a simple data structure, converting byte strings to unicode. Supports lists, tuples, and dictionaries. """ if isinstance(obj, dict): return dict((recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items()) elif isinstance(obj, list): r...
def MergeObjects(obj1, obj2): """Merges two objects (either dictionary, list, string or numbers).""" if type(obj1) != type(obj2): return obj2 if isinstance(obj2, dict): result = dict(obj1) for key in obj2: value1 = obj1.get(key, None) value2 = obj2.get(key, None) result[key] = Merge...
def nextCombination(listOfElements, combination, length): """Gets the next combination of a given length and elements Parameters ---------- listOfElements : list A list of elements allowed in the combination combination : list A list of elements contained in lisOfElements of len...
def omit_empty_items(sequence): """ Filters out sequence items which are :const:`None` or empty. If argument is :const:`None` than the return value is :const:`None` too, but if argument is an empty sequence, another empty sequence is returned. >>> list(omit_empty_items([])) [] >...
def read_annotation(annotation_string): """ Read the annotation string and return a dictionary with the annotation names as keys and the annotation values as values. """ annotation_dict = {} for annotation in annotation_string: annotation = annotation.split(':') annotation_dict[f"{an...
def insertion_sort_optimized(arr): """ a slightly faster version that moves A[i] to its position in one go and only performs one assignment in the inner loop body Time: O(n^2) Space: O(1) """ for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < a...
def is_mbi_format_valid(mbi): """ Validate MBI ID format. This includes the BFD's special case of an "S" in the 2nd position denoting a synthetic MBI value. Reference for MBI ID format: https://www.cms.gov/Medicare/New-Medicare-Card/Understanding-the-MBI-with-Format.pdf """ # Charac...
def remove_repetidos(lista): """ Recebe uma lista de inteiros e remove os repetidos e retorna uma lista ordenada. >>> remove_repetidos([2, 4, 2, 2, 3, 3, 1]) [1, 2, 3, 4] >>> remove_repetidos([1, 2, 3, 3, 3, 4]) [1, 2, 3, 4] :param lista: list :return: list """ list...
def get_http_body(http_request): """Given a HTTP request, return the body.""" return http_request.split("\r\n\r\n")[1]
def ML_sym(nbranch, ntree): """ Parameters ---------- nbranch: int The number of branches ntree: int the number of trees (non-trivials) Return ------ p: float (probability value) the best fitting value for the simple symmetric model """ p = float(nbranch)/...
def letterScore(letter, scorelist): """gets the score for a certain letter in the list""" if scorelist == []: return 0 first = scorelist[0] if first[0] == letter: return first[1] return letterScore(letter, scorelist[1:])
def set_in(input_data, path, value): """Set the value at the path in input_data. :param input_data: dict or list :param path: the path of the value to set, example: item.#1.name :param value: value to set :return: modified input_data """ if '*' in path: raise ValueError('* in path i...
def metadata_fn(book_id): """ Construct filename for metadata file. Args: book_id (int/str): ID of the book, without special characters. Returns: str: Filename in format ``meds_nk-BOOKID.xml``. """ return "mods_%s.xml" % str(book_id)
def list_to_string(list_of_anything, sep=";"): """ Helper function used for building the fields of a printable dataframe """ return sep.join(str(x) for x in list_of_anything)
def get_maxweight_params(**overrides): """ Get parameters for MaxWeight agent. If some parameter is not specified in overrides, then it takes a default value. :param overrides: Parameters coming from JSON file. :return: (weight_per_buffer, name) - weight_per_buffer: List whose entries weigh...
def relabel_inner_dicts(obj, key_map): """Update the keys of all dicts in a dict.""" for inner in obj.values(): for old_key, new_key in key_map.items(): inner[new_key] = inner.pop(old_key) return obj
def end_time(start_time) -> int: """Run 4 weeks.""" return start_time + 4 * 7 * 24 * 3600
def encode(message) -> str: """ Encode a string with run-length encoding\n Args: message: the message to encode Returns: the encoded string """ encoded_message = "" i = 0 while (i <= len(message) - 1): count = 1 ch = message[i] j...
def find_negative_temps(temps): """ Returns a new list with just the negative temperatures from temps. >>> find_negative_temps([-13, 45, -1, 0, 23]) [-13, -1] >>> find_negative_temps([]) [] >>> find_negative_temps([23, 36, 21]) [] >>> find_negative_temps([-30, -60, -10]) [-30, -60, -10] """ # Py...
def format_version(value, hero_version=False): """Formats integer to displayable version name""" label = "v{0:03d}".format(value) if not hero_version: return label return "[{}]".format(label)
def record_metadata(metrics, run): """ Send data to Neptune.ai :param metrics: metrics to log :param run: Neptune.new.Run :return: None """ # log them in Neptune for metric, value in metrics.items(): run[metric] = value return None
def data_has_value_from_substring_list(data, needle_list): """Recursively search for any values that contain a substring from the specified list Args: data (dict, list, primitive) needle_list (list) Returns: (bool) True or False if found """ if isinstance(data, list): ...
def get_source_detail(sources): """ Iterate over source details from response and prepare RiskSense context. :param sources: source details from response. :return: List of source details which includes required fields from resp. """ return [{ 'Name': source.get('name', ''), 'UuI...
def truncate(sequence): """ Do nothing. Just a placeholder. """ string = str(sequence) return string.split()[0]
def titleize(phrase): """Return phrase in title case (each word capitalized). >>> titleize('this is awesome') 'This Is Awesome' >>> titleize('oNLy cAPITALIZe fIRSt') 'Only Capitalize First' """ return " ".join([w.capitalize() for w in phrase.split()])
def Descending_Order(num): """ descending_order == PEP8 """ return int(''.join(sorted(str(num), reverse=True)))
def isNarcissistic(x): """Returns whether or not a given number is Narcissistic. A positive integer is called a narcissistic number if it is equal to the sum of its own digits each raised to the power of the number of digits. Example: 153 is narcissistic because 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 15...
def update_letter_view(puzzle: str, view: str, position: int, guess: str) -> str: """Return the updated view based on whether the guess matches position in puzzle >>> update_letter_view('apple', 'a^^le', 2, 'p') p >>> update_letter_view('banana', 'ba^a^a', 0, 'b') b >>> update_letter_view('bitt...
def bulk_events_to_event_pages(bulk_events): """ Transform a BulkEvents document into a list of EventPage documents. Note: The BulkEvents layout has been deprecated in favor of EventPage. Parameters ---------- bulk_events : dict Returns ------- event_pages : list """ # Thi...
def custom_props(extra_props): """ helper function for adding customDimensions to logger calls at execution time """ return {"custom_dimensions": extra_props}
def taber(msg, size): """ Function which tabulates strings. Example ------- >>> taber(msg='Example string', size=42) 'Example string ' """ return str(msg) + (size - len(str(msg)))*' '
def whitespace_around_comma(logical_line): """ Avoid extraneous whitespace in the following situations: - More than one space around an assignment (or other) operator to align it with another. JCR: This should also be applied around comma etc. """ line = logical_line for separator in...
def strStr(haystack, needle): """ :type haystack: str :type needle: str :rtype: int 72 / 72 test cases passed. Runtime: 49 ms """ if needle == "" or haystack == needle: return 0 size = len(needle) for i in range(len(hay...
def iterable_to_line(iterable): """ A utility function for outputting dfa - converts an iterable object (e.g. list) to one line string :param iterable: :return: returns one line string """ ret = '' for i in iterable: ret += str(i) + ' ' ret += '\n' return ret
def format_default_text(item: dict): """Creates the correct Slack text string based on the item context.""" if item.get("title_link"): return f"*<{item['title_link']}|{item['title']}>*\n{item['text']}" if item.get("datetime"): return f"*{item['title']}* \n <!date^{int(item['datetime'].timest...
def reverse(input_string): """Reverse a string. Useful for strings of binary numbers. >>> reverse('abc') 'cba' """ str_list = list(input_string) str_list.reverse() return ''.join(str_list)
def fix_date(date): """ Make sure the date has a uniform format. """ if len(date.split('-')[0]) == 2: date = '20' + date # Add century if '.' in date: date = date.split('.')[0] # Remove milliseconds return date
def PrevailingEOLName(crlf, cr, lf): """Describe the most common line ending. Args: crlf: How many CRLF (\r\n) sequences are in the file. cr: How many CR (\r) characters are in the file, excluding CRLF sequences. lf: How many LF (\n) characters are in the file, excluding CRLF sequences. Returns: ...
def _join_words(words, delimiter=",", conjunction="and"): """Join words together for nice printout. >>> _join_words(["first", "second", "third"]) 'first, second, and third' >>> _join_words(["first", "second"]) 'first and second' >>> _join_words(["first"]) 'first' """ if len(words) =...
def build_cz_text(cz_data, prefix): """ Create a summary of Conflict Zone activity """ if cz_data == {}: return "" text = "" if 'l' in cz_data and cz_data['l'] != '0' and cz_data['l'] != '': text += f"{cz_data['l']}xL " if 'm' in cz_data and cz_data['m'] != '0' and cz_data['m'] != '': text ...
def num_bits_for_value(x: int) -> int: """ Calculates the number if bits required to represent the given integer. """ num_bits = 0 while (x != 0): x = x >> 1 num_bits += 1 return max(num_bits, 1)
def str2bool(value): """ String to Boolean """ # because argparse does not support to parse "True, False" as python # boolean directly return value.lower() in ("true", "t", "1")
def label_format(model='yolo'): """ Return dnn model annotation format model : used model name, default a yolo """ try: model.lower() except AttributeError as e: print(model, "is not String Type \n" + "Debugging : Input String Parameters like 'yolo' \n...
def shutdown(opts, *args, **kw): """ Shuts down the service. """ # This is no-op method, which is required but makes nothing at this point. return True
def tshirt_code(tshirt_string): """ convert tshirt size strings into a code for us""" if not tshirt_string: return "" tshirt_code = "" if tshirt_string[0] == "f": tshirt_code += "0" tshirt_string = tshirt_string[1:] else: tshirt_code += "1" size_code = {"s": "1"...
def _get_platform_builder_group_name(platform_name): """ Returns the logGroup name of associated with the custom platform identified by `platform_name` :param platform_name: A custom platform whose logs to stream :return: """ return '/aws/elasticbeanstalk/platform/{}'.format(platform_name)
def character_tokenizer(line): """ Tokenize sentence based on NLTK's WordPunctTokenizer :param srt line: :rtype: List[str] """ tknzd = list(line) return tknzd
def toutf8(ustr): """Return UTF-8 `str` from unicode @ustr This is to use the same error handling etc everywhere if ustr is `str`, just return it """ if isinstance(ustr, str): return ustr return ustr.encode("UTF-8")
def max_le(seq, val): """ Same as max_lt(), but items in seq equal to val apply as well. >>> max_le([2, 3, 7, 11], 10) 7 >>> max_le((1, 3, 6, 11), 6) 6 """ idx = len(seq)-1 while idx >= 0: if seq[idx] <= val: return seq[idx] idx -= 1 return None
def label_counts(labels): """count occurences of each label""" unique_labels = sorted(list(set(labels))) counts = {k: 0 for k in unique_labels} for label in labels: counts[label] += 1 return [(label, counts[label]) for label in unique_labels], counts
def missing_digits(n): """Given a number a that is in sorted, increasing order, return the number of missing digits in n. A missing digit is a number between the first and last digit of a that is not in n. >>> missing_digits(1248) # 3, 5, 6, 7 4 >>> missing_digits(1122) # No missing numbers ...
def listify(to_list, None_as_list=False, prefix=None, padding=None): """ "Listify" the input, hopefully sensibly. Parameters ---------- to_list Thing to be listified. None_as_list : bool If False return None if to_list is None, otherwise return [None] prefix : str or None ...
def predicatize(term): """Formats a term (string) to look like a Predicate.""" # Replace spaces by underscores and lowercase first letter of a Predicate term term = term.replace(" ", "_") return term[0].lower() + term[1:]
def is_experiment(cfg): """ Check if the given configuration object specifies an :py:class:`~enrich2.experiment.Experiment`. Args: cfg (dict): decoded JSON object Returns: bool: True if `cfg` if specifies an :py:class:`~enrich2.experiment.Experiment`, else False. """...
def create_payload(item_type, item_id): """Helper function to create Post""" payload = { "type": item_type, "id": item_id, } return payload
def find_pos(ind, displs): """Find the position of ind relative to the displacement values stored in the displs list. This is used by MultipleDatasets objects; here displs[n] refers to the index of the first data point from dataset n. Args ---- ind : int A position index. displs : lis...
def extract(input_data: str) -> list: """take input data and return the appropriate data structure""" return [exp.rstrip() for exp in input_data.split('\n')]
def marked(word, mark): """ Return `true` iff `word` has a `mark` in front of it.""" return word[0] == mark
def json_int(int_string): """ Convert the string to an int or None on error. """ if int_string: try: return int(int_string) except ValueError: pass return None
def nth_item(n, generator): """Returns the `n`-th item yielded by `generator`. Item numbering starts from 0. """ for x in range(n): next(generator) return next(generator)
def hogid2fam(hog_id): """ For use with OMA HOGs Get fam given hog id :param hog_id: hog id :return: fam """ if not hog_id: return hog_id if type(hog_id) is int: return hog_id if ':' in hog_id: hog_id = hog_id.split(':')[1] if '.' in hog_id: ...
def find_difference(string1, string2): """ Find the differing character between strings. string2 must be one character longer than string1. """ assert len(string1) + 1 == len(string2) char_array = list(string2) # Iterates through the first string, popping characters out of the seco...
def bubble_sort(l): """ bubble sort algorithm: Time Complexity: O(n^2) """ j = 0 for i in range(len(l)-1): j = i+1 while j < len(l): if l[i] > l[j]: temp = l[j] l[j] = l[i] l[i] = temp j += 1 return l
def row_swap(matrix, row1, row2): """ Swaps two rows in a matrix :param matrix: list of lists :param row1: number of a row :param row2: number of a row :return: a list of lists """ if row1 != row2: matrix[row1], matrix[row2] = matrix[row2], matrix[row1] return matrix ...
def compare_dict_keys(dict1, dict2): """ Compare dict1 keys with dict2 keys and see if dict1 has extra keys compared to dict2 Parameters: dict1 (dict): response dict from API dict2 (dict): mock dict Returns: Set of keys """ return dict1.keys() - dict2.keys()
def iterPower(base, exp): """ base: int or float. exp: int >= 0 returns: int or float, base^exp """ res = 1 # <---- remember starting point while exp > 0: res *= base exp -= 1 return res
def isreal(x): """Returns a bool array, where True if input element is real. If element has complex type with zero complex part, the return value for that element is True. Args: x (cupy.ndarray): Input array. Returns: cupy.ndarray: Boolean array of same shape as ``x``. .. see...
def sequential_search(a_list, item): """Sequential search by iteration.""" pos = 0 is_found = False while pos < len(a_list) and not is_found: if a_list[pos] == item: is_found = True else: pos += 1 return is_found
def group_by(lst, column, comp_margin = None): """ Groups list entities by column values. """ sorted_values = [] result_list = [] current_value = None for i in range(0, len(lst)): x = lst[i] if x[column][0:comp_margin] in sorted_values or x[column][0:comp_margin] == current_...
def match_sp_sep(first, second): """ Verify that all the values in 'first' appear in 'second'. The values can either be in the form of lists or as space separated items. :param first: :param second: :return: True/False """ if isinstance(first, list): one = [set(v.split(" "))...
def _sort_dict_by_keys(dictionary: dict) -> dict: """ Utility method to recursively sort a dictionary by it's keys. Keys are sorted alphabetically in ascending order. :type dictionary: dict :param dictionary: input dictionary :rtype dict :return dictionary sorted by keys """ retur...
def probstr(prob): """Render probability / number of subtrees as string.""" if isinstance(prob, tuple): return 'subtrees=%d, p=%.4g ' % (abs(prob[0]), prob[1]) return 'p=%.4g' % prob
def nextpow2(value): """ Returns the next power of 2 integer larger than value. """ x = value - 1 npow2 = 1 << x.bit_length() return npow2
def _parse_pull_request(body): """ :type body: Dict[str, Any] :rtype: Tuple[str, str] """ if body['action'] not in {'opened', 'edited', }: # This indicates that this is not an applicable event. raise KeyError return ( body['pull_request']['body'], body['pull_requ...
def validate_preprocess_kwargs(preprocessing_kwargs): """ Tests the arguments of preprocess function and raises errors for invalid arguments. Parameters ---------- preprocessing_kwargs : dict-like or None or False A dictionary object to store keyword arguments for the preprocess function. ...
def replace_unicode(instr: str) -> str: """ Replace unicode-looking escape sequences with an ASCII equivalent. Args: instr (str): Input string. Returns: (str): Cleaned string. """ replacements = { '\u2010': '-', '\u2011': '-', '\u2012': '-', '\u20...
def _remove_empty_entries(entries): """Remove empty entries in a list""" valid_entries = [] for entry in set(entries): if entry: valid_entries.append(entry) return sorted(valid_entries)
def _learning_rate_schedule(global_step_value, max_iters, initial_lr): """Calculates learning_rate with linear decay. Args: global_step_value: int, global step. max_iters: int, maximum iterations. initial_lr: float, initial learning rate. Returns: lr: float, learning rate. """ lr = initial_l...
def convert_halflife(halflife): """Returns a decay constant given a half life. Parameters ---------- halflife : float A half life of a given isotope. Returns ------- float The decay constant of that isotope. Raises ------ None. """ retu...
def make_content_dict(input_string): """Method that takes an input string and returns a dict with characters as keys and occurrences as values""" frequency_dict = dict() for character in input_string: if character not in frequency_dict: frequency_dict[character] = 1 else: ...
def get_parent_index(child_index): """ Get the index of the given key's parent given the index of the child key. """ # The root of the tree is at index position 1 # and can have no parent if child_index == 1: return 0 return child_index // 2
def class_name(cls): """Return a string representing the class""" # NOTE: can be changed to str(class) for more complete class info return cls.__name__
def check_matches(list1, list2, num_matches): """ Check whether two lists of sites contain at least a certain number of matches between the two lists Args: :param list1: (List) list of sites :param list2: (List) list of sites :param num_matches: (int) number of matches we are looking for between...
def dns_name_encode(name): """ DNS domain name encoder (string to bytes) name -- example: "www.example.com" return -- example: b'\x03www\x07example\x03com\x00' """ name_encoded = [b""] # "www" -> b"www" labels = [part.encode() for part in name.split(".") if len(part) != 0] for label in labels: # b"www" -> ...
def is_proto_range(proto): """protocol range is 0-255""" try: val_int = int(proto) if val_int < 0 or val_int > 255: return False except Exception: return False return True
def qc_filter_get(columns, values, aliases=None, and_or='and'): """ Return an eveluation string to filter the rows of a queryset. This function takes the following arguments: o "columns" is a list of columns to be matched against items within the "values" parameter. o "values" is...
def indent(text, amount=4): """Indent each lines of the given string. Args: text (str): Text to indent amount (int): Number or character padding Returns: str: Indented text. """ return "".join(amount * " " + line for line in text.splitlines(True))
def similarity_hash(hash_digests): # type: (list[bytes]) -> bytes """ Creates a similarity preserving hash from a sequence of equal sized hash digests. :param list hash_digests: A sequence of equaly sized byte-hashes. :returns: Similarity byte-hash :rtype: bytes """ n_bytes = len(hash_...
def dataToComponent(data, component): """Converts data to the desired component. Parameters ---------- data : `dict`, `object` Data from which the component will be constructed. This can be an dictionary with keys that are exact match for parameters required by component, or a s...
def is_arbor(a): """ A valid arborization dict must adhere to the following schema: {'neurite': set, 'neuropil': str, 'regions': set} """ try: is_arbor.v(a) except: return False else: return True
def erd(active, rest): """The event-related de/sync formula. Output is in percents. If result is < 0, than what we have is ERD. Positive numbers denote ERS. """ return ((active-rest)/rest)*100
def list_math_addition_number(a, b): """! @brief Addition between list and number. @details Each element from list 'a' is added to number 'b'. @param[in] a (list): List of elements that supports mathematic addition. @param[in] b (double): Value that supports mathematic addition. ...
def per_at_1(ranking): """ todo """ if len(ranking) < 1: return 0 if int(ranking[0]) >= 4: return 1 else: return 0