content
stringlengths
42
6.51k
def calculate_immediate_dominators(nodes, _dom, _sdom): """ Determine immediate dominators from dominators and strict dominators. """ _idom = {} for node in nodes: if _sdom[node]: for x in _sdom[node]: if _dom[x] == _sdom[node]: # This must be th...
def seconds_described(s): """ UTILITY FUNCTION returns the equivalent time in days, hours, minutes and seconds as a descriptive string. INPUT: s (int) - time in seconds. """ minutes, seconds = divmod(s,60) hours, minutes = divmod(minutes, 60) days, hours = divmod(ho...
def IncludeCompareKey(line): """Sorting comparator key used for comparing two #include lines. Returns the filename without the #include/#import/import prefix. """ for prefix in ('#include ', '#import ', 'import '): if line.startswith(prefix): line = line[len(prefix):] break # The win32 api ha...
def combinedJunctionDist(dist_0, dist_1): """Computes the combined genomic distance of two splice junction ends from the closest annotated junctions. In essence, it is finding the size indel that could have created the discrepancy between the reference and transcript junctions. Examples ('|' ...
def primal_gap(best_sol, feas_sol): """ :param best_sol: optimal or best known solution value: c^Tx*, :param feas_sol: feasible solution value: c^Tx~ """ if (abs(best_sol) == 0) & (abs(feas_sol) == 0): return 0 elif best_sol * feas_sol < 0: return 1 else: return abs(b...
def cal_proc_loc_from_rank(pnx: int, rank: int): """Calculate the location of a rank in a 2D Cartesian topology. Arguments --------- pnx : int Number of MPI ranks in x directions. rank : int The rank of which we want to calculate local cell numbers. Returns ------- pi, ...
def splitbytwos(x): """Split a string into substrings of length two. Args: x: The string to split. Returns: A list of strings of length two """ return [x[2*i:2*i+2] for i in range(len(x)//2)]
def _format_argval(argval): """Remove newlines and limit max length From Allure-pytest logger (formats argument in the CLI live logs). Consider using the same function.""" MAX_ARG_LENGTH = 100 argval = argval.replace("\n"," ") if len(argval) > MAX_ARG_LENGTH: argval = argval[:3]+" ... "...
def _calc_scalar_potential( coeff, cos_theta, sin_n, cos_n, legendre_poly, legendre_poly_der, a_over_r_pow, max_n, ): """ Calculates the partial scalar potential values """ B_r = 0 B_theta = 0 B_phi = 0 for n in range(1, max_n): current_a_over_r_power ...
def get_field_description(field, description_keyword='description'): """ Gets field description if available, using the description_keyword""" return getattr(field, description_keyword, '')
def compute_f1(actual, predicted): """ Computes the F1 score of your predictions. Note that we use 0.5 as the cutoff here. """ num = len(actual) true_positives = 0 false_positives = 0 false_negatives = 0 true_negatives = 0 for i in range(num): if actual[i] >= 0.5 and predic...
def operation(instuction_sign, value_1, value_2): """Perform operation between two values """ if instuction_sign == '+': return value_1 + value_2 elif instuction_sign == '-': return value_1 - value_2
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ return sum(hand.values())
def _tiff(h): """TIFF (can be in Motorola or Intel byte order)""" if h[:2] in (b'MM', b'II'): return 'tiff'
def bytearray_to_bits(x): """Convert bytearray to a list of bits""" result = [] for i in x: bits = bin(i)[2:] bits = '00000000'[len(bits):] + bits result.extend([int(b) for b in bits]) return result
def note_hash(channel, pitch): """Generate a note hash.""" return channel * 128 + pitch
def nocrc(byte_cmd): """ CRC function to provide no crc """ return ['', '']
def isCFile(filename): """Returns True if `filename` ends in .c, .cpp, .cc""" return filename.endswith(".c") or filename.endswith(".cpp") or filename.endswith(".cc")
def is_install_cmd(argv): """Method checks if installation is requested Args: argv (list): command arguments Returns: bool: result """ res = False if ('install' in argv or 'bdist_egg' in argv or 'bdist_wheel' in argv): res = True return res
def ones_complement_addition(number1, number2): """ Build the one's complement addition as used in the calculation of IP-, TCP- and UDP-headers. To see how the one's complement addition works, visit: https://youtu.be/EmUuFRMJbss :param number1: A 16-bit number as Integer :param number2: A 16-bit nu...
def _int_from_val(x, default=None): """ Returns an integer from the passed in value, unless it is None or the string 'None' - in which case it returns default. """ if (x is not None and x != 'None' and x != ''): return int(x) else: return default
def _e_f(rho, rhou, e, p): """Computes the flux of the energy equation.""" return (e + p) * rhou / rho
def shatter_seq(seq, size): """shatters a sequnce into fragments of length = size. Output list of fragments.""" fragments = [] i = 0 while i+size <= len(seq): fragments.append(seq[i:i+size]) i += 1 # print('shatter', fragments) return fragments
def insertion_sort_swaps(array): """Number of times insertion sort performs a swap Args: array: An unsorted list that will undergo insertion sort. Returns: The number of swaps that insertion sort performed. """ swap = 0 for i, x in enumerate(array): k = i while ...
def from_bits(bin_str: str): """ This function will convert a binary string (with or without prefix) into a integer; :param bin_str: A binary string to convert into integer :return: A integer representing the given binary string """ return int(bin_str, 2)
def tracklims(lims, x_i=[], y_i=[]): """ Return modified limits list. INPUT: - ``lims`` -- A list with 4 elements ``[xmin,xmax,ymin,ymax]`` - ``x_i`` -- New x values to track - ``y_i`` -- New y values to track OUTPUT: A list with 4 elements ``[xmin,xmax,ymin,ymax]`` EXAMPLES:: ...
def executeSQL(query): """ Dummy function to test android-api interactions. Will be deprecated. """ print(query) #result = database.query_db(query) # print([x for x in result]) #return helper.row_jsonify(result) if 'delete' in query.lower() or 'drop' in query.lower(): return ...
def lowerconv(upperdecision: int, upperllr: float, lowerllr: float) -> float: """PERFORMS IN LOG DOMAIN llr = lowerllr * upperllr, if uppperdecision == 0 llr = lowerllr / upperllr, if uppperdecision == 1 """ if upperdecision == 0: return lowerllr + upperllr else: return lowerllr...
def check(number): """check that the number of robots is between 1 and 100.""" number = int(number) if number < 1: number = 1 if number > 100: number = 100 return number
def get_sequence(center_idx, half_len, sample_rate, max_num_frames): """ Sample frames among the corresponding clip. Args: center_idx (int): center frame idx for current clip half_len (int): half of the clip length sample_rate (int): sampling rate for sampling frames inside of the c...
def _find_gap_positions(accession): """ In the longest sequence, find each gapped position. 0-index """ list_gap = [] gap_start = 0 gap_end = 0 current_gap = False accession_len = len(accession) for i in range(accession_len): #Get current position base call curr...
def macthing_templates(templates_peptide, templates_minipept): """ The function searching atoms of peptide bonds in small peptide pattern. Parameters ---------- templates_peptide : list List of atoms of peptide bonds. templates_minipept : list List of atoms of part of peptide bo...
def _subsequence(s, c): """ Calculate the length of a subsequence Takes as parameter list like object `s` and returns the length of the longest subsequence of `s` constituted only by consecutive character `c`s. Example: If the string passed as parameter is "001000111100", and `c` is '0', t...
def __format_command(command): """ Formats the command taken by run_command/run_pipe. Examples: > __format_command("sort") 'sort' > __format_command(["sort", "-u"]) 'sort -u' > __format_command([["sort"], ["unique", "-n"]]) 'sort | unique -n' """ if i...
def get_sep(file_path: str) -> str: """Figure out the sep based on file name. Only helps with tsv and csv. Args: file_path: Path of file. Returns: sep """ if file_path[-4:] == '.tsv': return '\t' elif file_path[-4:] == '.csv': return ',' raise ValueError('Input fil...
def catalan_recursive(n: int) -> int: """ Returns the nth catalan number with exponential time complexity. >>> catalan_recursive(5) 42 >>> catalan_recursive(10) 16796 >>> catalan_recursive(0) 1 >>> catalan_recursive(-5) 1 >>> catalan_recursive(1.5) -1 """...
def order(letter): """Given letter, returns it alphabetic index""" return ord(str.lower(letter))-96
def MergeTwoListsAsDic(keys, values): """ """ dic = {} for i in range(len(keys)): dic[keys[i]] = values[i] return dic
def n_line(file): """ Return the number of lines for a file Args: file (str): File path Returns: int: number of lines """ count = 0 buffer = 16 * 1024 * 1024 # buffer=16MB with open(file, "rb") as inf: while True: block = inf.read(buffer) if...
def volume(length, width, height): """ (float, float, float) -> float Computes the volume of a rectangular box (cuboid) defined by it's length, width and height """ return length * width * height
def checksum(buf): """ @param buf: buffer without the checksum part """ c = 0x1234567 for i, b in enumerate(buf): c += b * (i+1) return c
def as_dict_with_keys(obj, keys): """ Convert SQLAlchemy model to list of dictionary with provided keys. """ return [dict((a, b) for (a, b) in zip(keys, item)) for item in obj]
def get_email_domain_part(address): """ Get the domain part from email ab@cd.com -> cd.com """ return address[address.find("@") + 1 :].strip().lower()
def display_lef(lef_dict): """ Used to display lef extracted information to user for verification of pins""" cell_name = lef_dict['cell_name'] cell_area = lef_dict['area'] pin_list = list(lef_dict['pin'].keys()) input_pins_list = [ pin for pin in pin_list if lef_dict['pin'][pin]['direction']...
def bytes_endswith_range(x: bytes, suffix: bytes, start: int, end: int) -> bool: """Does specified slice of given bytes object end with the subsequence suffix? Compiling bytes.endswith with range arguments compiles this function. This function is only intended to be executed in this compiled form. Arg...
def line_name_to_pyneb_format(lineName): """ Takes a line name in the form similar to OIII-5007A or H-Alpha and returns the pyneb format: H1r_6563A. This function is basic and assumes tha the letter 'I' in the lineName are used only for roman numerals """ if 'H-Alpha' in lineName: atomName,...
def compare_lists(bench, val): """ Checks to see if two list like objects are the same. """ if not len(bench) == len(val): return False if not sorted(bench) == sorted(val): return False return True
def rows_to_columns(input_matrix): """ Turn matrix row into columns :param input_matrix: list of lists of numerical values of consistent length :return: """ return [[input_matrix[p][i] for p in range(len(input_matrix))] for i in range(len(input_matrix[0]))]
def less_than(values, puzzle_input): """if the first parameter is less than the second parameter, it stores 1 in the position given by the thrid parameter. Otherwise it stores 0. """ if values[0] < values[1]: puzzle_input[values[2]] = 1 else: puzzle_input[values[2]] = 0 return pu...
def unpack(variables): """ remove first dimension and zero padding from each variable variables is a list with one tensor per variable a tensor [3, 5, 4] may be unpacked to [[5, 4], [2, 4], [1, 4]] """ all_unpacked = [] for v in variables: # note on gpu sorted; on cpu not unless spe...
def heuristic(a, b): """ Function used to heuristic :param a: :param b: :return: """ (x1, y1) = a (x2, y2) = b return abs(x1 - x2) + abs(y1 - y2)
def _get_single_limb(asm_str): """returns a single limb with a potential increment (e.g "*6++" or "*7")""" if len(asm_str.split()) > 1: raise SyntaxError('Unexpected separator in limb reference') if not asm_str.startswith('*'): raise SyntaxError('Missing \'*\' character at start of limb refe...
def getArch(rec): """Return arch type (intel/amd/arm). """ info = rec["product"]["attributes"] if info["physicalProcessor"].startswith("Intel "): return "intel" if info["physicalProcessor"].startswith("High Frequency Intel "): return "intel" if info["physicalProcessor"].startswit...
def add_trailing_slash(path): """Add a trailing slash if not present Parameters ---------- path : str A string representing a path Returns ------- str A new string with a trailing / if not previously present. """ if path[-1] != '/': path += '/' return pa...
def _collatz_next_number(n): """Given a non negative whole number: Return n // 2 if n is equal. Return 3 * n + 1 otherwise. Throw an error, if n <= 0 or n is not an integer. """ if n % 2 == 0: return n // 2 else: return 3 * n + 1
def calculate_precision(total_correct: int, total_found: int) -> float: """ Calculate precision as the ratio of correct acronyms to the found acronyms. :param total_correct: :param total_found: :return: """ return total_correct / total_found if total_found != 0 else 0
def listdir_matches(match): """Returns a list of filenames contained in the named directory. Only filenames which start with `match` will be returned. Directories will have a trailing slash. """ import os last_slash = match.rfind('/') if last_slash == -1: dirname = '.' ...
def get_unique_characters_again(string: str) -> str: """Returns string with all recurring characters removed.""" return ''.join(set(string.lower()))
def multiply_by_two(number): """Returns the given number multiplied by two The result is always a floating point number. This keyword fails if the given `number` cannot be converted to number. """ return float(number) * 2
def map_pronoun(word, male_names, female_names): """ map word with male and females names, profession, title etc. """ pronoun = "" if word in male_names or word.lower() in male_names: pronoun = "he" elif word in female_names or word.lower() in female_names: pronoun = "she" re...
def get_value(registers, register): """Gets the value""" if register >= 'a' and register <= 'z': return registers[register] return int(register)
def to_weird_case(string): """ Transforms a string into weird case. :param string: a string of words. :return: the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. """ final = [] for x in string.split...
def isuzatv(znak): """Provjerava je li znak UZATV""" return znak ==']'
def getDescr(bitInfo, intVal): """Return information about the bits in an integer Inputs: - bitInfo a sequence (list or tuple) of sequences: - bit number, 0 is the least significant bit - info: string describing the associated bit - intVal an integer whose bits are to be described ...
def mk_number(results): """ Given a list of predicted tag values (prediction for filtered chunks is None), return a list contain the most common prediction of each interval of consecutive chunks with a prediction other than None >>> results = [None, 1, 1, 1, 1, None, None, 2, 2, 3, 2, None, None, 'bana...
def changed(old,new,delta,relative=True): """ Tests if a number changed significantly -) delta is the maximum change allowed -) relative decides if the delta given indicates relative changes (if True) or absolute change (if False) """ delta = abs(delta) epsilon = 1.0 if old > epsilo...
def KK_RC20(w, Rs, R_values, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ return ( Rs + (R_values[0] / (1 + w * 1j * t_values[0])) + (R_values[1] / (1 + w * 1j * t_values[1])) + (R_values[2] / (...
def payoff_put_fprime(underlying, strike, gearing=1.0): """payoff_put_fprime derivative of payoff of call option with respect to underlying. :param underlying: :param strike: :param gearing: :return: value of derivative with respect to underlying. :rtype: float """ if underlying < s...
def normalized_probabilistic_similarity(lang_model, query_model): """ Returns the 'normalized probability' (invented by me) of a query text belongs to a language model :rtype : float :param lang_model: The model of a language (usually a dictionary of features and it's values) :param query_model: Th...
def urgency(t, base, t1, slope): """Ramping urgency function. Evaluate the ramping urgency function at point `t`. Returns ReLu(t-t1)*slope + base. """ return base + ((t-t1)*slope if t>=t1 else 0)
def cell(data, html_class='center'): """Formats table cell data for processing in jinja template.""" return { 'data': data, 'class': html_class, }
def create_GAN_hparams(generator_hidden_layers=[30, 30], discriminator_hidden_layers=[30, 30], learning_rate=None, epochs=100, batch_size=32, activation='relu', optimizer='Adam', loss='mse', patience=4, reg_term=0, generator_dropout=0, discriminator_d...
def get_precedent_type(type1, type2): """Compare and return the most precedent type between two numeric types, i.e., int, float or complex. Parameters ---------- type1 : type The first type to be compared with. type2 : type The second type to be compared with. Returns -...
def validate_required_keys_in_dict(dictionary, key_list): """ Check if the dictionary contains the required keys. If not, raise an exception. :param args: A request instance. :param key_list: The keys that should be in the json structure (only 1st level keys). :return: Returns an array of individua...
def dist_flat_top_hex_grid(path): """https://www.redblobgames.com/grids/hexagons/#coordinates .""" x = 0 y = 0 z = 0 max_distance = 0 for direction in path.split(','): if direction == 'n': y += 1 z += -1 elif direction == 'ne': x += ...
def get_mirror_path_from_module(app_module): """ >>> app_module = {'git_repo': 'git@github.com:claranet/ghost.git'} >>> get_mirror_path_from_module(app_module) '/ghost/.mirrors/git@github.com:claranet/ghost.git' >>> app_module = {'git_repo': ' git@github.com:claranet/spaces.git '} >>> get_mirror...
def get_header(headers: dict, keyname: str, default: str) -> str: """ This function deals with the inconsistent casing of http headers :( A fine example of why we can't have nice things """ for k, v in headers.items(): if k.lower() == keyname.lower(): return v return default
def gather_squares_triangles(p1,p2,depth): """ Draw Square and Right Triangle given 2 points, Recurse on new points args: p1,p2 (float,float) : absolute position on base vertices depth (int) : decrementing counter that terminates recursion return: squares [(float,float,float,float)...] : absolut...
def find_max_time_overlap(hypseg, reflist): """Find reference segment which encompasses the maximum time of the hypothesis segment.""" hbeg, hend = hypseg[0], hypseg[2] times = [] for [rlbl, rseg] in reflist: b = max(hbeg, rseg[0]) e = min(hend, rseg[2]) times.append(e - b) r...
def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None, all_projects=False): """Generate common filters for any list request. :param all_projects: list containers in all projects or not :param marker: entity ID from which to start returning entities. :param limit: m...
def captcha_dupes(numbers): """Sum only the digits that match the one next in a cyclic string.""" Total = 0 for i in range(len(numbers)): if numbers[i] == numbers[i - 1]: Total += int(numbers[i]) return Total
def formula_search_to_dict(raw_result): """Dictionary form for API""" return [ { "id": item.cluster_id, "text": item.text, "n_entries": item.n_entries, "n_texts": item.unique_text, "verb_text": item.verb_text, } for item in raw_...
def escape_facet_value(value: str) -> str: """Escape and quote a facet value for an Algolia search.""" value = value.replace('"', r"\"").replace("'", r"\'") value = f'"{value}"' return value
def call_safe(*args, **kwargs): """ Safely call function that involves a report. If function raises an error, log the error with report.log_error() method. """ report, func, *args = args if not callable(func): func = getattr(report, func) try: return func(*args, **kwargs) ...
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: O(n) Space Complexity: O(1) """ if nums == None: return 0 if len(nums) == 0: return 0 max_sum = nums[0] curr...
def _make_sequence(x): """Convert an event _sequence to a python list""" s = [] if x: s = [x[0]] + x[1] return s
def tile_type(tile_ref, level, ground_default, sky_default): """Returns the tile type at the given column and row in the level. tile_ref is the column and row of a tile as a 2-item sequence level is the nested list of tile types representing the level map. ground_default is the tile type to r...
def check_name(obj): """ Function for returning the name of a callable object. Function and class instances are handled differently, so we use a try/except clause to differentiate between the two. :param obj: An object for which we want to find the name. :return: The name of the object """ ...
def _compare_results_paths(truth_path: str, compare_path: str, source_particle: str, replace_particle: str) -> bool: """Handles comparing paths that need to be changed Arguments: truth_path - the path that's to be compared against compare_path - the path that is to be checked source_part...
def _split_line(s, parts): """ Parameters ---------- s: string Fixed-length string to split parts: list of (name, length) pairs Used to break up string, name '_' will be filtered from output. Returns ------- Dict of name:contents of string at given location. """ ...
def gndvi(b3, b8): """ Green Normalized Difference Vegetation Index \ (Gitelson, Kaufman, and Merzlyak, 1996). .. math:: GNDVI = (b8 - b3) / (b8 + b3) :param b3: Green. :type b3: numpy.ndarray or float :param b8: NIR. :type b8: numpy.ndarray or float :returns GNDVI: Index value ...
def _mapping_has_all(mapping, **key_values): """Test if a `Mapping` has all key/value pairs in `key_values` (by equality). Or: is `key_values` a "sub-mapping" of `mapping` (as sets of key/value pairs)? >>> dct = {'A': 1, 'B': 2, 'C': 3} >>> _mapping_has_all(dct, A=1, B=2) True >>> _map...
def add_mod(x: int, y: int, modulo: int = 32) -> int: """ Modular addition :param x: :param y: :param modulo: :return: """ return (x + y) & ((1 << modulo) - 1)
def format_text(text): """Transform special chars in text to have only one line.""" return text.replace('\n', '\\n').replace('\r', '\\r')
def load_YvsX_config(config): """ the input is a list of tuples, each of them having as first element as entry key and the second a string, which should be converted to a list basically this takes the confg as a list of tuples and converts it to dictionary """ #~ keys which values should b...
def remove_in_dict(d, value = 0): """ In a dictionary, remove keys which have certain value :param d: the dictionary :param value: value to remove :returns: new dictionary whithout unwanted value >>> remove_in_dict({'b': 1, 'a': 0}) == {'b': 1} True >>> remove_in_dict({'b': 1, 'a': 0}, 1) ...
def format_lazy_import(names): """Formats lazy import lines""" lines = '' for _, name, asname in names: pkg, _, _ = name.partition('.') target = asname or pkg if asname is None: line = '{pkg} = _LazyModule.load({pkg!r}, {mod!r})\n' else: line = '{asnam...
def mkinput(txid, vout): """ Create an input record with empty scriptSig, as appropriate for Transaction object. """ return {'prevout_hash':txid, 'prevout_n':vout, 'sequence':0, 'x_pubkeys': [], 'pubkeys': [], 'address': None, 'type': 'unknown', 'signatures': [], 'num_sig': 0, 'scriptSig': ''}
def parse_metadata_records(metadata_records, header): """ Group metadata records by Experiment accession metadata_records is a dict indexed by fastq_ID. If experiment is a knockdown, add related control experiments. There may be multiple knockdown experiments with same controls, so control...
def clean_breaks(val_breaks, d): """ Merge breakpoints that are within d bp of each other. """ breaks = sorted(list(set(val_breaks))) i, j = 0, 1 while j < len(breaks): if breaks[j] - breaks[i] < d: breaks.pop(j) else: i += 1 j += 1 return breaks