content
stringlengths
42
6.51k
def isiterable(iterable): """ https://stackoverflow.com/a/36407550/3356840 """ if isinstance(iterable, (str, bytes)): return False try: _ = iter(iterable) except TypeError: return False else: return True
def is_pr_comment(event): """Determine if a comment applies to a pull request.""" try: right_type = event.type == 'IssueCommentEvent' right_payload = 'pull_request' in event.payload['issue'].to_json() return right_type and right_payload except (KeyError, IndexError, AttributeError, TypeError): return False
def bound(low, value, high): """ If value is between low and high, return value. If value is below low, return low. If value is above high, return high. If low is below high, raise an exception. """ assert low <= high return max(low, min(value, high))
def build_preferences(first, second, third): """Given three preferences, reduces them in order to unique choices. Args: first: project name second: project name third: project name Returns: List[str] """ end_result = [] for pref in (first, second, third): if pref not in end_result and pref: end_result.append(pref) return end_result
def map_pathogen_id_to_name(pathogen_id): """ """ mapping = { "p00": "Acinetobacter baumannii", "p01": "Baceroides fragilis", "p02": "Burkholderia cepacia", "p03": "Candida albicans", "p04": "Candida giabrata", "p05": "Candida parapsilosis", "p06": "Candida tropicalis", "p07": "Citrobacter diversus", "p08": "Citrobacter freundii", "p09": "Citrobacter koseri", "p10": "Clostridium difficile", "p11": "Enterobacter aerogenes", "p12": "Enterobacter cloacae", "p13": "Enterococcus faecalis", "p14": "Enterococcus faecium", "p15": "Escherichia coli", "p16": "Haemophilus influenzae", "p17": "Klebsiella oxytoca", "p18": "Klebsiella pneumoniae", "p19": "Moraxella catarrhalis", "p20": "Morganella morganii", "p21": "Proteaus mirabilis", "p22": "Pseudomonas aeruginosa", "p23": "Serratia marcescens", "p24": "Staphylococcus aureus (MSSA, MRSA)", "p25": "Staphylococcus auricularis", "p26": "Staphylococcus capitis ssp. capitis", "p27": "Staphylococcus capitis ssp. unspecified", "p28": "Staphylococcus coagulase negative", "p29": "Staphylococcus cohnii", "p30": "Staphylococcus epidermidis", "p31": "Staphylococcus gallinarum", "p32": "Staphylococcus haemolyticus", "p33": "Staphylococcus hominis", "p34": "Staphylococcus lentus", "p35": "Staphylococcus lugdenensis", "p36": "Staphylococcus saccharolyticus", "p37": "Staphylococcus saprophyticus", "p38": "Staphylococcus schleiferi", "p39": "Staphylococcus sciuri", "p40": "Staphylococcus simulans", "p41": "Staphylococcus warneri", "p42": "Staphylococcus xylosus", "p43": "Stenotrophomonas maltophilia", "p44": "Streptococcus group A (Streptococcus pyogenes)", "p45": "Streptococcus group B (Streptococcus agalactiae)", "p46": "Streptococcus group D (Sterptococcus bovis)", "p47": "Streptococcus pneumoniae (pneumococcus)", "p49": "Strepotcuccus viridans (includes angiosus, bovis, mitis, mutans, salivarius)", "p48": "Torulopsis glabrata (Candida glabrata)", "p50": "Other pathogen", } pathogen = '' if pathogen_id in mapping: pathogen = mapping[pathogen_id] return pathogen
def get_missing_coordinate(x1: float, y1: float, x2: float, angular_coefficient: float = -1.0) -> float: """Returns the y2 coordinate at the point (x2, y2) of a line which has an angular coefficient of "angular_coefficient" and passes through the point (x1, y1).""" linear_coefficient = y1 - (angular_coefficient * x1) y2 = linear_coefficient + (x2 * angular_coefficient) return y2
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths): """Given a prediction and multiple valid answers, return the score of the best prediction-answer_n pair given a metric function. """ scores_for_ground_truths = [] for ground_truth in ground_truths: score = metric_fn(prediction, ground_truth) scores_for_ground_truths.append(score) return max(scores_for_ground_truths)
def remove_template(s): """Remove template wikimedia markup. Return a copy of `s` with all the wikimedia markup template removed. See http://meta.wikimedia.org/wiki/Help:Template for wikimedia templates details. Note: Since template can be nested, it is difficult remove them using regular expresssions. """ # Find the start and end position of each template by finding the opening # '{{' and closing '}}' n_open, n_close = 0, 0 starts, ends = [], [] in_template = False prev_c = None for i, c in enumerate(iter(s)): if not in_template: if c == '{' and c == prev_c: starts.append(i - 1) in_template = True n_open = 1 if in_template: if c == '{': n_open += 1 elif c == '}': n_close += 1 if n_open == n_close: ends.append(i) in_template = False n_open, n_close = 0, 0 prev_c = c # Remove all the templates s = ''.join([s[end + 1:start] for start, end in zip(starts + [None], [-1] + ends)]) return s
def CompareResults(manifest, actual): """Compare sets of results and return two lists: - List of results present in ACTUAL but missing from MANIFEST. - List of results present in MANIFEST but missing from ACTUAL. """ # Collect all the actual results not present in the manifest. # Results in this set will be reported as errors. actual_vs_manifest = set() for actual_result in actual: if actual_result not in manifest: actual_vs_manifest.add(actual_result) # Collect all the tests in the manifest that were not found # in the actual results. # Results in this set will be reported as warnings (since # they are expected failures that are not failing anymore). manifest_vs_actual = set() for expected_result in manifest: # Ignore tests marked flaky. if 'flaky' in expected_result.attrs: continue if expected_result not in actual: manifest_vs_actual.add(expected_result) return actual_vs_manifest, manifest_vs_actual
def nova_except_format(logical_line): """ nova HACKING guide recommends not using assertRaises(Exception...): Do not use overly broad Exception type N202 """ if logical_line.startswith("self.assertRaises(Exception"): return 1, "NOVA N202: assertRaises Exception too broad"
def get_page_as_ancestor(page_id): """ Get ancestors object accepted by the API from a page id :param page_id: the ancestor page id :return: API-compatible ancestor """ return [{'type': 'page', 'id': page_id}]
def get_array_slice_start_end(length, num_slices, slice_index): """ """ if not (length > 0): raise Exception("Invalid length, must be > 0") if not (1 <= num_slices <= length): raise Exception("Invalid number of slices, must be >= 1 and <= length") if not (0 <= slice_index < length): raise Exception("Invalid slice index, must be >= 0 and < length") slice_size = length // num_slices # if (length % slice_size) != 0: # if (length - (slice_size * (num_slices - 1))) >= num_slices: # slice_size += 1 slice_start = slice_size * slice_index if slice_index == (num_slices - 1): slice_end = length else: slice_end = (slice_index + 1) * slice_size return slice_start, slice_end
def _real_2d_func(x, y, func): """Return real part of a 2d function.""" return func(x, y).real
def meta_caption(meta) -> str: """makes text from metadata for captioning video""" caption = "" try: caption += meta.title + " - " except (TypeError, LookupError, AttributeError): pass try: caption += meta.artist except (TypeError, LookupError, AttributeError): pass return caption
def truncate(text, maxlen=128, suffix='...'): """Truncates text to a maximum number of characters.""" if len(text) >= maxlen: return text[:maxlen].rsplit(' ', 1)[0] + suffix return text
def sqlite3_call(database, query): """ Differentiate between SELECT and INSERT, UPDATE, DELETE (hack -> wont work with sub-selects in e.g. update) """ if query == "" or query is None: return "Warning: Empty query string!" elif query and query.lower().find("select") >= 0: return database.get(query) else: return database.put(query)
def validate_int(value): """ Validate an int input. Parameters: value (any): Input value Returns: boolean: True if value has type int """ return isinstance(value, int)
def slot_id(hsm): """Provide a slot_id property to the template if it exists""" try: return hsm.relation.plugin_data['slot_id'] except Exception: return ''
def calcSurroundingIdxs(idxs, before, after, idxLimit=None): """ Returns (idxs - before), (idxs + after), where elements of idxs that result in values < 0 or > idxLimit are removed; basically, this is useful for extracting ranges around certain indices (say, matches for a substring) that are contained fully in an array. >>> idxs = [1, 3, 4] >>> calcSurroundingIdxs(idxs, 0, 0) ([1, 3, 4], [1, 3, 4]) >>> calcSurroundingIdxs(idxs, 1, 0) ([0, 2, 3], [1, 3, 4]) >>> calcSurroundingIdxs(idxs, 1, 1) ([0, 2, 3], [2, 4, 5]) >>> calcSurroundingIdxs(idxs, 1, 1, 4) ([0, 2], [2, 4]) """ if idxLimit is None: idxs = [idx for idx in idxs if (idx - before >= 0)] else: idxs = [idx for idx in idxs if (idx - before >= 0) and (idx + after <= idxLimit)] beforeIdxs = [x - before for x in idxs] afterIdxs = [x + after for x in idxs] return beforeIdxs, afterIdxs
def _is_fileobj(obj): """ Is `obj` a file-like object?""" return hasattr(obj, 'read') and hasattr(obj, 'write')
def is_known_mersenne_prime(p): """Returns True if the given Mersenne prime is known, and False otherwise.""" primes = frozenset([2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933]) return p in primes
def midpoint(f, a, b, N): """ f ... function to be integrated [a,b] ... integration interval N ... number steps(bigger the better but slower) This method uses rectangles to approximate the area under the curve. Rectangle width is determined by the interval of integration. The interval of integration is then divided into n smaller intervals of equal lengths as step sizes increase, and n rectangles would used to approximate the integral; each smaller rectangle has the width of the smaller interval. The rectangle height is the function value at the midpoint of its base. """ h = float(b-a)/N output = 0 for i in range(N): output += f((a+h/2.0)+i*h) output *= h return output
def rat(n, d, nan=float('nan'), mul=1.0): """ Calculate a ratio while avoiding division by zero errors. Strictly speaking we should have nan=float('nan') but for practical purposes we'll maybe want to report None (or 0.0?). """ try: return ( float(n) * mul ) / float(d) except (ZeroDivisionError, TypeError): return nan
def is_unsigned_integer(value): """ :param value: :return: >>> is_unsigned_integer(0) True >>> is_unsigned_integer(65535) True >>> is_unsigned_integer(-1) False >>> is_unsigned_integer(65536) False >>> is_unsigned_integer('0') False >>> is_unsigned_integer(0.0) False """ return isinstance(value, int) and (value >= 0) and (value.bit_length() <= 16)
def norm2d(x, y): """Calculate norm of vector [x, y].""" return (x * x + y * y) ** 0.5
def clamp(minimum, value, maximum): """Clamp value between given minimum and maximum.""" return max(minimum, min(value, maximum))
def safe_float(string, default=None): """ Safely parse a string into a float. On error return the ``default`` value. :param string string: string value to be converted :param float default: default value to be used in case of failure :rtype: float """ value = default try: value = float(string) except TypeError: pass except ValueError: pass return value
def ucfirst(msg): """Return altered msg where only first letter was forced to uppercase.""" return msg[0].upper() + msg[1:]
def tsorted(a): """Sort a tuple""" return tuple(sorted(a))
def selection_sort(a: list) -> list: """Given a list of element it's return sorted list of O(n^2) complexity""" a = a.copy() n = len(a) for i in range(n): mni = i for j in range(i+1, n): if a[j] < a[mni]: mni = j a[i], a[mni] = a[mni], a[i] return a
def urlify(str, length=None): """Write a method to replace all spaces with '%20'. Args: str - String whose spaces should be replaced by '%20' length - length of str minus any spaces padded at the beginning or end Returns: A string similar to str except whose spaces have been replaced. """ return str.strip().replace(' ', '%20')
def get_table_schema_query(schema_table, source_table_name): """ Query to get source schema for table from BQ (previously ingested). """ return f" select distinct * from (select COLUMN_NAME, DATA_TYPE from `{schema_table}` \ where TABLE_NAME = '{source_table_name}' order by ORDINAL_POSITION)"
def boarding_pass_to_seat_id(boarding_pass: str) -> int: """Convert a boarding pass string into seat ID Because the strings are just binary representations of integers, we can abuse Python's booleans and convert them from FBFBBFFRLR to 0101100101 """ seat_id = "".join(str(int(char in {"B", "R"})) for char in boarding_pass) return int(seat_id, 2)
def validateUnits(cmodel, layers): """Validate model units. Args: cmodel (dict): Sub-dictionary from config for specific model. layers (dict): Dictionary of file names for all input layers. Returns: dict: Model units. """ units = {} for key in cmodel['layers'].keys(): if 'units' in cmodel['layers'][key]: units[key] = cmodel['layers'][key]['units'] else: raise Exception('No unit string configured for layer %s' % key) return units
def selection_sort(to_be_sorted): """ O(n^2) as there are two nested loops :param to_be_sorted: :return: """ if len(to_be_sorted) < 2: return to_be_sorted for i1 in range(len(to_be_sorted)): min = i1 for i2 in range(i1 + 1, len(to_be_sorted)): if to_be_sorted[i2] < min: min = i2 to_be_sorted[i1], to_be_sorted[min] = to_be_sorted[min], to_be_sorted[i1] return to_be_sorted
def get_pairs(word): """ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
def subvector(y, head, tail): """Construct a vector with the elements v[head], ..., v[tail-1].""" result = [] for i in range(head, tail, 1): result.append(y[i]) return result
def add_color_to_scheme(scheme, name, foreground, background, palette_colors): """Add foreground and background colours to a color scheme""" if foreground is None and background is None: return scheme new_scheme = [] for item in scheme: if item[0] == name: if foreground is None: foreground = item[1] if background is None: background = item[2] if palette_colors > 16: new_scheme.append((name, '', '', '', foreground, background)) else: new_scheme.append((name, foreground, background)) else: new_scheme.append(item) return new_scheme
def interpret_as_slice(column): """Interprets the 'column' argument of loadFitnessHistory into a slice()""" if column is None: # No specific column is requested, return everything return slice(None) elif isinstance(column, int): # One specific column is requested return slice(column, column + 1) elif len(column) == 2 and all(isinstance(val, int) for val in column): # Multiple columns are requested return slice(*column) else: # 'column' does not match expected format raise Exception("Invalid format for 'column': {col}".format(col=column))
def state_utility(ufuncs, state): """computes utility for a state""" utility = 0 for attr, value in state.items(): if attr in ufuncs: utility += ufuncs[attr](state[attr]) return utility
def sieve(n): """ Input n>=6, Returns a list of primes, 2 <= p < n """ correction = (n % 6 > 1) n = {0:n, 1:n - 1, 2:n + 4, 3:n + 3, 4:n + 2, 5:n + 1}[n % 6] sieve = [True] * (n // 3) sieve[0] = False for i in range(int(n ** 0.5) // 3 + 1): if sieve[i]: k = 3 * i + 1 | 1 sieve[ ((k * k) // 3) ::2 * k] = [False] * ((n // 6 - (k * k) // 6 - 1) // k + 1) sieve[(k * k + 4 * k - 2 * k * (i & 1)) // 3::2 * k] = [False] * ((n // 6 - (k * k + 4 * k - 2 * k * (i & 1)) // 6 - 1) // k + 1) return [2, 3] + [3 * i + 1 | 1 for i in range(1, n // 3 - correction) if sieve[i]]
def validate_bst(root): """ This solution does an inorder traversal, checking if the BST conditions hold for every node in the tree. """ if root is not None: validate_bst(root.left) if root.left is not None: if root.left.data > root.data: return False if root.right is not None: if root.right.data <= root.data: return False validate_bst(root.right) return True
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ start_pos_0 = 0 end_pos_2 = len(input_list) - 1 front_index = 0 count = 0 if len(input_list) < 0: # no value detected in list return -1 while front_index <= end_pos_2: count += 1 #for debugging to ensure the loop traverses just once if input_list[front_index] < 0 or input_list[front_index] > 2: # invalid number detected in the list return -1 if input_list[front_index] == 0: # move value in start position to front index input_list[front_index] = input_list[start_pos_0] # add 0 to start position input_list[start_pos_0] = 0 # increase start position so the next zero found in the array can be placed there start_pos_0 += 1 front_index += 1 elif input_list[front_index] == 2: # move value in end position to front index input_list[front_index] = input_list[end_pos_2] # add 2 to end position position input_list[end_pos_2] = 2 # decrease end position so the next value can be placed there end_pos_2 -= 1 else: # traverse to next front index front_index += 1 # print(len(input_list) == count) Test to ensure traversal is a single traversal return input_list
def is_kwarg(argument: str) -> bool: """`True` if argument name is `**kwargs`""" return "**" in argument
def is_2d_vector(block): """ Returns True if ``block is a 2-d list. :param block: A list. """ return all([isinstance(r, list) for r in block]) and all([len(r) == 1 for r in block])
def iou(box1, box2, x1y1x2y2 = True): """ Intersection Over Union """ if x1y1x2y2: mx = min(box1[0], box2[0]) Mx = max(box1[2], box2[2]) my = min(box1[1], box2[1]) My = max(box1[3], box2[3]) w1 = box1[2] - box1[0] h1 = box1[3] - box1[1] w2 = box2[2] - box2[0] h2 = box2[3] - box2[1] else: #(x, y, w, h) mx = min(box1[0] - box1[2] / 2, box2[0] - box2[2] / 2) Mx = max(box1[0] + box1[2] / 2, box2[0] + box2[2] / 2) my = min(box1[1] - box1[3] / 2, box2[1] - box2[3] / 2) My = max(box1[1] + box1[3] / 2, box2[1] + box2[3] / 2) w1 = box1[2] h1 = box1[3] w2 = box2[2] h2 = box2[3] uw = Mx - mx uh = My - my cw = w1 + w2 - uw ch = h1 + h2 - uh corea = 0 if cw <= 0 or ch <= 0: return 0.0 area1 = w1 * h1 area2 = w2 * h2 corea = cw * ch uarea = area1 + area2 - corea return corea / uarea
def make_edges(nodes, directed=True): """ Create an edge tuple from two nodes either directed (first to second) or undirected (two edges, both ways). :param nodes: nodes to create edges for :type nodes: :py:list, py:tuple :param directed: create directed edge or not :type directed: bool """ edges = [tuple(nodes)] if not directed: edges.append(nodes[::-1]) return edges
def parse_mime_type(mime_type): """Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) """ parts = mime_type.split(';') params = dict([tuple([s.strip() for s in param.split('=', 1)])\ for param in parts[1:] ]) full_type = parts[0].strip() # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' (type, subtype) = full_type.split('/') return (type.strip(), subtype.strip(), params)
def g_logv(s): """read a logical variable :param str s: :return bool: """ return s == '1' or s.lower() == 'yes' or s.lower() == 'true'
def convert_filter_for_tator_search(filter_condition: dict) -> str: """ Converts the given filter condition into a Tator REST compliant search string """ modifier_str = filter_condition["modifier"] modifier_end_str = "" if filter_condition["modifier"] == "==": modifier_str = "" elif filter_condition["modifier"] == "Includes": modifier_str = "*" modifier_end_str = "*" # Lucene search string requires spaces and parentheses to have a preceding backslash field_str = filter_condition["field"].replace(" ","\\ ").replace("(","\\(").replace(")","\\)") value_str = filter_condition["value"].replace(" ","\\ ").replace("(","\\(").replace(")","\\)") search = f"{field_str}:{modifier_str}{value_str}{modifier_end_str}" return search
def _make_package(x): """Get the package name and drop the last '.' """ package = '' for p in x: package += p[0] + p[1] if package and package[-1] == '.': package = package[:-1] return package
def method_func(klass, method_name): """ Get the function object from a class and a method name. In Python 2 doing getattr(SomeClass, 'methodname') returns an instancemethod and in Python 3 a function. Use this helper to reliably get the function object """ method = getattr(klass, method_name) # in Python 2 method will be an instancemethod, try to get its __func__ # attribute and fall back to what we already have (for Python 3) return getattr(method, '__func__', method)
def parseFlows(flows): """ Parse out the string representation of flows passed in. Example: NXST_FLOW reply (xid=0x4): cookie=0x0, duration=4.329s, table=0, n_packets=0, n_bytes=0, idle_timeout=120,hard_timeout=120,in_port=3 actions=output:4 """ switchFlows = {} for flow in flows.split('\n'): line = flow.split() if len(line) > 3: #get rid of first line in flow output inputPort = line[5].split(',')[2].split('=')[1] outputPorts = line[6].split('actions=')[1] switchFlows[inputPort] = outputPorts return switchFlows
def fahrenheit_to_celsius(temp_fahrenheit, difference=False): """Transform Fahrenheit temperatures to Celsius Args: temp_fahrenheit (float): temperature in fahrenheit difference (bool, optional): relative difference to zero. Defaults to False. Returns: [type]: temperature in Celsius """ if not difference: return (temp_fahrenheit - 32) * 5 / 9 else: return temp_fahrenheit * 5 / 9
def get_start_vertex(searchers_info): """Return list of searchers start position start indexing follow model style [1,2..]""" start = [] for k in searchers_info.keys(): dummy_var = searchers_info[k]['start'] my_var = dummy_var start.append(my_var) return start
def isPrime(x): """ Checks whether the given number x is prime or not """ if x == 5: return True if x % 2 == 0: return False for i in range(3, int(x**0.5)+1, 2): if x % i == 0: return False return True
def form_gene_str(gene): """Form the string form of a gene.""" return ''.join(str(i) for i in gene)
def index(haystack, needle, start=1): """returns the character position of one string, needle, in another, haystack, or returns 0 if the string needle is not found or is a null string. By default the search starts at the first character of haystack (start has the value 1). You can override this by specifying a different start point, which must be a positive whole number. """ if start <= 0: raise ValueError("start="+repr(start)+" is not valid") return 1+haystack.find(needle, start-1)
def int_to_binary_string(n): """ Return the binary representation of the number n :param n: a number :return: a binary representation of n as a string """ return '{0:b}'.format(n)
def get_avg_duration(persons, fps): """ Compute the average duration of detection for an array of persons :param persons: array of the detected persons :param fps: frame-per-second rate for the video :return: None """ if len(persons) > 0: total_nb_frames = 0 for person in persons: total_nb_frames = total_nb_frames + person[5] - person[4] # return the average number of frames by person, divided by the FPS rate to get a value in seconds return (total_nb_frames / len(persons)) / fps else: return 0
def colorTransfer(val): """Convert 0-1 into a grayscale terminal color code""" minCol = 235 maxCol = 256 return int((maxCol-minCol)*val + minCol)
def _LookupMeOrUsername(cnxn, username, services, user_id): """Handle the 'me' syntax or lookup a user's user ID.""" if username.lower() == 'me': return user_id return services.user.LookupUserID(cnxn, username)
def convert_geographic_coordinate_to_pixel_value(refpx, refpy, transform): """ Converts a lat/long coordinate to a pixel coordinate given the geotransform of the image. Args: refpx: The longitude of the coordinate. refpx: The latitude of the coordinate. transform: The geotransform array of the image. Returns: Tuple of refpx, refpy in pixel values. """ # transform = ifg.dataset.GetGeoTransform() xOrigin = transform[0] yOrigin = transform[3] pixelWidth = transform[1] pixelHeight = -transform[5] refpx = int((refpx - xOrigin) / pixelWidth) refpy = int((yOrigin - refpy) / pixelHeight) return int(refpx), int(refpy)
def speed2dt(speed): """Calculate the time between consecutive fall steps using the *speed* parameter; *speed* should be an int between 1 and 9 (inclusively). Returns time between consecutive fall steps in msec.""" return (10-speed)*400
def getPercentIdentity(seq1, seq2, gap_char="-"): """get number of identical residues between seq1 and seq2.""" ntotal = 0 nidentical = 0 for a in range(len(seq1)): if seq1[a] != gap_char and seq2[a] != gap_char: ntotal += 1 if seq1[a] == seq2[a]: nidentical += 1 if ntotal == 0: return 0.0 return float(nidentical) / ntotal
def part_2_fuel(pos, list_): """gives the fuel amount for a specific position according to rules of part 2""" fuel = [(abs(pos - i)*(abs(pos-i)+1))/2 for i in list_] return sum(fuel)
def find_mean(values): """Gets the mean of a list of values Args: values (iterable of float): A list of numbers Returns: float """ mean = sum(values) / len(values) return mean
def get_data_from_region(region_url_list, rent_or_sale): """ Given a list of urls of different regions and the listing type (rent or buy), returns a list of urls with all the properties for this specific listing type, each url for a particular region. """ regional_data = [] for url in region_url_list: region_name = url.split('/')[-1] regional_data.append( f'https://phoenix.onmap.co.il/v1/properties/mixed_search?' f'option={rent_or_sale}&section=residence&city={region_name}&$sort=-is_top_promoted+-search_date') return regional_data
def _get_valid_bool(section, option, provided): """Validates a boolean type configuration option. Returns False by default if the option is unset. """ if provided is None: return False if not isinstance(provided, bool): error = "Value provided for '{0}: {1}' is not a valid boolean".format( section, option) raise ValueError(error) return provided
def commastring_to_list(string, capitalize=False): """Turn a comma separated list in a string to a python list.""" if capitalize: return [item.strip().capitalize() for item in string.split(',')] return [item.strip() for item in string.split(',')]
def check_bool_is_false(val): """Check if a value is a false bool.""" if not val and isinstance(val, bool): return True raise ValueError('Value should be "False"; got {}'.format(val))
def scalar_multiply(c, u): """ return the vector u scaled by the scalar c """ return tuple((c * a for a in u));
def dyadic_string_lists(l1,l2): """Compute the dyadic product of two lists of strings""" if(len(l1)==1): l1 = ([l1[0],[]],) l = [[[str(l1v[0])+str(l2v),[t for t in l1v[1]]+[l2v]] for l1v in l1] for l2v in l2] return [item for sublist in l for item in sublist]
def _merge_lists(one, two, keyfn, resolvefn): """Merges two lists. The algorithm is to first iterate over the first list. If the item in the first list does not exist in the second list, add that item to the merged list. If the item does exist in the second list, resolve the conflict using the resolvefn. After the first list has been iterated over, simply append any items in the second list that have not already been added. If the items in the list are objects, then the objects will be mutated directly and not copied. :param one: The first list to be merged. :param two: The second list to be merged. :param keyfn: A function that takes an element from the list as an argument and returns a unique identifier for that item. :param resolvefn: A function that takes two elements that resolve to the same key and returns a single element that has resolved the conflict between the two elements. :returns: A list of the merged elements """ merged = [] two_keys = {keyfn(obj): obj for obj in two} for obj in one: obj_key = keyfn(obj) if obj_key in two_keys: # If obj exists in both list, must merge new_obj = resolvefn( obj, two_keys.pop(obj_key), ) else: new_obj = obj merged.append(new_obj) # Get the rest of the objects in the second list merged.extend(list(two_keys.values())) return merged
def clean_library_name(assumed_library_name): """ Most CP repos and library names are look like this: repo: Adafruit_CircuitPython_LC709203F library: adafruit_lc709203f But some do not and this handles cleaning that up. Also cleans up if the pypi or reponame is passed in instead of the CP library name. :param str assumed_library_name: An assumed name of a library from user or requirements.txt entry :return: str proper library name """ not_standard_names = { # Assumed Name : Actual Name "adafruit_adafruitio": "adafruit_io", "adafruit_busdevice": "adafruit_bus_device", "adafruit_display_button": "adafruit_button", "adafruit_neopixel": "neopixel", "adafruit_sd": "adafruit_sdcard", "adafruit_simpleio": "simpleio", "pimoroni_ltr559": "pimoroni_circuitpython_ltr559", } if "circuitpython" in assumed_library_name: # convert repo or pypi name to common library name assumed_library_name = ( assumed_library_name.replace("-circuitpython-", "_") .replace("_circuitpython_", "_") .replace("-", "_") ) if assumed_library_name in not_standard_names.keys(): return not_standard_names[assumed_library_name] return assumed_library_name
def multi_lstrip(txt: str) -> str: """Left-strip all lines in a multiline string.""" return "\n".join(line.lstrip() for line in txt.splitlines()).strip()
def evaluate_ensemble(data, prediction): """ Evaluate the prediction (List[int]) base on the valid/test data (dict) """ total_prediction = 0 total_accurate = 0 for i in range(len(data["is_correct"])): if prediction[i] >= 0.5 and data["is_correct"][i]: total_accurate += 1 if prediction[i] < 0.5 and not data["is_correct"][i]: total_accurate += 1 total_prediction += 1 return total_accurate / float(total_prediction)
def cell_get_units(value, default_units): """ Given a single string value (cell), separate the name and units. :param value: str :param default_units: indicate return units string subset :return: unit for row """ if '(' not in value: return default_units spl = value.split(' ') name = '' found_units = False for sub in spl: if ')' in sub: found_units = False if '(' in sub or found_units: name = f'{name} {sub.replace("(", "").replace(")", "")} ' found_units = True return name.strip()
def dummy_task(**kwargs): """Use this one for testing mule""" print("Hi! I'm dummy! My kwargs are: %s", kwargs) return True
def torch_dim_to_trt_axes(dim): """Converts torch dim, or tuple of dims to a tensorrt axes bitmask""" if not isinstance(dim, tuple): dim = (dim,) # create axes bitmask for reduce layer axes = 0 for d in dim: axes |= 1 << (d - 1) # -1 to remove batch dimension return axes
def get_slope(x1, y1, x2, y2): """slope is used to seperate the lines to left and right """ if round(x1 - x2, 2) == 0: return None else: return (y2 - y1) / (x2 - x1)
def _split_docstring(docstring: str): """Splits the docstring into a summary and description.""" if not docstring: docstring = "" lines = docstring.splitlines() if not lines: return "", "" # Skip leading blank lines. while lines and not lines[0]: lines = lines[1:] if len(lines) > 2: return lines[0], "\n".join(lines[2:]) else: return lines[0], ""
def make_id_response(id): """ Usually used for requests that create single resources. :param id: ID of of the created resource. :return: Single ID response. """ return {'id': id}
def append_key(stanzas, left_struc, keypath=None): """Get the appropriate key for appending to the sequence ``left_struc``. ``stanzas`` should be a diff, some of whose stanzas may modify a sequence ``left_struc`` that appears at path ``keypath``. If any of the stanzas append to ``left_struc``, the return value is the largest index in ``left_struc`` they address, plus one. Otherwise, the return value is ``len(left_struc)`` (i.e. the index that a value would have if it was appended to ``left_struc``). >>> append_key([], []) 0 >>> append_key([[[2], 'Baz']], ['Foo', 'Bar']) 3 >>> append_key([[[2], 'Baz'], [['Quux', 0], 'Foo']], [], ['Quux']) 1 """ if keypath is None: keypath = [] addition_key = len(left_struc) for stanza in stanzas: prior_key = stanza[0] if (len(stanza) > 1 and len(prior_key) == len(keypath) + 1 and prior_key[-1] >= addition_key): addition_key = prior_key[-1] + 1 return addition_key
def guessPeriodicity(srcBounds): """ Guess if a src grid is periodic Parameters ---------- srcBounds : the nodal src set of coordinates Returns ------- 1 if periodic, warp around, 0 otherwise """ res = 0 if srcBounds is not None: res = 1 # assume longitude to be the last coordinate lonsb = srcBounds[-1] nlon = lonsb.shape[-1] dlon = (lonsb.max() - lonsb.min()) / float(nlon) tol = 1.e-2 * dlon if abs((lonsb[..., -1] - 360.0 - lonsb[..., 0] ).sum() / float(lonsb.size)) > tol: # looks like a regional model res = 0 return res
def split_v(v): """Given V-gene, returns that V-gene, its subgroup, name and allele. If a part cannot be retrieved from v, empty string will be returned for that part""" star = '*' in v if '-' in v: vs = v.split('-') subgroup = vs[0] if star: vs=vs[-1].split('*') name=vs[0] allele=vs[1] else: name=vs[1] allele='' elif star: vs = v.split('*') subgroup = vs[0] name = '' allele = vs[1] else: subgroup=v name='' allele='' return([v,subgroup,name,allele])
def get_pgsnapshot(module, array): """Return Snapshot (active or deleted) or None""" try: snapname = module.params['name'] + "." + module.params['suffix'] for snap in array.get_pgroup(module.params['name'], pending=True, snap=True): if snap['name'] == snapname: return snapname except Exception: return None
def dfs(grid, x, y): """When find a `0` in the grid, visit all neighbor `0` s and decide whether it is an island.""" height, width = len(grid), len(grid[0]) is_island = True if (x == 0 or x == height - 1) or (y == 0 or y == width - 1): is_island = False # When visited, set grid[x][y] = -1 to avoid visiting repeatly. grid[x][y] = -1 directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] for direction in directions: new_x = x + direction[0] new_y = y + direction[1] if (0 <= new_x < height and 0 <= new_y < width and grid[new_x][new_y] == 0): dfs_result = dfs(grid, new_x, new_y) is_island = is_island & dfs_result return is_island
def call_put_split(current_price, call_chain, put_chain): """ Returns true if the call volume and impliedint point to rise """ if len(call_chain) > len(put_chain): if abs(float(call_chain[0][0]) - current_price) > abs(float(put_chain[0][0]) - current_price): # if spread is greater for call -> watch for covered calls return 0 else: return 1 else: return 0
def getPooledVariance(data): """return pooled variance from a list of tuples (sample_size, variance).""" t, var = 0, 0 for n, s in data: t += n var += (n - 1) * s assert t > len(data), "sample size smaller than samples combined" return var / float(t - len(data))
def set_to_provider_client(unparsed_set): """Take a oai set and convert into provider_id and client_id""" # Get both a provider and client_id from the set client_id = None provider_id = None if unparsed_set: # Strip any additional query if "~" in unparsed_set: unparsed_set, _ = unparsed_set.split("~") if unparsed_set: # DataCite API deals in lowercase unparsed_set = unparsed_set.lower() if "." in unparsed_set: provider_id, _ = unparsed_set.split(".") client_id = unparsed_set else: provider_id = unparsed_set return provider_id, client_id
def multiply_nums(n1, n2): """Function to multiplies two numbers. n1 : Must be a numeric type n2 : Must be a numeric type """ result = n1 * n2 return result
def isfalsy(x): """Given an input returns True if the input is a "falsy" value. Where "falsy" is defined as None, '', or False.""" return x is None or x == '' or x == False
def ifact(n): """Iterative""" for i in range(n - 1, 0, -1): n *= i return n
def collate_fn(x_y_list): """ :param x_y_list: len(N * (x, y)) :return: x_list, y_list """ return [list(samples) for samples in zip(*x_y_list)]
def get_urls_from_object(tweet_obj): """Extract urls from a tweet object Args: tweet_obj (dict): A dictionary that is the tweet object, extended_entities or extended_tweet Returns: list: list of urls that are extracted from the tweet. """ url_list = [] if "entities" in tweet_obj.keys(): if "urls" in tweet_obj["entities"].keys(): for x in tweet_obj["entities"]["urls"]: try: url_list.append(x["expanded_url"] if "expanded_url" in x.keys() else x["url"]) except Exception: pass return url_list
def transpose_and_multiply(m, multiplier=1): """swap values along diagonal, optionally adding multiplier""" for row in range(len(m)): for col in range(row + 1): temp = m[row][col] * multiplier m[row][col] = m[col][row] * multiplier m[col][row] = temp return m
def caesar_cipher_decryptor(key: int, encrypted_message: str) -> str: """Decrypts a message which has been encrypted using a Caesar Cipher. Args: encrypted_message (str): Message to be decrypted. key (int): Original shift. Returns: decrypted_message (str): Decrypted message. """ decrypted_message = "".join([chr(((ord(char) - ord("a") - key) % 26) + ord("a")) for char in encrypted_message]) return decrypted_message
def not_empty(data): """Checks if not empty""" if data != "": return True else: return False
def has_checked_all_boxes(array, total): """ Return a string indicating length of array compared with expected total :param array eg ["value"]: :param total eg 2: :return "failed": """ if len(array) < total: return "failed" else: return "passed"