content
stringlengths
42
6.51k
def __get_beta(beta, eta): """ Get and check the beta argument. The argument can be None (which then uses 0.4/eta) or a single value. The value must be positive and less than 1/eta. """ if beta is None: return 0.4/eta if beta <= 0 or beta >= 1/eta: raise ValueError('beta') return beta
def get_object_path(obj): """ :param obj: :return: """ return obj.__module__ + "." + obj.__name__
def unqote(text): """Strip pair of leading and trailing quotes from text.""" # -- QUOTED: Strip single-quote or double-quote pair. if ((text.startswith('"') and text.endswith('"')) or (text.startswith("'") and text.endswith("'"))): text = text[1:-1] return text
def _call_with_frames_removed(f, *args, **kwds): """remove_importlib_frames in import.c will always remove sequences of importlib frames that end with a call to this function Use it instead of a normal call in places where including the importlib frames introduces unwanted noise into the traceback...
def is_mca(config): """Returns whether or not the configured account is an MCA.""" return config.get('isMCA', False)
def capfirst(x): """Capitalize the first letter of a string.""" if not x: return x if not isinstance(x, str): x = str(x) return x[0].upper() + x[1:]
def non_negative_int(s: str) -> int: """ Return integer from `s`, if `s` represents non-negative integer, otherwise raise ValueError. """ try: n = int(s) if n < 0: raise ValueError return n except ValueError: raise ValueError('Must be non-negative inte...
def min_cw(l): """Return min value of a list.""" a = sorted(l) return a[0]
def infection_rate_logging(lesson_day, current_step, lesson_list, infection_rate_dic): """ Generate a current list containing the lesson classroom and infection rate. """ output_list = [] for one_lesson in lesson_list: if one_lesson in infection_rate_dic.keys(): temp_list = [str(lesson_d...
def normalize(features, mean, std): """ Normalizes features with the specificed mean and std """ return (features - mean) / std
def get_left_child_index(parent_index, heap): """ Get the index of the left child given the parent node's index. """ # Remember, this is a 1-based index. if parent_index * 2 >= len(heap): # There is no left child return 0 return parent_index * 2
def listAverage(input_list): """ This function finds the average value in a list :param list input_list: a list of all integer values :return float average: calculated list average """ if len(input_list) < 1: print("\nCannot take average. List has length=0\n") # raise IndexError...
def create_deposition_metadata(title, upload_type, description, creators): """ creators = [{'name': 'Doe, John', 'affiliation': 'Zenodo'}] """ return {'title': title, 'upload_type': upload_type, 'description': description, 'creators': creators ...
def defined_submodule(arr): """ Check if model uses submodules """ return any([el.endswith('_module]') for el in arr])
def format_value(value, datatype): """ Format a value for a CSV file, escaping double quotes and backslashes. None maps to empty. datatype should be 's' for string (escaped) 'n' for number 'd' for datetime """ if value is None: return '' elif datatype == 's': ...
def increment_index_versions(client, old_indices: list): """ Increment versions numbers for new indices, these kind don't matter because they should always be aliased to the original format of {app_label}_{cls.__name__.lower()}_{year}. :param old_indices: indices to be updated :return: indices name...
def double_quote(raw_string: str) -> str: """Return raw_string after stripping white space and double quoting.""" raw_string = raw_string.strip('"') return '"' + raw_string + '"'
def format_descriptor(descriptors): """ formats a descriptor dictionary Args: descriptors(dict): the descriptor dictionary Returns: String: formated string to show dict """ string_descriptors = '' for entry in descriptors: string_descriptors = (string_descriptors + ...
def mandelbrot(cx, cy, maxiter): """Calculate number of iterations for given complex number to escape from set.""" c = complex(cx, cy) z = 0 for i in range(0, maxiter): if abs(z) > 2: return i z = z ** 3 + c return 0
def rangeSum(*, lowIncl, highIncl): """Compute sum(range(lowIncl, highIncl + 1)).""" gap = highIncl - lowIncl + 1 return (lowIncl + highIncl) * gap // 2
def thickness(points): """Find contour thickness in x and y dimensions. This method determines contour thickness (i.e., maximal extent/width) in x and y dimensions given a set of contour points. Thickness is defined as the maximal difference between two points along that dimension. Args: p...
def check_multiple_close(a, b, tol=1e-8): """check if a = b*i +- tol where i = 1,2,3,4,... :param a: :param b: :param tol: :return: """ remainder = a % b if remainder < tol: return True else: assert b > remainder, "something wrong." if (b - remainder) < tol: ...
def hello(who: str = 'world') -> str: """Return a greeting. :param who: Who to greet. """ if who: return f'Hello {who}! Hi!' else: return f'Hello! Hi!'
def when_did_student_drop(activity, weeks): """ Determine when did a student drop out of the course given the student activity. """ if activity[-1] == True: return -1 else: activity = list(activity) activity.reverse() return weeks[len(activity) - activity.index(True)]
def check_namespace_name(namespace_name): """Check if namespace name is valid.""" if namespace_name.isalnum() is False: return False if len(namespace_name) > 15: return False return True
def check_palindrome(s): """Checks whether the given string is palindrome""" if s == s[::-1]: return True
def _make_listlist(x): """ Helper function to clean up arguments. INPUT: - ``x`` -- ``None`` or an iterable of iterables. OUTPUT A list of lists. EXAMPLES:: sage: import sage.geometry.polyhedron.misc as P sage: [] == P._make_listlist(tuple()) True sage: ...
def partition(iterable, predicate): """ >>> partition('12321233221', lambda c: int(c) % 2 == 0) (['2', '2', '2', '2', '2'], ['1', '3', '1', '3', '3', '1']) """ falses = [] trues = [] for item in iterable: if predicate(item): trues.append(item) else: ...
def binlist2int(x): """Convert a list of binary digits to integer""" return int("".join(map(str, map(int, x))), 2)
def find_smallest(num_vars): """Find the smallest exponent of two that is greater than the number of variables Parameters ---------- num_vars : int Number of variables Returns ------- x : int Smallest exponent of two greater than `num_vars` """ for x in range(10...
def create_count_neighbors_ca1d(width): """ Returns a list with the weights for 'neighbors' and 'center_idx' parameters of evodynamic.connection.cellular_automata.create_conn_matrix_ca1d(...). The weights are responsible to count the number of alive neighbors. Parameters ---------- width : int Neig...
def _remove_empty_params(dict): """Returns copy of dictionary with empty values removed. Keyword arguments: dict -- Dictionary to process """ return {k: v for k, v in dict.items() if v is not None}
def hit(row, column, fleet): """ This method returns a tuple (fleet, ship) where ship is the ship from the fleet that receives a hit by the shot at the square represented by row and column, and fleet is the fleet resulting from this hit. :param row: int :param column: int :param fleet: lis...
def FormatBytesSize(num): """ Given an integer value of bytes, convert to the most appropriate units ('bytes', 'kB', 'MB', 'GB', ...), and return a string containing the number of units and the unit label ('bytes', 'kB', 'MB', 'GB', ...) """ base = 1024 for unit in ['bytes', 'kB', 'MB', 'GB...
def dict_raise_on_duplicates(ordered_pairs): """ Reject duplicate keys. """ d = {} for k, v in ordered_pairs: if k in d: raise ValueError("duplicate key: %r" % (k,)) else: d[k] = v return d
def is_range_superset_of_range(superset_range, subset_range): """Are all the elements of subset_range elements of superset_range? """ if subset_range.start not in superset_range: return False if subset_range.step % superset_range.step != 0: return False if subset_range[-1] > superset...
def is_int(value): """Check if the given value is an integer. @param value: The value to check @type value: str, or int @return bool """ try: int(value) return True except (ValueError, TypeError): return False
def filter_none(kwargs): """ Remove all `None` values froma given dict. SQLAlchemy does not like to have values that are None passed to it. :param kwargs: Dict to filter :return: Dict without any 'None' values """ n_kwargs = {} for k, v in kwargs.items(): if v: n_kw...
def checkIfExist(arr): """ :type arr: List[int] :rtype: bool """ final_output = 'false' arr.sort(reverse=True) print(arr) print (len(arr)-1) for i in range(len(arr)): j=i+1 print(j) while j<len(arr)-1: if arr[i] == 2 * arr[j]: final...
def is_chinese(tokens): """Judge if the tokens are in Chinese. The current criterion is if each token contains one single character, because when the documents are in Chinese, we tokenize each character when formatting the dataset. """ is_of_len_1 = all([len(t)==1 for t in tokens[:100]]) return is_of_len_1
def _get_container_name(prefix, image_uri): """ Create a unique container name based off of a test related prefix and the image uri :param prefix: test related prefix, like "emacs" or "pip-check" :param image_uri: ECR image URI :return: container name """ return f"{prefix}-{image_uri.split(...
def findEmpty(grid): """[Find next 0 in grid] Args: grid ([2D Array]): 2D Matrix to represent sudoku grid Returns: (Y,X): positon of next 0 in grid False: if no 0 found """ for i in range(9): for j in range(9): if grid[i][j] == 0: ...
def get_class_path(cls) -> str: """ Utility for building the class path """ return f"{cls.__module__}.{cls.__name__}"
def frequencies(words): """ Parameters ---------- words : LIST Get the frequency each word occurs Returns ------- Dictionary of words and its frequency as its value """ freq_dict = {} for word in words: if word in freq_dict: freq_dict[word] += 1 ...
def escape_string(s): """Escapes double-quote, tab and new line characters in a string.""" s = s.replace('"', '\\"') s = s.replace("\t", "\\t") s = s.replace("\n", "\\n") return s
def calculate_predicted_solo_points(calculated_data): """Predicts the points that a team would score by themselves. calculated_data is the data for a team that is calculated in the 'team_calculations()' function. Used to calculate the team's ability to complete each of the scoring objectives.""" sa...
def clean_labels(_labels, keep=1): """An input list of string numeric labels is split and casted to int Args: _labels (list): List of strings to be processed keep (int, optional): [description]. Defaults to 1. Tells the function if either the labels or the value is to be kept R...
def cumsum(iter): """ Cumulative sum: >>> pydigree.cumsum([0,1,2,3,4]) [0, 1, 3, 6, 10] :param iter: the iterable to be cumsum'ed Returns: cumulative sums :rtype: integer """ if not iter: return [] value = 0 g = [None] * len(iter) for idx, x in enumerat...
def _append_sep(line, syntax): """Append statement separator to `line`. Omit separator if entire `line` is a comment. Raise `ValueError` if `line` contains code and comment. """ com = syntax['COMMENT'] if line.startswith(com): return line if com in line: raise ValueError(lin...
def check_angle(angle): """Check ``angle`` parameter and return as `int`. Parameters ---------- angle : {0, 90, -90} Returns ------- int Raises ------ ValueError """ if angle not in [0, 90, -90]: raise ValueError("'angle' must be 0, 90, or -90") return int...
def find_node(nodes, *values): """Find the node having all of the search values. Parameters ---------- nodes : dict each key is a node name each value is a 2-tuple containing up to two values flowing through the node values : *args every value in values must ...
def already_cached(finder): """ Checks to see if the finder class has already been modified. @param finder - Class that should contain a find_metrics method. """ return hasattr(finder, '__cached_find_metrics__')
def parse_chunks(arg): """Returns file name, chunks, and frame number. File string format: file-<filename>.<framenum>.<chunk1>%<chunk2>%<chunk3>&user_or_cache """ filestr = arg.split('&')[0] binarystr = arg.split('&')[1] if filestr.find('file-') != -1: filestr = (filestr.split('...
def heptagonal(n: int) -> int: """ Heptagonal Number Conditions: 1) n >= 0 :param n: non-negative integer :return: nth heptagonal number """ if not n >= 0: raise ValueError return n*(5*n - 3)//2
def identifiersFrom(hits): """ Convert iterable of hits into list of integer unique identifiers. """ return [int(h.uniqueIdentifier) for h in hits]
def monomial_min(*monoms): """ Returns minimal degree for each variable in a set of monomials. Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`. We wish to find out what is the minimal degree for each of `x`, `y` and `z` variables:: >>> from sympy.polys.monomialtools impo...
def _update_grid_rows_with_candidate(grid_rows, row_index, col_index, candidate): """ update rows with candidate function :param row_index: :param col_index: :param candidate: :return: """ grid_rows[row_index][col_index] = candidate return grid_rows
def get_longest_str(l): """ Get the string length of the element with the longest string representation """ max_len = 0 obj_w_max = None for thing in l: string = len(str(thing)) if string > max_len: max_len = string obj_w_max = thing return max_le...
def is_sorted(array): """ Helper function to check if the given array is sorted. :param array: Array to check if sorted :return: True if sorted in ascending order, else False """ for i in range(len(array) - 1): if array[i] > array[i + 1]: return False return True
def format_table(table): """ Convert a list of tuples into a pretty tabulated table. :param table: List of tuples, each one will be a row of the printed table """ col_width = [max(len(x) for x in col) for col in zip(*table)] result = "" for line in table: result += "%s\n" % ((" " * 3...
def convert_array(a): """Converts a numpy array into tuples recursively""" try: return tuple(convert_array(i) for i in a) except TypeError: return a
def _median(collection): """ Calculates the median of an collection, eg a list. """ ordered = sorted(collection) len_ = len(collection) middle = len_ // 2 if not ordered: return -1 elif len_ % 2 == 1: return ordered[middle] else: return (ordered[middle - 1] + ordered...
def args_to_list(arg_string): """ Parses argument-string to a list """ # Strip whitespace -> strip brackets -> split to substrings -> # -> strip whitespace arg_list = [x.strip() for x in arg_string.strip().strip("[]").split(',')] return arg_list
def get_ext_cons_prod(producer_list, consumer_list, xml_producer_function_list, xml_consumer_function_list): """Get external cons/prod associated to main_fun_elem allocated functions""" external_function_list = set() for elem in consumer_list: if not any(elem[0] in s for s in p...
def get_body_from_division(division): """ Returns a body from a given division. (e.g. "04" returns "house"). """ if division == "sen" or division == "sen-special": return "senate" if division == "gov": return "governor" else: return "house"
def augment(matlist, column, K): """ Augments a matrix and a column. Examples ======== >>> from sympy.matrices.densetools import augment >>> from sympy import ZZ >>> a = [ ... [ZZ(3), ZZ(7), ZZ(4)], ... [ZZ(2), ZZ(4), ZZ(5)], ... [ZZ(6), ZZ(2), ZZ(3)]] >>> b = [ ... [ZZ...
def calculate_accuracy_overall(actual_labels, predicted_labels): """ Calculate accuracy percentage for all labels (classes). """ correct = sum(1 for i in range(len(actual_labels)) if actual_labels[i] == predicted_labels[i]) return correct / len(actual_labels) * 100.0
def SmartSize(x): """ Given a size, return it as bytes, k, m, g, or t. This will round it down to that """ size_table = [ ["", 1024, 1], ["k", 1024 * 1024, 1024], ["m", 1024 * 1024 * 1024, 1024 * 1024], ["g", 1024 * 1024 * 1024 * 1024, 1024 * 1024 * 1024], ["t...
def get_seat_id(row, col): """ Get position of the seat and return its Seat ID. """ return row * 8 + col
def zigzag2(i, curr=.45, upper=.48, lower=.13): """ Generalized version of the zig-zag function. Returns points oscillating between two bounds linearly. """ if abs(i) <= (upper-curr): return curr + i else: i = i - (upper-curr) i = i%(2*(upper-lower)) if i < (u...
def src_as_binary(source, size=8): """Convert str/bytes object into 0's and 1's.""" if isinstance(source, str): return [format(ord(char), f'0{size}b') for char in source] return [format(char, f'0{size}b') for char in source]
def wrap_text_to_lines(string, max_chars): """wrap_text_to_lines function A helper that will return a list of lines with word-break wrapping :param str string: The text to be wrapped :param int max_chars: The maximum number of characters on a line before wrapping :return list the_lines: A list of ...
def fib_list(n): """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a + b return result
def reveal_magic(source: str) -> str: """ Reveal any notebook magic hidden by hide_magic(). """ return source.replace("###MAGIC###", "")
def _FirewallSourceTagsToCell(firewall): """Comma-joins the source tags of the given firewall.""" return ','.join(firewall.get('sourceTags', []))
def format_offenders(control): """Summary Args: control (TYPE): Control Returns: TYPE: Formatted offender """ offenders_links = '' # print(control) if control['Offenders']: if not 'OffendersLinks' in control: # Just output the offenders. of...
def get_neighbor_index(i, j): """ 1 6 2 center 5 3 4 return index of neighbor 1, 2, 3, 4, 5,6 in the matrix """ neighbor_matrix_ids = [] if j % 2 == 0: neighbor_matrix_ids = [[i - 1, j ], ...
def MergePList(plist1, plist2): """Merges |plist1| with |plist2| recursively. Creates a new dictionary representing a Property List (.plist) files by merging the two dictionary |plist1| and |plist2| recursively (only for dictionary values). Args: plist1: a dictionary representing a Property List (.plist...
def batchify(instances, batch_size=32): """splits instances into batches, each of which contains at most batch_size""" batches = [instances[i:i + batch_size] if i + batch_size <= len(instances) else instances[i:] for i in range(0, len(instances), batch_size)] return batches
def profile_most_probable_kmer_noPR(text, k, profile): """[a kmer that was most likely to have been generated by profile among all kmers in text] Dependancies: probability_kmer Args: text ([string]): [string to be searched against] k ([int]): [determines length of kmer] ...
def clip_slice(idx, dim): """ Clip slice to its effective size given the shape. Parameters ---------- idx : The index. dim : The size along the corresponding dimension. Returns ------- idx : slice Examples -------- >>> clip_slice(slice(0, 20, 1), 10) slice(0, 10, 1...
def _get_koji_task_result_package_name(path): """ Strips the package name from a koji rpm result. This makes the assumption that rpm names are in the following format: <package_name>-<version>.<release>.<arch>.rpm For example, given a koji rpm result might look like: tasks/6745/9666745/kernel...
def istext(s, text_characters="".join(map(chr, range(32, 127))) + "\n\r\t\b", threshold=0.30): """ Helper to attempt support of serializing binary text by base64 encoding `s` if this returns False Credit: https://www.oreilly.com/library/view/python-cookbook-2nd/0596007973/ch01s12.html """ if isinst...
def _joinclass(codtuple): """ The opposite of splitclass(). Joins a (service, major, minor) class-of- device tuple into a whole class of device value. """ if not isinstance(codtuple, tuple): raise TypeError("argument must be tuple, was %s" % type(codtuple)) if len(codtuple) != 3: ...
def selection_sort(array): """Selection sort.""" length = len(array) for i in range(length - 1): val = array[i] k = i for j in range(i + 1, length): if array[j] < val: k = j val = array[j] array[i], array[k] = array[k], array[i] ...
def _convert_recipes_to_seller_counts(ps_recipes: list, num_categories:int)->list: """ >>> logger.setLevel(logging.INFO) >>> _convert_recipes_to_seller_counts([[1,0,1],[0,1,2]], 3) [1, 2] >>> _convert_recipes_to_seller_counts([[1,0,0,3],[0,1,0,4],[0,0,1,5]], 4) [3, 4, 5] """ map_buyer_ca...
def pgnum_from_pgint(pgint): """ Return the number of the pointgroup (from 1 to 32) from the international pointgroup name. """ table = { u"C1": 1, u"C2": 3, u"C2h": 5, u"C2v": 7, u"C3": 16, u"C3h": 22, u"C3i": 17, u"C3v": 19, u...
def fill_leaf_values(tree): """ Recursive function that populates empty dict leaf nodes. This function will look for all the leaf nodes in a dictionary and replace them with a value that looks like the variable in the template - e.g. {{ foo }}. >>> fill_leaf_values({'a': {}, 'b': 'c': {}})...
def kw_cases(keyword): """ Returns 3 variations on a passed keyword string: uppercase, lowercase, and Title Case. """ return [keyword.upper(), keyword.lower(), keyword.title()]
def longuest_common_prefix(s, t, compare_function=None): """Return the longest common prefix of s and t. :param s: a string :param t: a string :param compare_function: a function for comparing two items :type s: str :type t: str :type compare_function: function (musta take 2 args) ...
def get_time_info(diff): """Return a human representation based of the delta against current time""" if diff > 60 * 24 * 3600: desc = '%d+ months ago' % (diff/(30*24*3600)) color = 'hot1' elif diff > 2 * 24 * 3600: desc = '%d+ days ago' % (diff/(1*24*3600)) color = 'hot2' ...
def get_equipment_slot_string(equipment_item) -> str: """ This function is called specifically for the print_character_equipment function in information_printer.py Returns the string representation of an Equipment object or returns empty if there is no such item. """ if equipment_item: retur...
def trapc(f, a, b, m): """Composite trapezoid rule for function f on [a,b]""" h = 1.0*(b-a)/m sum = 0 for i in range(1,m+1): x = a + i*h if i==0 or i==m: sum += 0.5*f(x) else: sum += f(x) return h*sum
def calculate_mean(nums): """Calculate the meand of a given list of numbers.""" mean = sum(nums) / len(nums) return mean
def as_property(fact): """Convert a fact name to the name of the corresponding property""" return 'is_%s' % fact
def build_client_response_topic(user_id: str, app_id: str) -> str: """ Builds the MQTT topic where the device sends back ACKs to commands :param app_id: :param user_id: :param client_uuid: :return: """ return f"/app/{user_id}-{app_id}/subscribe"
def resolve_argument_type(arg_type, source_type): """ Alter type based on source file type :param arg_type: :param source_type: :return: """ if arg_type == "frame_or_time": if source_type == "audio": return "time" else: return "int[0:1000000000]" # Fra...
def get_dct_subset(dct, keys): """ Returns a subset of the dictionary, limited to the input keys """ return dict((k, dct[k]) for k in keys if k in dct)
def image_check(link: str): """ Function that checks the passed in link's end extension. Parameters ---------- link: str the link to check for Returns ------- bool whether or not the passed in link contains "image" format ending """ return link.lower().endswith(...
def BinarySearch(arr, target): """ :type nums: List[int] :type target: int :rtype: int """ low = 0 high = len(arr)-1 while low <= high: mid = (low+high)//2 if arr[mid] == target: return mid elif arr[mid] < target: low = mid + 1 else: high = mid - 1