content
stringlengths
42
6.51k
def readable_size(n): """Return a readable size string.""" sizes = ['K', 'M', 'G'] fmt = '' size = n for i, s in enumerate(sizes): nn = n / (1000 ** (i + 1)) if nn >= 1: size = nn fmt = sizes[i] else: break return '%.2f%s' % (size, fmt)
def custom_func_quotify(populator, value, **kwargs): """Add quotes to the value. """ value = value if value is None else str(value) value = value.replace('"', '""') return f'"{value}"'
def num2bits(num, length=0): """ Convert a number to an array of bits of the give length """ if length and num.bit_length() > length: raise ValueError('Number does not fit in bits') bits = [] while num: bits.insert(0, num & 1) num = num >> 1 return [0] * (length - len(bits)) + bits
def md_getAccuracy(field): """Get accuracy""" return field.split(',')[2].strip()
def factorial(n): """ factorial @param n: @return: """ return 1 if n < 2 else n * factorial(n-1)
def orthogonal(a): """Return an arbitrary vector orthogonal to the input vector. :type a: tuple of floats. :return b: tuple of floats. """ if len(a) == 1: return None # Handle the vector generation one way if any elements # of the input vector are zero. if not all(a): return tuple(0 if a_i else 1 for a_i in a) # If none of the elements of a are zero, set the first n-1 # elements of b to 1. Set the n-th element of b as follows: return (1,) * len(a[:-1]) + (-1 * sum(a[:-1]) / a[-1],)
def linear_search_iterative(elements, key): """ An index, i, where A[i] = k. If there is no such i, then NOT_FOUND. """ for idx, value in enumerate(elements): if key == value: return idx return "Not Found"
def get_sid_trid_combination_score(site_id, tr_ids_list, idfilt2best_trids_dic): """ Get site ID - transcript ID combination score, based on selected transcripts for each of the 10 different filter settings. 10 transcript quality filter settings: EIR EXB TSC ISRN ISR ISRFC SEO FUCO TCOV TSL idfilt2best_trids_dic: "site_id,filter_id" -> top transcript ID(s) after applying filter on exon IDs > min_eir >>> site_id = "s1" >>> idfilt2best_trids_dic = {"s1,EIR" : ["t1"], "s1,EXB" : ["t1"], "s1,TSC" : ["t1"], "s1,ISRN" : ["t1"], "s1,ISR" : ["t1"], "s1,ISRFC" : ["t1"], "s1,SEO" : ["t1"], "s1,FUCO" : ["t1"], "s1,TCOV" : ["t1"], "s1,TSL" : ["t1"]} >>> tr_ids_list = ["t1"] >>> get_sid_trid_combination_score(site_id, tr_ids_list, idfilt2best_trids_dic) {'t1': 10} >>> idfilt2best_trids_dic = {"s1,EIR" : ["t1", "t2"], "s1,EXB" : ["t1", "t2"], "s1,TSC" : ["t1"], "s1,ISRN" : ["t2"], "s1,ISR" : ["t1"], "s1,ISRFC" : ["t1"], "s1,SEO" : ["t1"], "s1,FUCO" : ["t1", "t2"], "s1,TCOV" : ["t1"], "s1,TSL" : ["t2"]} >>> tr_ids_list = ["t1", "t2", "t3"] >>> get_sid_trid_combination_score(site_id, tr_ids_list, idfilt2best_trids_dic) {'t1': 8, 't2': 5, 't3': 0} """ assert tr_ids_list, "tr_ids_list empty" filter_ids = ["EIR", "EXB", "TSC", "ISRN", "ISR", "ISRFC", "SEO", "FUCO", "TCOV", "TSL"] trid2comb_sc_dic = {} for tr_id in tr_ids_list: trid2comb_sc_dic[tr_id] = 0 for tr_id in tr_ids_list: for fid in filter_ids: sitefiltid = "%s,%s" %(site_id, fid) if tr_id in idfilt2best_trids_dic[sitefiltid]: trid2comb_sc_dic[tr_id] += 1 return trid2comb_sc_dic
def white_listed(url, white_listed_urls, white_listed_patterns): """ check if link is in the white listed URLs or patterns to ignore. """ # check white listed urls if url in white_listed_urls: return True # check white listed patterns i = 0 while i < len(white_listed_patterns): if white_listed_patterns[i] in url: return True i += 1 # default return return False
def pt(n): """ Return list of pythagorean triples as non-descending tuples of ints from 1 to n. Assume n is positive. @param int n: upper bound of pythagorean triples """ # helper to check whether a triple is pythagorean and non_descending # you could also use a lambda instead of this nested function def. def _ascending_pythagorean(t): # """ # Return whether t is pythagorean and non-descending. # # @param tuple[int] t: triple of integers to check # """ return (t[0] <= t[1] <= t[2]) and (t[0]**2 + t[1]**2) == t[2]**2 # filter just the ones that satisfy ascending_pythagorean # produce a list from the filter for ascending_pythagoreans from... return list(filter(_ascending_pythagorean, # ...list of all triples in the range 1..n [(i, j, k) for i in range(1, n + 1) for j in range(1, n + 1) for k in range(1, n + 1)]))
def trapped_water(heights): """ Question 18.8: Compute the maximum water trapped by a pair of vertical lines """ max_water = 0 left = 0 right = len(heights) - 1 while left < right: max_water = max( max_water, (right - left) * min(heights[left], heights[right]) ) if heights[left] > heights[right]: right -= 1 elif heights[left] < heights[right]: left += 1 else: left += 1 right -= 1 return max_water
def gitlab_build_params_pagination(page, per_page): """https://docs.gitlab.com/ce/api/README.html#pagination""" return { 'page': str(page), 'per_page': str(per_page) }
def is_file_like(obj): """ Check if the object is a file-like object. For objects to be considered file-like, they must be an iterator AND have either a `read` and/or `write` method as an attribute. Note: file-like objects must be iterable, but iterable objects need not be file-like. .. versionadded:: 0.20.0 Parameters ---------- obj : The object to check. Returns ------- is_file_like : bool Whether `obj` has file-like properties. Examples -------- >>> buffer(StringIO("data")) >>> is_file_like(buffer) True >>> is_file_like([1, 2, 3]) False """ if not (hasattr(obj, 'read') or hasattr(obj, 'write')): return False if not hasattr(obj, "__iter__"): return False return True
def breadcrumb_trail(context): """ Renders a two-tuple of page URLs and titles (see the :ref:`breadcrumb_trail <context_breadcrumb_trail>` context variable for more information) """ return { 'breadcrumb_trail': context.get('breadcrumb_trail') }
def spasser(inbox, s=None): """ Passes inputs with indecies in s. By default passes the whole inbox. Arguments: - s(sequence) [default: ``None``] The default translates to a range for all inputs of the "inbox" i.e. ``range(len(inbox))`` """ seq = (s or range(len(inbox))) return [input_ for i, input_ in enumerate(inbox) if i in seq]
def prefix(values, content): """ Discover start and separate from content. Will raise ValueError if none of the starts match. """ for value in values: if content.startswith(value): break else: raise ValueError('invalid starts') content = content[len(value):] return (value, content)
def symbol_converted(symbol): """ Input: symbol in the form '0005.HK' (from Alpha Vantange data) Output: symbol in the form '5' (for TWS) """ slice_index = 0 for i in range(0,4): if symbol[i]=='0': slice_index = i+1 else: break return symbol[slice_index:-3]
def is_comment(s): """ function to check if a line starts with some character. Here # for comment """ # return true if a line starts with # return s.startswith('#')
def format_data(account): """Takes the account data and returns the printable format.""" account_name = account["name"] account_descr = account["description"] account_country = account["country"] return f"{account_name}, a {account_descr}, from {account_country}"
def is_web_safe(r: int, g: int, b: int, a: int): """ True if the rgba value is websafe. Cite: https://www.rapidtables.com/web/color/Web_Safe.html """ if a != 255: return False else: return all(x in (0, 0x33, 0x66, 0x99, 0xCC, 0xFF) for x in (r, g, b))
def chan_id(access_address): """ Compute channel identifier based on access address """ return ((access_address&0xffff0000)>>16) ^(access_address&0x0000ffff)
def order(x): """ Determine sort order of char (x) :param x: character to test :return: order value char class order value ---------- ----------- '~' -1 digits 0 empty 0 letters ascii x non-letters ascii x + 256 """ return \ -1 if x == '~' \ else 0 if x.isdigit() \ else 0 if not x \ else ord(x) if x.isalpha() \ else ord(x) + 256
def Re_intube_waste(W_mass, z_way_waste, d_inner_waste, n_pipe_waste, mu_waste_avrg): """ Calculates the Reynold criterion. Parameters ---------- F_mass : float The mass flow rate of feed [kg/s] z_way_waste : float The number of ways in heat exchanger [dimensionless] d_inner_waste : float The diametr of inner pipe, [m] n_pipe_waste : float The number of pipes in heat exchanger, [dimensionless] mu_waste_avrg : float The mix viscocity of liquid, [Pa/s] Returns ------- Re_intube_waste : float The Reynold criterion in tube(waste), [dimensionless] References ---------- &&&&&& """ return 0.785 * W_mass * z_way_waste / (d_inner_waste * n_pipe_waste * mu_waste_avrg)
def pack_rle(data): """Use run-length encoding to pack the bytes""" rle = [] value = data[0] count = 0 for i in data: if i != value or count == 255: rle.append(count) rle.append(value) value = i count = 1 else: count += 1 rle.append(count) rle.append(value) return rle
def num_desc_seq_given_total_and_head(total, head): """ Subproblem in dynamic programming. Count the number of descending sequences given a total and the head. Note that a one-term sequence is also considered a sequence. """ if total < 1 or head < 1: return 0 # base case: sequence has only one term if total == head: return 1 # recursive case: sequence has more than one term # the second term cannot exceed the head; take advantage of transitivity num_seq = 0 for _second in range(1, head + 1): num_seq += num_desc_seq_given_total_and_head(total - head, _second) return num_seq
def fs15f16(x): """Convert float to ICC s15Fixed16Number (as a Python ``int``).""" return int(round(x * 2 ** 16))
def Wday(month, day): """ Function that yields the weekday given the month and the day Works for the year 2013, months 11 and 12 """ out=["Mo","Tu","We","Th","Fr","Sa","Su"] if(month==11): return out[(4+day)%7] if(month==12): return out[(6+day)%7]
def sort_dictionary_lists(dictionary): """ Give a dictionary, call `sorted` on all its elements. """ for key, value in dictionary.items(): dictionary[key] = sorted( value ) return dictionary
def multiplicative_inverse(e, phi): """ Euclid's extended algorithm for finding the multiplicative inverse of two numbers """ d, next_d, temp_phi = 0, 1, phi while e > 0: quotient = temp_phi // e d, next_d = next_d, d - quotient * next_d temp_phi, e = e, temp_phi - quotient * e if temp_phi > 1: raise ValueError('e is not invertible by modulo phi.') if d < 0: d += phi return d
def attribute( name, anchor_id, attribute_type, desc=None, options=None, default_option_id=None ): """ Create VIA attribute. :param name: str, attribute name :param anchor_id: 'FILE1_Z0_XY0':'Attribute of a File (e.g. image caption)', 'FILE1_Z0_XY1':'Spatial Region in an Image (e.g. bounding box of an object)', 'FILE1_Z0_XYN':'__FUTURE__', // File region composed of multiple disconnected regions 'FILE1_Z1_XY0':'__FUTURE__', // Time marker in video or audio (e.g tongue clicks, speaker diarisation) 'FILE1_Z1_XY1':'Spatial Region in a Video Frame (e.g. bounding box of an object)', 'FILE1_Z1_XYN':'__FUTURE__', // A video frame region composed of multiple disconnected regions 'FILE1_Z2_XY0':'Temporal Segment in Video or Audio (e.g. video segment containing an actor)', 'FILE1_Z2_XY1':'__FUTURE__', // A region defined over a temporal segment 'FILE1_Z2_XYN':'__FUTURE__', // A temporal segment with regions defined for start and end frames 'FILE1_ZN_XY0':'__FUTURE__', // ? (a possible future use case) 'FILE1_ZN_XY1':'__FUTURE__', // ? (a possible future use case) 'FILE1_ZN_XYN':'__FUTURE__', // ? (a possible future use case) 'FILEN_Z0_XY0':'Attribute of a Group of Files (e.g. given two images, which is more sharp?)', 'FILEN_Z0_XY1':'__FUTURE__', // ? (a possible future use case) 'FILEN_Z0_XYN':'__FUTURE__', // one region defined for each file (e.g. an object in multiple views) 'FILEN_Z1_XY0':'__FUTURE__', // ? (a possible future use case) 'FILEN_Z1_XY1':'__FUTURE__', // ? (a possible future use case) 'FILEN_Z1_XYN':'__FUTURE__', // ? (a possible future use case) 'FILEN_Z2_XY0':'__FUTURE__', // ? (a possible future use case) 'FILEN_Z2_XY1':'__FUTURE__', // ? (a possible future use case) 'FILEN_Z2_XYN':'__FUTURE__', // ? (a possible future use case) 'FILEN_ZN_XY0':'__FUTURE__', // one timestamp for each video or audio file (e.g. for alignment) 'FILEN_ZN_XY1':'__FUTURE__', // ? (a possible future use case) 'FILEN_ZN_XYN':'__FUTURE__', // a region defined in a video frame of each video :param attribute_type: 'TEXT', 'CHECKBOX', 'RADIO', 'SELECT', 'IMAGE' :param desc: :param options: :param default_option_id: :return: """ VIA_ATTRIBUTE_TYPE = {"TEXT": 1, "CHECKBOX": 2, "RADIO": 3, "SELECT": 4, "IMAGE": 5} if desc is None: desc = "" if options is None: options = [] if default_option_id is None: default_option_id = "" return { "aname": name, "anchor_id": anchor_id, "type": VIA_ATTRIBUTE_TYPE[attribute_type], "desc": desc, "options": {i: val for i, val in enumerate(options, start=1)}, "default_option_id": default_option_id, }
def get_dict( date: str, time: str, sender: str, message: str, weekday: str, hour_of_day: str, ) -> dict: """Return dictionary to build DF.""" return dict( date=date, time=time, sender=sender, message=message, weekday=weekday, hour_of_day=hour_of_day, )
def format_sequence(sequence): """Convert a binary sequence of 16 bits into an int. :param sequence: String composed of 16 zeroes or ones. :return: int value of the binary sequence, or -1 if the sequence is not 16 characters long or contains characters others than 0 or 1. """ is_binary = True for frame in sequence: if frame not in ('0', '1'): is_binary = False if is_binary and len(sequence) == 16: return int(sequence, 2) return -1
def is_index_out(index, arr): """ :param index: looping index :param arr: array / list :return: bool -> if index out of range """ return index < len(arr)-1
def wavelength_to_rgb(wavelength, gamma=0.8): """ This converts a given wavelength of light to an approximate RGB color value. The wavelength must be given in nanometers in the range from 380 nm through 750 nm (789 THz through 400 THz). Based on code by Dan Bruton http://www.physics.sfasu.edu/astro/color/spectra.html """ wavelength = float(wavelength) if 380 <= wavelength <= 440: attenuation = 0.3 + 0.7 * (wavelength - 380) / (440 - 380) R = ((-(wavelength - 440) / (440 - 380)) * attenuation) ** gamma G = 0.0 B = (1.0 * attenuation) ** gamma elif 440 <= wavelength <= 490: R = 0.0 G = ((wavelength - 440) / (490 - 440)) ** gamma B = 1.0 elif 490 <= wavelength <= 510: R = 0.0 G = 1.0 B = (-(wavelength - 510) / (510 - 490)) ** gamma elif 510 <= wavelength <= 580: R = ((wavelength - 510) / (580 - 510)) ** gamma G = 1.0 B = 0.0 elif 580 <= wavelength <= 645: R = 1.0 G = (-(wavelength - 645) / (645 - 580)) ** gamma B = 0.0 elif 645 <= wavelength <= 750: attenuation = 0.3 + 0.7 * (750 - wavelength) / (750 - 645) R = (1.0 * attenuation) ** gamma G = 0.0 B = 0.0 else: R = 0.0 G = 0.0 B = 0.0 return R, G, B
def quadinout(x): """Return the value at x of the 'quadratic in out' easing function between 0 and 1.""" if x < 0.5: return 2*x**2 else: return 1/2 - x*(2*x-2)
def format_mask(bitmask): """ Formats a numerical bitmask into a binary string. :Parameters: bitmask: integer A bit mask (e.g. 145) :Returns: bitstring: str A string displaying the bitmask in binary (e.g. '10010001') """ assert isinstance(bitmask, int) return "{0:b}".format(bitmask)
def armenian_date(year, month, day): """Return the Armenian date data structure.""" return [year, month, day]
def _expand_ranges(ranges_text, delimiter=',', indicator='-'): """ Expands a range text to a list of integers. For example: .. code-block:: python range_text = '1,2-4,7' print(_expand_ranges(range_text)) # [1, 2, 3, 4, 7] :param str ranges_text: The text of ranges to expand :returns: A list of integers :rtype: list[int] """ results = set() for group in filter(None, ranges_text.split(delimiter)): group = group.strip() if indicator not in group: if not group.isdigit(): raise ValueError(( "group '{group}' could not be interpreted as a valid digit" ).format(**locals())) results.add(int(group)) else: (start, finish,) = list(filter(None, group.split(indicator))) if not start.isdigit() or not finish.isdigit(): raise ValueError(( "group '{group}' could not be interpreted as a valid range" ).format(**locals())) for entry in range(int(start), (int(finish) + 1), 1): results.add(entry) return sorted(list(results))
def getdeepattr(d, keys, default_value=None): """ Similar to the built-in `getattr`, this function accepts a list/tuple of keys to get a value deep in a `dict` Given the following dict structure .. code-block:: python d = { 'A': { '0': { 'a': 1, 'b': 2, } }, } Calling `getdeepattr` with a key path to a value deep in the structure will return that value. If the value or any of the objects in the key path do not exist, then the default value is returned. .. code-block:: python assert 1 == getdeepattr(d, ('A', '0', 'a')) assert 2 == getdeepattr(d, ('A', '0', 'b')) assert 0 == getdeepattr(d, ('A', '0', 'c'), default_value=0) assert 0 == getdeepattr(d, ('X', '0', 'a'), default_value=0) :param d: A dict value with nested dict attributes. :param keys: A list/tuple path of keys in `d` to the desired value :param default_value: A default value that will be returned if the path `keys` does not yield a value. :return: The value following the path `keys` or `default_value` """ d_level = d for key in keys: if key not in d_level: return default_value d_level = d_level[key] return d_level
def are_overlapping_edges( source_minimum, source_maximum, filter_minimum, filter_maximum ): """Verifies if two edges are overlapping in one dimension. :param source_minimum: The minimum coordinate of the source edge. :param source_maximum: The maximum coordinate of the source edge. :param filter_minimum: The minimum coordinate of the filter edge. :param filter_maximum: The maximum coordinate of the filter edge. :return: True is the two edges are overlapping, False otherwise. Returns False if one or more coordinates are None. """ return ( source_maximum > filter_minimum and filter_maximum > source_minimum if None not in [source_minimum, source_maximum, filter_minimum, filter_maximum] else False )
def clean_key(key): """ Unescapes and removes trailing characters on strings """ return key.replace("''", "'").strip().rstrip(":")
def extract_model_name_and_run(model_string): """ `model_string` is a string in the format "model_name/run_id[ft]". Returns the name as a string and the run as an id. """ sp = model_string.split('/') assert len(sp) == 2 or len(sp) == 3 name = sp[0] if len(sp) == 2 else '{}/{}'.format(sp[0], sp[1]) run = sp[-1] discard_foot_contacts = 'f' in run replace_traj = 't' in run remove = 0 + discard_foot_contacts + replace_traj run_id = int(run[:-remove]) if remove > 0 else int(run) return name, run_id, discard_foot_contacts, replace_traj
def pad(s1): """ Pad a string to make it a multiple of blocksize. If the string is already a multiple of blocksize, then simply return the string """ if len(s1) % 16 == 0: return s1 else: return s1 + "\x00"*(16 - len(s1) % 16)
def get_rc(re): """ Return the reverse complement of a DNA/RNA RE. """ return re.translate(str.maketrans('ACGTURYKMBVDHSWN', 'TGCAAYRMKVBHDSWN'))[::-1]
def star_generator(individual_rating, star_rating=5): """Generates rating stars when rating is passed through""" output_html = '' star = 1 # html output strings checked_star = '<i class="fas fa-star checked" aria-hidden="true"></i>' unchecked_star = '<i class="fas fa-star unchecked" aria-hidden="true"></i>' # loop until break is called while True: # make sure that a value exists if individual_rating: if star <= int(individual_rating): output_html += checked_star else: output_html += unchecked_star else: # if no value exists, return unchecked output_html += unchecked_star star += 1 if star > int(star_rating): break return output_html
def dict_update(base_dict, update_dict): """Return an updated dictionary. If ``update_dict`` is a dictionary it will be used to update the ` `base_dict`` which is then returned. :param request_kwargs: ``dict`` :param kwargs: ``dict`` :return: ``dict`` """ if isinstance(update_dict, dict): base_dict.update(update_dict) return base_dict
def split_data(data, num_part): """ Split data for each device. """ if len(data) == num_part: return data data = data[0] inst_num_per_part = len(data) // num_part return [ data[inst_num_per_part * i:inst_num_per_part * (i + 1)] for i in range(num_part) ]
def RPL_ISON(sender, receipient, message): """ Reply Code 303 """ return "<" + sender + ">: " + message
def format_chrom(chrom, want_chr): """ Pass in a chromosome (unknown format), return in your format @param chrom: chromosome ID (eg 1 or 'chr1') @param want_chr: Boolean - whether you want "chr" at the beginning of chrom @return: "chr1" or "1" (for want_chr True/False) """ if want_chr: if chrom.startswith("chr"): return chrom else: return "chr%s" % chrom else: return chrom.replace("chr", "")
def show_bits(string: int, nbits: int = 16) -> str: """Return a string showing the occupations of the bitstring Args: string (int): bit string nbits (int): the number of bits to show Returns: str: string representation of the bit string """ return str(bin(int(string))[2:].zfill(nbits))
def format_host_address(value): """format ipv4 vs ipv6 address to string""" return value if ':' not in value else '[%s]' % value
def isnumber(s): """ General Boolean test for for a floating point value """ try: float(s) return True except ValueError: return False except TypeError: return False
def quick_sort(array): """ Sort function using quick sort algorithm. array - unsorted array """ if len(array) <= 1: return array pivot = array[0] # Separation element on less, equal, greater than pivot less = [i for i in array if i < pivot] equal = [i for i in array if i == pivot] greater = [i for i in array if i > pivot] return quick_sort(less) + equal + quick_sort(greater)
def derive_ppop_state(obj, state_dict): """ Deriving ppop code and ppop state name Args: obj: a dictionary containing the details we need to derive from and to state_dict: a dictionary containing all the data for State objects keyed by state code Returns: Place of performance code, state code, and state name as 3 return values (all strings or None) """ ppop_code = None state_code = None state_name = None if obj['place_of_performance_code']: ppop_code = obj['place_of_performance_code'].upper() if ppop_code == '00*****': state_name = 'Multi-state' elif ppop_code != '00FORGN': state_code = ppop_code[:2] state_name = state_dict.get(state_code) obj['place_of_perfor_state_code'] = state_code obj['place_of_perform_state_nam'] = state_name return ppop_code, state_code, state_name
def how_many (aDict): """ aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. """ key = aDict.keys() val = [] for key in aDict: aDict[key] val = val + aDict[key] return len(val)
def digit_sum(n): """Calculating with integer arithmetic instead of char/int/list method doubles the speed. """ result = 0 while n: result += n % 10 n = n // 10 return result
def expand_default_args(methods): """This function takes a collection of method tuples and expands all of the default arguments, returning a set of all methods possible.""" methitems = set() for mkey, mrtn in methods: mname, margs = mkey[0], mkey[1:] havedefaults = [3 == len(arg) for arg in margs] if any(havedefaults): # expand default arguments n = havedefaults.index(True) items = [((mname,)+tuple(margs[:n]), mrtn)] + \ [((mname,)+tuple(margs[:i]), mrtn) for i in range(n+1,len(margs)+1)] methitems.update(items) else: # no default args methitems.add((mkey, mrtn)) return methitems
def cost(actions): """A cost function""" return len([x for x in actions if x.islower()])
def is_prime(integer: int) -> bool: """Function to check if an integer is a prime""" if integer < 1: return False for i in range(2, integer): if integer % i == 0: return False return True
def get_tokens_from_line(line): """ Given a line split it into tokens and return them. Tokens are runs of characters separated by spaces. If there are no tokens return an empty list. Args: line (str): line to convert to tokens Returns: list(str): The tokens """ # Does line have any content if not line: return [] # Does the line have any content after splitting it line_tokens = line.split() if not line_tokens: return [] return line_tokens
def _toks2feats(a_tweet_toks): """Convert set of tweet's tokens to a dictionary of features. @param a_tweet_toks - set of tweet's uni- and bigrams @return feature dictionary with tweet's tokens as keys and values 1 """ return {w: 1. for w in a_tweet_toks}
def mean(data): """Return the sample arithmetic mean of data.""" n = len(data) if n < 1: raise ValueError('mean requires at least one data point') return sum(data)/n # in Python 2 use sum(data)/float(n)
def left_rotate(value, shift): """Returns value left-rotated by shift bits. In other words, performs a circular shift to the left.""" return ((value << shift) & 0xffffffff) | (value >> (32 - shift))
def mean(values): """Calculate the mean. Parameters ---------- values : list Values to find the mean of Returns ------- out : float The mean """ return sum(values)/float(len(values)) if len(values) > 0 else 0.0
def extract_data(page_data): """ extract file data from page json :param page_data: page data in json :return: extracted data in dic """ extracted_data = {} # loop through all cid in this page for file in page_data['hits']: cid = file['hash'] first_seen = file['first-seen'] score = file['score'] file_type = file['mimetype'] file_size = file['size'] file_data = {'first-seen': first_seen, 'score': score, 'size': file_size, 'mimetype': file_type} extracted_data[cid] = file_data return extracted_data
def clear(tupleo): """ clear(...) method of tupleo.tuple instance T.clear(tupleo) -> None -- Remove all elements from tuple, tupleo """ if type(tupleo) != tuple: raise TypeError("{} is not tuple".format(tupleo)) convertlist = list(tupleo) convertlist.clear() return tuple(convertlist)
def max_length(position, active_segments): """ Returns the maximum length of any segment overlapping ``position`` """ if not active_segments: return None return max(s.length for s in active_segments)
def parse_dec_or_hex(string): """Parses a string as either decimal or hexidecimal""" base = 16 if string.startswith('0x') else 10 return int(string, base)
def join(left, right): """ Join two dag paths together :param str left: A node dagpath or name. :param str right: A node name. :return: A dagpath combining the left and right operant. :rtype:str """ dagpath = "%s|%s" % (left.strip("|"), right.strip("|")) if left.startswith("|"): dagpath = "|" + dagpath return dagpath
def ccw(A, B, C): """Tests whether the turn formed by A, B, and C is ccw""" return (B[0] - A[0]) * (C[1] - A[1]) > (B[1] - A[1]) * (C[0] - A[0])
def reset_bits(value: int, pos: int) -> int: """ Resets bits higher than the given pos. """ reset_bits_mask = ~(255 << pos) value &= reset_bits_mask return value
def _search_to_regex(search): """ """ return f'.*{search}'
def display_mal_graph(value): """ Function that either displays the graph of the top 20 malicious domains or hides them depending on the position of the toggle switch. Args: value: Contains the value of the toggle switch. Returns: A dictionary that communicates with the Dash interface whether to display the graph of the top 20 malicious domains or hide them. """ if value is False: return {'display': 'unset'} else: return {'display': 'none'}
def is_valid_action(action): """Return whether or not the action function is a valid detcord action Args: action (function): the function to check Returns: bool: Whether or not the action is valid """ return getattr(action, 'detcord_action', False) != False
def json_value(obj): """Format obj in the JSON style for a value""" if type(obj) is bool: if obj: return '*true*' return '*false*' if type(obj) is str: return '"' + obj + '"' if obj is None: return '*null*' assert False
def mid_price(book): """ ratio of top bid to top ask """ bids,asks = book['bids'],book['asks'] #asks.reverse() level = 0 bp = bids[level]['price'] ap = asks[level]['price'] mid = (bp+ap)/2 return mid
def max(x, y): """``max :: a -> a -> a`` Maximum function. """ return x if x >= y else y
def ancestor_width(circ, supp, verbose=False): """ Args: circ(list(list(tuple))): Circuit supp(list): List of integers Returns: int: Width of the past causal cone of supp """ circ_rev= circ[::-1] supp_coded = 0 for s in supp: supp_coded |= (1<<s) for unitcirc in circ_rev: for gate in unitcirc: if verbose: print("gate={}".format(gate)) if (1<<gate[0]) & supp_coded: if not ((1<<gate[1]) & supp_coded): supp_coded |= (1<<gate[1]) elif (1<<gate[1]) & supp_coded: supp_coded |= (1<<gate[0]) return bin(supp_coded).count('1')
def parsepath(path): """internal use only: parsepath(path) - transform path like 'node/subnode(attr1=value,attr2=value2)[2]/subsubnode' into processible structure""" # remove first and last '/' if path[0] == '/': path=path[1:] if path[-1] == '/': path=path[:-1] el = path.split('/') elements=[] for e in el: where=0 # state in finite automaton element=u'' attrs={} idx='' attrname=u'' attrvalue=u'' for c in e: if where==0: # inside element if c == '(': where=1 elif c == '[': where=4 else: element += c elif where==1: # inside attribute name if c == '=': where=2 else: attrname += c elif where==2: # inside attribute value if c == ',' or c == ')': attrs[attrname] = attrvalue attrname=u'' attrvalue=u'' if c == ',': where=1 elif c == ')': where=3 else: attrvalue += c elif where==3: # before element index if c == '[': where=4 elif where==4: # inside element index if c == ']': idx=int(idx); where=5 else: idx += c if idx == '': idx=-1 elements.append((element, attrs, idx)) return elements
def better_bottom_up_mscs(seq: list) -> tuple: """Returns a tuple of three elements (sum, start, end), where sum is the sum of the maximum contiguous subsequence, and start and end are respectively the starting and ending indices of the subsequence. Let sum[k] denote the max contiguous sequence ending at k. Then, we have sum[0] = seq[0] sum[k + 1] = max(seq[k], sum[k] + seq[k]). To keep track where the max contiguous subsequence starts, we use a list. Time complexity: O(n). Space complexity: O(1).""" _max = seq[0] _sum = seq[0] index = 0 start = end = 0 for i in range(1, len(seq)): if _sum > 0: _sum = _sum + seq[i] else: _sum = seq[i] index = i if _sum > _max: _max = _sum end = i start = index return _max, start, end
def split_transactions(transactions): """ Split transactions into 80% to learn and 20% to test :param transactions: The whole transactions list :return: The transactions list to be learnt, the transactions list to be tested """ i = int(len(transactions) * 0.8) transactions_to_learn = transactions[:i] print(str(len(transactions_to_learn)) + " transactions will be used to learn.") transactions_to_test = transactions[i:] print(str(len(transactions_to_test)) + " transactions will be used to test.") return transactions_to_learn, transactions_to_test
def empty(list): """ Checks whether the `list` is empty. Returns `true` or `false` accordingly.""" return len(list) == 0
def mod360_distance(a, b): """distance between a and b in mod(360)""" # Surprisingly enough there doesn't seem to be a more elegant way. # Check http://stackoverflow.com/questions/6192825/ a %= 360 b %= 360 if a < b: return mod360_distance(b, a) else: return min(a-b, b-a+360)
def normalise_U(U): """ This de-fuzzifies the U, at the end of the clustering. It would assume that the point is a member of the cluster whose membership is maximum. """ for i in range(0,len(U)): maximum = max(U[i]) for j in range(0,len(U[0])): if U[i][j] != maximum: U[i][j] = 0 else: U[i][j] = 1 return U
def flatten(nav): """ Flattens mkdocs navigation to list of markdown files See tests/test_flatten.py for example Args: nav (list): nested list with dicts Returns: list: list of markdown pages """ pages = [] for i in nav: # file if type(i) == str: pages.append(i) continue item = list(i.values())[0] if type(item) == list: pages += flatten(item) else: pages.append(item) return pages
def get_three_level_class(value, red_thresh, yellow_thresh): """ Map a continuous value to a three level (green, yellow, red) classification in which intermediate ("yellow") values are tagged with class -1. The idea is that these values will be removed from the data set. """ if value >= red_thresh: return 1 elif value < yellow_thresh: return 0 else: return -1
def _safe_read(filepath): """Returns the content of the file if possible, None otherwise.""" try: with open(filepath, 'rb') as f: return f.read() except (IOError, OSError): return None
def get_process_name(proc_name): """ Get the exe process. @param proc_name: Sanitized name of the process. """ indexOfExe = proc_name.lower().find(".exe") if indexOfExe != -1: return proc_name[:indexOfExe + 4] else: return "{0} not an exe process.".format(proc_name)
def detect_cycle(variable, substitutions): """check whether variable has been substituted before""" # cycle detection if not isinstance(variable, list) and variable in substitutions: return True elif tuple(variable) in substitutions: return True else: has_cycle = False for key in substitutions: if isinstance(key, list) and variable in key: has_cycle = True return has_cycle
def analyse_sample_attributes_extended(sample): """ To find sample attributes Attributes: min_position_value - [index, value] max_position_value - [index, value] status - up, up_variates, down, down_variates, same, same_variates # noqa """ attributes = { "min_position_value": [0, sample[1]], "max_position_value": [0, sample[1]], "status": -1, } for index, value in enumerate(sample): if value < attributes["min_position_value"][1]: attributes["min_position_value"] = [index, value] if value > attributes["max_position_value"][1]: attributes["max_position_value"] = [index, value] if attributes["min_position_value"][0] == 0 and attributes["max_position_value"][0] == len(sample)-1: # noqa attributes["status"] = "up" elif attributes["min_position_value"][0] == len(sample)-1 and attributes["max_position_value"][0] == 0: # noqa attributes["status"] = "down" else: if sample[0] < sample[-1]: attributes["status"] = "up_variates" elif sample[0] > sample[-1]: attributes["status"] = "down_variates" else: if attributes["min_position_value"][0] == attributes["max_position_value"][0]: # noqa attributes["status"] = "same" else: attributes["status"] = "same_variates" return attributes
def limit(string, print_length=58): """Limit the length of a string to print_length characters Replaces the middle with ... """ if len(string) > print_length: trim = int((print_length-3)/2) return string[:trim] + '...' + string[-trim:] else: return string
def spatial_scale_conv_3x3_stride_1(s, p): """ This method computes the spatial scale of 3x3 convolutional layer with stride 1 in terms of its input feature map's spatial scale value (s) and spatial overal value (p). """ return s + 4 * (1-p) * s + 4 * (1-p) ** 2 * s
def round_to_nearest(x, base=5): """Round to nearest base. Parameters ---------- x : float Input Returns ------- v : int Output """ return int(base * round(float(x) / base))
def _normalise(s): """ Normalise the supplied string in the following ways: 1. String excess whitespace 2. cast to lower case 3. Normalise all internal spacing :param s: string to be normalised :return: normalised string """ if s is None: return "" s = s.strip().lower() while " " in s: # two spaces s = s.replace(" ", " ") # reduce two spaces to one return s
def camelcase(a): """Convert string to camelcase.""" return a.title().replace('_', '')
def with_trailing_slash(p): """Returns a path with a single trailing slash or None if not a path""" if not p: return p return type(p)(p.rstrip('/') + '/')
def get_giturl_from_url(url) : """extracts the actual git url from an url string (splits off the branch name after the optional '#') :param url: an url string, with optional '#' branch name appended :returns: the actual git url """ return url.split('#')[0]
def span_cover(sa,sb): """return smallest span covering both sa and sb; if either is None other is returned; 0-length spans aren't allowed - use None instead""" if sa is None: return sb if sb is None: return sa return (min(sa[0],sb[0]),max(sa[1],sb[1]))
def is_password_valid_with_old_rules(dataset): """ Validate password according to the old rules """ letter_count = dataset['password'].count(dataset['letter']) return int(dataset['first']) <= letter_count and letter_count <= int(dataset['last'])
def sarsa(currQ, alpha, gamma, reward, nextQ): """ nextQ = Q(curr, nextAction) where nextAction is selected according to policy - eGreedy or softmax """ newQ = currQ + alpha * (reward + gamma * nextQ - currQ) # update currQ to newQ in DB return newQ