content
stringlengths
42
6.51k
def exclude(items, excludes): """Exclude removes all items in a list that is in the excludes list (for dirs)""" for ex in excludes: items = [x for x in items if not ex in x] # return items return items
def vis18(n): # DONE """ O O O OO OOO OOO ..OO ..OOO ....OO Number of Os: 3 6 9""" result = 'O\n' for i in range(n - 1): result += '.' * (i * 2) + 'OOO\n' result += '.' * ((n - 1) * 2) + 'OO\n' return result
def escape_shell(arg): """Escape a string to be a shell argument.""" result = [] for c in arg: if c in "$`\"\\": c = "\\" + c result.append(c) return "\"" + "".join(result) + "\""
def get_filename_from_path(path): """ :param path :return: file name without type """ return ".".join(path.replace('\\', '/').split('/')[-1].split('.')[:-1])
def size(o, default=None): """Helper to return the len() of an object if it is available""" if hasattr(o, "__len__"): return len(o) return default
def isSquare(mat): """ :param mat: a matrix of any dimension :return: if the matrix is true, it returns true, else returns false """ return all(len(row) == len(mat) for row in mat)
def MAPE(y_true, y_pred): """Mean Absolute Percentage Error Calculate the mape. # Arguments y_true: List/ndarray, ture data. y_pred: List/ndarray, predicted data. # Returns mape: Double, result data for train. """ y = [x for x in y_true if x > 0] y_pred = [y_pred[i] for i in range(len(y_true)) if y_true[...
def is_signed_out_of_range(num: int, size: int) -> bool: """ Check if the signed number `num` is out of range for signed numbers of `size` byte length. :param num: :param size: :return: """ if size == 1: return -128 <= num <= 127 elif size == 2: return -32_768 <= num <= 3...
def simple_overlap(regions0, regions1): """ Check whether two regions in a neuropil other than EB overlap. """ if regions0.intersection(regions1): return True else: return False
def convert(coord, delim=":"): """ Convert a hex RA/DEC value to float. """ segments = coord.split(delim) s = -1.0 if "-" in segments[0] else 1.0 return s * (abs(float(segments[0])) + float(segments[1]) / 60.0 + float(segments[2]) / 3600.0)
def isImage(link): """ Returns True if link ends with img suffix """ suffix = ('.png', '.jpg', '.gif', '.tiff', '.bmp', '.jpeg', '.svg') return link.lower().endswith(suffix)
def calc_nbases(DNA): """This command takes a seq and calculates its nbases.""" DNA = DNA.upper() for i in DNA: if i not in 'AGCTN': return 'Invalid Seq' return DNA.count('N')
def fix_time(t): """The change of BPM causes a mess with Noodle Extensions... """ return t if t < 320 else 320 + 122 * (t - 320) / 136
def get_event_type(tweet_id, labels_path, normal_tweets=[], mis_tweets=[]): """takes a tweet_id, and a groundtruth file path, then returns the type of this tweet either misinformation or normal""" if tweet_id in normal_tweets: return 'n' if tweet_id in mis_tweets: return 'm' ...
def is_pdb(datastr): """Detect if `datastr` if a PDB format v3 file.""" assert isinstance(datastr, str), \ f'`datastr` is not str: {type(datastr)} instead' return bool(datastr.count('\nATOM ') > 0)
def get_whos_up(dates_selected): """ return members_dict['Bob'] = [0, 'Bob', ('middle','Mon 12/24'), ('middle','Tue 12/25'), ] for use by show_whos_up() """ members_dict = {} p_ord = 0 for event in dates_selected: member = event['member'] try: members_dict[member]...
def is_external(config): """ Checks if the configuration is for an external transport. :param dict config: configuration to check :return: True if external, False otherwise :rtype: bool """ return config.get("external") == "1"
def _int_decode(data: bytes) -> int: """ Interpret a byte array to an integer (big endian) """ if len(data) == 0: return 0 return int.from_bytes(data, "big")
def format_error(error): """ Converts error into one line string representation. Extracts the exception type and message from the error to build a simple string summarizing the information to be used when logging. Parameters ---------- error : tuple Exception type, exception messag...
def to_base(n, b=1000000): """ represent the number n in base B string :param n: :param b: :return: """ return "0" if not n else to_base(n // b, b).lstrip("0") + chr(n % b)
def compute_iou(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) S_r...
def create_host_string(hosts): """ Creates a string with a pleasant style to display ip address/hostnames in the Jira issue description=. :param hosts: a list of dictionaries :return: string """ result = '' for host in hosts: result = result + ' | ' + host['ip'] ...
def number_indice_to_string(index)->str: """ Convert a number to a string. """ indicename = ["x", "y", "z"] return "".join([indicename[i] for i in index])
def arxiv_url_sanitizer(url): """ as of now, just converts arxiv.org/pdf/ to arxiv.org/abs """ # if its an arxiv pdf url then if url.find("pdf") != -1: url = url.replace("/pdf","/abs") url = url.replace(".pdf","") return url
def resource_not_found(payload=None): """Return custom JSON if a resource is not found :param payload: Customize the JSON to return if needed :type payload: dict, optional :return: A JSON dict with a message :rtype: dict """ if payload is not None: return payload else: r...
def strtobool (val, yesvals = ["yes", "y"], novals = ["no", "n"]): """Convert a string representation of truth to true (1) or false (0). Raises ValueError if 'val' is anything else.""" val = val.lower() if val in yesvals: return 1 elif val in novals: return 0 else: raise ...
def set_bitfield_bit(bitfield, i): """ Set the bit in ``bitfield`` at position ``i`` to ``1``. """ byte_index = i // 8 bit_index = i % 8 return ( bitfield[:byte_index] + bytes([bitfield[byte_index] | (1 << bit_index)]) + bitfield[byte_index+1:] )
def type_chain(iterable, type_iterable): """ Compares the type chain of an iterable, checks with only the first element Args: iterable (list): a list type_iterable (list): type chain Returns: bool: If the type chain is true for the iterable. """ for c_type in type_iterable: ...
def inv(a, n): """Inversion""" lm, hm = 1, 0 low, high = a % n, n while low > 1: r = high / low nm, new = hm - lm * r, high - low * r lm, low, hm, high = nm, new, lm, low return lm % n
def bit_width(value): """ Determine how many bits are needed to store this value. Args: value (int): The value to see how many bits we need to store it. Must be an integer >= 0. Returns: int: The number of bits needed to store this value """ # Check value is >= 0 ...
def test_header(calver, exp_type): """Create a header-like dictionary from `calver` and `exp_type` to support testing header-based functions. """ header = { "META.INSTRUMENT.NAME" : "SYSTEM", "REFTYPE" : "CRDSCFG", "META.CALIBRATION_SOFTWARE_VERSION" : calver, "META.EXPOS...
def parse_reaction(line): """ Takes a string declaring a new reaction in an Avida environment file and returns the name of the associated task. """ sline = line.split() return sline[2].strip()
def get_bbox(points): """Get the bounding box around the data, Parameters ---------- points : list of list of float List of (x, y) coordinates Returns ------- dict Dictionary containing the top left and bottom right points of a bounding box """ xs = [p[0] for p in p...
def _ensure_value_shape(value, layer): """Ensure that a value has the right shape for an input layer.""" # Add or remove dimensions of size 1 to match the shape of the layer. try: value_dims = len(value.shape) layer_dims = len(layer.shape) if value_dims < layer_dims: if all(i == 1 for i in layer...
def ceil_half_step(value): """Return value to the next/highest 0.5 units""" intval = round(value) if value > intval: return intval + 0.5 elif value == intval: return value else: return intval - 0.5
def calc_I_Chance2014_STTxx2_I(TEMP): """ Temp. (C) to Chance2014 parameterised [iodide] in nmol/dm^-3 (nM) """ # Parameterisation is a linear regression # y= 0.225(x**2) + 19 return (0.225*(TEMP**2)) + 19.0
def _strip_namespace(value_or_map): """ Remove the namespace part from the given cache key(s). """ def _strip(value): return value.split(":", 1)[-1] if hasattr(value_or_map, "keys"): return {_strip(k): v for k, v in value_or_map.iteritems()} elif hasattr(value_or_map, "__iter__"): ...
def normalize(value): """Returns the string that the decimal separators are normalized.""" return value.replace(',', '.')
def get_footer(modname): """print footer of documentation page, includes lots of extra lines so that anchor tags can jump to the correct element""" return '</div>' + '<br />'*20 + '</body></html>'
def _ffs(x): """Gets the index of the least significant set bit of x.""" return (x & -x).bit_length() - 1
def _parse_overscan_shape(rows, columns): """ Parse the number of overscan rows and columns into indices that can be used to reshape arrays. :param rows: The number of overscan rows. :type rows: int :param columns: The number of overscan columns. :type columns: ...
def escaped_str(s: str): """Escape all special characters in the string. Some special characters can have surprising effect, such as the newline character. For example it is common that the vocabulary file have one line per token, but if the token contain a newline character, it will be counted as two tokens...
def convert_data_to_backend_friendly(dic): """Convert the data coming from frontend in a form that can be used by serializer easily to update the database Args: dic ([dictionary]): [JSON data coming from frontend] Returns: [dictionary]: [Data in the form that can easily be used by seri...
def common_neighbors(neighbors_target, neighbors_source): """Compute the common neighbors between a source and a target node. """ common_neighbors = len(set(neighbors_source).intersection(set(neighbors_target))) return common_neighbors
def factorial(n): """Calculate n factorial n int > 0 returns n! """ if n == 1: return 1 return n * factorial(n - 1)
def checkWinner(board, width, default_value=' '): """ Function to check winner of tic-tac-toe IF your board is a single array that represents all the slots, i.e. [....] We are NOT going to validate that this is a square, we are trusting the user input. The only limitation is that the width * width ...
def untranspose(items, transposition): """Undoes a transpose >>> untranspose(['a', 'b', 'c', 'd'], [0,1,2,3]) ['a', 'b', 'c', 'd'] >>> untranspose(['d', 'b', 'c', 'a'], [3,1,2,0]) ['a', 'b', 'c', 'd'] >>> untranspose([13, 12, 14, 11, 15, 10], [3,2,4,1,5,0]) [10, 11, 12, 13, 14, 15] ...
def get_variants_from_log(trace_log, attribute_key="concept:name"): """ Gets a dictionary whose key is the variant and as value there is the list of traces that share the variant Parameters ---------- trace_log Trace log attribute_key Field that identifies the attribute (mus...
def quote(string): """Surround string with single quotes.""" return "'{0}'".format(string)
def ERR_NOPERMFORHOST(sender, receipient, message): """ Error Code 463 """ return "ERROR from <" + sender + ">: " + message
def get_square_indices(row, col): """ Given row and col of a cell, find all adjacent cells in its square. Return a list of zero-based indices """ sq_row, sq_col = row/3, col/3 # Identify the start location of square index in the grid sq_start_ndx = (sq_row*9*3) + (sq_col*3) sq_indices = ...
def nextpow2(x): """ Return the smallest integral power of 2 that >= x """ n = 2 while n < x: n = 2 * n return n
def longest_common_substring(string1, string2): """ Function to find the longest common substring of two strings :param string1: string1 :type string1: str :param string2: string2 :type string2: str :returns: longest common substring :rtype: str :Example: ...
def str2list(v): """Converts a string of comma separated values to a list of strs.""" if len(v) == 0: return [] return [str(item) for item in v.split(",")]
def sibpath(path, sibling): """Return the path to a sibling of a file in the filesystem. This is useful in conjunction with the special __file__ attribute that Python provides for modules, so modules can load associated resource files. Borrowed from twisted.python.util """ import os.path ...
def singlify(queryDict): # noqa """Convert queryDict into a normal dict. Return a dict of queryDict where lists of size 1 are replaced with a single value. """ result = {} for key in queryDict: val = queryDict.get(key) if isinstance(val, type([])) and len(val) == 1: ...
def euler_problem_25(n=1000): """ The Fibonacci sequence is defined by the recurrence relation: Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 ...
def str2bool(value): """ Converts a string with a boolean value into a proper boolean mostly useful for variables coming from ini parser """ if value in ['yes', 'true', 'True', 'on', '1']: return True return False
def product(list_of_numbers): """ Returns a product of numbers. :param list_of_numbers: the input list of numbers whose product is sought. """ answer = 1 for number in list_of_numbers: answer *= number return answer
def _ApplyFilter(filt, obj): """Apply the filter from _GenerateFilter to incoming message object.""" if not filt: return obj if isinstance(obj, list): # Lists are not filtered for now. return [_ApplyFilter(filt, o) for o in obj] elif isinstance(obj, dict): return {key: _ApplyFilter(filt[key], ob...
def safe_position(n): """ function to get the safe position formulae Initial(n) = 2^a +l W(n) = 2l + 1; where n = the total number a = the power of two l = the reminder after the power is deducted from n """ pow_two = 0 i = 0 while (n - pow_two) >= pow_two: pow_two = 2**i i = i+1 ...
def create_firmware_update_payload(device_info: dict, compliance_data_list: list) -> list: """ Creates the payload to send to OME to execute the firmware update Args: device_info: A dictionary of dictionaries containing the type information for each device compliance_data_list: A list of di...
def count_occurances(comment, word): """ A helper function to get number of words in a comment. """ a = comment.split(" ") count = 0 for i in range(len(a)): if (word == a[i]): count = count + 1 return count
def urljoin(*args): """Joins components of URL. Ensures slashes are inserted or removed where needed, and does not strip trailing slash of last element. Arguments: str Returns: str -- Generated URL """ trailing_slash = "/" if args[-1].endswith("/") else "" return "/".join(ma...
def minimum_migration_time_max_cpu(last_n, vms_cpu, vms_ram): """Selects the VM with the minimum RAM and maximum CPU usage. :param last_n: The number of last CPU utilization values to average. :param vms_cpu: A map of VM UUID and their CPU utilization histories. :param vms_ram: A map of VM UUID and the...
def compliment(pattern): """[finds the complimentary strand of dna "pattern"] Args: pattern ([string]): [dna strand of which compliment is found] Returns: [string]: [compliment of dna pattern: A -> T, G -> C, T -> A, C -> G] """ return pattern.replace("A", "t").replace("T"...
def convert_data_for_TXT(orig_data): """handles string formatting specified in https://www.terraform.io/docs/providers/google/r/dns_record_set.html""" orig_data = f'\\"{orig_data}\\""' # for very long rrdatas, need to add quotes between each 255char substring idx = 0 tgt = '"' while idx < len(o...
def extract_password(data: bytes) -> str: """Extract the password.""" if not data: return "" length: int = data[-1] res: bytes = data[8:-length] return res.decode("utf-8")
def miller(p: int): """Miller primality test. Arguments: {p} integer -- The {p} number. Returns: True -- If {p} is prime. False -- If {p} is not prime. """ bases = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] if p in bases: return True r, d = 0, p - ...
def jobs_api_url(config: dict) -> str: """The URL of the jobs API.""" return config["jobs_api_url"]
def c_to_f(temp): """ Convert celcius temperature to fahrenheit. """ return temp * 1.8 + 32
def _render_condition_value(value, field_type): """Render a query condition value. Args: value: the value of the condition. field_type: the data type of the field. Returns: a value string. """ # BigQuery cannot cast strings to booleans, convert to ints if field_type ==...
def partial_ordering(cls): """Class decorator, similar to :func:`functools.total_ordering`, except it is used to define `partial orderings`_ (i.e., it is possible that *x* is neither greater than, equal to, or less than *y*). It assumes the presence of the ``__le__()`` and ``__ge__()`` method, but n...
def map_action(entry, _): """ Stringify an action entry and signature. Args: entry: action entry second argument is not used Returns: str """ try: bact = entry.bact bactsig = entry.bactsig except AttributeError: return None return '%s [%s]' % (b...
def _GetTopN(objects, n): """Returns top n objects with maximum count. Args: objects: any object that has count property n: number of top elements to return Returns: top N elements if objects size is greater than N otherwise the map elements in a sorted order. """ return sorted(objects, key=l...
def countDigits(string): """return number of digits in a string (Helper for countHaveTenDigits)""" count = 0 for char in string: if char == '0' or char == '1' or char == '2' or char == '3' or char == '4' or \ char == '5' or char == '6' or char == '7' or char == '8' or char == '9': ...
def _legacy_worker_key_set(workers): """ Transform a set of worker states into a set of worker keys. """ return {ws.address for ws in workers}
def betacf(a:float,b:float,x:float)->float: """ This function evaluates the continued fraction form of the incomplete Beta function, betai. (Adapted from: Numerical Recipies in C.) Usage: lbetacf(a,b,x) """ ITMAX = 200 EPS = 3.0e-7 bm = az = am = 1.0 qab = a+b qap = a+1.0 qam = a-1.0 ...
def distribute(N,nmax): """ Distribute N things into cells as equally as possible such that no cell has more than nmax things. """ actual_max = int(2.*(nmax+1)/3.) numcells = int(round(N*1./actual_max)) each_cell = [actual_max]*(numcells-1) rem = N-sum(each_cell) if rem>0: each_cell.append(rem) assert sum(ea...
def coord_comp(n, a=0, b=1): """Function also does the same but uses a list comprehension instead of loops. """ coords=[(b-a)*k/n for k in range(n+1)] return coords
def ordinal(num): """ Returns the ordinal number of a given integer, as a string. eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc. """ if 10 <= num % 100 < 20: return '{0}th'.format(num) else: ord = {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(num % 10, 'th') return '{0}{1}'.format(num, ord)
def rosenbrock(ind): """Rosenbrock function defined as: $$ f(x) = \sum_{i=1}^{n-1} 100 \times (x_{i+1} - x_i^{2})^{2} + (1 - x_{i})^{2} $$ with a search domain of $-2.048 < x_i < 2.048, 1 \leq i \leq n$. The global minimum is at $f(x_1, ..., x_n) = f(1, ..., 1) = 0. """ return sum((100. * (ind[i...
def get_course_id_from_capa_module(capa_module): """ Extract a stringified course run key from a CAPA module (aka ProblemBlock). This is a bit of a hack. Its intended use is to allow us to pass the course id (if available) to `safe_exec`, enabling course-run-specific resource limits in the safe exe...
def flatten(obj): """ Flattens a json object into a single level using dot notation. """ out = {} def _flatten(x, name=''): if type(x) is dict: for a in x: _flatten(x[a], f"{name}{a}.") elif type(x) is list: for i, a in enumerate(x): ...
def u4(bytes): """ Convert a little endian Ublox U4 type to a native integer """ if len(bytes) != 4: raise ValueError('Need exactly 4 bytes') return int(bytes[0]) + \ int(bytes[1]) * 256 + \ int(bytes[2]) * 65536 + \ int(bytes[3]) * 16777216
def get_model_epoch(file): """ returns the epoch of the provided model file """ n = file.split('_')[-1].split('.')[0] return int(n)
def truncate_string(input_string, character_limit): """Used to truncate a string to ensure it may be imported into database Parameters ---------- input_string : str string to be truncated character_limit : int the maximum number of allowed characters Returns ------- str...
def strip_special_chars(filename): """Removes shell special characters from a filename. Args: filename (str): Filename to be sanitized. Note that this should be a single filename and not a full path, as this will strip path separators. Returns: (str) Sanitized versi...
def is_affiliation(item: str) -> bool: """Return true if a string contains an affiliation.""" return item.startswith('(')
def sizeof_fmt(num, suffix="B"): """ Human-readable memory size. Adapted from https://stackoverflow.com/a/1094933/2996578 """ for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: if abs(num) < 1024.0: return "%3.1f %s%s" % (num, unit, suffix) num /= 1024.0 ret...
def dni_to_value(scale_value): """ This method will transform a string value from the DNI scale to its confidence integer representation. The scale for this confidence representation is the following: .. list-table:: DNI Scale to STIX Confidence :header-rows: 1 * - DNI Scale ...
def LevenshteinDistance(first, second): """Find the Levenshtein distance between two strings.""" if len(first) > len(second): first, second = second, first if len(second) == 0: return len(first) first_length = len(first) + 1 second_length = len(second) + 1 distance_matrix = [[0] ...
def complementary_color(my_hex): """Returns maximal contrast color to provided. Example: >>>complementaryColor('FFFFFF') '000000' """ if my_hex[0] == '#': my_hex = my_hex[1:] my_hex_number = int(my_hex, 16) absolute_grey = int('ffffff', 16) / 2 if my_hex_number > absolut...
def __get_walks_slices(walks0, slices0, sample, ndim): """ Get the best number of steps for random walk/slicing based on the type of sampler and dimension Arguments: walks0: integer (provided by user or none for auto) slices0: integer (provided by user or none for auto) sample: string (samp...
def move(space: int, d: int) -> int: """For parm current space and die roll, return the new space the pawn will land on.""" return (space - 1 + d) % 10 + 1
def power_law(a,b,x): """ Power law function Parameters ---------- a : float Power law coefficient. b : float Power law exponent. """ return a*x**(b)
def zset_score_pairs(response, **options): """ If ``withscores`` is specified in the options, return the response as a list of (value, score) pairs """ if not response or not options['withscores']: return response return zip(response[::2], map(float, response[1::2]))
def nub(x): """Deletes all duplicates from a list""" new = [] new .append(x[0]) for x1 in range(1, len(x)): if x[x1] in new: pass if x[x1] not in new: new.append(x[x1]) return new
def parser(user_input): """ Delegates to evaluate() Args: str: User input Return: str: Splits into list at white space """ if user_input is None or user_input == "": user_input = "default" parsed_string = user_input.split() return parsed_string
def calc_U_slip(eps, E, x, mu): """ Slip velocity (DC field) """ u_slip = -eps*E**2*x/mu return u_slip