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_features, )``. :param kernels: (``Iterable``) Iterable of pointers to kernels. :param kernels_args: (``Iterable``) Iterable with dictionaries, of the same length as `kernels`. Arguments are passed to kernels as kwargs. :param kernels_weights: (``Iterable``) Iterable with kernel weights, of the same length as `kernels`. :return: """ assert len(kernels) == len(kernels_args) if kernels_weights is not None: return sum(w * k(x, y, **kw) for k, kw, w in zip(kernels, kernels_args, kernels_weights)) else: return sum(k(x, y, **kw) for k, kw in zip(kernels, kernels_args))
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' """ if ts.get("kind") == "OBJECT": return ts["name"] if ts.get("kind") == "INTERFACE": return ts["name"] if ts.get("kind") == "INPUT_OBJECT": return ts["name"] if ts.get("kind") == "UNION": return ts["name"] if ts.get("kind") == "ENUM": return ts["name"] if ts.get("args"): return "Method" if ts.get("kind") == "SCALAR": return ts["name"] subKind = ts.get("type") or ts.get("ofType") if not subKind: raise ValueError(ts) if subKind["kind"] == "LIST": subT = of_type(ts.get("type") or ts.get("ofType")) return "[{}]".format(subT) if subKind["name"]: return subKind["name"] return subKind["ofType"]["name"]
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 = lst[0] else: s = '' return s
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: float: the updated average """ return (value + field * tracked) / (1 + tracked)
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: return value else: if isinstance(d, dict): return d[key] if key in d else get_recursive(list(d.values()), key) elif isinstance(d, (list, tuple, set)): for item in d: value = get_recursive(item, key) if value != None: return value return default
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): if value.lower() in ["0", "no", "n", "false", "f", "off"]: return False elif value.lower() in ["1", "yes", "y", "true", "t", "on"]: return True else: raise ValueError("Invalid truth value '%s'" % value) elif isinstance(value, bool): return value else: raise TypeError("invalid type %s, expect bool or str" % type(value))
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: return '0 B' i = 0 while nbytes >= 1024 and i < len(suffixes) - 1: nbytes /= 1024. i += 1 f = ('%.2f' % nbytes).rstrip('0').rstrip('.') return '%s %s' % (f, suffixes[i])
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] if seg_dur > max_subseg_dur: num_subsegs = int(seg_dur / shift) # Taking 0.01 sec as small step seg_start = float(row[3]) seg_end = seg_start + seg_dur # Now divide this segment (new_row) in smaller subsegments for i in range(num_subsegs): subseg_start = seg_start + i * shift subseg_end = min(subseg_start + max_subseg_dur - 0.01, seg_end) subseg_dur = subseg_end - subseg_start new_row = [ "SPEAKER", rec_id, "0", str(round(float(subseg_start), 4)), str(round(float(subseg_dur), 4)), "<NA>", "<NA>", row[7], "<NA>", "<NA>", ] subsegments.append(new_row) # Break if exceeding the boundary if subseg_end >= seg_end: break else: subsegments.append(row) return subsegments
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 if is_commit_msg: if is_git and line.startswith(' '): line = line[4:] msg.append(line) elif msg: msgs.append('\n'.join(msg)) msg = [] if msg: msgs.append('\n'.join(msg)) return msgs
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 range(1, 1 + len(s2)): if s1[x - 1] == s2[y - 1]: m[x][y] = m[x - 1][y - 1] + 1 if m[x][y] > longest: longest = m[x][y] x_longest = x else: m[x][y] = 0 return s1[x_longest - longest: x_longest]
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_dict[key] += value return added_dict
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: for k, v in row["Subjects"].items(): if v > subjects[k]: print( f"VALIDATION ERROR: '{k}' subject of {row.get('Name')} has more marks than the max possible marks." ) exit(1) return data
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 = [] while left <= right: mid = (left + right) // 2 if lst[mid] == target: index.append(mid) if lst[mid] < target: left = mid + 1 else: right = mid - 1 # search in left side i = index[0] - 1 while i >= 0: if lst[i] == target: index.append(i) i -= 1 # search in right side i = index[0] + 1 while i < len(lst): if lst[i] == target: index.append(i) i += 1 return sorted(index)
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 == '' or min == value: return 0 if min == None or min == '': min = 0 try: min = float(min) step = float(step) value = float(value) except: pass if min < value: while min < value: value = round(value - step, round_by) if min == value: return 0 break return round((value + step) - min, round_by) elif min > value: while value < min: value = round(value + step, round_by) if min == value: return 0 break return round(min - (value - step), round_by)
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 modules_ids
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": list_out = [item.strip() for item in list_in] elif strip_method == "leading": list_out = [item.rstrip() for item in list_in] elif strip_method == "trailing": list_out = [item.lstrip() for item in list_in] else: raise NotImplementedError( 'Strip method: "{}" is not implemented. Please use "all", ' '"leading" or "trailing"'.format(strip_method) ) return list_out
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] return 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: timestamp_int = int(timestamp) except TypeError: raise ValueError('Invalid type for timestamp value: {0}.'.format(timestamp)) else: if timestamp_int != timestamp: raise ValueError('{0} must be a numeric value and a whole number.'.format(label)) if timestamp_int <= 0: raise ValueError('{0} timestamp must be a positive interger.'.format(label)) return timestamp_int
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. This can be useful when used within a create_circuit_list inner loop to build a operation sequence lists where a string must be repeated at least once to be added to the list. Returns ------- tuple or Circuit (whichever x was) """ if assertAtLeastOneRep: assert(nTimes > 0) return x * nTimes
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 artists if a.name])
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 not is_open return is_open
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 capitalization/spaces when deciding: >>> is_palindrome('taco cat') True >>> is_palindrome('Noon') True """ new_phrase = phrase.replace(" ", "") new_phrase2 = new_phrase.lower() reverse = new_phrase2[::-1] if new_phrase2 == reverse: return True else: return False
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 open(sam_input_file_path) as f: html += f.read().replace('\n', '<br>') return html
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_class = 'btn' if button_type: button_class += ' btn-' + button_type if button_size: button_class += ' btn-' + button_size if button_disabled: button_class += ' disabled' # Build icon classes icon_class = '' if button_icon: icon_class = 'icon-' + button_icon if button_type and button_type != 'link': icon_class += ' icon-white' # Return context for template return { 'text': text, 'url': kwargs.get('url', '#'), 'button_class': button_class, 'icon_class': icon_class, }
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) '2.59e-05' """ if number >= 0.1: return str(round(number, 2)) else: return ('{:0.' + str(precision) + 'e}').format(number)
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 type(spList) is int: resList = "%d" % spList else: resList=",".join(["%d" % (i) for i in spList]) return resList
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 Returns: int: The number of tracks to merge """ merge_num = 1 seeking_merge_num = True while seeking_merge_num: merge_num = merge_num + 1 if(num_tracks / merge_num < max_tracks): seeking_merge_num = False return merge_num
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 generation: using the "Register Message Rich Menu" API 3. Rich Menu Image Settings: Use the "Message Rich Menu Image Settings" API """ return {"name": name, "size": size, "areas": areas}
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 = submission.crosspost_parent.split('_')[1] s = reddit.submission(crosspost_id) media_url = s.media['reddit_video']['fallback_url'] except Exception as f: print(f) print("Can't read media_url, skipping") return media_url
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 list :return bool : tells if lists are similar or not """ # check if both the lists are of same size if len(list_1) != len(list_2): return False # create a zipped object from 2lists final_list = zip(list_1, list_2) # iterate over the zipped object for elem in final_list: if elem[0] != elem[1]: return False return True
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('\"', r'\"')
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", "y", "true", "t", "1"): return True if str(value).lower() in ( "no", "n", "false", "f", "0", "0.0", "", "none", "[]", "{}", ): return False raise Exception("Invalid value for boolean conversion: " + str(value))
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) b1 = int(hex_color[5:7], 16) # Black RGB black_color = "#000000" r2_black_color = int(black_color[1:3], 16) g2_black_color = int(black_color[3:5], 16) b2_black_color = int(black_color[5:7], 16) # Calc contrast ratio l1 = 0.2126 * pow(r1 / 255, 2.2) + 0.7152 * pow(g1 / 255, 2.2) + 0.0722 * pow(b1 / 255, 2.2) l2 = 0.2126 * pow(r2_black_color / 255, 2.2) + 0.7152 * pow(g2_black_color / 255, 2.2) + 0.0722 * pow( b2_black_color / 255, 2.2) if l1 > l2: contrast_ratio = int((l1 + 0.05) / (l2 + 0.05)) else: contrast_ratio = int((l2 + 0.05) / (l1 + 0.05)) # If contrast is more than 5, return black color if contrast_ratio > 5: return '#000000' # if not, return white color return '#FFFFFF'
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:" in medusa_stdout and "[SUCCESS]" in medusa_stdout: return True return False
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 """ padding = nspaces * ch padded_lines_list = [padding+line for line in text.splitlines(True)] return ''.join(padded_lines_list)
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 True if lower_string == 'false': return False raise ValueError('Expected "true" or "false"; got "{}".'.format(string))
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"{prefix}/{mosaic_info['id']}/{item_info['id']}/data.tif"
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 }} dragon{{ active crew_capacity description diameter {{ feet meters }} dry_mass_kg dry_mass_lb first_flight heat_shield {{ dev_partner material size_meters temp_degrees }} height_w_trunk {{ feet meters }} launch_payload_mass {{ kg lb }} name orbit_duration_yr pressurized_capsule{{ payload_volume{{ cubic_feet cubic_meters }} }} return_payload_mass {{ kg lb }} return_payload_vol {{ cubic_feet cubic_meters }} sidewall_angle_deg thrusters {{ amount fuel_1 fuel_2 pods type }} trunk{{ cargo{{ solar_array unpressurized_cargo }} trunk_volume{{ cubic_feet cubic_meters }} }} }} }} }} ''' return query
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 >= len(values): space_needed = index - len(values) + 1 values.extend([0] * (space_needed + padding)) return values
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, mid1, 0, 0, chrom2, mid2, 1) """ pair1 = pair_list[0] pair2 = pair_list[1] weight = pair_list[2] other_list = [] if file_type == 'bedpe': other_list.extend(pair1) other_list.extend(pair2) elif file_type == 'short': other_list = [0, pair1[0], int((pair1[1] + pair1[2])/2), 0, 0, pair2[0], int((pair2[1] + pair2[2])/2), 1] if weight != -1: other_list.append(weight) return other_list
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 otherwise. """ for i in range(len(alist) - len(sublist) + 1): if sublist == alist[i: i + len(sublist)]: return True return False
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) + (1 << ((size * 8) - 1)) return ("0x{:" + str(size) + "X}").format(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(adjective):] == []: return [] return [" ".join(nominal_group[len(determinant) + len(adjective):])]
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.5], [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"] return probabilities, classes
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, old_s = 0, 1 t, old_t = 1, 0 r, old_r = p, n while r != 0: quotient = old_r // r old_r, r = r, old_r - quotient * r old_s, s = s, old_s - quotient * s old_t, t = t, old_s - quotient * t gcd, x, y = old_r, old_s, old_t assert gcd == 1 assert (n * x) % p == 1 return x % p
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_packets) = data_all_hosts[board_n] all_packet_ns.extend(packet_ns) all_latencies_ms.extend(latencies_ms) all_total_n_packets += total_n_packets if all_filenames == "": all_filenames = filename else: all_filenames += (", %s" % filename) return [(all_filenames, all_packet_ns, all_latencies_ms, all_total_n_packets)]
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)): empty_list.append(float(str_liste[i])) return empty_list
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_rates): try: rxn_dict[equation] += rate except KeyError: rxn_dict[equation] = rate return rxn_dict
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 """ new_array = [] for item in array: if isinstance(item, list): new_array += expand_list(item) else: new_array.append(item) return new_array
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, ')': 0} for i in string: for key, val in brackets.items(): if i == key: brackets[key] += 1 if brackets['{'] - brackets['}'] == 0 and\ brackets['['] - brackets[']'] == 0 and\ brackets['('] - brackets[')'] == 0: return True return False
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): end = idx else: stack.pop() start = end if not len(stack) else stack[-1] max_length = max(max_length, idx - start) return max_length
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: if key in dict2 and type(dict2[key] == dict): merge_dict(dict1[key], dict2[key]) else: if key in dict2: dict1[key] = dict2[key] for key, val in dict2.items(): if not key in dict1: dict1[key] = val return dict1
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: string to validate hexadecimal color """ value = value.lstrip('#') try: return int(value, 16) >= 0 and len(value) in (3, 6) except ValueError: return False
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_steps / 2 falling_steps = rising_steps + cruise_steps % 2 rising = [start_scale] if rising_steps: scale_step = (max_scale - start_scale) / float(rising_steps) rising_scales = [start_scale + scale_step * (i + 1) for i in range(rising_steps)] rising.extend(rising_scales) scale_step = (max_scale - target_scale) / float(falling_steps) falling = [target_scale + scale_step * i for i in range(falling_steps)] falling.reverse() scales = rising + falling else: middle = [max_scale] * cruise_steps if accelerate_steps > 3: scale_accel_steps = accelerate_steps / 2 scale_decel_steps = scale_accel_steps + accelerate_steps % 2 scale_rate = ( (max_scale - start_scale) / (0.5 * (scale_accel_steps**2 - scale_decel_steps**2) + scale_accel_steps * scale_decel_steps)) rising = [start_scale + 0.5 * scale_rate * i**2 for i in range(scale_accel_steps + 1)] decel_scales = [max_scale - 0.5 * scale_rate * i**2 for i in range(scale_decel_steps)] decel_scales.reverse() rising.extend(decel_scales) scale_rate = ( (max_scale - target_scale) / (0.5 * (scale_accel_steps**2 - scale_decel_steps**2) + scale_accel_steps * scale_decel_steps)) falling = [max_scale - 0.5 * scale_rate * (i + 1)**2 for i in range(scale_accel_steps)] decel_scales = [target_scale + 0.5 * scale_rate * i**2 for i in range(scale_decel_steps)] decel_scales.reverse() falling.extend(decel_scales) else: # Not enough steps for acceleration and deceleration, so go linear scale_step = (max_scale - start_scale) / float(accelerate_steps) rising = [start_scale + scale_step * i for i in range(1 + accelerate_steps)] scale_step = (target_scale - max_scale) / float(accelerate_steps) falling = [max_scale + scale_step * (i + 1) for i in range(accelerate_steps)] scales = rising + middle + falling return scales
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'<@{user_id}> ' else: names_to_prepend += f'<!{user_id}> ' return names_to_prepend
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 return A
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 c not in h: return False h[c] -= 1 for (_, count) in h.items(): if count != 0: return False return True
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[index*2 + 2:])
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 elif headers is not None: for header in headers: if header.name.lower() == header_name.lower(): return header.value return None
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 left[0] <= right[0]: result.append(left[0]) left = left[1:] else: result.append(right[0]) right = right[1:] while left: result.append(left[0]) left = left[1:] while right: result.append(right[0]) right = right[1:] return result
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 = list(t_tuple) lista[posisao] = valor_a_alterar t_tuple = tuple(lista) return t_tuple
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) if i3 < 0: i3 = len(doc) - 2 ans += [' ' * (i3 - i2 + 2)] i = i3 + 2 return ''.join(ans)