content
stringlengths
42
6.51k
def map_dict(d, fn): """Recursively does operations to all values in a nested dictionary and returns a new dictionary of the result. Arguments: \n d = dictionary to do operations on \n fn = function to apply\n""" o = {} for key, value in d.items(): if isinstance(value, dict): o[key] = map_dict(...
def get_refdes(anno_record): """ Build and return a reference designator from the subsite, node and sensor fields in record supplied. """ subsite = anno_record.get('subsite', None) node = anno_record.get('node', None) sensor = anno_record.get('sensor', None) if node is None: return subsi...
def BytesToMebibyte(value): """Converts bytes to mebibytes. @type value: int @param value: Value in bytes @rtype: int @return: Value in mebibytes """ return int(round(value / (1024.0 * 1024.0), 0))
def is_current_page(href: str, *args, **kwargs) -> bool: """ Check for a given urlencoded path if the wanted href is in the current page. If `exact_path` is set to True, `path`and `href` will be check for equality (default to false) Return `False` if the `href` or `path` is missing Parame...
def test_cardinal(array,yval,xval,reach): """ Test cardinal directions, takes a list and indices as arguments, returns True if no obstructions in n,s,e,w else returns False. Also takes 'reach' parameter which is the distance from the origin """ North=South=East=West=False if yval - r...
def fib(n): """ Assumes n an int >= 0 Returns Fibonacci of n""" if n == 0 or n == 1: return 1 else: return fib(n-1) + fib(n-2)
def flip_box(box): """ box (list, length 4): [x1, y1, x2, y2] """ # Get top right corner of prediction w = box[2] - box[0] h = box[3] - box[1] topRight = (box[2], box[1]) # Top left corner of flipped box is: newTopLeft = (1024. - topRight[0], topRight[1]) return [newTopLeft[0], ...
def carmichael_of_ppower(pp): """ Carmichael function of the given power of the given prime. """ p, a = pp if p == 2 and a > 2: return 2 ** (a - 2) else: return (p - 1) * (p ** (a - 1))
def calculate_affinity(pop): """ :param pop: :return: sorted pop { bitstring: '11000...' vector: [x1, x2] cost: fx affinity: 0.0 --> 1.0 } """ # Sap xep lai cost tang dan trong pop sorted_pop = sorted(pop, key=lambda elem: elem['co...
def is_list(obj): """ Check if object is a list """ return isinstance(obj, list)
def is_valid_address(address): """is_valid_rom_address""" if address == None: return False if type(address) == str: address = int(address, 16) if 0 <= address <= 2097152: return True else: return False
def hinted_tuple_hook(obj): """ This hook can be passed to json.load* as a object_hook. Assuming the incoming JSON string is from the MultiDimensionalArrayEncoder, tuples are marked and then reconstructed into tuples from dictionaries. Args: obj (object): Object to be parsed Returns: ...
def update_api_operation(instance, display_name=None, description=None, method=None, url_template=None): """Updates the details of the operation in the API specified by its identifier.""" if display_name is not None: instance.display_name = display_name if description is not None: instance...
def ar_and(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with AND logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array Concentration of r...
def json_default_type_checker(o): """ From https://stackoverflow.com/questions/11942364/typeerror-integer-is-not-json-serializable-when-serializing-json-in-python """ if isinstance(o, int): return int(o) raise TypeError
def point_is_none(board, column: int, row: int) -> bool: """Determine if board is "None" at given row and column""" try: if board[row][column] is None: return True return False except IndexError: print("That is an invalid move, please try again") return ...
def clear_file_name(config_name): """ remove illegal char """ error_char = ['<', '>', ':', '\"', '/', '\\', '|', '?', '*'] for ecr in error_char: config_name = config_name.replace(ecr, '_') return config_name
def slice_percentage_range(sequence, start, end): """ return the slice range between coefficient `start` and `end` where start and end represents fractions between 0 and 1. Corner elements may be repeated in consecutive slices. """ total = len(sequence) return slice(int(round(total * start)...
def binary_to_decimal(n): """ Convert a number from binary to decimal Args: n -- string -- binary number return decimal value of n """ return int(n, 2)
def _check_sequence_stderr(x): """ If stderr created by fastaFromBed starts with 'index file', then don't consider it an error. """ if isinstance(x, bytes): x = x.decode('UTF-8') if x.startswith('index file'): return True if x.startswith("WARNING"): return True re...
def expressionfordateb(corpus, i): """ This function is a helper to check if previous token is a digit. Args: corpus (list), i (int) Returns: bool """ if i > 0 and corpus[i - 1][0].isdigit() is True and \ (len(corpus[i - 1]) == 1 or corpus[i - 1][1].isdigit() is True):...
def binary_search_word(list1, word): """ Carry out a binary search of the given sorted list for a given word Parameters ---------- list1: input list, sorted word: the value to be searched Returns ------- True/False """ size = len(list1) mid = size // 2 #de...
def parse_shutter_type(x): """ Get the shutter type as 'Mechanical', 'Electronic' or 'Other'. """ if 'mechanical' in str(x).lower(): return 'Mechanical' elif 'electronic' in str(x).lower(): return 'Electronic' else: return 'Other'
def _class_definition_lines(name, name_super_type): """ Create lines that define a class. """ return ["class {t}({st}):\n".format(t=name, st=name_super_type), "\tdef __init__(self, *args, **kwarggs):\n", "\t\tsuper({t}, self).__init__(*args, **kwargs)".format( t=name, st=...
def prepare_sequence(sequence_string): """Takes a sequence as string and converts it into a list containing the passes of the sequence. """ result = sequence_string.replace('[', '') result = result.replace(']', '') result = result.replace(' ', '') result = result.replace("'", '') if len...
def all_close(max_side, area_origins, limit): """Return region size where distance sum of point from origins < limit.""" close_region_size = 0 for row in range(max_side+1): for col in range(max_side+1): distance = limit for origin in area_origins: distance -= ...
def getac(x): """Shortcut to return the second value of a data line. """ return x.split(":\\t")[1]
def calc_prob_item_in_list(ls, it): """[Calculates the frequency of occurences of item in list] Arguments: ls {[list]} -- [list of items] it {[int, array, str]} -- [items] """ n_items = len(ls) n_occurrences = len([x for x in ls if x == it]) return n_occurrences/n_items
def compile_rule(rule): """ Compiles a rule in string format. Basically checks that is valid python format. :param rule: :return: """ if len(rule) == 0: return None try: c_rule = compile(rule, "<string>", "exec") return c_rule except: return None
def agent_texts(agents): """Return a list of all agent texts from a list of agents. None values are associated to agents without agent texts Parameters ---------- agents : list of :py:class:`indra.statements.Agent` Returns ------- list of str/None agent texts from input list o...
def round_to_nearest_integer(x): """ Round the value x to the nearest integer. This method is necessary since in Python 3 the builtin round() function is performing Bankers rounding, i.e. rounding to the nearest even integer value. :param x: value to be rounded :type x: Union[int, float] :return: t...
def check_video_format(name: str) -> bool: """Accept only mov, avi, and mp4.""" if name.endswith((".mov", ".avi", ".mp4")): return True return False
def _scalePoints(points, scale=1, convertToInteger=True): """ Scale points and optionally convert them to integers. """ if convertToInteger: points = [ (int(round(x * scale)), int(round(y * scale))) for (x, y) in points ] else: points = [(x * scale, y ...
def under_next(parse,label,nextlabel): """ transform a node with label into child of the following sibling node if it has nextlabel operates on list objects """ if(len(parse)==0): return parse if(type(parse)==dict): if "children" in parse: parse["children"]=under_next(parse["children"],label,nextlabel)...
def unmangle_bucket_name(bucket): """corresponds to mangle_db_name in influxdbmeta.py""" if bucket == u'monitoring': bucket = u'_monitoring' # to handle monitoring bucket. Bucket shouldn't start with special char bucket = bucket.replace('_dsh_', '-') return bucket
def get_record_if_exists(dh_records, params): """Checks to see if record specified in config.json exists in current Dreamhost records.""" for record in dh_records: if record["record"] == params["record"] and record["type"] == params["type"]: # Return Dreamhost record if record does currently...
def load_table(loader, filename, index): """ Load a table from the specified index within a file as an array-like object. """ return loader(filename, index)
def maybeJoinStr(value): """If a string was splitted in multiple lines joins it again""" t = type(value) if issubclass(t, str) or issubclass(t, bytes): return value return "".join(value)
def json_field(value): """ Replace spaces with _ and turn value to lowercase :param value: the value to transform :return the json value """ return value.replace(" ", "_").lower()
def get_pos_in_fft(f,fz,fft_size,bw): """ Get the coefficient corresponding to a certain frequency in the visibilities. Parameters ---------- f : float lower edge frequency of the band. fz : float frequency between f and f+bw (which associated coefficient is to be found)...
def midpoint1(x1: float, y1: float) -> complex: """ Returns the Midpoint of a line, assuming one points is 0,0""" x = x1 / 2 y = y1 / 2 return complex(x, y)
def split_duration(start_hour, duration): """ Split the interval [start_hour, start_hour+duration] into two equal parts separated by a 1h break and return a list of start and stop hours. """ pass start_hours = [] stop_hours = [] half = duration // 2 start_hours += [start_hour] stop_hours += [star...
def bf_necessary( vertices_map ): """Argument is expected to contain items like { 'v1': ( 'value', False ) }, i.e. the hash as key and a tuple ('value', False) as value. This method iterates vertices_map and returns in turn a dictionary with those items where the value-tuple contains False...
def _get_persistence_values(diagram): """Auxiliary function for calculating persistence values.""" return [abs(x - y) for x, y in diagram]
def separate_features_into_lists(features): """ makes separate lists of MQN features and MD3D features """ mqn = [] md3d = [] for feature in features: if feature in ['pmi1', 'pmi2', 'pmi3', 'rmd02', 'rmd24', 'rmd46', 'rmd68', 'rmd8p']: md3d.append(feature) else: m...
def infer_year(collection_id): """Infer the year from the collection ID. Many paper entries do not explicitly contain their year. This function assumes that the paper's collection identifier follows the format 'xyy', where x is some letter and yy are the last two digits of the year of publication. ...
def isinstanceinh(obj, parent_class): """ Returns True if 'obj' is is an instance of class 'parent_class', or of a subclass of 'parent_class'. :param obj: object to be tested :type obj: Any :param parent_class: class to be checked against :type parent_class: type (e.g. list, tuple, int, bool) ...
def same_dir_movement(rel1, rel2): """ Takes 2 relations, and checks if they move in the same axis (i.e. right and left, right and right, left and left, front and front, back and back, back and front and so on. If yes, it returns True. If no, it returns False. It assumes that movement can be in only...
def summy(string_of_ints): """Take a string of integers and return their sum.""" answer = 0 for number in string_of_ints.split(" "): answer += int(number) return answer
def recode_to_utf8(text): """ FEC spec allows ascii 9,10,11,13,32-126,128-156,160-168,173. """ return text.decode('cp1252').encode('utf8')
def _is_valid_sub_path(path, parent_paths): """ Check if a sub path is valid given an iterable of parent paths. :param (tuple[str]) path: The path that may be a sub path. :param (list[tuple]) parent_paths: The known parent paths. :return: (bool) Examples: * ('a', 'b', 'c') is a valid ...
def _clean_item_list_limit(value): """Check that value is a positive integer.""" int_value = int(value) if int_value <= 0: raise ValueError('item_list_limit must be positive') return int_value
def _merge_dicts(dict1, dict2): """ Recursively merges dict2 into dict1 """ if not isinstance(dict1, dict) or not isinstance(dict2, dict): return dict2 for k in dict2: if k in dict1: dict1[k] = _merge_dicts(dict1[k], dict2[k]) else: dict1[k] = dict2[k] ret...
def summation(num): """ Finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0. :param num: an integer. :return: the sum of the range of numbers. """ return sum(x for x in range(num+1))
def removeprefix(target, prefix): """Remove a prefix from a string, based on 3.9 str.removeprefix()""" if target.startswith(prefix): return target[len(prefix) :] else: return target[:]
def filtered_dict(dictionary: dict, threshold, invert: bool = False): """ Removes all keys from a dictionary whose value is less than a given threshold :param dictionary: The dictionary to filter :param threshold: The threshold below which to remove elements :param invert: Whether to invert the thr...
def logger(level=None, handler=None, **kwds): """generate a logger instance for pathos Args: level (int, default=None): the logging level. handler (object, default=None): a ``logging`` handler instance. name (str, default='pathos'): name of the logger instance. Returns: conf...
def insert_dollar_sign_and_commas(data: int) -> str: """Takes a string of numbers and inserts the '$' and ','""" return '${:,}'.format(data)
def get_item(dictionary, key): """ Given a dictionary and a key, return the key's value """ return dictionary.get(key)
def recent_mstones(mstone): """Returns the list of milestones considered 'recent' for the given mstone. Flag unexpiry is available only for flags that expired at recent mstones.""" return [mstone - 1, mstone]
def numeric_validator(value): """Validator for numeric values.""" return isinstance(float(value), float) or isinstance(int(value), int)
def parse_commamd (cmd): """Parses a command provide from the command line. Parses a command found on the command line. I Args: cmd: The command, e.g. `paste` or `type:hello` Returns: a list of command, data """ parts = cmd.split(":") data = ":".join(parts[1:]) return (parts[...
def sum(*args): """ caculate the summary """ result = 0 for i in args: result += i return result
def error(p:float, p_star:float) -> tuple: """ Compute the absolute error and relative error in approximations of p by p^\\star. ---------------------------- Args: p, p_star: Float. Returns: (absolute error, relative error). Raises: None. """ absolute_e...
def mean(v): """ mean function of bounch of values """ return sum(v) / len(v)
def _tag_encloses_foreign_namespace(tag: str) -> bool: """ Checks whether the tag encloses a foreign namespace (MathML or SVG). https://html.spec.whatwg.org/multipage/syntax.html#foreign-elements """ return tag.lower() in ("math", "svg")
def _filter_y_pred(y_pred, conf_threshold): """ Given a list of list of predicted craters return those with a confidence value above given threshold Parameters ---------- y_pred : list of list of tuples conf_threshold : float Returns ------- y_pred_filtered : list of list of tu...
def get_name(ent, attr_dict, dataset): """ retrieve name from entity (D_W / D_Y / others) """ if ent not in attr_dict: return ent.split('/')[-1].replace('_', ' ').lower() if 'D_Y' in dataset: name_attribute_list = ['skos:prefLabel', 'http://dbpedia.org...
def board_max(vals): """ board_max: return max of a list when contains strings and ints """ max_val = -float("inf") for val in vals: if isinstance(val, int) and val > max_val: max_val = val return max_val
def multiply(x, y): """Karatsuba Multiplication Algorithm.""" if len(str(x)) == 1 or len(str(y)) == 1: # base case return x * y else: m = max(len(str(x)), len(str(y))) # larger of the 2 numbers m2 = m // 2 # truncates fractional part of m/2 a = x // 10**m2 # first half ...
def wrap_angle(x): """Wraps an angle in degrees between -180 and 180 degrees""" x = (x + 180) % 360 if x < 0: x += 360 return x - 180
def product_4x4(b,a) : """multiply two 4x4 matrices""" a1= a[0][0]*b[0][0]+a[0][1]*b[1][0]+a[0][2]*b[2][0]+a[0][3]*b[3][0] a2= a[0][0]*b[0][1]+a[0][1]*b[1][1]+a[0][2]*b[2][1]+a[0][3]*b[3][1] a3= a[0][0]*b[0][2]+a[0][1]*b[1][2]+a[0][2]*b[2][2]+a[0][3]*b[3][2] a4= a[0][0]*b[0][3]+a[0][1]*b[1][3]+a[0][2]*b[2][3]+a[0]...
def number_to_choice(number): """Convert number to choice.""" # If number is 0, give me 'rock' # If number is 1, give me 'paper' # If number is 2, give me 'scissors' random_dict = {0: 'rock', 1: 'paper', 2: 'scissors'} return random_dict[number]
def merge_dicts(d1, d2): """Merge the two dicts and return the result. Check first that there is no key overlap.""" assert set(d1.keys()).isdisjoint(d2.keys()) return {**d1, **d2}
def check_list_of_lists(matrix): """checks if a list is a list of lists (aka a matrix) """ for row in matrix: if not isinstance(row, list): return False return True
def is_init_st(id): """Used in p_one_line() --- Checks if id begins with i or I. """ return id[0] in {'i','I'}
def list_split(X, idxs, feature, split): """Another implementation of "split_list" function for performance comparison. Arguments: nums {list} -- 1d list with int or float split {float} -- The split point value Returns: list -- 2d list with left and right split result """ ...
def get_gae_public_ips(gcloud_instances_list): """Parses out the monstrous gcloud output into a dict of instance name -> IP. For reference, gcloud returns a list of these: https://cloud.google.com/compute/docs/reference/rest/v1/instances""" all_instance_nics = {inst["name"]:inst["networkInterfaces"] for ins...
def call_git(args, verbose=False): """ Helper function for calling a 'git' command. @param args: list of arguments to the git shell script. @return string stdout of git """ from subprocess import check_output if isinstance(args,str): args = args.split() if verbose: print ...
def matrix_divided(matrix, div): """Function divides elements of a matrix""" matrix_err = "matrix must be a matrix (list of lists) of integers/floats" if not isinstance(matrix, type([])): raise TypeError(matrix_err) if not isinstance(div, (float, int)): raise TypeError("div must be a n...
def cPlusPlusPrerequisites(fileDesc): """ Writes the prerequisites depending on the main's project language. Parameters ------- fileDesc : TextIOWrapper | None Filedescriptor describing the README.md file """ fileDesc.write("To use this project, you'll need G++ Compiler.\n\n") r...
def _popup_footer(view, details): """ Generate a footer for the package popup that indicates how the package is installed. """ return """ {shipped} <span class="status">Ships with Sublime</span> &nbsp; &nbsp; {installed} <span class="status">In Installed Packages Folder</span> &nbsp;...
def encode_second(sec=18, month=10): """ >>> encode_second( ) == bytearray(b'\x92') True >>> quick_hex(encode_second( )) '0x92' """ high = (month & (0x3 << 2)) >> 2 encoded = sec | (high << 6) return bytearray( [ encoded ] )
def parse_inpaint_params(**kwargs): """ function to parse the inpainting params :param kwargs: :return: """ sigma_colour = 75 max_level = 4 patch_size = { "x": 5, "y": 5, "t": 5 } texture_feature_activated = 1 return [max_level, patch_size, texture_...
def createPlotMetaData( title, xLabel, yLabel, xMajorTicks=None, yMajorTicks=None, legendLabels=None ): """ Create plot metadata (title, labels, ticks) Parameters ---------- title : str Plot title xLabel : str x-axis label yLabel : str y-axis label xMajorT...
def _default_value(argument, default): """Returns ``default`` if ``argument`` is ``None``""" if argument is None: return default else: return argument
def checkConsecutive(l): """https://www.geeksforgeeks.org/python-check-if-list-contains-consecutive-numbers/""" return sorted(l) == list(range(min(l), max(l) + 1))
def find_motif(motif, visit, chain, nsteps, current, previous, motifset, allover, natom, bond, atom, eqv): """ This recursive function finds a specific motif in the structure. FIXIT - the comments here nsteps: the number of steps made current: atom selected for testing, this is a candidate to be ...
def get_camera_from_topic(topic): """ Gets the camera name from the image topic. Note, assumes that topic is of the form /<machine>/<camera>/... """ topic_split = topic.split('/') camera = topic_split[2] return camera
def odd_parity(bits): """ Determines if the array has even or odd parity. Returns True if odd, False if even. Note: this is an extremely inefficient computation, fix later. """ count = sum(1 for x in bits if x==1) return count % 2
def get_lazo_sketches(data_profile, filter_=None): """ Get Lazo sketches of the input dataset, if available. :param data_profile: Profiled input dataset. :param filter_: list of column indices to return. If an empty list, return all the columns. :return: dict, where key is the column index, ...
def mark_entities(tokens, positions, markers=[], style="insert"): """Adds special markers around tokens at specific positions (e.g., entities) Args: tokens: A list of tokens (the sentence) positions: 1) A list of inclusive ranges (tuples) corresponding to the token range...
def ell2ang(ell): """Convert the given ell(s) to its analogous angular scale(s) in arcmins. Return the angular scale(s) in arcmins corresponding to the Fourier mode ell(s). Parameters ---------- ell: value, array of values The ell mode(s). Returns ------- a: float, array ...
def convert(angle): """ Convert an ephem angle (degrees, minutes, seconds) to an EXIF-appropriate representation (rationals) e.g. '51:35:19.7' to '51/1,35/1,197/10' Return a tuple containing a boolean and the converted angle, with the boolean indicating if the angle is negative. """ degr...
def _check_ddl_statements(value): """Validate DDL Statements used to define database schema. See https://cloud.google.com/spanner/docs/data-definition-language :type value: list of string :param value: DDL statements, excluding the 'CREATE DATABASE' statement :rtype: tuple :returns: tuple...
def geometricmean(inlist): """ Calculates the geometric mean of the values in the passed list. That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list. Usage: lgeometricmean(inlist) """ mult = 1.0 one_over_n = 1.0 / len(inlist) for item in inlist: mult = mult * pow(item, one_over_n)...
def remove_element(list, remove): """[summary] Args: list ([list]): [List of objects] remove ([]): [What element to remove] Returns: [list]: [A new list where the element has been removed] """ for object in list: if object._id == remove[0]: list.remove(o...
def bytes2human(n: int) -> str: """Convert `n` bytes into a human readable string. >>> bytes2human(10000) '9.8K' >>> bytes2human(100001221) '95.4M' """ # http://code.activestate.com/recipes/578019 symbols = ("K", "M", "G", "T", "P", "E", "Z", "Y") prefix = {} for i, s in enumera...
def ackermann_no_memo( m, n ): """Evaluates Ackermann's function. """ if m == 0: return n + 1 elif m > 0 and n == 0: return ackermann_no_memo( m - 1, 1 ) elif m > 0 and n > 0: return ackermann_no_memo( m - 1, ackermann_no_memo( m, n - 1 ) )
def countSetBits(n): """ Counts the number of bits that are set to 1 in a given integer. """ count = 0 while (n): count += n & 1 n >>= 1 return count