content
stringlengths
42
6.51k
def natural_sort(key): """Sort numbers according to their value, not their first character""" import re return [int(t) if t.isdigit() else t for t in re.split(r'(\d+)', key)]
def kernel_sum(x, y, kernels, kernels_args, kernels_weights=None): """ Sum of arbitrary kernel functions. :param x: (``numpy.ndarray``) Data point(s) of shape ``(n_samples, n_features)`` or ``(n_features, )``. :param y: (``numpy.ndarray``) Data point(s) of shape ``(n_samples, n_features)`` or ``(n_featu...
def site_bit(number, N, site): """ 0/1 bit of the i-th atom in the base of N atoms chain from left-side :param number: state base :param N: length of atoms chain :param site: index of the atom in the atoms chain :return: 0/1 """ return number >> (N-site) & 1
def of_type(ts): """ >>> of_type({'kind': 'OBJECT', 'name': 'User', 'ofType': None}) 'User' >>> of_type({'kind': 'NON_NULL', 'name': None, 'ofType': {'kind': 'SCALAR', 'name': 'String', 'ofType': None}}) 'String' >>> of_type({"kind": "ENUM", "name": "ProjectState"}) 'ProjectState' """ ...
def _join_list(lst, oxford=True): """Join a list of words in a gramatically correct way.""" if len(lst) > 2: s = ', '.join(lst[:-1]) if oxford: s += ',' s += ' and ' + lst[-1] elif len(lst) == 2: s = lst[0] + ' and ' + lst[1] elif len(lst) == 1: s = ls...
def filename_from_url(url): """Extract and returns the filename from the url.""" return url.split("/")[-1].split("?")[0]
def update_average(field, value, tracked) -> float: """Updates a previously calculated average with a new value. Args: field: the current average; value: the new value to include in the average; tracked: the number of elements used to form the _original_ average Returns: fl...
def get_recursive(d, key, default=None): """ Gets the value of the highest level key in a json structure. key can be a list, will match the first one """ if isinstance(key, (list, tuple, set)): for k in key: value = get_recursive(d, k) if value != None: ...
def str_igrep(S, strs): """Returns a list of the indices of the strings wherein the substring S is found.""" return [i for (i,s) in enumerate(strs) if s.find(S) >= 0] #return [i for (s,i) in zip(strs,xrange(len(strs))) if s.find(S) >= 0]
def boolean(value): """Test truth value. Convert the string representation of a truth value, such as '0', '1', 'yes', 'no', 'true', or 'false' to :class:`bool`. This function is suitable to be passed as type to :meth:`icat.config.BaseConfig.add_variable`. """ if isinstance(value, str): ...
def readable_size(nbytes): """ Translate a number representing byte size into a human readable form @param nbytes: number representing bytes @type nbytes: int @return: readable size @rtype : string """ suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] if nbytes == 0: retur...
def get_subsegments(merged_segs, max_subseg_dur=3.0, overlap=1.5): """Divides bigger segments into smaller sub-segments """ shift = max_subseg_dur - overlap subsegments = [] # These rows are in RTTM format for row in merged_segs: seg_dur = float(row[4]) rec_id = row[1] ...
def extract_commit_msgs(output, is_git=True): """ Returns a list of commit msgs from the given output. """ msgs = [] if output: msg = [] for line in output.split('\n'): if not line: continue is_commit_msg = line.startswith(' ') or not line ...
def find_match(list_substrings, big_string): """Returns the category a trace belongs to by searching substrings.""" for ind, substr in enumerate(list_substrings): if big_string.find(substr) != -1: return ind return list_substrings.index("Uncategorized")
def longest_common_substring(s1, s2): """ References: # https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python2 """ m = [[0] * (1 + len(s2)) for i in range(1 + len(s1))] longest, x_longest = 0, 0 for x in range(1, 1 + len(s1)): for y in ran...
def coq_param(name, type): """Coq parameter Arguments: - `name`: name of the variable - `type`: type of the variable """ return "Parameter {0!s} : {1!s}.\n".format(name, type)
def dictionary_addition(dictionaries): """Add corresponding values in dictionary.""" keys = list(set([key for dictionary in dictionaries for key in dictionary])) added_dict = dict((key, 0) for key in keys) for dictionary in dictionaries: for key, value in dictionary.items(): added_di...
def is_floatstr(s): """ test if a string can be converted to a float """ try: float(s) return True except ValueError: return False
def marks_validator_pipe(data, config): """ Pipe to validate the marks' entries for every student. Checks happening here: 1. If marks for a particular subject exceed the maximum possible marks """ subjects = config.get("subjects") for row in data: if "Subjects" in row: fo...
def is_sorted(values, ascending=True): """Return True if a sequence is sorted""" for i, j in zip(values, values[1:]): if ascending and i > j: return False if not ascending and i < j: return False return True
def array_str(array, fmt='{:.2f}', sep=', ', with_boundary=True): """String of a 1-D tuple, list, or numpy array containing digits.""" ret = sep.join([fmt.format(float(x)) for x in array]) if with_boundary: ret = '[' + ret + ']' return ret
def target_variables(byte): """variables that will be profiled""" return ["rin", "rout"] + [ f"{base}_{byte}" for base in ("x0", "x1", "xrin", "yrout", "y0", "y1") ]
def search(lst: list, target: int): """search the element in list and return index of all the occurances Args: lst (list): List of elements target (int): Element to find Returns: list: list of index. """ left = 0 right = len(lst) - 1 mid = 0 index = [] whi...
def rjust(value, arg): """ Right-aligns the value in a field of a given width Argument: field size """ return value.rjust(int(arg))
def cloudsearch_to_django_id(s): """ convert cloudsearch index field names to haystack ids """ return s.replace('__', '.')
def diff_to_step(min, max, step, value): """Returns '0' if value is in step or how much value should change to reach step""" round_by = len(str(value).split('.')[1])#round the value to avoid many decimal ponit 1 stuff in result if ( min == max and (min != None or min == '') ) or step == None or step == ''...
def updateModulesIdList(campaign,m): """Updates the Modules ID list (main use is the argparse choices)""" modules_ids = [] for c in campaign: modules_ids.insert(len(modules_ids),c["id"]) if len(modules_ids) > 0 and m != "edit": modules_ids.insert(len(modules_ids),"all") return modul...
def strip_spaces_list(list_in, strip_method="all"): """ Remove spaces from all items in a list :param list_in: :param strip_method: Default: 'all' for leading and trailing spaces. Can also be 'leading' or 'trailing' :return: List with items stripped of spaces """ if strip_method == "all...
def percentage(x, pos): """ Adds percentage sign to plot ticks. """ return '%.0f%%' % x
def _h(key: str, mkg=None): """An gettext (...) Args: key ([str]): Key term. If MKG is none, will return this mkg ([dict], optional): An dict to search by falues. Defaults to None. Returns: [str]: The result """ if mkg: if key in mkg: return mkg[key] ...
def validate_timestamp(timestamp, label, required=False): """Validates the given timestamp value. Timestamps must be positive integers.""" if timestamp is None and not required: return None if isinstance(timestamp, bool): raise ValueError('Boolean value specified as timestamp.') try: ...
def repeat(x, nTimes, assertAtLeastOneRep=False): """ Repeat x nTimes times. Parameters ---------- x : tuple or Circuit the operation sequence to repeat nTimes : int the number of times to repeat x assertAtLeastOneRep : bool, optional if True, assert that nTimes > 0. ...
def artists_to_mpd_format(artists): """ Format track artists for output to MPD client. :param artists: the artists :type track: array of :class:`mopidy.models.Artist` :rtype: string """ artists = list(artists) artists.sort(key=lambda a: a.name) return u', '.join([a.name for a in art...
def toggle_navbar_collapse(n_clicks: int, is_open: bool) -> bool: """Toogle navigation bar on mobile devices Arguments: n_clicks {int} -- number of clicks is_open {bool} -- is navigation bar open Returns: bool -- new state of navigation bar """ if n_clicks: return n...
def is_palindrome(phrase): """Is phrase a palindrome? Return True/False if phrase is a palindrome (same read backwards and forwards). >>> is_palindrome('tacocat') True >>> is_palindrome('noon') True >>> is_palindrome('robert') False Should ignore capi...
def convert_to_DNA(sequence): """ Converts RNA to DNA """ sequence = str(sequence) sequence = sequence.upper() return sequence.replace('U', 'T')
def convert_text_to_html(sam_input_file_path): """ sam_input_file_path: String; Absolute path to SAM.inp for current run returns: String; SAM.inp as HTML, where endline chars are replace with <br> Converts SAM.inp from text file to HTML. """ html = "<br><b>SAM.inp created:</b><br>" with ...
def power_series(z, cs): """ returns cs[0] + cs[1] * z + cs[2] * z ** 2 + ... + cs[-1] * z ** (len(cs) - 1) """ s = cs[-1] for c in reversed(cs[:-1]): s *= z s += c return s
def bootstrap_button(text, **kwargs): """ Render a button """ button_type = kwargs.get('type', '') button_size = kwargs.get('size', '') button_disabled = kwargs.get('disabled', False) and kwargs.get('enabled', True) button_icon = kwargs.get('icon', '') # Build button classes button_...
def smart_round_format(number, precision): """ Args: number (float): precision (int): Returns: str: Examples: >>> smart_round_format(258.658, 2) '258.66' >>> smart_round_format(0.258658, 2) '0.26' >>> smart_round_format(0.0000258658, 2) ...
def convertSucPrecListToString(spList): """Method to convert the integer, integer list or None to comma seperated values for server returns None is the input is None, else returns a stirng with comma seperated values""" if spList is None: return None else: resList=None if ...
def calc_merge_track_num(num_tracks: int, max_tracks: int) -> int: """Calculate the number of tracks to concatenate so that the final number of tracks generated is less than MAX_TRACKS Args: num_tracks (int): The number of tracks max_tracks (int): The maximum number of tracks possible ...
def make_add_rich_menu(name, size, areas): """ add rich menu content: reference - https://developers.worksmobile.com/jp/document/1005040?lang=en You can create a rich menu for the message bot by following these steps: 1. Image uploads: using the "Upload Content" API 2. Rich menu ge...
def create_media_url(submission, reddit): """Read video url from reddit submission""" media_url = "False" try: media_url = submission.media['reddit_video']['fallback_url'] media_url = str(media_url) except Exception as e: print(e) try: crosspost_id = submissio...
def check_if_exactly_equal(list_1, list_2): """ Referenced and pulled from: https://thispointer.com/python-check-if-two-lists-are-equal-or-not-covers-both-ordered-unordered-lists/ Checks if two lists are exactly identical :param list_1 (list): generic list list_2 (list): generic lis...
def sse_pack(event_id: int, event: str, data: int, retry: str = "2000") -> str: """Pack data in Server-Sent Events (SSE) format.""" return f"retry: {retry}\nid: {event_id}\nevent: {event}\ndata: {data}\n\n"
def constant(connector, value): """the constraint that connector=value""" constraint = {} connector["set_val"](constraint, value) return constraint
def escape(st): """ Escapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in the given string ``st`` and returns it. """ return st.replace('\\', r'\\')\ .replace('\t', r'\t')\ .replace('\r', r'\r')\ .replace('\n', r'\n')\ .replace('\...
def union(sequences): """ Perform set union """ if sequences: if len(sequences) == 1: return sequences[0] else: return set.union(*sequences) else: return set()
def single_list_to_tuple(list_values): """ >>> single_list_to_tuple([1, 2, 3, 4]) [(1, 1), (2, 2), (3, 3), (4, 4)] >>> single_list_to_tuple(['a', 'b', 'c', 'd']) [('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd')] """ return [(v, v) for v in list_values]
def to_bool(value): """ Converts 'something' to boolean. Raises exception for invalid formats Possible True values: 1, True, "1", "TRue", "yes", "y", "t" Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ... """ if str(value).lower() in ("yes...
def contrast_color(hex_color): """ Util function to know if it's best to use a white or a black color on the foreground given in parameter :param str hex_color: the foreground color to analyse :return: A black or a white color """ r1 = int(hex_color[1:3], 16) g1 = int(hex_color[3:5], 16) ...
def _autoconvert(value): """Convert to int or float if possible, otherwise return string""" try: return int(value) except ValueError: pass try: return float(value) except ValueError: return value
def check_found_credentials(medusa_stdout: str) -> bool: """ Check medusa output if bruteforce ran successfully and found valid credentials. :param medusa_stdout: Stdout of medusa bruteforce :return: Value representing if medusa was successful in finding valid credentials """ if "ACCOUNT FOUND:...
def check_hair_colour(val): """hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.""" return len(val) == 7 and val[0] == '#' and all(c in "0123456789abcdef" for c in val[1:])
def car(pair): """return the first element of a pair""" def createArray(a,b): array = [] array.append(a) array.append(b) return array #perform closure array = pair(createArray) return array[0]
def indent(text, nspaces, ch=' '): """ Indent every line of the text string nspaces :param text: Text string to be indented nspaces amount :param nspaces: Amount spaces to indent :param ch: The space char or another char to prepend to the indent :return: The new indented string ...
def strip(source: list): """ Strip. :param list source: Source list :return: list """ r = [] for value in source: if isinstance(value, str): r.append(value.strip()) else: r.append(value) return r
def check_number(input: float, max: float): """Enforces coordinates to an interval of valid values """ max = max - 64 if input < 0: output = 0 elif input > max > 0: output = max else: output = input return output
def str_to_bool(string): """Converts a case-insensitive string 'true' or 'false' into a bool. Args: string: String to convert. Either 'true' or 'false', case-insensitive. Raises: ValueError if string is not 'true' or 'false'. """ lower_string = string.lower() if lower_string == 'true': return...
def text2float(txt: str) -> float: """Converts text to float. If text is not number, then returns `0.0` """ try: return float(txt.replace(",", ".")) except: return 0.0
def name_blob(mosaic_info, item_info): """ Generate the name for a data file in Azure Blob Storage. This follows the pattern {kind}/{mosaic-id}/{item-id}/data.tif where kind is either analytic or visual. """ prefix = "analytic" if "analytic" in mosaic_info["name"] else "visual" return f"{pr...
def dot2string(dot): """Return a string repr of dots.""" return "*" * int(dot)
def query_capsule(id): """ build capsule query by id. """ query = f''' {{ capsule (id: "{id}") {{ id landings original_launch reuse_count status type missions {{ flight name ...
def expand(values, index, padding=128): """ Modify in place and return the list values[] by appending zeros to ensure that values[index] is not out of bounds. An error is raised if index is negative. """ assert index >= 0, f"Oops: negative index in expand(values, index={index})" if index...
def pairs2other(pair_list, file_type): """ Conbert pairs to short. Args: pair_list (list of pairs): [[chrom,start,end], [chrom,start,end], weight] for each interaction file_type (string): 'short' or 'bedpe' Returns: short (list of list): all pairs of frags in short format (0, chrom1...
def isSubListInList(sublist, alist): """ Predicates that checks if a list is included in another one Args: sublist (list): a (sub)-list of elements. alist (list): a list in which to look if the sublist is included in. Result: True if the sublist is included in the list. False otherwi...
def formatHexOfSize(size, number): """ Format any size integer as any length hexidecimal. The hexidecimal should be representitive of the bits that make up the number and not nessicarially the number itself. """ # Account for twos compliment and format behaviour number = number if (number >= 0) else (-number) ...
def return_noun(nominal_group, adjective, determinant): """ returns the noun of the nominal group :param nominal group, the determinant and the adjecvtive :return: the noun """ #If nominal_group is empty if nominal_group == [] or nominal_group[len(determinant) + len(adjectiv...
def expected_toy_predictions_rf_weighted(add_boolean_features=False): """Expected prediction values.""" if add_boolean_features: probabilities = [[0.0, 0.8, 0.2], [0.5, 0.5, 0.0], [0.1, 0.8, 0.1], [0.8, 0.1, 0.1]] classes = [b"v1", b"v2", b"v3"] else: probabilities = [[0.0, 0.5, 0...
def to_int(string): """ Convert string to int >>> to_int("42") 42 """ try: number = int(float(string)) except: number = 0 return number
def inverse_mod(n, p): """Returns the inverse of n modulo p. This function returns the only integer x such that (x * n) % p == 1. n must be non-zero and p must be a prime. """ if n == 0: raise ZeroDivisionError('division by zero') if n < 0: return p - inverse_mod(-n, p) s,...
def _extension_filter(files, extension): """Filtre par extension""" filtered_files = [] for file in files: file_extension = ("".join(file.split('/')[-1])).split('.')[-1] if file_extension == extension: filtered_files.append(file) return filtered_files
def merge_all_hosts(data_all_hosts): """ Concenate data from all hosts, for combined analysis. """ all_packet_ns = [] all_latencies_ms = [] all_total_n_packets = 0 all_filenames = "" for board_n in range(len(data_all_hosts)): (filename, packet_ns, latencies_ms, total_n_p...
def convert_str_list_to_float_list(str_liste:list) -> list : """function to convert a list with str to a list with float Args: str_liste ([list]): [list with string] Returns: [list]: [return the same list, but with float] """ empty_list = [] for i in range(len(str_liste)): ...
def decode(symbol): """Decode from binary to string Parameters ---------- symbol : binary A string in binary form, e.g. b'hola'. Returns ------- str Symbol as a string. """ try: return symbol.decode() except AttributeError: return symbol
def __get_rxn_rate_dict(reaction_equations, net_rates): """ makes a dictionary out of the two inputs. If identical reactions are encountered, called duplicates in Cantera, the method will merge them and sum the rate together """ rxn_dict = {} for equation, rate in zip(reaction_equations, net_rat...
def expand_list(array): """ Recursively flatten a nested list Any lists found are flattened and added to output, any other values are just appended to output. Parameters ---------- array : list The (nested) input list Returns ------- list A flat list of values ...
def is_last_page(page): """ The last page is either empty or only the one Tweet, the last Tweet of the previous page repeated. Args: page: a Twitter timeline page Returns: boolean: True if page is the last page. """ return len(page) == 1 or len(page) == 0
def multi_bracket_validation(string): """ This function return True if brackets are all matched up in string, and \ return False if there is unmatched brackets. """ if not isinstance(string, str): raise TypeError('It\'s not a string.') brackets = {'{': 0, '}': 0, '[': 0, ']': 0, '(': 0,...
def filter_none(some_list): """ Just filters None elements out of a list """ old_len = len(some_list) new_list = [l for l in some_list if l is not None] diff = old_len - len(new_list) return new_list, diff
def longest_valid_parentheses(ls): """ Question 22.13: Given a string, find the longest substring of matching parentheses """ max_length = 0 end = -1 stack = [] for idx, elt in enumerate(ls): if elt == '(': stack.append(idx) elif not len(stack): ...
def merge_dict(dict1, dict2): """Merges two nested dictionaries. Args: dict1 (dict): The first dictionary to merge. dict2 (dict): The second dictionary to merge. Returns: dict: The merged dictionary. """ for key, val in dict1.items(): if type(val) == dict: ...
def as_int(x) -> int: """Convert a value to an int or 0 if this fails.""" try: return int(x) except: return 0
def ishexcolor(value): """ Return whether or not given value is a hexadecimal color. If the value is a hexadecimal color, this function returns ``True``, otherwise ``False``. Examples:: >>> ishexcolor('#ff0034') True >>> ishexcolor('#ff12FG') False :param value: s...
def _get_scales(accelerate_steps, cruise_steps, start_scale, max_scale, target_scale): """Determine scale to use at each step given input steps.""" if accelerate_steps == 0 and cruise_steps == 0: scales = [target_scale] elif accelerate_steps == 0: rising_steps = cruise_s...
def create_name_tags(user_id_list): """ Create a string that consists of all the user_id tags that will be added at the beginning of a message. """ names_to_prepend = '' for user_id in user_id_list: if user_id not in ['channel', 'here', 'everyone']: names_to_prepend += f'<@{...
def insertion_sort_inc1(A): """ insertion sort always maintains a sorted sublist it has O(n2) time complexity sorted sublist is in the higher positions of the list """ for i in range(len(A)-2, -1, -1): key = A[i] j = i + 1 while ( j < len(A) and A[j] < key): A[j-1] = A[j] j += 1 A[j-1] = key re...
def check_permutation(str1, str2): """ 1.2 Check Permutation: Given two strings, write a method to decide if one is a permutation of the other. Complexity: O(n) time, O(n) space """ h = {} for c in str1: if c not in h: h[c] = 0 h[c] += 1 for c in str2: if ...
def write_uint8(data, value, index): """ Write 8bit value into data string at index and return new string """ data = data.decode('utf-8') # This line is added to make sure both Python 2 and 3 works return '{}{:02x}{}'.format( data[:index*2], value, data[ind...
def pycalc(arg1, arg2): """Return the product and division of the two arguments""" return arg1*arg2, arg1/arg2
def gcd(a, b): """Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive). """ while b: a, b = b, a%b return a
def get_header_value(headers, header_name): """ :return: The value of the header with the given name, or None if there was no such header. """ if isinstance(headers, dict): for name, value in headers.items(): if name.lower() == header_name.lower(): return value el...
def merge(left, right): """helper function for merge_sort() inputs: 2 sorted arrays output: 1 merged sorted array Compares first value of each array. Removes lesser value and adds it to new array. Continues until both arrays are empty. """ result = [] while left and right: if...
def alternatives_in_profile(P): """ Return the list of alternatives appearing in profile P, in sorted order. """ A = set() for ballot in P: for alternative in ballot: if alternative != "=": A.add(alternative) return sorted(list(A))
def atualizar_tuple (t_tuple , valor_a_alterar , posisao): """ atualizar_tuple : tuplo , int , int -> tuplo atualizar_tuple(t_tuple , valor_a_alterar , posisao) atualiza um valor de um tuple, com um valor recebido (valor_a_alterar),com uma posisao especifica (posisao) """ lista = ...
def valid_mmsi(mmsi): """Checks if a given MMSI number is valid. Arguments --------- mmsi : int An MMSI number Returns ------- Returns True if the MMSI number is 9 digits long. """ return not mmsi is None and len(str(int(mmsi))) == 9
def is_number(number_str): """Test if number_str is number including infraformat logic.""" try: complex(number_str) except ValueError: if number_str == "-": return True return False return True
def subtract_counter(line, counter): """Subtract the length of the line from the index.""" if counter < len(line): return counter else: return subtract_counter(line, counter - len(line))
def _remove_comments(doc): """ Replaces commented out characters with spaces in a CSS document. """ ans = [] i = 0 while True: i2 = doc.find('/*', i) if i2 < 0: ans += [doc[i:]] break ans += [doc[i:i2]] i3 = doc.find('*/', i2 + 1) i...