content
stringlengths
42
6.51k
def strip_ref_to_name(ref: str) -> str: """Strip a full ref to a name.""" strips = ("refs/heads/", "refs/tags/") for strip in strips: if ref.startswith(strip): return ref[len(strip) :] return ref
def groupAndSort(result_list): """ sort result list: input: result_list - [102, '98', ('102', '98'), ('97', '99'), ('101', '99'), '101', '97', '99', ('97', '98'), ('98', '99')] output: group = {1: ['101', '102', '97', '98', '99'], 2: [('101', '99'), ('102', '98'), ('97', '98'), ('97', '99'), ('9...
def min_first(iterable): """Returns the smallest value of all items in the iterable, compared by their zeroth elems.""" return min(iterable, key=lambda element: element[0])
def get_hand_position(hand): """ Gets the position of a hand found. :param hand: A hand found by the hand haarcascade. :return: (x, y,) representing the centre position of the hand provided. """ x, y, w, h = hand # todo: Work out whether this works to get the centre of the hands position: Pr...
def wind_direction_to_beta(wind_dir_deg): """ Beta = 0.0 -> [1.0,0.0,0.0] Wind = 0.0 -> [0.0,-1.0,0.0] Therefore Beta = Wind + 90.0 """ return 360.0 - (wind_dir_deg + 90.0)
def Dc(m,n): """partition density""" try: return m*(m-n+1.0)/(n-2.0)/(n-1.0) except ZeroDivisionError: # numerator is "strongly zero" return 0.0
def find_license(classifiers, license_name): """Find `license_name` in `classifiers`.""" for classifier in classifiers: if classifier.startswith("License ::") and license_name in classifier: return classifier return None
def levenshtein_distance(s1, s2): """Compute Levenshtein distance btw two strings Note ---- Taken from wikibooks.org-wiki-Algorithm_Implementation """ if len(s1) < len(s2): return levenshtein_distance(s2, s1) # len(s1) >= len(s2) if len(s2) == 0: return len(s1) pr...
def great_circle_pole_pts(lon_p, lat_p): """Find two orthogonal points on the great circle from its polar axis. Parameters ---------- lon_p: float Polar axis west longitude (degree). lat_p: float Polar axis latitude (degree). Returns ------- float West longitude...
def find_ns_subelements(element, subelement_name, ns_dict): """ retuns list of subelements with given name in any given namespace Arguments: - element (ElementTee.Element): main element to search in - subelement_name (string): searched name of element - ns_dict: dict of ...
def get_auth_headers(token): """Get token-based auth headers for a KG HTPP request Parameters ---------- token: str EBRAINS Auth-token Returns ------- dict Auth headers as a dict, fit for requests.get() """ return { 'Content-Type': 'application/json', 'A...
def remove_improbable_entities(results, cutoff=3): """Remove improbable entities. E.g. if less than 3 characters (dm, eq, tx)""" # Should remove links from Amazon, which give amazon undue credit. new_results = [] for r in results: if len(r[0]) >= cutoff: new_results.append(r) re...
def is_bot_message(event: dict) -> bool: """ Determine if the message is generated by the SlackBot or not. """ if 'bot_id' in event: return True elif 'message' in event and 'bot_id' in event['message']: return True else: return False
def rgb_to_hex_string(value): """Convert from an (R, G, B) tuple to a hex color. :param value: The RGB value to convert :type value: tuple R, G and B should be in the range 0.0 - 1.0 """ color = ''.join(['%02x' % x1 for x1 in [int(x * 255) for x in value]]) return '#%s' % color
def is_group(item_type): """Return whether or not the given item_type is a group.""" group_types = [ 'adversary', 'campaign', 'document', 'email', 'event', 'incident', 'intrusion set', 'signature', 'report', 'threat', 'task'...
def bytes_to_human_readable_repr(b: bytes) -> str: """Converts bytes into some human-readable representation. Unprintable bytes such as the nul byte are escaped. For example: >>> b = bytes([102, 111, 111, 10, 0]) >>> s = bytes_to_human_readable_repr(b) >>> print(s) foo\n\x00 ...
def debug_request_func(uri, *args, **kwargs): """ An optional request function which will simply print its arguments. """ msg = "request for %s" % uri if args: msg += " with %s" % str(args) if kwargs: msg += " with %s" % str(kwargs) print(msg) return {}
def parse_curie(s: str): """ Takes a CURIE formatted string and returns the namespace and identifier in a tuple. If multiple colons appear in the string, the first is taken to be the delimiter. Does not allow empty namespace elements (s starts with colon). """ if ":" in s: cidx = s.index...
def get_padded_filename(num_pad, idx): """ Get the filename padded with 0. """ file_len = len("%d" % (idx)) filename = "0" * (num_pad - file_len) + "%d" % (idx) return filename
def search(_list, target): """ This function performs a binary search on a sorted list and returns the index of item if successful else returns False :param _list: list to search :param target: item to search for :return: index of item if successful else returns False """ if type(_...
def get_sequences_length(sequences): """ Args: sequences: a generator of list or tuple Returns: a list record original length of sequences """ sequence_length = [] for seq in sequences: seq = list(seq) sequence_length += [len(seq)] return sequence_length
def mime_type_has_charset(mime_type): """Return whether the MIME media type supports a charset parameter. Note: According to RFC4627, we do not output a charset parameter for "application/json" (this type always uses a UTF encoding). """ if not mime_type: return False if mime_type.star...
def react(char1: str, char2: str) -> bool: """Check if pair reacts.""" return char1 != char2 and char1.lower() == char2.lower()
def gridlegend(cur, gridpart): """ Return grid line definitions. This implementation ignores cur and just hard codes the defs here. """ if gridpart == 'gridmajor': d = {'linecolor' : '#f5a142', 'linethick' : 1.5, 'linestyle': '-'} else: d = {'linec...
def remove_digits(text): """Given string, remove digits.""" text = ''.join([i for i in text if not i.isdigit()]) return text
def neutral_mass_from_mz_charge(mz: float, charge: int) -> float: """ Calculate the neutral mass of an ion given its m/z and charge. Parameters ---------- mz : float The ion's m/z. charge : int The ion's charge. Returns ------- float The ion's neutral mass. ...
def get_variables_used(string, variable_dict): """Returns what variables are used in the given string as a list.""" used_variables = [] for key in variable_dict: temp_string = string.replace(key, "") if temp_string != string: used_variables.append(key) string = temp_s...
def global_pct_id( segments ): """ Calculated like this: 10bp @ 50% id = 5 matching residues, 10 total residues 10bp @ 80% id = 8 matching residues, 10 total residues 13 matching residues, 20 total residues --------------------------------------- ...
def singlequot(value): """Removes all values of arg from the given string""" return (value or '').replace('"', "'")
def num_sevens(x): """Returns the number of times 7 appears as a digit of x. >>> num_sevens(3) 0 >>> num_sevens(7) 1 >>> num_sevens(7777777) 7 >>> num_sevens(2637) 1 >>> num_sevens(76370) 2 >>> num_sevens(12345) 0 >>> from construct_check import check >>> # b...
def find_next_in_list(lst, what, start=0, reverse=False): """ Finds the next occurrence of what in lst starting at start. :param lst: The list to search :param what: The item to find, should be an iterable :param start: The starting position in the list :param reverse: Set this to True in order ...
def unfold(val, min, max): """ Transform values normalized between 0-1 back to their regular range. Parameters ---------- val : float value to be unfolded. min: float min of value range. max: float max of value range. """ unfold_list = [] for i in val: ...
def and_(source, added): """Combine two queries with 'and'""" if source is None: source = added else: source &= added return source
def _get_padding(alignment, current_size, next_element_size): """Calculate number of padding bytes required to get next element in the correct alignment """ if alignment == 1: return 0 # Always aligned elem_size = min(alignment, next_element_size) remainder = current_size % elem_size if remainder...
def __update(d, u): """ Deep merge or update of a dictionary. """ for key, value in u.items(): if type(value) is dict: r = __update(d.get(key, {}), value) d[key] = r elif type(d) is dict and d.get(key) is None: d[key] = u[key] elif type(d) is d...
def distr(tt): """Computes the maximum distance, the sum of distances and the distribution.""" res = {} ttt = [x.upper() for x in tt] # print(ttt) st = set(ttt) en = 0 km = -1 xm = "" suma = 0 wsuma = 0 for x in st: i = ttt.index(x) j = ttt.index(x,i+1) ...
def andor_list(items, andor='and'): """ Join a list of stings into a comma-separated con/disjunction. Forms: a a a and b a or b a, b, and c a, b, or c """ return_str = ', '.join(items) k = return_str.rfind(',') if k > 0: k += 1 return_str = return_str[...
def split_raw_run_list(raw_list): """ Split the result of a raptr query into groups such that each group consists of only one anls_run. Args: raw_list (list): List of tuples - the result of a raptr query. Returns: raptr_records (dict): raptr_records[run_name] is a list of records. ...
def std_trans_map_dtmc(sourceidx, destidx, p): """Standard graphziv attributes used for transitions in dtmc. Computes the attributes for a given source, destination, action and probability. :param stateidx: The index of the source-state. :type stateidx: int :param destidx: The index of the destinati...
def to_ps(obj, parlen=False): """Converts object into postscript literal >>> to_ps(None) 'null' >>> to_ps(123) '123' >>> to_ps(456.78) '456.78' >>> to_ps(True), to_ps(False) ('true', 'false') >>> to_ps('foo bar baz') 'foo bar baz' >>> to_ps('foo bar baz', parlen=True) ...
def gen_random_string(length=6): """ Generate fixed-length random string. """ import random import string letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(length))
def int_to_hex(num, upper=False): """Ensures that there is an even number of characters in the hex string""" hexed = hex(num)[2:] if len(hexed) % 2 != 0: hexed = '0' + hexed return hexed.upper() if upper else hexed
def get_msb(value, size): """ Get most significant bit. :param value: value to obtain msb from :size: bit width of value in bytes :return: most significant bit """ return value >> ((8 * size) - 1)
def multm(A, B): """ produit matriciel: A * B """ a00, a10, a01, a11 = A b00, b10, b01, b11 = B return [a00 * b00 + a10 * b01, a00 * b10 + a10 * b11, a01 * b00 + a11 * b01, a01 * b10 + a11 * b11]
def str2tuple(s): """ Returns tuple representation of product state. Parameters ---------- s : str Product state. """ return tuple( pos for pos, char in enumerate(s) if char == "1" )
def concat(a: str, b: str) -> str: """Concatenate two strings together""" # Existing 'add' filter isn't suitable for strings as it will try to coerce them into integers return str(a) + str(b)
def totype(v, default): """ Tries to convert the value 'v' into the same type as 'default'. >>> totype('24', 0) 24 >>> totype('True', False) True >>> totype('0', False) False >>> totype('1', []) '1' >>> totype('none', True) #doctest: +ELL...
def scale4(a,c): """ 4 vector ``a`` times scalar ``c``""" return [a[0]*c,a[1]*c,a[2]*c,a[3]*c]
def reduce_json_array(j): """Recursively go over a JSON and unpack arrays which have only one item, i.e. remove unnecessary arrays (brackets). Args: j (list of dict): A JSON to be reduced. Returns: list or dict: a reduced JSON with unnecessary array removed. """ if isinstance(...
def fpow1(x, n): """ Perform iterative fast exponentiation by squaring. :param x: the base number :param n: the target power value, an integer :return: x to the power of n """ if n < 0: return fpow1(1 / x, -n) if n == 0: return 1 if x == 0: return 0 y = ...
def _combine_stats(n_1, mu_1, sigma2_1, n_2, mu_2, sigma2_2): """ based on: https://stats.stackexchange.com/questions/43159/how-to-calculate-pooled-variance-of-two-groups-given-known-group-variances-mean http://stats.stackexchange.com/questions/55999/is-it-possible-to-find-the-combined-standard-deviatio...
def _len_guards(M: int) -> bool: """Handle small or incorrect window lengths""" if int(M) != M or M < 0: raise ValueError('Window length M must be a non-negative integer') return M <= 1
def minimaxDepthTLCovers(tlcovs): """ Prune top-level covers for minimax depth Inputs: tlcovs: A list of top-level covers as returned by explain. Outputs: tlcovs_xd: The pruned top level covers. xd: The minimax depth found. """ xd = max(min(d_min) for (_,_,d_min,_,_) in t...
def get_DNA_seq(mutant_position, all_lines): """ Get the DNA lines as a list knowning the mutant position. :param all_lines = [str] :param mutant_position: int :rtype: [str] """ dna_lines = [] for i in range(mutant_position + 2, len(all_lines)): line = all_lines[ i ] if...
def replace_eumjul(target, index, replacement): """Recreate the unicode string with new Eumjul. :param target: a single or series of Hangul. :type target: unicode :type index: int :param index: an index to use the given replacement. :param replacement: an Eumjul to use as an replacement. :t...
def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values)
def remove_tags(s: str) -> str: """ Remove tags and replace them with tilde ("~") characters. Args: s (str): String to clean up. Returns: (str): Cleaned string. """ in_tag = False plain_text = '' field = '' for character in s: if in_tag: if charac...
def readint(bs, count): """Read an integer `count` bits long from `bs`.""" n = 0 while count: n <<= 1 n |= next(bs) count -= 1 return n
def get_cell_values_from_row(row): """Returns string representation of cell values from row in a list Parameters ---------- row : list list of values Returns ------- list string representation of cell values from row in a list """ return [str(cell.value) for cell i...
def is_multiclass(args): """ Check args for any hint of a multiclass problem (Check is option dependent and may be incomplete) """ # Not sure if --wap, --ect multi-class are actually right for mc_opt in ('--oaa', '--csoaa', '--ect', '--wap', '--sequence'): if mc_opt in args: ...
def remap(value, old_min, old_max, new_min, new_max): """ Remaps the value to a new min and max value Args: value: value to remap old_min: old min of range old_max: old max of range new_min: new min of range new_max: new max of range Returns: The remapped...
def home(request): """Home View""" return {'msg': 'Desafio Web 1.0'}
def joinf(sep, seq): """sep.join(seq), omitting None, null or so.""" return sep.join([s for s in filter(bool, seq)]) or None
def least_interval(tasks, n): """ Return the least number of intervals the CPU will take to finish all the given tasks :param tasks: list of tasks :type tasks: list[str] :param n: non-negative cooling interval :type n: int :return: the least number of intervals to finish tasks :rtyp...
def get_failure_array(pattern): """ Calculates the new index we should go to if we fail a comparison :param pattern: :return: """ failure = [0] i = 0 j = 1 while j < len(pattern): if pattern[i] == pattern[j]: i += 1 elif i > 0: i = failure[i - ...
def mean(values): """ returns mean value of a list of numbers >>> mean([1, 2, 3, 4, 1, 2, 3, 4]) 2.5 >>> round(mean([1, 2, 3, 4, 1, 2, 3, 4.1, 1000000]), 4) 111113.3444 """ return sum(values) / float(len(values))
def makeInNotNullConditions(columns): """ Make the WHERE clause conditions of IS NOT NULL for columns""" clause = '' for col in columns: clause += str(f" {col} IS NOT NULL AND ") # Strip off the last AND ret = clause[0:-4] return ret
def domain_has_protocol(domain): """ check if the user provided domain name includes the protocol (http or https) """ if domain.find("https://") >= 0: return True elif domain.find("http://") >= 0: raise Exception('Invalid protocol provided in uiDomainName (http:// should be https:// or not i...
def letter_counter(lst: list, letter: str) -> int: """Count the number of times letter shows up in the word search.""" return sum([1 for row in lst for letters in row if letter == letters] )
def round_down(n: int, m: int) -> int: """Round the given number *n* down to the nearest multiple of *m*. :param int n: number to round :param int m: multiple to round to :return: n rounded down to a multiple of m. :rtype int: """ return n & ~(m - 1)
def convert_string_bools_to_bool(parameters): """ Change string bool values to bool()s. """ new_parameters = parameters.copy() # Convert all boolean options to proper booleans for parameterKey in new_parameters: if (new_parameters[parameterKey]).lower() == "true": new_parameters[...
def label2dict(label): """ Converts labels like "{ph:0, Farnesol:1, Serum:0, Rapamycin:0}" to dict """ terms = label[1:-1].split(',') d = dict() for term in terms: key, val = term.split(":") d[key.strip()] = val.strip() return d
def get_sub_value(dictionary, aliases): """ :param dictionary: a dictionary to check in for aliases :param aliases: list of keys to check in dictionary for value retrieval :return: returns value if alias found else none """ if (dictionary and aliases) is not None: for alias in aliases:...
def parse_free_results(stdout): """Parse results of `free` command Parameters ---------- stdout : str Output of running `free` command Returns ------- int Free Disk space """ line = stdout.split('\n')[1] assert 'Mem:' in line return int(line.split()[3])
def two2one(x, y): """Maps a positive (x,y) to an element in the naturals.""" diag = x + y bottom = diag * (diag + 1) / 2 return bottom + y
def convert_string_to_list(comma_delimited_list: str): """ Converts the comma delimited list of string to a list type and skips adding empty strings to the list. Args: comma_delimited_list (string): comma delimited list of strings Returns: list[string] """ retu...
def google_fixed_width_font(style): """check if the css of the current element defines a fixed width font""" font_family = '' if 'font-family' in style: font_family = style['font-family'] if 'Courier New' == font_family or 'Consolas' == font_family: return True return False
def has_method(obj, name): """ Check if function 'name' was defined in obj. """ return callable(getattr(obj, name, None))
def normalize_tourism_kind(shape, properties, fid, zoom): """ There are many tourism-related tags, including 'zoo=*' and 'attraction=*' in addition to 'tourism=*'. This function promotes things with zoo and attraction tags have those values as their main kind. See https://github.com/mapzen/vect...
def _round_to_multiple_of(val: float, divisor: int, round_up_bias: float = 0.9) -> int: """Asymmetric rounding to make `val` divisible by `divisor`. With default bias, will round up, unless the number is no more than 10% greater than the smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88.""" ...
def majorityElementC(nums): """ :type nums: List[int] :rtype: int """ a = sorted(nums) return a[int(len(a)/2)]
def _add_leading_slash(string): """Add leading slash to a string if there is None""" return string if string.startswith('/') else '/' + string
def value_in_choices(value, choices): """ Check if the value appears in the choices list (a iterable of tuples, the first value of which is the choice value) :param value: :param choices: :return: True if value is in the choices iterable. """ for choice in choices: if value == choi...
def pretty_size(size, sep=' ', lim_k=1 << 10, lim_m=10 << 20, plural=True, floor=True): """Convert a size into a more readable unit-indexed size (KiB, MiB) :param size: integral value to convert :param sep: the separator character between the integral value and ...
def _convert_key(key): """Convert a key.""" return [ord(x) for x in key]
def is_video(mime): """ Returns `True` if the specified file pointer represents a video. `False` otherwise. """ return mime.startswith("video/")
def is_iscsi_uid(uid): """Validate the iSCSI initiator format. :param uid: format like iqn.yyyy-mm.naming-authority:unique """ return uid.startswith('iqn')
def isfloat(x): """Determine if provided object is convertible to a float Args: x: object Returns: bool """ if x is None: return False try: float(x) return True except: return False
def board_full(board): """ Utility function that returns True if the given board is full and False otherwise Arg board: board - the board you want to check """ for row in board: for piece in row: if piece == '*': return False; return True;
def app_files(proj_name): """Create a list with the project files Args: proj_name (str): the name of the project, where the code will be hosted Returns: files_list (list): list containing the file structure of the app """ files_list = [ "README.md", "setup.py", ...
def descending_order(num): """Return non-negative integer input into descending order. i.e. return the highest number possible from the given numbers input = integer output = integer sorted in descending order ex. Input: 21445 Output: 54421 ex. Input: 145263 Output: 654321 ex. Input: 125485...
def exps_int(to_convert): """Converts to integer, auto-detecting the base (if string).""" if isinstance(to_convert, str): return int(to_convert, 0) return int(to_convert)
def palindrome(a): """ Given a string a, turn it into a palindrome with minimum # of additions. returns triple (original input, palindrome, # of additions) """ if len(a) == 0: return ("", "", 0) cache = {} def inner(i, j): # returns a palindrome generated from the substr...
def combination(n, k , repetition = False): """ Returns binomial coefficient. Parameters ---------- n : int non-negative integer k : int non-negative integer return : int returns integer value denoting binomial coefficient Optional Parameters ---------...
def isFloat(input): """ This function check input is a float value. :param input: unknown type object """ return isinstance(input, float)
def get_str_index(index): """Return '1' to '9' or '010' to '099'""" if index < 10: return str(index) else: return '{:03}'.format(index)
def using_concatenation_to_construct_a_list(n): """ Constructs [1, 2, 3, ... n] by using list concatenation. """ new = [] for k in range(1, n + 1): new = new + [k] return new
def dot(A1, B1): """ Returns the DOTproduct between A1 and B1 A1: Takes input as lis B1: Takes input as lis """ return sum(x*y for x,y in zip(A1,B1))
def find_all_starts(seq): """Find the starting index of all start codons in a lowercase seq""" # Initialize array of indices of start codons starts = [] # Find index of first start codon (remember, find() returns -1 if not found) i = seq.find('atg') # Keep looking for subsequence incrementing ...
def escape(html): """Returns the given HTML with ampersands, quotes and carets encoded.""" return html.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')