content
stringlengths
42
6.51k
def is_position_in_coding_feature(position, cds_features): """Checks whether the given position lies inside of a coding feature in the given genome record. """ for feature in cds_features: if (feature.location.start <= position and position < feature.location.end): return True return False
def is_empty_alignment(alignment): """Returns True if alignment is empty. Args: alignment (str/Bio.Align.MultipleSequenceAlignment): A multiple sequence alignment string in FASTA format or a multiple sequence alignment object, either as a Bio.Align.MultipleSequenceAlignment or a biostructmap.SequenceAlignment object. Returns: bool: True if alignment is empty, False otherwise. """ if isinstance(alignment, str) and len(alignment.split('\n')[1]) == 0: return True elif not alignment or len(alignment[0]) == 0: return True else: return False
def get_indexes(start_index, chunk_size, nth): """ Creates indexes from a reference index, a chunk size an nth number Args: start_index (int): first position chunk_size (int): Chunk size nth (int): The nth number Returns: list: First and last position of indexes """ start_index = nth * chunk_size stop_index = chunk_size + nth * chunk_size return([start_index,stop_index])
def currency_to_protocol(amount): """ Convert a string of 'currency units' to 'protocol units'. For instance converts 19.1 bitcoin to 1910000000 satoshis. Input is a float, output is an integer that is 1e8 times larger. It is hard to do this conversion because multiplying floats causes rounding nubers which will mess up the transactions creation process. examples: 19.1 -> 1910000000 0.001 -> 100000 """ if type(amount) in [float, int]: amount = "%.8f" % amount return int(amount.replace(".", ''))
def parseIndex(index=None): """ Parse index query based on string Parameters ---------- index:str Examples --------- """ try: if index is None: value=slice(None,None,None) else: index=str(index) if ":" in index: start,end=index.split(":") if start=="":start=None else: start=int(start) if end=="":end=None else: end=int(end) value=slice(start,end,None) elif "[" in index: index=index.replace("[","").replace("]","") index=index.split(",") value=list(map(lambda x:int(x),index)) else: value=int(index) return value except Exception as err: raise Exception("Format needs to be \"{int}\" or \":\" or \"{int}:{int}\" or \"[{int},{int}]\"")
def get_diagonal_points(start_x, start_y, end_x, end_y): """ Returns a list of tuples that contains diagonal points from one point to another :param start_x: :param start_y: :param end_x: :param end_y: :return: """ points = [] y_inc = 1 if int(start_x) > int(end_x): start_x, start_y, end_x, end_y = end_x, end_y, start_x, start_y if start_y > end_y: y_inc = -1 while start_x <= end_x: points.append((start_x, start_y)) start_x += 1 start_y += y_inc return points
def __convert_size(size_in_bytes, unit): """ Converts the bytes to human readable size format. Args: size_in_bytes (int): The number of bytes to convert unit (str): The unit to convert to. """ if unit == 'GB': return '{:.2f} GB'.format(size_in_bytes / (1024 * 1024 * 1024)) elif unit == 'MB': return '{:.2f} MB'.format(size_in_bytes / (1024 * 1024)) elif unit == 'KB': return '{:.2f} KB'.format(size_in_bytes / 1024) else: return '{:.2f} bytes'.format(size_in_bytes)
def longest_repetition(lst): """ Takes as input a list, and returns the element in the list that has the most consecutive repetitions. If there are multiple elements that have the same number of longest repetitions, returns the one that appears first. If the input list is empty, returns None. """ most_element = None most_count = 0 current_element = None current_count = 0 for item in lst: if current_element != item: current_element = item current_count = 1 else: current_count += 1 if current_count > most_count: most_element = current_element most_count = current_count return most_element
def convert_list_to_dict(origin_list): """ convert HAR data list to mapping @param (list) origin_list [ {"name": "v", "value": "1"}, {"name": "w", "value": "2"} ] @return (dict) {"v": "1", "w": "2"} """ return { item["name"]: item["value"] for item in origin_list }
def esc_seq(n, s): """Escape sequence. Call sys.stdout.write() to apply.""" return '\033]{};{}\007'.format(n, s)
def format_sizeof(num, suffix='', divisor=1000): """ Code from tqdm Formats a number (greater than unity) with SI Order of Magnitude prefixes. Parameters ---------- num : float Number ( >= 1) to format. suffix : str, optional Post-postfix [default: '']. divisor : float, optional Divisor between prefixes [default: 1000]. Returns ------- out : str Number with Order of Magnitude SI unit postfix. Examples -------- >>> format_sizeof(800000) '800K' >>> format_sizeof(40000000000000) '40.0T' >>> format_sizeof(1000000000000000000000000000) '1000.0Y' """ for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 999.5: if abs(num) < 99.95: if abs(num) < 9.995: return '{0:1.2f}'.format(num) + unit + suffix return '{0:2.1f}'.format(num) + unit + suffix return '{0:3.0f}'.format(num) + unit + suffix num /= divisor return '{0:3.1f}Y'.format(num) + suffix
def corr_units(varlist): """ The unit correction is necessary as in the case when there are subscripts, the units are not associated correctly with all the subscript instances therefore the same unit needs to be passed down to other instances unit_dict is not used anywhere else, but could be: {'exo BL1': 'Month', 'exo BL2': '1/Month', 'exo RL1': 'Month', ... :param varlist: list of dict of the variables :return: list of dict of the variables with corrected units """ unit_dict = {} for var in varlist: if var['unit'] != '': unit_dict[var['name'].split('[')[0]] = var['unit'] for var in varlist: if var['type'] != 'subscript list' and var['unit'] == '': var['unit'] = unit_dict.get(var['name'].split('[')[0]) return varlist
def PathHasDriveLetter(path): """Check path for windows drive letter. Use 1:2 to avoid raising on single character paths. Args: path: path string Returns: True if this path has a drive letter. """ return path[1:2] == ":"
def get_attribute_value(owner_uri: str, attribute_name: str): """Get attribute value for given attribute name from the owner uri""" if owner_uri is not None and '/' in owner_uri: sliced_owner_uri = owner_uri[owner_uri.rindex('/'):len(owner_uri)] splited_owner_uri = sliced_owner_uri.split('|') for item in splited_owner_uri: if attribute_name in item: final_value = item.split(':') return final_value[1]
def solve_fast(k, lim): """A little faster version of 'solve', but with a high memory usage. This version uses an array to store all the previous values, it uses the value as the index and the previous index as the element. """ seq = [*k] nums = [None] * (max(seq) + 1) for i, elem in enumerate(seq): nums[elem] = i for i in range(len(k) - 1, lim): res = nums[seq[i]] if nums[seq[i]] is not None else i seq.append(i-res) nums.append(None) nums[seq[i]] = i return seq[lim - 1]
def convert_keys_to_string(dictionary): """ Recursively converts dictionary keys to strings. Found at http://stackoverflow.com/a/7027514/104365 """ if not isinstance(dictionary, dict): return dictionary return dict([(str(k), convert_keys_to_string(v)) for k, v in dictionary.items()])
def get_high_and_water_ways(ways): """ Extracts highways and waterways from all ways. :param ways: All ways as a dict :return: highways (list), waterways (list) """ highways = list() waterways = list() for way_id in ways: way = ways[way_id] if "highway" in way.tags: highways.append(way) elif "waterway" in way.tags: waterways.append(way) return highways, waterways
def format_website_string(website): """Returns a formatted website string to be used for siteinfo. Args: website (string): user-supplied. Returns: string: lower-case, prefixes removed. """ formatted = website.lower() prefixes = ["https://", "http://", "www."] for prefix in prefixes: if formatted.startswith(prefix): formatted = formatted[len(prefix) :] return formatted
def pe44(limit=1500): """ >>> pe44() (5482660, 7042750, 1560090, 2166, 1019) """ pents = [i * (3 * i - 1) >> 1 for i in range(1, limit << 1)] ps = set(pents) for i in range(limit): p1 = pents[i] for j in range(i + 1, (limit << 1) - 1): p2 = pents[j] diff = p2 - p1 if p2 + p1 in ps and diff in ps: return (diff, p2, p1, j, i) return None
def parse_sk_m(line): """ Parse sk_m measurements. This is a line having this format: $ sk_m_print(0,send-1-0-1) idx= 4 tscdiff= 42 @return None, in case the lines is not an sk_m, a tuple (core, title, idx, tscdiff) otherwise """ if line.startswith('sk_m_print'): (desc, _, idx, _, tscdiff) = line.split() desc = desc.replace('sk_m_print(', '') desc = desc[:-1] (core, title) = desc.split(',') return (int(core), title, int(idx), int(tscdiff)) else: return None
def accepts(source): """ Do we accept this source? """ if source["type"] == "git": return True # There are cases where we have a github repo, but don't wanna analyze the code, just issues if source["type"] == "github" and source.get("issuesonly", False) == False: return True return False
def dict_attr(attr_dict: dict, attr_dict_key: str): """ :rtype: dict """ if attr_dict_key in attr_dict.keys(): return attr_dict[attr_dict_key] return {}
def is_instrinsic(input): """ Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single key that is the name of the intrinsics. :param input: Input value to check if it is an intrinsic :return: True, if yes """ if input is not None and isinstance(input, dict) and len(input) == 1: key = list(input.keys())[0] return key == "Ref" or key == "Condition" or key.startswith("Fn::") return False
def _closure_service(target, type = "binary"): """ Computes a target name, postfixed with a sentinel indicating a request for a Closure-based gRPC client. """ return "%s-%s-%s" % (target, "grpc_js", type)
def logBase2(n): """assumes that n is a postivie int returns a float that approximates the log base 2 of n""" import math return math.log(n, 2)
def order_annotations(annotation): """ Standardizes the annotations that are presented to users where more than one is applicable. Parameters ---------- annotation : str The annotation to be returned to the user in the command bar. """ single_annotations = ["Akk", "Dat", "Gen"] if annotation in single_annotations: return annotation annotation_split = sorted(annotation.split("/")) return "/".join(annotation_split)
def factorial(n): """ Calculate n! Args: n(int): factorial to be computed Returns: n! """ if n == 0: return 1 # by definition of 0! return n * factorial(n-1)
def validate_package_weight_normal_code_type_annotation(weight: int) -> bool: """ :param weight: weight of mail package, that we need to validate :return: if package weight > 200 - return False (we cannot deliver this package) """ if weight <= 0: raise Exception("Weight of package cannot be 0 or below") elif weight > 200: return False else: return True
def bisection(func, low, high, eps): """ Find the root on the interval [low, high] to the tolerance eps ( eps apples to both function value and separation of the bracketing values ) """ # if bracket is backwards, correct this if low > high: low, high = high, low # standard way to swap two variables # other way: #tmp = low #low = high #high = tmp flow = func(low) fhigh = func(high) if flow*fhigh > 0: print("root is not bracketd by [", low, ", ", high,"]") exit(1) mid = 0.5*(high+low) fmid = func(mid) while (high-low) > eps and abs(fmid)>eps: if fmid*flow < 0: high = mid fhigh = fmid else: low = mid flow = fmid mid = 0.5*(high+low) fmid = func(mid) return mid
def get_samples_panfamilies(families, sample2family2presence): """Get the sorted list of all the families present in the samples Can be a subset of the pangenome's set of families""" panfamilies = set() for f in families: for s in sample2family2presence: if sample2family2presence[s][f]: panfamilies.add(f) break return sorted(panfamilies)
def add(a, b): """This program adds two numbers and return result""" result = a + b return result
def num_splits(s: list, d: int) -> int: """Return the number of ways in which s can be partitioned into two sublists that have sums within d of each other. >>> num_splits([1, 5, 4], 0) # splits to [1, 4] and [5] 1 >>> num_splits([6, 1, 3], 1) # no split possible 0 >>> num_splits([-2, 1, 3], 2) # [-2, 3], [1] and [-2, 1, 3], [] 2 >>> num_splits([1, 4, 6, 8, 2, 9, 5], 3) 12 """ def helper_part(lst: list): # return a list of lists, each list is a unique way to partition lst parts = [] for i in range(len(lst)): parts.append([lst[i]]) rest_parts = [[lst[i]] + p for p in helper_part(lst[i+1:])] parts += rest_parts return parts total = 0 for part in helper_part(s): temp = s[:] for p in part: temp.remove(p) # print('DEBUG: ', 'part: ', part, 'rest: ', temp) if abs(sum(part) - sum(temp)) <= d: # print('DEBUG: ', 'diff: ', sum(part), sum(temp)) if len(temp) == 0: total += 2 else: total += 1 return total // 2
def partial_clique_graph(i, set_cliques, minimum, num_cliques): """ Function that supports the creation of the clique graph, the second stage of CPM. This function is detached from the main function since it is parallelised (based on the amout of workers). Parameters ---------- i : integer The iterator for parallelisation. set_cliques : list(set) List containing all found cliques. Each clique is a set so it becomes easier to compare minimum : int Minimum overlapping between two cliques (size_of_cliques-1). num_cliques : int Number of cliques found in the graph. Returns ------- edge_list : list List of edges belonging to the iterated node. """ edge_list = list() this_set = set_cliques[i] for j in range(i+1, num_cliques): if len(this_set.intersection(set_cliques[j])) == minimum: edge_list.append((i,j)) return edge_list
def create_ref(path): """ Create a json definition reference to a specific path """ return '#/definitions/' + path
def ordlist(s): """Turns a string into a list of the corresponding ascii values.""" return [ord(c) for c in s]
def _is_trivial_paraphrase(exp1, exp2): """ Return True if: - w1 and w2 differ only in gender and/or number - w1 and w2 differ only in a heading preposition :param exp1: tuple/list of strings, expression1 :param exp2: tuple/list of strings, expression2 :return: boolean """ def strip_suffix(word): if word[-2:] == 'os' or word[-2:] == 'as': return word[:-2] if word[-1] in 'aos': return word[:-1] return word prepositions = {'de', 'da', 'do', 'das', 'dos', 'em', 'no', 'na', 'nos', 'nas'} if exp1[0] in prepositions: exp1 = exp1[1:] if exp2[0] in prepositions: exp2 = exp2[1:] if len(exp1) == 0 or len(exp2) == 0: return True if exp1[-1] in prepositions: exp1 = exp1[:-1] if exp2[-1] in prepositions: exp2 = exp2[:-1] if len(exp1) != len(exp2): return False if exp1 == (',',) or exp2 == (',',): return True for w1, w2 in zip(exp1, exp2): w1 = strip_suffix(w1) w2 = strip_suffix(w2) if len(w1) == 0 or len(w2) == 0: if len(w1) == len(w2): continue else: return False if w1 != w2 and \ not (w1[-1] == 'l' and w2[-1] == 'i' and w1[:-1] == w2[:-1]): return False return True
def lchop(string, prefix): """Removes a prefix from string :param string: String, possibly prefixed with prefix :param prefix: Prefix to remove from string :returns: string without the prefix """ if string.startswith(prefix): return string[len(prefix):] return string
def _convert_FtoK(T): """ convert Fahrenheit to Kelvin. :param T: Temperature (F). :return: Temperature (K). """ return (T - 32.0)*5.0/9.0 + 273.15
def get_feature_directory_name(settings_dict): """Get the directory name from the supplied parameters and features.""" dir_string = "%s_%d_%d_%d_%d" % ( settings_dict["feature"], settings_dict["fft_sample_rate"], settings_dict["stft_window_length"], settings_dict["stft_hop_length"], settings_dict["frequency_bins"], ) if settings_dict["feature"] == "cqt": dir_string += "_%d" % settings_dict["cqt_min_frequency"] if settings_dict["feature"] == "mfcc": dir_string += "_%d" % settings_dict["mfc_coefficients"] return dir_string
def decode_modm(limbs): """ Decodes scalar mod m from limbs with base 30 :param n: :return: """ n = 0 c = 0 shift = 0 mask = (1 << 30) - 1 for i in range(9): n += ((limbs[i] & mask) + c) << shift c = limbs[i] >> 30 shift += 30 return n
def fibonacci_sequence(size): """fibonacci """ sequence = [] for n in range(size): if n == 0: sequence.append(1) elif n == 1: sequence.append(1) else: sequence.append(sequence[-1] + sequence[-2]) return sequence
def extract_state_from_event(state_key: str, event_data: dict): """ Extract information from the event data to make a new sensor state. Use 'dot syntax' to point for nested attributes, like `service_data.entity_id` """ if state_key in event_data: return event_data[state_key] elif state_key.split(".")[0] in event_data: try: nested_data = event_data for level in state_key.split("."): nested_data = nested_data[level] # Don't use dicts as state! if isinstance(nested_data, dict): return str(nested_data) return nested_data except (IndexError, TypeError): pass return "bad_state"
def get_one_hot_index_from_ints(tonic, quality, num_qualities=3): """ Get the one-hot index of a chord with the given tonic and quality. Parameters ========== tonic : int The tonic of the chord, where 0 is C. None represents a chord with no tonic. quality : int The quality of the chord, where 0 is major, 1 is minor, and 2 is diminished. num_qualities : int The number of allowable qualities in this set of chords. Defaults to 3. Returns ======= index : int The one-hot index of the given chord and quality. A chord with no tonic returns an index of 36. """ try: return tonic + 12 * quality except: return 12 * num_qualities
def init_times(times, **kwargs): """Add attributes to a set of times.""" for t in times: t.update(**kwargs) return times
def load_array_meta(loader, filename, index): """ Load the meta-data data associated with an array from the specified index within a file. """ return loader(filename, index)
def get_link(js): """ @todo """ if 'url' in js: return js['url'] if 'architecture' not in js: return None for bits in ['64bit', '32bit']: if bits not in js['architecture']: continue if 'url' not in js['architecture'][bits]: continue return js['architecture'][bits]['url'] return None
def Wrap(content, cols=76): """Wraps multipart mime content into 76 column lines for niceness.""" lines = [] while content: lines.append(content[:cols]) content = content[cols:] return '\r\n'.join(lines)
def friendly_repr(obj, *attributes): """Render a human friendly representation of a database model instance.""" values = [] for name in attributes: try: value = getattr(obj, name, None) if value is not None: values.append("%s=%r" % (name, value)) except Exception: pass return "%s(%s)" % (obj.__class__.__name__, ", ".join(values))
def unlist(collection): """Extracts element from @collection if len(collection) 1. :returns: element in collection or None. :raises: TypeError if len(collection) > 1 """ if len(collection) > 1: raise TypeError("Cannot unlist collection: {0}\n".format(collection) + "Collection size is greater than 1.") return collection[0] if len(collection) == 1 else None
def _change_from_camel_case(word): """Changes dictionary values from camelCase to camel_case. This is done so that attributes of the object are more python-like. :param word: A string of a word to convert :type word: string :return: A string of the converted word from camelCase to camel_case :rtype: string """ return_word = '' for letter in word: if letter.isupper(): letter = f'_{letter.lower()}' return_word += letter return return_word
def edit_string_for_tags(tags): """ Given list of ``Tag`` instances, creates a string representation of the list suitable for editing by the user, such that submitting the given string representation back without changing it will give the same list of tags. Tag names which contain commas will be double quoted. If any tag name which isn't being quoted contains whitespace, the resulting string of tag names will be comma-delimited, otherwise it will be space-delimited. Ported from Jonathan Buchanan's `django-tagging <http://django-tagging.googlecode.com/>`_ """ names = [] for tag in tags: name = tag.name if ',' in name or ' ' in name: names.append('"%s"' % name) else: names.append(name) return ', '.join(sorted(names))
def to_cuda(*args): """Move tensors to GPU device. """ return [None if x is None else x.cuda() for x in args]
def has_form_encoded_header(header_lines): """Return if list includes form encoded header""" for line in header_lines: if ":" in line: (header, value) = line.split(":", 1) if header.lower() == "content-type" \ and "x-www-form-urlencoded" in value: return True return False
def fix_month(bib_str: str) -> str: """Fixes the string formatting in a bibtex entry""" return ( bib_str.replace("{Jan}", "jan") .replace("{jan}", "jan") .replace("{Feb}", "feb") .replace("{feb}", "feb") .replace("{Mar}", "mar") .replace("{mar}", "mar") .replace("{Apr}", "apr") .replace("{apr}", "apr") .replace("{May}", "may") .replace("{may}", "may") .replace("{Jun}", "jun") .replace("{jun}", "jun") .replace("{Jul}", "jul") .replace("{jul}", "jul") .replace("{Aug}", "aug") .replace("{aug}", "aug") .replace("{Sep}", "sep") .replace("{sep}", "sep") .replace("{Oct}", "oct") .replace("{oct}", "oct") .replace("{Nov}", "nov") .replace("{nov}", "nov") .replace("{Dec}", "dec") .replace("{dec}", "dec") )
def _any(iterable): """Same as built-in version of any() except it explicitly checks if an element "is not None".""" for element in iterable: if element is not None: return True return False
def binary_search(arr, key): """Given a search key, this binary search function checks if a match found in an array of integer. Examples: - binary_search([3, 1, 2], 2) => True - binary_search([3, 1, 2], 0) => False Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm Args: arr (list): A list of integer key (int) : Integer search key Returns: bool: True if key exists in arr, False otherwise """ arr.sort() L = 0 R = len(arr) - 1 if L > R: return False mid = R//2 if key == arr[mid]: return True elif key < arr[mid]: return binary_search(arr[:mid], key) else: return binary_search(arr[mid+1:], key)
def seq_fib(num=6): """Stores and reuses calculations to avoid redundancies and time build up. Args: num (int): Wanted number from the sequence. Returns: fib[num]: Gets the n'th number from storage values. """ fib = {} for k in range(1, num+1): if k <= 2: fib_current = 1 else: fib_current = fib[k-1] + fib[k-2] fib[k] = fib_current return fib[num]
def isLeapYear(year): """ Returns True if the year is a Leap Year else, returns False """ if year % 400 == 0: return True elif year % 100 == 0: return False elif year % 4 == 0: return True return False
def calc_wait(da, speed): """ Given an angular delta and the speed (servo counts), calculate the how long to wait for the servo to complete the movement [Join Mode] 0 ~ 1,023(0x3FF) can be used, and the unit is about 0.111rpm. If it is set to 0, it means the maximum rpm of the motor is used without controlling the speed. If it is 1023, it is about 114rpm. For example, if it is set to 300, it is about 33.3 rpm. AX12 max rmp is 59 (max speed 532) rev min 360 deg deg --- ------- ------- = 6 ---- min 60 sec rev sec da deg wait = ---------------------------------------- rpm 360 deg min 0.111 --- * speed_cnt * ------- * ------ cnt rev 60 sec wait = abs(new_angle - old_angle)/(0.111 * speed * 6) """ try: w = abs(da)/(0.111*speed*6) except ZeroDivisionError: w = 1 print("*** calc_wait() div error: {}".format(speed)) return w
def base_slots(cls): """Return all member descriptors in C and its bases.""" slots = set() for c in type.mro(cls): slots.update(getattr(c, '__slots__', ())) return slots
def find_min_rotate(array): """ Finds the minimum element in a sorted array that has been rotated. """ low = 0 high = len(array) - 1 while low < high: mid = (low + high) // 2 if array[mid] > array[high]: low = mid + 1 else: high = mid return array[low]
def parse_file_type(file_type, file_name, output=False, logger=None): """Parse the file_type from the file_name if necessary :param file_type: The input file_type. If None, then parse from file_name's extension. :param file_name: The filename to use for parsing if necessary. :param output: Limit to output file types (FITS/ASCII)? (default: False) :param logger: A logger if desired. (default: None) :returns: The parsed file_type. """ if file_type is None: import os name, ext = os.path.splitext(file_name) if ext.lower().startswith('.fit'): file_type = 'FITS' elif ext.lower().startswith('.hdf'): file_type = 'HDF' elif not output and ext.lower().startswith('.par'): file_type = 'Parquet' else: file_type = 'ASCII' if logger: logger.info(" file_type assumed to be %s from the file name.",file_type) return file_type.upper()
def divides(a, b): """ :param a: A nonzero integer. :param b: An integer. :returns: Returns a boolean value indicating whether a divides b. """ return b % a == 0
def valid_password(password): """ The password must be at least nine characters long. Also, it must include characters from two of: -alphabetical -numerical -punctuation/other """ punctuation = set("""!@#$%^&*()_+|~-=\`{}[]:";'<>?,./""") alpha = False num = False punct = False if len(password) < 9: return False for character in password: if character.isalpha(): alpha = True if character.isdigit(): num = True if character in punctuation: punct = True return (alpha + num + punct) >= 2
def followers_and_retweets_of_tweet(tweet): """ Function that retrieves number of followers of account that posted tweet and the number of times that tweet was retweeted Parameters ---------- tweet: dict data for individual tweet Returns ------- followers: int numbers of followers retweets: int number of retweets """ # search tweet dictionary for follower count followers = 0 if 'user' in str(tweet): if 'followers_count' in str(tweet['user']): followers = tweet['user']['followers_count'] # search tweet dictionary for retweet count retweets = 0 if 'retweeted_status' in str(tweet): if 'retweet_count' in str(tweet['retweeted_status']): retweets = tweet['retweeted_status']['retweet_count'] return followers, retweets
def prf(correct, pred_sum, gold_sum): """ Calculate precision, recall and f1 score Parameters ---------- correct : int number of correct predictions pred_sum : int number of predictions gold_sum : int number of gold answers Returns ------- tuple (p, r, f) """ if pred_sum: p = correct / pred_sum else: p = 0 if gold_sum: r = correct / gold_sum else: r = 0 if p + r: f = 2 * p * r / (p + r) else: f = 0 return p, r, f
def ham_dist(bv1, bv2): """ returns the hamming distance between two bit vectors represented as lists """ if len(bv1) != len(bv2): raise Exception("fail: bitvectors of different length "+\ str(len(bv1))+", "+str(len(bv2))) total = 0 for i, bit in enumerate(bv1): if bit != bv2[i]: total += 1 return total
def coerce_result(result): """ Coerces return value to a tuple if it returned only a single value. """ if isinstance(result, tuple): return result else: return (result,)
def _split_columns(x): """Helper function to parse pair of indexes """ try: a, b = map(int, x.split(",")) # columns from command line are numbered starting from 1 # but internally we start counting from 0 return a - 1, b - 1 except ValueError as ex: message = """ Cannot understand the pair of columns you want to print. Columns are identified by numbers starting from 1. Each pair of columns is identified by two numbers separated by a comma without a space 1,2 1,5 6,4\n\n\n""" print(message, ex) raise ex
def binary_transition(transitions, state, symbol): """Binary state machine transition computation. Computes next state. :param transitions: Transition "matrix", in the form of: {True: state_inverting_symbols, False: state_inverting_symbols} :param state: Current state. True or False :param symbol: Incoming symbol :return: New state >>> transitions = {False: {1, 2}, True: {3}} >>> binary_transition(transitions, False, 3) False >>> binary_transition(transitions, False, 1) True >>> binary_transition(transitions, True, 1) True >>> binary_transition(transitions, True, 2) True >>> binary_transition(transitions, True, 3) False """ if symbol in transitions[state]: # if symbol is in the set of triggering symbols... return not state # reverse the state else: return state
def create_phone_number(n): """ Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number. The returned format must be correct in order to complete this challenge. Don't forget the space after the closing parentheses! :param n: An input array of integers. :return: A string of those numbers in the array in phone number form. """ return "({}) {}-{}".format("".join(map(str, n[0:3])), "".join(map(str, n[3:6])), "".join(map(str, n[6:])))
def findNubInDict(id, nubDict): """ Return the named nub, or None if it does not exist. """ return nubDict.get(id, None)
def inverse_word_map(word_map): """ Create an inverse word mapping. :param word_map: word mapping """ return {v: k for k, v in word_map.items()}
def is_digit(str_value: str) -> bool: """Checks if a string represents a digit after replacing thousand and decimal separators""" return str_value.replace(".", "").replace(",", "").isdigit()
def count_steps(path): """Count the number of replacement steps in a given path :param path: the path through the CYK table :return steps: the number of replacement steps """ # path is always a branching of the form # (a, (b, c)) # standing for a => (b, c) name, result = path steps = 1 # count the branching that `path` stands for # add all sub-branchings for x in result: if not isinstance(x, str): steps += count_steps(x) return steps
def calculate_label_counts(examples): """Assumes that the examples each have ONE label, and not a distribution over labels""" label_counts = {} for example in examples: label = example.label label_counts[label] = label_counts.get(label, 0) + 1 return label_counts
def triangle(base, height): """Calculate the area of a triangle.""" return base * height / 2
def _create_accum_slots(optimizer, var_list, name): """Create accumulation slots.""" slots = [] for v in var_list: s = optimizer._zeros_slot(v, "accum", name) # pylint: disable=protected-access slots.append(s) return slots
def parseBoolValue(value): """ Utility function to parse booleans and none from strings """ if value == 'false': return False elif value == 'true': return True elif value == 'none': return None else: return value
def empty_columns(board): """Returns list of "" with length equal to length of expected column. >>> empty_columns(['***21**', '412453*', '423145*', '*543215', '*35214*',\ '*41532*', '*2*1***']) ['', '', '', '', '', '', ''] """ columns = [] while len(columns)!= len(board[0]): columns.append("") return columns
def product_calculator(*args: int) -> int: """ Calculates the product of the given inputs. :param args: A set of input values :return: The product of the given values """ value = 1 for i in args: value *= i return value
def validate_non_humanreadable_buff(data: str, buff_min_size: int = 256, whitespace_ratio: float = 0.10) -> bool: """ Checks if a buffer is not human readable using the porportion of whitespace data: the buffer buff_min_size: minimum buffer size for the test to be meaningful whitespace_ratio: ratio of whitespace to non-whitespace characters returns: if the buffer size is appropriate and contains less whitespace than whitespace_ratio """ ws_count = data.count(" ") ws_count += data.count("%20") * 3 return len(data) >= buff_min_size and ws_count / len(data) < whitespace_ratio
def z_region_pass(region, upper_limit=None, lower_limit=None): """return True if extended region [xmin, xmax, ymin, ymax, zmin, zmax] is within upper and lower z limits Args: region (list): a long-region [xmin, xmax, ymin, ymax, zmin, zmax] upper_limit (float): the z-max lower_limit (float): the z-min Returns: bool: True if region z values are within upper and lower limit """ if region is not None: z_region = region[4:] if z_region is not None and len(z_region) >= 2: if upper_limit is not None: if z_region[0] >= upper_limit: return(False) if lower_limit is not None: if z_region[1] <= lower_limit: return(False) return(True)
def limit(q, lim): """Non-MS SQL Server implementation of 'limit'""" return "SELECT sq.* FROM ({}) sq LIMIT {}".format(q, lim)
def addelems(list1, list2): """ Adds list1 and list2 element wise. Summands may contain None, which are ignored. :type list1: list :param list1: First summand :type list2: list :param list2: Second summand :return: list """ # Make sure the lists are of the same length assert len(list1) == len(list2), "Summands must have the same length." # Add return [(item1 + item2 if not (item1 is None or item2 is None) else None) for item1, item2 in zip(list1, list2)]
def can_move(index, state, zero_index): """Check whether the empty sign could be moved.""" if index < 0: return state[zero_index + index] == 1 and zero_index + index > -1 return zero_index + index < len(state) and state[zero_index + index] == 2
def reduction(op, elements, accumulator): """ Combines a list of elements into one using an accumulator. Returns the final state of the accumulator. ---------- op : Operation to apply to each element and the accumulator. Must be associative and distributive. elements : List of elements. accumulator : Initial state of the accumulator. """ for element in elements: accumulator = op((accumulator, element)) return accumulator
def merge_blocks(ivs, dist=0): """ Merge blocks Args: ivs (list): List of intervals. Each interval is represented by a tuple of integers (start, end) where end > start. dist (int): Distance between intervals to be merged. Setting dist=1 will merge adjacent intervals Returns: list: Merged list of intervals Examples: >>> merge_interval_list([]) [] >>> merge_interval_list([(1,10)]) [(1, 10)] >>> merge_interval_list([(4, 9), (10, 14), (1, 3)]) [(1, 3), (4, 9), (10, 14)] >>> merge_interval_list([(4, 9), (10, 14), (1, 3)], dist=1) [(1, 14)] """ if len(ivs)<= 1: return ivs ivs.sort(key=lambda x:x[0]) ret = [ivs[0]] for iv in ivs[1:]: if iv[0] - ret[-1][1] > dist: ret.append(iv) else: ret[-1] = (ret[-1][0], max(iv[1],ret[-1][1])) return ret
def compile_per_chrom(hbar_list): """Return [{chr: upper: lower:}]""" if hbar_list == []: return [] mylist = [] comp = {"chr": None , "xranges":[], "upper":[], "lower":[]} mylist.append(comp) for i in hbar_list: # same chromosome, add to lists if mylist[-1]['chr'] is None: mylist[-1]['chr'] = i["chr"] mylist[-1]['xranges'].append(i["xranges"]) mylist[-1]['upper'].append(i["hbar_upper"]) mylist[-1]['lower'].append(i["hbar_lower"]) elif mylist[-1]['chr'] == i["chr"]: mylist[-1]['xranges'].append(i["xranges"]) mylist[-1]['upper'].append(i["hbar_upper"]) mylist[-1]['lower'].append(i["hbar_lower"]) else: mylist.append({"chr": i["chr"], "xranges":[i["xranges"]], "upper":[i["hbar_upper"]], "lower":[i["hbar_lower"]]}) return mylist
def get_recursively(search_dict, field): """Takes a dict with nested dicts, and searches all dicts for a key of the field provided.""" fields_found = [] for key, value in search_dict.items(): if key == field: fields_found.append(value) elif isinstance(value, dict): results = get_recursively(value, field) for result in results: fields_found.append(result) return fields_found
def parse_method_path(method_path): """ Returns (package, service, method) tuple from parsing method path """ # unpack method path based on "/{package}.{service}/{method}" # first remove leading "/" as unnecessary package_service, method_name = method_path.lstrip("/").rsplit("/", 1) # {package} is optional package_service = package_service.rsplit(".", 1) if len(package_service) == 2: return package_service[0], package_service[1], method_name return None, package_service[0], method_name
def dot(x, y): """ Dot product as sum of list comprehension doing element-wise multiplication """ return (sum(x_i * y_i for x_i, y_i in zip(x, y)))
def get_sbo_int( miriam_urns): """ takes a list of miriam encoded urn, e.g. ['urn:miriam:GO:0016579', 'urn:miriam:SBO:0000330'] and returns the integers [330] """ return [ int( i[15:]) for i in miriam_urns if i.startswith( "urn:miriam:SBO:")]
def count_punkt(list_of_lists_of_tokens, punkt_list=[]): """ Return count of "meaningful" punctuation symbols in each text Parameters ---------- - list_of_lists_of_tokens : dataframe column whose cells contain lists of words/tokens (one list for each sentence making up the cell text) - punkt_list : list of punctuation symbols to count (e.g., ["!", "?", "..."]) - OUTPUT : pandas Series of integer, each being the count of punctuation in each text cell """ OUTPUT = len( [tok for sent in list_of_lists_of_tokens for tok in sent if tok in punkt_list] ) return OUTPUT
def replace(key: str, value: str, line: str) -> str: """ Replaces a key with a value in a line if it is not in a string or a comment and is a whole word. Complexity is pretty bad, so might take a while if the line is vvveeeerrrrryyyyyy long. """ i = 0 in_string = False in_comment = False while i < len(line) - len(key) and len(line) >= len(key): # Line length may change, so re evaluate each time if(line[i] == "\""): # Start or end of a string in_string = not in_string elif(line[i] == "'" or line[i] == ";") and line[i:i+8] != ";#sertxd": # Start of a comment in_comment = True elif(line[i] == "\n"): # New line. Reset comment in_comment = False elif not in_comment and not in_string: # We can check for the key starting at this position if (line[i:i+len(key)] == key) and not (i > 0 and (line[i-1].isalpha() or line[i-1] == "_")) and not (i+len(key) < len(line) and (line[i+len(key)].isalpha() or line[i+len(key)] == "_" or line[i+len(key)].isnumeric())): line = line[:i] + str(value) + line[i+len(key):] # Replace that appearance i += len(value) # Skip over the value we replaced it with i += 1 return line
def color_blend(a, b): """Performs a Screen blend on RGB color tuples, a and b""" return (255 - (((255 - a[0]) * (255 - b[0])) >> 8), 255 - (((255 - a[1]) * (255 - b[1])) >> 8), 255 - (((255 - a[2]) * (255 - b[2])) >> 8))
def starts2dshape(starts): """ Given starts of tiles, deduce the shape of the decomposition from them. Args: starts (list of ints) Return: tuple: shape of the decomposition """ ncols = 1 for start in starts[1:]: if start[1] == 0: break ncols += 1 nrows = len(starts) // ncols assert len(starts) == nrows * ncols return (nrows, ncols)
def ease_in_out_cubic(n): """ :param float n: 0-1 :return: Tweened value """ n *= 2 if n < 1: return 0.5 * n**3 else: n -= 2 return 0.5 * (n**3 + 2)
def _str2bool(s): """Convert string to boolean.""" return s.lower() in ("true", "t", "yes", "y", "1")
def find_number_of_digits(number): """ it takes number as input, then finds number_of_digits. """ number_of_digits = 0 while (number > 0): number_of_digits+=1 number //= 10 return number_of_digits