content
stringlengths
42
6.51k
def determine_native_name(coreclr_args, base_lib_name, target_os): """ Determine the name of the native lib based on the OS. Args: coreclr_args (CoreclrArguments): parsed args base_lib_name (str) : root name of the lib target_os (str) : os to run tests on Return: (str) : name of the native lib for this OS """ if target_os == "OSX": return "lib" + base_lib_name + ".dylib" elif target_os == "Linux": return "lib" + base_lib_name + ".so" elif target_os == "windows": return base_lib_name + ".dll" else: raise RuntimeError("Unknown OS.")
def video_type(compress: bool = False, trim: bool = False, trim_compress: bool = False) -> str: """Return type of the video. The returned value is generated by conditional checks. Args: compress: Boolean value (default: False) if video to be compress. trim: Boolean value (default: False) if video is to be trimmed. trim_compress: Boolean value (default: False) if trimmed video is to be compressed. Returns: String for video type. """ temp = ['a', 'a'] if compress: temp[0] = 'c' if trim: temp[1] = 'n' if trim_compress: temp[1] = 'c' return ''.join(temp)
def get_lock_filepath(filepath): """Get a lock file path for filepath. Args: filepath (str): Path. Returns: str: Lock file path. """ return f'{filepath}.lock'
def next_power(x: int, k: int = 2) -> int: """Calculate x's next higher power of k.""" y, power = 0, 1 while y < x: y = k ** power power += 1 return y
def getAngleStatus(angle): """ returns status based on the angle. Status codes: 0 - straight (-10 to +10) 1 - left or down (less than -10) 2 - right or up (greater than 10) """ if angle < -10: return 1 elif angle > 10: return 2 return 0
def transform(data, pse): """The transformer function.""" param = "payload" pos = data.find(param + "=") pos += len(param + "=") body = data[pos:] if body.endswith("\r\n"): body = body.rstrip("\r\n") elif body.endswith("\n"): body = body.rstrip("\n") elif body.endswith("\r"): body = body.rstrip("\r") return body + "\n"
def cpu_bound_summing_custom(number: int): """ Multiprocessing doesn't seem to like the library "deal". """ return sum(i * i for i in range(number + 1))
def use_middleware_script(container_type): """ Should the pilot use a script for the stage-in/out? Check the container_type (from queuedata) if 'middleware' is set to 'container' or 'bash'. :param container_type: container type (string). :return: Boolean (True if middleware should be containerised). """ # see definition in atlas/container.py, but also see useful code below (in case middleware is available locally) #:param cmd: middleware command, used to determine if the container should be used or not (string). #usecontainer = False #if not config.Container.middleware_container: # logger.info('container usage for middleware is not allowed by pilot config') #else: # # if the middleware is available locally, do not use container # if find_executable(cmd) == "": # usecontainer = True # logger.info('command %s is not available locally, will attempt to use container' % cmd) # else: # logger.info('command %s is available locally, no need to use container' % cmd) # FOR TESTING #return True if config.Container.middleware_container_stagein_script else False return True if container_type == 'container' or container_type == 'bash' else False
def iou_set(set1, set2): """Calculate iou_set """ union = set1.union(set2) return len(set1.intersection(set2)) / len(union) if union else 0
def camel_case(st): """ Convert a string to camelCase. From: https://stackoverflow.com/questions/8347048/camelcase-every-string-any-standard-library """ output = ''.join(x for x in st.title() if x.isalnum()) return output[0].lower() + output[1:]
def pad(input, size=8): """ >>> pad('foo') 'foo=====' >>> pad('MZXW6YTBOJUWU23MNU') 'MZXW6YTBOJUWU23MNU======' """ quanta, remainder = divmod(len(input), size) padding = '=' * ((size - remainder) % size) return input + padding
def _merge_keys(dicts): """Return the union of the keys in the list of dicts.""" keys = [] for d in dicts: keys.extend(d.keys()) return frozenset(keys)
def fix_file(filename): """ ASCII STL file from 3D GNOME have a broken first line so we patch it into another file, leaving the original untouched """ new_filename = filename.replace('.stl','_fix.stl') # Kludgy with open(filename,'r') as f: first_line = f.readline() if 'pixelfacet' in first_line: new_line = first_line.replace('pixelfacet','pixel\nfacet') with open(new_filename,'w') as g: g.write(new_line) for line in f: g.write(line) else: return filename return new_filename
def duo_anonymous_ip_failure(rec): """ author: airbnb_csirt description: Alert on Duo auth logs marked as a failure due to an Anonymous IP. reference: https://duo.com/docs/policy#anonymous-networks playbook: N/A """ return rec['result'] == 'FAILURE' and rec['reason'] == 'Anonymous IP'
def fibonacci(n): """Function that provides nth term of a fibonacci series.""" x, y = 0, 1 for i in range(n - 1): x, y = y, x + y return x
def all_equal(values: list): """ Check that all values in given list are equal """ return all(values[0] == v for v in values)
def removePenBob(data): """ Merge segments with same beginning and end """ outData = {} for pen in data: outSegments = [] outSegment = [] for segment in data[pen]: if not outSegment: outSegment = list(segment) elif outSegment[-1] == segment[0]: outSegment += segment[1:] else: outSegments.append(outSegment) outSegment = list(segment) if outSegment: outSegments.append(outSegment) if outSegments: outData[pen] = outSegments return outData
def ScaleData(data, old_min, old_max, new_min, new_max): """Scale the input data so that the range old_min-old_max maps to new_min-new_max. """ def ScalePoint(x): if x is None: return None return scale * x + translate if old_min == old_max: scale = 1 else: scale = (new_max - new_min) / float(old_max - old_min) translate = new_min - scale * old_min return list(map(ScalePoint, data))
def get_user_video_url(user_type, key): """Compile the user videos url.""" return f'https://www.pornhub.com/{user_type}/{key}/videos'
def does_intersect_rect(p, particles, padding, rect, is_3d = False): """ Returns true if particle p is sufficiently close or outside the rectangle (in 2d) or cuboid (in 3d) Parameters ---------- p : list Coordinates of center and radius of particle [x,y,z,r] particles : list List of center + radius of multiple particles. E.g. particles[0] is a list containing coordinates of center and radius. padding: float Minimum distance between circle boundaries such that if two circles rect: list Coordinates of left-bottom and right-top corner points of rectangle (2d) or cuboid (3d). E.g. [x1 y1, z1, x2, y2, z2] is_3d: bool True if we are dealing with cuboid Returns ------- bool True if particle intersects or is near enough to the rectangle """ if len(p) < 4: raise Exception('p = {} must have atleast 4 elements'.format(p)) if len(particles) == 0: raise Exception('particles = {} can not be empty'.format(particles)) if padding < 0.: raise Exception('padding = {} can not be negative'.format(padding)) if len(rect) < 6: raise Exception('rect = {} must have 6 elements'.format(rect)) pr = [p[0] - p[3], p[1] - p[3], p[2], p[0] + p[3], p[1] + p[3], p[2]] if is_3d: pr[2] -= p[3] pr[5] += p[3] if pr[0] < rect[0] + padding or pr[1] < rect[1] + padding or pr[3] > rect[3] - padding or pr[4] > rect[4] - padding: if is_3d: if pr[2] < rect[2] + padding or pr[5] > rect[5] - padding: return True else: return True return False
def to_string(tag): """ Creates a pretty string from any given XML tag. """ temp = tag.replace('_', ' ').title() temp = temp.replace('Fir', 'FIR') return temp
def get_numeric_columns(columns): """Identify numeric string elements in a list. Parameters ---------- columns : list List of str with column names. Returns ------- list List containing all string elements which are numeric. """ numeric_elements = [] for column in columns: try: float(column) except ValueError: continue numeric_elements.append(column) return numeric_elements
def hyphen_last(s): """Converts '-foo' to 'foo-', so that 'foo-' comes after 'foo' which is useful for sorting.""" if s.startswith('-'): return s[1:] + '-' return s
def selected_summary(summaries: list = []): """ The gene summary selection algorithm used to select the summary that is displayed at the top of the gene report. :param summaries: An ordered list containing counts of each gene summary type. :return: The name of the summary that would be selected given the list of counts. """ selected = "Automatic summary" if int(summaries[0]) >= 1: selected = "Gene Snapshot" elif int(summaries[1]) >= 1: selected = "UniProt Function" # elif int(summaries[2]) == 1: # selected = "FlyBase Pathway" # elif int(summaries[2]) > 1: # selected = "FlyBase Pathway (multiple)" # elif int(summaries[3]) == 1: # selected = "FlyBase Gene Group" # elif int(summaries[3]) > 1: # selected = "FlyBase Gene Group (multiple)" elif int(summaries[4]) >= 1: selected = "Interactive Fly" elif int(summaries[5]) >= 1: selected = "Alliance Gene Description" return selected
def decUTF8(inp): """ Recursively decode bytes as utf8 into unicode """ if isinstance(inp, bytes): return inp.decode('utf8') elif isinstance(inp, list): return [decUTF8(x) for x in inp] elif isinstance(inp, dict): return {decUTF8(key): decUTF8(val) for key, val in inp.items()} else: return inp
def read_file(path: str) -> str: """ Get the content of a file """ try: return open(path, "r").read() except FileNotFoundError: return ""
def flight_time_movies_3_utilize_set(movie_lengths, flight_length): """ Solution: As we iterate through our movie lengths, store the matching movie length needed in a set for a constant time lookup on all subsequent iterations. Complexity: Time: O(n) Space: O(n) """ if len(movie_lengths) < 2: raise ValueError('movie length list must be at least 2 items long') movie_lengths_needed = set() # For each movie length for movie_length_first in movie_lengths: if movie_length_first in movie_lengths_needed: return True movie_lengths_needed.add(flight_length - movie_length_first) return False
def remove_path_segments(segments, remove): """ Removes the path segments of <remove> from the end of the path segments <segments>. Examples: # '/a/b/c' - 'b/c' == '/a/' remove_path_segments(['','a','b','c'], ['b','c']) == ['','a',''] # '/a/b/c' - '/b/c' == '/a' remove_path_segments(['','a','b','c'], ['','b','c']) == ['','a'] Returns: The list of all remaining path segments after the segments in <remove> have been removed from the end of <segments>. If no segments from <remove> were removed from <segments>, <segments> is returned unmodified. """ # [''] means a '/', which is properly represented by ['', '']. if segments == ['']: segments.append('') if remove == ['']: remove.append('') ret = None if remove == segments: ret = [] elif len(remove) > len(segments): ret = segments else: toremove = list(remove) if len(remove) > 1 and remove[0] == '': toremove.pop(0) if toremove and toremove == segments[-1 * len(toremove):]: ret = segments[:len(segments) - len(toremove)] if remove[0] != '' and ret: ret.append('') else: ret = segments return ret
def tokenize(source): """ Splits an input string into meaningful tokens (left parens, right parens, other whitespace-separated values). Returns a list of strings. Arguments: source (str): a string containing the source code of a carlae expression """ # Separate all the tokens with blank space, and then split the string into a list source = source.replace('(', ' ( ').replace(')', ' ) ').replace('\n', ' \n ').replace('\t', ' ') source = source.split(' ') # Keep all the meaningful tokens by checking which part is the comment semicolon = False result = [] for i in range(len(source)): token = source[i] if token == '\n': semicolon = False continue elif token == ';' or semicolon: semicolon = True continue if token != '': result.append(source[i]) return result
def retriable_error(exception): """Return True if test should be re-run based on the Exception""" return isinstance(exception, (AssertionError,))
def _maybe_right_split(s, splitter): """If we can, split the string `s` by `splitter` and take the right-hand component (the second item in the returned tuple). """ if splitter and splitter in s: return s.split(splitter)[1] else: return s
def flatten(d, sep='_', parent_key=''): """Flattens a nested map. Adapted from https://stackoverflow.com/a/6027615/254190""" items=dict() for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if v and isinstance(v, dict): items = {**items, **flatten(v, sep, new_key)} else: items[new_key] = v return items
def path_shift(script_name, path_info, shift=1): """ Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1) """ if shift == 0: return script_name, path_info pathlist = path_info.strip('/').split('/') scriptlist = script_name.strip('/').split('/') if pathlist and pathlist[0] == '': pathlist = [] if scriptlist and scriptlist[0] == '': scriptlist = [] if 0 < shift <= len(pathlist): moved = pathlist[:shift] scriptlist = scriptlist + moved pathlist = pathlist[shift:] elif 0 > shift >= -len(scriptlist): moved = scriptlist[shift:] pathlist = moved + pathlist scriptlist = scriptlist[:shift] else: empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO' raise AssertionError("Cannot shift. Nothing left from %s" % empty) new_script_name = '/' + '/'.join(scriptlist) new_path_info = '/' + '/'.join(pathlist) if path_info.endswith('/') and pathlist: new_path_info += '/' return new_script_name, new_path_info
def pascal_row(n): """ Returns n-th row of Pascal's triangle """ result = [1] x, numerator = 1, n for denominator in range(1, n // 2 + 1): x *= numerator x /= denominator result.append(x) numerator -= 1 if n & 1 == 0: result.extend(reversed(result[:-1])) else: result.extend(reversed(result)) return result
def format_runtime(runtime): """Formats the given running time (in seconds).""" if runtime < 60: # Just seconds. return '{:.2f}s'.format(runtime) # Minutes and seconds. return '{}m {}s'.format(int(runtime // 60), int(runtime % 60))
def printable_glyph_list(glyph_list, quote=False): """Returns a printable form for a list of glyphs.""" if quote: suffix = "'" else: suffix = "" if len(glyph_list) == 1: return glyph_list[0] + suffix else: glyph_list = [glyph + suffix for glyph in glyph_list] return " ".join(glyph_list)
def filter_by_value(dct, func=lambda val: val): """ filter dictionary entries by their values """ return {key: val for key, val in dct.items() if func(val)}
def create_final_top_msg(top_songs: list) -> str: """ Function, that create top command response message. """ msg = f"TOP {len(top_songs)} songs\n" for song in top_songs: msg += f"{song['artist']} - {song['title']} ---- {len(song['voted_users'])}\n" return msg
def get_strs_in_cats(str_list, cats, compl=False): """ str_list is the general list of strings, usually the list of all cell names cats is a selection of strings, it is usually a list for any x in str_list, if x is part of any y (y is an element of cats) then x is chosen. Example of str_list: all the cells in the experiment example of cats: ['Broad T', 'Keystone L'], then all the cells which have a substring 'Broad T' or the substring 'Keystone L' will be chosen. An other way of putting it: choosing all the cells that are part of any of the categories in cats the option compl gives the complementary set of names """ if not compl: return [name for name in str_list if any(x in name for x in cats)] else: return [name for name in str_list if not any(x in name for x in cats)]
def contigs_n_bases(contigs): """Returns the sum of all n_bases of contigs.""" return sum(c.n_bases for c in contigs)
def classToExceptionCode(cls): """ return C++ enum exception code for class Args: cls: an exception class, must be inheriting from Exception Returns: integer encoding exception type """ lookup = {BaseException : 100, Exception : 101, ArithmeticError : 102, BufferError : 103, LookupError : 104, AssertionError : 105, AttributeError : 106, EOFError : 107, GeneratorExit : 108, ImportError : 109, ModuleNotFoundError : 110, IndexError : 111, KeyError : 112, KeyboardInterrupt : 113, MemoryError : 114, NameError : 115, NotImplementedError : 116, OSError : 117, OverflowError : 118, RecursionError : 119, ReferenceError : 120, RuntimeError : 121, StopIteration : 122, StopAsyncIteration : 123, SyntaxError : 124, IndentationError : 125, TabError : 126, SystemError : 127, SystemExit : 128, TypeError : 129, UnboundLocalError : 130, UnicodeError : 131, UnicodeEncodeError : 132, UnicodeDecodeError : 133, UnicodeTranslateError : 134, ValueError : 135, ZeroDivisionError : 136, EnvironmentError : 137, IOError : 138, BlockingIOError : 139, ChildProcessError : 140, ConnectionError : 141, BrokenPipeError : 142, ConnectionAbortedError : 143, ConnectionRefusedError : 144, FileExistsError : 145, FileNotFoundError : 146, InterruptedError : 147, IsADirectoryError : 148, NotADirectoryError : 149, PermissionError : 150, ProcessLookupError : 151, TimeoutError : 152 } try: return lookup[cls] except: return
def get_env_logname(name): """ get_env_logname """ modname = name.split('.')[0].upper() envname = f"{modname}_LOGLEVEL" # print(envname) return envname
def _getname(infile): """ Get file names only. Examples -------- >>> _getname("drop/path/filename.txt") 'filename.txt' >>> _getname(["drop/path/filename.txt", "other/path/filename2.txt"]) ['filename.txt', 'filename2.txt'] """ from pathlib import Path if isinstance(infile, (list, tuple)): return [Path(f).name for f in infile] return Path(infile).name
def _generate_params(kwargs): """ Generate JSON based on the arguments passed to this function """ params = {} for key in kwargs: if kwargs[key] != None: params[key] = kwargs[key] return params
def compute_max_shape(shapes, max_dims=None): """Computes the maximum shape combination from the given shapes. Parameters ---------- shapes : iterable of tuple Shapes to coombine. max_dims : int, optional Pre-computed maximum dimensions of the final shape. If None, is computed on the fly. Returns ------- max_shape : tuple Maximum shape combination. """ shapes = tuple(shapes) if max_dims is None: max_dims = max(len(shape) for shape in shapes) max_shape = [0, ] * max_dims for dim in range(max_dims): for shape in shapes: try: dim_len = shape[dim] except IndexError: pass else: if dim_len > max_shape[dim]: max_shape[dim] = dim_len return tuple(max_shape)
def eliminate(problem, location, listOfLocations): """ Given a list of locations, eliminate from the problem the number that is present at the `location`. :param list problem: Two-dimensional list of sets :param tuple location: Location with the number to be removed :param list<tuple> listOfLocations: List of locations to have the number removed :return: Count of eliminations :rtype: int """ loc_r, loc_c = location number_set = problem[loc_r][loc_c] # Don't perform any elimination if the location contains more than a number if len(number_set) != 1: return 0 number = next(iter(number_set)) count = 0 for loc_remove in listOfLocations: if loc_remove == location: continue loc_r, loc_c = loc_remove if number in problem[loc_r][loc_c]: problem[loc_r][loc_c] = problem[loc_r][loc_c] - number_set count += 1 return count
def sqlchar_encode(encvalue): """ SQL char encode the specified value. Example Format: CHAR(72)+CHAR(101)+CHAR(108)+CHAR(108)+CHAR(111)""" charstring = "" for item in encvalue: val = "CHAR(" + str(ord(item)) + ")+" charstring += val return(charstring.rstrip("+"))
def normalize(text, *, title_case: bool = True, underscores: bool = True, **kwargs): """Attempts to normalize a string Parameters ----------- text: Any The string or object to attempt to normalize title_case: bool Returns the formatted string as a Title Case string. Any substitutions specified as keyword arguments are done before the string is converted to title case. underscores: bool Whether or not underscores are replaced with spaces """ text = str(text) if underscores: text = text.replace("_", " ") for item in kwargs: text = text.replace(item, kwargs[item]) if title_case: text = text.title() return text
def elipses(long_string,max_length=40,elipses='...'): """!Returns a shortened version of long_string. If long_string is longer than max_length characters, returns a string of length max_length that starts with long_string and ends with elipses. Hence, the number of characters of long_string that will be used is max_length-len(elipses) @param long_string a basestring or subclass thereof @param max_length maximum length string to return @param elipses the elipses string to append to the end""" strlen=len(long_string) if strlen<max_length: return long_string else: return long_string[0:max_length-len(elipses)]+elipses
def runnable_validator(language, options): """Options validator for runnable codemirror code blocks.""" okay = True if 'lang' not in options: okay = False return okay
def get_tool_info(whitelist, tool_name): """ Search the whitelist by tool name. :returns: A dictionary , or none if no tool matching that name was found. :rtype: dict or None """ for category, category_tools in whitelist.items(): for tool_info in category_tools: if tool_info.get("name") == tool_name: tool_info.update({"category": category}) return tool_info return None
def XYToInd(location, width, height): """Location (x,y) to index""" return location[1] * width + location[0]
def stringify_value(value): """Convert any value to string. """ if value is None: return u'' isoformat = getattr(value, 'isoformat', None) if isoformat is not None: value = isoformat() return type(u'')(value)
def code_to_str(code,alphabet): """ Takes a code list/tensor and gets the corresponding sentence using the alphabet. Alphabet must have has blank(0) at index zero, each symbol is an idx. """ return "".join([alphabet[symbol] for symbol in code])
def to_bool(value: str) -> bool: """ Convert a string to a boolean. Arguments: value: The string to convert. Returns: True or False. """ return value.lower() not in {"", "0", "no", "n", "false", "off"}
def sunset_float(solar_noon_float, hour_angle_sunrise): """Returns Sunset as float with Solar Noon Float, solar_noon_float and Hour Angle Deg, hour_angle_deg""" sunset_float = (solar_noon_float * 1440 + hour_angle_sunrise * 4) / 1440 return sunset_float
def get_user(user_id=None): """ Return object representing the logged in user Keyword Parameters: user_id -- String, identifier representing the logged in user (Default: None, representing an public/anonymous user session) >>> # Check public/Anonymous user >>> from pprint import pprint >>> anonymous_user = get_user() >>> pprint(anonymous_user) {'user': {'description': 'Anonymous user.', 'id': None}} >>> anonymous_user = get_user(None) #public/Anonymous user >>> pprint(anonymous_user) {'user': {'description': 'Anonymous user.', 'id': None}} >>> # Check logged in user >>> user = get_user('uid=bob.newhart,ou=People,o=bobnewhart.com') >>> pprint(user) {'user': {'description': 'Authenticated user.', 'id': 'uid=bob.newhart,ou=People,o=bobnewhart.com'}} """ description = "Authenticated user." if user_id is None: description = "Anonymous user." attributes = {'id': user_id, 'description': description} user_object = {'user': attributes} return user_object
def get_lake_abbrev(record): """A helper function used by get_latlon() Arguments: - `record`: """ lake = record.get("lake") if lake: lake = lake.strip() if len(lake) > 2: return lake[:2].upper() else: return lake.upper() else: return None
def go_up_right(x: int, y: int) -> tuple: """ Go 1 unit in both positive x and y directions :param x: x-coordinate of the node :param y: y-coordinate of the node :return: new coordinates of the node after moving diagonally up-right """ return x + 1, y + 1
def make_pairs(I, mid): """ We take pairs as [ [9, 1], [8, 2], [7, 3], [6, 4]] :param I: :param mid: :return: """ h = 0 t = len(I) - 1 pairs = [] while h < mid-1: pairs.append([I[h], I[t]]) h += 1 t -= 1 return pairs
def sample_bounded_Pareto(alpha = 1., L = 1., H = 100., size=None, seed=None): """ Use: sample_bounded_Pareto(alpha = 1., L = 1., H = 100., size=None, seed=None) random samples drawn from the bounded Pareto distribution, p_X(x) ~ x^(-alpha-1), L<x<H 0, else See https://en.wikipedia.org/wiki/Pareto_distribution Input: alpha: scale parameter. ......................... float, alpha>0 L: lower bound .................................. float, L>0 H: upper bound .................................. float, H>L size: number of points to draw. 1 by default. ... int, size>0 seed: specify a random seed. .................... int Output: X: Array of randomly distributed values. ........ (size,) np array """ import numpy as np prng = np.random.RandomState(seed=seed) U = prng.uniform(size=size) return H*L*( (1-U)*H**alpha + U*L**alpha )**(-1./alpha)
def create_zero_matrix(rows: int, columns: int) -> list: """ Creates a matrix rows * columns where each element is zero :param rows: a number of rows :param columns: a number of columns :return: a matrix with 0s e.g. rows = 2, columns = 2 --> [[0, 0], [0, 0]] """ matrix = [] if not isinstance(rows, int) or not isinstance(columns, int): return [] if type(rows) == bool or type(columns) == bool: return [] if columns < 1 or rows < 1: return [] for i in range(rows): new = [] for y in range(columns): new.append(0) matrix.append(new) return matrix
def calories(snacks): """ >>> calories(0) 0 >>> calories(1) 5 >>> calories(2) 55 >>> calories(3) 60 >>> calories(4) 110 """ unhealthy = 50 healthy = 5 if snacks % 2 == 0 and snacks != 0: return calories(snacks - 1) + unhealthy elif (snacks % 2 == 1) and snacks != 1: return calories(snacks - 1) + healthy elif snacks == 1: return healthy else: return 0
def complete_english(string): """ >>> complete_english('dont do this') "don't do this" >>> complete_english('doesnt is matched as well') "doesn't is matched as well" """ for x, y in [("dont", "don't"), ("doesnt", "doesn't"), ("wont", "won't"), ("wasnt", "wasn't")]: string = string.replace(x, y) return string
def is_float_like(val): """Check if a value looks like a float.""" try: return str(float(val)) == str(val) except Exception: return False
def equation(operation, firstnum, secondnum): """ Solve a simple maths equation manually """ if operation == 'plus': return firstnum + secondnum elif operation == 'minus': return firstnum - secondnum elif operation == 'multiply': return firstnum * secondnum elif operation == 'divide': if not secondnum == 0: return firstnum / secondnum raise ZeroDivisionError("Unable to divide by 0.") raise ValueError('Invalid operation provided.')
def get_bold_token(token): """Apply bold formatting to a given token. https://api.slack.com/docs/message-formatting#message_formatting Args: token (str): String sequence with a specific definition (for parser). Returns: str: bold formatted version of a token. """ return "*{}*".format(token)
def cdf_points(marginal_hist): """ Generate the points for a CDF of a distribution from its marginal histogram. """ cumulative = 0 total = sum(x[1] for x in marginal_hist) points = [] for (val, count) in marginal_hist: cumulative += count points.append((val, cumulative / (total + 1))) return points
def get_max_len(in_string, max_len): """Gets current length of string and returns it if it exceeds the provided max_len. Otherwise, returns the provided max_len. """ curr_len = len(in_string) if curr_len > max_len: return curr_len return max_len
def chunkIt(seq, num): """ Divide a sequence seq into num roughly equal pieces. :param seq: :param num: :return: """ avg = len(seq) / float(num) out = [] last = 0.0 while last < len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return out
def uncap_sentence(sent): """ Workaround for tweets: sometimes the entire sentence is in upper case. If more than 99% of the sentence is in upper case, this function will convert it to lower case. :param sent: the tweet :return: the sentence, lower cased if it is all in upper case """ ssent = sent.split() ssent_cap = [word for word in ssent if word[0].isupper()] if len(ssent_cap) * 1.00 / len(ssent) > 0.9: return sent.lower() else: return sent
def ext(name): """Extracts the filename extension.""" dot = name.rfind(".") if -1 != dot: return name[dot:] return ""
def hash_function_2(key: str) -> int: """ Sample Hash function #2 to be used with A5 HashMap implementation DO NOT CHANGE THIS FUNCTION IN ANY WAY """ hash, index = 0, 0 index = 0 for letter in key: hash += (index + 1) * ord(letter) index += 1 return hash
def street_not_in_use(street, items): """ Check if elements of street are not in use already. For example [[(2, 'black'), (3, 'black'), (4, 'black'),(5, 'black)],[(3, 'black'), (4, 'black'), (5, 'black')]] would return false, because 3, 4 and 5 are already used :param street: List of elements that will be checked :param items: list of items that are already planned to be played (here 2,3,4,5) :return: True if new street can be played as well, otherwise false """ for element in street: if element in items: return False return True
def prime_factors(n): """Returns all the prime factors of a positive integer""" factors = [] d = 2 while n > 1: while n % d == 0: factors.append(d) n /= d d = d + 1 if d*d > n: if n > 1: factors.append(n) break return factors
def escape_for_tsv(text: str) -> str: """Changes double-quotes to single-quotes, and adds double-quotes around the text if it has newlines/tabs.""" text.replace("\"", "'") if "\n" in text or "\t" in text: return "\"{}\"".format(text) return text
def pixel_pos_to_game_grid(x_pixel, y_pixel): """ input: position in pixels, touple return: position in gridtouple """ grid_nx = x_pixel // 100 # integere division grid_ny = y_pixel // 100 return(grid_nx, grid_ny)
def unnormalize_parameters(normed_parameters, minvals, maxvals): """takes in a list of parameters and undoes simple min/max normalization according to min/max values INPUTS normed_parameters: length n, containing parameters for a star minvals: length n, minimum parameter values maxvals: length n, max parameter values OUTPUTS unnormed_parameters: length n, unnormalized parameters """ unnormed_parameters = normed_parameters*(maxvals-minvals) + minvals return unnormed_parameters
def checkio(array): """ sums even-indexes elements and multiply at the last """ res = 0 if len(array)>0: sum = 0 for i in range(0,len(array)): if i % 2 == 1: continue print ('Selecting ', i , '->', array[i]) sum += array[i] print ('Last item = ', array[-1]) res = sum * array[-1] print (array, '->', res,'\n\n') return res
def get_pp_line(cv, vals): """ Return a point that gives a particular CV, when the collective variables are defined through a line. Parameters ---------- cv : array The target cv. vals : list A list of the line defining the CV. Returns ------- pp : array The value of the point. """ v1,v2 = vals pp = v1 + cv*(v2-v1) return pp
def c2scToSmcpName( c2scname ): """Turns 'Aacute.c2sc' into 'aacute.smcp'.""" glyphname = c2scname[:c2scname.find(".")].lower() suffix = c2scname[c2scname.find("."):].replace("c2sc", "smcp") return glyphname + suffix
def format_tweet_url(tweet: dict) -> str: """ Construct tweet link url :param tweet: :return: """ tweet_url = "https://twitter.com/{}/status/{}".format(tweet['user']['screen_name'], tweet['id_str']) return tweet_url
def make_tuple_fromstr(s, value_type): """ Create a tuple from a string. :param str s: string to convert to a tuple :param value_type: type of values to be contained within tuple :return: tuple from string :rtype: tuple """ # remove tuple braces and strip commands and space from all values in the tuple string values = [] for x in s.strip("(), ").split(","): x = x.strip("' ") if x: values.append(x) return tuple(value_type(i) for i in values)
def convert_row_to_dict(row): """ Convert a list of fields in the CloudFlare CSV file into a dict with field names. """ cf_dict = dict() cf_dict['hostname'] = row[0] cf_dict['clientIp'] = row[1] # CloudFlare Placeholder, always a hyphen cf_dict['col3'] = row[2] # CloudFlare Placeholder, always a hyphen cf_dict['col4'] = row[3] # CloudFlare timestamp is RFC 3339 and Loggly wants # ISO 8601. Should be compatible as RFC3339 is stricter # version of ISO 8601. cf_dict['timestamp'] = row[4] cf_dict['request'] = row[5] cf_dict['status'] = row[6] cf_dict['content-length'] = row[7] cf_dict['referer'] = row[8] cf_dict['user-agent'] = row[9] cf_dict['ray-id'] = row[10] return cf_dict
def ByteToHex( byteStr ): """ Convert a byte string to it's hex string representation e.g. for output. """ return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip()
def get_min_dr(frequency): """ Returns the MIN data rate for the provided frequency.""" # if frequency in VALID_FREQ: # return 0 # else: # return 0 return 0
def lwavg(a1, a2, w1, w2): """ A linear weighted average for comparison """ return (w1*a1 + w2*a2), 0
def nemoFibonacci(n, nemo): """Recursive Fibonacci function with nemoization. """ if n <= 0: return 0 elif n ==1: return 1 elif nemo[n] == 0: nemo[n] = nemoFibonacci(n-2, nemo) + nemoFibonacci(n-1, nemo) return nemo[n]
def _api_cmd(cmd): """Prefix the container command with the docker cmd""" return f"docker exec -it mpasocial_api {cmd}"
def GetGapSequenceConsensus_old(origTopoMSASeqList, indexIDTTopo):#{{{ """Get a sequence of gap fractions of the consensus topology """ gapSeqCons =[]; apd=gapSeqCons.append lengthAlignment = len(origTopoMSASeqList[0]); numIDTTopo = len(indexIDTTopo) for i in range(0, lengthAlignment): cntGap=0 for j in range(0, numIDTTopo): if origTopoMSASeqList[indexIDTTopo[j]][i] == '-': cntGap += 1 try: freq = cntGap/float(numIDTTopo) except ZeroDivisionError: freq = 0 apd(freq) return gapSeqCons
def convert_truelike_to_bool(input_item, convert_int=False, convert_float=False, convert_nontrue=False): """Converts true-like values ("true", 1, True", "WAHR", etc) to python boolean True. Taken from korbinian python package by Mark Teese. This is allowed under the permissive MIT license. Parameters ---------- input_item : string or int Item to be converted to bool (e.g. "true", 1, "WAHR" or the equivalent in several languagues) convert_float: bool Convert floats to bool. If True, "1.0" will be converted to True convert_nontrue : bool If True, the output for input_item not recognised as "True" will be False. If True, the output for input_item not recognised as "True" will be the original input_item. Returns ------- return_value : True, or input_item If input_item is True-like, returns python bool True. Otherwise, returns the input_item. Usage ----- # convert a single value or string convert_truelike_to_bool("true") # convert a column in a pandas DataFrame df["column_name"] = df["column_name"].apply(convert_truelike_to_bool) """ list_True_items = [True, 'True', "true", "TRUE", "T", "t", 'wahr', 'WAHR', 'prawdziwy', 'verdadeiro', 'sann', 'istinit', 'veritable', 'Pravda', 'sandt', 'vrai', 'igaz', 'veru', 'verdadero', 'sant', 'gwir', 'PRAWDZIWY', 'VERDADEIRO', 'SANN', 'ISTINIT', 'VERITABLE', 'PRAVDA', 'SANDT', 'VRAI', 'IGAZ', 'VERU', 'VERDADERO', 'SANT', 'GWIR', 'bloody oath', 'BLOODY OATH', 'nu', 'NU', 'damn right', 'DAMN RIGHT'] # if you want to accept 1 or 1.0 as a true value, add it to the list if convert_int: list_True_items += ["1"] if convert_float: list_True_items += [1.0, "1.0"] # check if the user input string is in the list_True_items input_item_is_true = input_item in list_True_items # if you want to convert non-True values to "False", then nontrue_return_value = False if convert_nontrue: nontrue_return_value = False else: # otherwise, for strings not in the True list, the original string will be returned nontrue_return_value = input_item # return True if the input item is in the list. If not, return either False, or the original input_item return_value = input_item_is_true if input_item_is_true == True else nontrue_return_value # special case: decide if 1 as an integer is True or 1 if input_item == 1: if convert_int == True: return_value = True else: return_value = 1 return return_value
def idx_to_zbin_nob(idx): """ Alternative to idx_to_zbin for when shear B modes are not included. Return the z bin corresponding to a particular row or column index, assuming 2 fields per z bin. Args: idx (int): Field index. Returns: int: z-bin corresponding to field index, where 1 is the first redshift bin. """ return 1 + idx // 2
def convert(names, midterm1, midterm2, final): """ Takes dictinaries and convert them to a list Args: names: dictionary keys are numbers values are names midterm1: dictionary keys are numbers values are midterm1 scores midterm2: dictionary keys are numbers values are midterm2 scores final: dictionary keys are numbers values are final scores Return: lst: list of tuples. Tuples includes number, name, midterm1, midterm2, final scores """ # /$$$$$$$$ /$$$$$$ /$$ /$$ # | $$_____/|_ $$_/| $$ | $$ # | $$ | $$ | $$ | $$ # | $$$$$ | $$ | $$ | $$ # | $$__/ | $$ | $$ | $$ # | $$ | $$ | $$ | $$ # | $$ /$$$$$$| $$$$$$$$| $$$$$$$$ # |__/ |______/|________/|________/ lst = [] return lst
def idtp(df, id_global_assignment, num_objects, idfn): """ID measures: Number of true positives matches after global min-cost matching.""" del df, id_global_assignment # unused return num_objects - idfn
def zipformat(ll, header_list): """ zips together FORMAT labels, Sample name and format values into one dict """ for nr, plist in enumerate(ll[9:]): formatlist = [ header_list[nr + 9] + "_" + i for i in plist[0].split(":") ] ll[nr + 9] = dict(zip(formatlist, plist[1].split(":"))) return ll
def unpack_str(bytes): """Convert a list of bytes to a string.""" return b''.join(bytes).decode("utf-8")
def _to_mask_bits(size): """Create a 32-bit integer representing a mask of the given # of bits""" mb = 0 for bs in range(31, 31 - size, -1): mb = mb | 1 << bs return mb
def assert_that_rectangles_do_not_overlap(rectangles): """given a list of rectangles and a description (any string) verify that all the rectangles are disjoint. The rectangles list consists of tuples, containing a rectangle and a description""" def geometry_to_string(rectangle): return '%dx%d%+d%+d' % (rectangle.width, rectangle.height, rectangle.x, rectangle.y) for i, (rect1, description1) in enumerate(rectangles): for (rect2, description2) in rectangles[0:i]: # compute the intersection of rect1 and rect2. # code identical to Rectangle::intersectionWith() tl_x = max(rect1.x, rect2.x) tl_y = max(rect1.y, rect2.y) br_x = min(rect1.x + rect1.width, rect2.x + rect2.width) br_y = min(rect1.y + rect1.height, rect2.y + rect2.height) overlap = tl_x < br_x and tl_y < br_y assert not overlap, \ '{} ({}) and {} ({}) overlap' \ .format(description1, geometry_to_string(rect1), description2, geometry_to_string(rect2))
def flatten(xs): """ Flatten any recursive list or tuple into a single list. For instance: - `flatten(x) => [x]` - `flatten([x]) => [x]` - `flatten([x, [y], [[z]]]) => `[x, y, z]` """ if isinstance(xs, (list, tuple)): return [y for ys in [flatten(x) for x in xs] for y in ys] return [xs]
def is_rejected_with_high_vaf(vaf, status, vaf_th): """Check if SNV is rejected with vaf over threshold. Args: vaf: vaf of the SNV. vaf_th: vaf threshold. status: reject/pass status of SNV. Returns: True if rejected, False otherwise """ if vaf > vaf_th and status == 'REJECT': return True else: return False