content
stringlengths
42
6.51k
def set_insertion_sieve(n): """Performing insertion over deletion""" factors = set() for i in range(2,int(n**0.5+1)): if i not in factors: factors |= set(range(i*i, n+1, i)) return set(range(2,n+1)) - factors
def query_string_to_kwargs(query_string: str) -> dict: """ Converts URL query string to keyword arguments. Args: query_string (str): URL query string Returns: dict: Generated keyword arguments """ key_value_pairs = query_string[1:].split("&") output = {} for key_value_p...
def compute_ratio(hyp: str, ref: str) -> float: """ :param hyp: :param ref: :return: """ # naive tokenization hyp_len = len(hyp.split(" ")) ref_len = len(ref.split(" ")) return hyp_len / ref_len
def merge_runs_by_tag(runs, tags): """ Collect the (step, value) tuples corresponding to individual tags for all runs. Therefore the result might look like this: <tagA> + step: - <run-1-steps> - <run-2-steps> + value: - <run-1-values> - <run-2-values> ....
def calc_prior_probability(clazz, total_num_instances): """ Calculates the prior probability for clazz """ num_instances = len(clazz) prior_probability = (num_instances/total_num_instances) return prior_probability
def IsCloudPath(path): """Checks whether a given path is Cloud filesystem path.""" return path.startswith("gs://") or path.startswith("s3://")
def check_alleles(alleles, num_sites): """ Checks the specified allele list and returns a list of lists of alleles of length num_sites. If alleles is a 1D list of strings, assume that this list is used for each site and return num_sites copies of this list. Otherwise, raise a ValueError if all...
def value_from_char(character): """ Args: character (string): Takes an ASCII alphabet character and maps it 0-25, a-z. Returns: int: Numerical representation of the ASCII alphabet character inputted. """ return ord(character.lower()) - ord('a')
def ARGMAX(agg_column,out_column): """ Builtin arg maximum aggregator for groupby Example: Get the movie with maximum rating per user. >>> sf.groupby("user", ... {'best_movie':tc.aggregate.ARGMAX('rating','movie')}) """ return ("__builtin__argmax__",[agg_column,out_column])
def remove_any_pipe_values_from_topic_name(topic_name): """Removes any passed in piped values if they exist from the topic name. Keyword arguments: topic_name -- the topic name """ return topic_name.split("|")[0] if "|" in topic_name else topic_name
def calc_box_length(part_num, density, aspect_ratio): """ part_num, density, aspect_ratio = [x, y, z] -> x:y:z """ box_length = (float(part_num) / float(density) / (aspect_ratio[0] * aspect_ratio[1] * aspect_ratio[2]))**(1.0 / 3.0) return [box_length * aspect_ratio[0], box_length * aspect_...
def SIZE(expression): """ Counts and returns the total the number of items in an array. See https://docs.mongodb.com/manual/reference/operator/aggregation/size/ for more details :param expression: Any expression as long as it resolves to an array :return: Aggregation operator """ return ...
def _smallest_change(h, alpha): """Return smallest point not fixed by ``h`` else return None.""" for i in range(alpha, len(h)): if h[i] != i: return i
def path_nodes_to_edges(path): """ Returns an ordered list of edges given a list of nodes Args: path - a path, as a sequence of nodes Returns: An ordered list of edges. """ # Edge sequence initialization edge_sequence = [] for i in range(len(path) - 1): ...
def solution(A): # O(N^2) """ Sort numbers in list A using bubble sort. >>> solution([5, 2, 2, 4, 1, 3, 7, 9]) [1, 2, 2, 3, 4, 5, 7, 9] >>> solution([2, 4, 6, 2, 0, 8]) [0, 2, 2, 4, 6, 8] >>> solution([1, 3, 5, 7, 3, 9, 1, 5]) [1, 1, 3,...
def format_domain_name(domain_name): """ :param domain_name: :return: """ format_domain_name = domain_name.split(",") return format_domain_name
def case_insensitive_equal(str1, str2): """ Compares two strings to determine if they are case-insensitively equal Args: str1 (str): str2 (str): Returns: bool: True if the strings are equal, ignoring case """ return str1.lower() == str2.lower()
def get_highest_action(life): """Returns highest action in the queue.""" if life['actions'] and life['actions'][0]: return life['actions'][0] else: return None
def _filter_scaling(reduction_indices, start_cell_num): """Compute the expected filter scaling at given PNASNet cell start_cell_num. In the pnasnet.py code, filter_scaling starts at 1.0. We instead adapt filter scaling to depend on the starting cell. At first cells, before any reduction, filter_scalling is 1.0...
def dict_to_conf_str(obj): """Dump dict as key=value to str object.""" config_list = [] for key in sorted(obj.keys()): value = obj[key] config_list.append("%s=%s" % (key, obj[key])) return '\n'.join(config_list)
def minNumberOfCoinsForChange(n, denoms): """ nc = number_coins nc[i=amount] = { min (nc[amount-coin] + 1 coin, nc[amount]) for i > 0, 0, for i = 0 """ number_coins = [float('inf')] * (n + 1) n...
def cleanopts(optsin): """Takes a multidict from a flask form, returns cleaned dict of options""" opts = {} d = optsin for key in d: opts[key] = optsin[key].lower().replace(" ", "_") return opts
def reinterpret_latin1_as_utf8(wrongtext): """ :see:recode_unicode """ newbytes = wrongtext.encode('latin-1', 'replace') return newbytes.decode('utf-8', 'replace')
def parse_split_conf(conf): """ Function parse comma separated values from config """ result = [] if len(conf.strip()): conf = conf.split(',') for item in conf: index = conf.index(item) conf[index] = item result = list(map(str.strip, conf)) return result
def resample(X, n=None): """ Bootstrap resample an array_like Parameters :param X: array_like data to resample :param n: int, optional length of resampled array, equal to len(X) if n==None Results """ from random import sample, uniform if n == None: n = int(uniform(1,len(X))) X_res...
def GetSvnBranchName(url, postfix_branch, logger): """ get svn branch name using it's url Args : url : svn url of module postfix_branch : postfix of branch logger : the object of Log.Log Returns : return svn branch name of module, if enconters some errors return None ...
def rgb_to_hex(rgb): """ [255,255,255] -> "#FFFFFF" """ # Components need to be integers for hex to make sense rgb = [int(x) for x in rgb] hex_rgb = "".join([f"0{v:x}" if v < 16 else f"{v:x}" for v in rgb]) return f"#{hex_rgb}"
def str_to_seconds(tstring): """ Convert time strings to seconds. Strings can be of the form: <int> (ninutes) <int>m (minutes) <int>h (hours) <int>d (days) <int>y (years) Args: tstring (str): An integer followed by an (optional) 'm...
def test_tiff(h, f): """TIFF (can be in Motorola or Intel byte order)""" if h[:2] in (b'MM', b'II'): return 'tiff'
def remove_list_indices(a_list, del_indices, opposite = True): """ ================================================================================================= remove_list_indices(a_list, del_indices, opposite) This function is meant to remove el...
def _get_permission_filters(permission_ids): """Helper function to filter permissions.""" if permission_ids == 'all': return {} else: return {'id': permission_ids}
def list_sum(num_list): """Returns the sum of all of the numbers in the list""" if len(num_list) == 1: return num_list[0] else: return num_list[0] + list_sum(num_list[1:])
def rescale(n, after=[0,1], before=[]): """ Helper function to rescale a vector between specified range of values :param numpy array n: a vector of numbers to be rescale :param list after: range of values to which to scale n :param list before: range of values in which n is contained """ ...
def build_mpi_call_str(task_specs,common_options,format_opts=None,runner='mpiexec'): """Summary Args: task_specs (list): List of strings, each containing an MPI task description, eg e.g: ['-n {nrunners} python3 awrams.module.example {pickle_file}'] common_options ...
def get_hyperhdr_device_id(server_id: str, instance: int) -> str: """Get an id for a HyperHDR device/instance.""" return f"{server_id}_{instance}"
def AVL(game_board, rebalance): """Addional game rules when the DS is AVL.""" # Check if the graph is in rebalance state if rebalance and (game_board['graph']['balanced']): return {'cheat': True, 'reason': str('Tree is already balanced!')} # Check if user is attempting to do an action while tr...
def decode_uint48(bb): """ Decode 6 bytes as an unsigned 48 bit integer Specs: * **uint48 len**: 6 bytes * **Format string**: 'J' """ return int.from_bytes(bb, byteorder='little', signed=False)
def correct_name_servers(logger, result, zone): """ This is to deal with issues in the whois library where the response is a string instead of an array. Known variants include: - "Hostname: dns-1.example.org\nHostname: dns-2.example.org\nHostname..." - "No nameserver" - "dns...
def monophonic(plain_txt: str, all_letters: list, shifted_letters: dict): """ enciphers a line of plaintext with monophonic shift (rot-key) cipher i.e. number of unique chars across plaintext and ciphertext remains conserved """ cipher_txt = [] for char in plain_txt: if char in all_lette...
def is_node_active_at_timestamp(node, ts): """Check if a node is active at a given timestamp""" return node.get("from", 0) <= ts <= node.get("to", float("inf"))
def _all_same(all_gen): """ helper function to test if things are all the same """ if len(all_gen) == 1: return True for gen in all_gen[1:]: if gen != all_gen[0]: return False # I don't want to use 'set' because thing might not be hashable return True
def is_float(value: str) -> bool: """ Check value for float """ try: float(value) except (ValueError, TypeError): return False return True
def get_mail_domain_list(domain): """ Get an array of domains that should be covered for a given primary domain that uses email. Args: domain - The primary domain to use to create the list of domains/subdomains """ return [domain, 'www.' + domain, 'mail.' + domain, 'webmail....
def _f_to_c(f): """ Converts temperature in Fahrenheit to Celsius Args: f (real) -- Fahrenheit Returns: real -- Celsius """ return (f-32)*5.0/9.0
def tlvs_by_subtype(tlvs, subtype): """Return list of TLVs with matching type.""" return [tlv for tlv in tlvs if tlv.subtype == subtype]
def year_cycle(year=0): """Year cycle. Parameters ---------- year : int, optional (dummy value). Returns ------- out : dict integer (1) as key, 'Year' as value. Notes ----- Appropriate for use as 'year_cycles' function in :class:`Calendar`, this allows to e...
def create_permutation_list(length): """ Create a list of each permutation of length 'length'. """ numbers = range(1,length+1) permutations_dict = {} for number in numbers: permutations_dict[number] = (len(numbers) - 1) * [number] #For each number, reserve a list that starts wit...
def atoi(s): """ Convert s to an integer. """ # determine sign sgn = 1 if s[0] == '-': sgn = -1 s = s[1:] # accumulate digits i = 0 for d in s: x = ord(d) - ord('0') if x < 0 or x > 9: raise ValueError('bad digit') i = 10*i + x ...
def reduceVtype(vtypeDict, taxis, period): """Reduces the vtypeDict to the relevant information.""" newVtypeDict = {} for t in vtypeDict: if t in taxis: newVtypeDict[t] = [] index = 0 for e in vtypeDict[t]: if index % period == 0: ...
def _check_vdj_len(nt_seq): """ Verifies the length of a VDJ nucleotide sequence mod 3 equals 1 (The constant region continues the reading frame) """ if len(nt_seq) % 3 == 1: return True else: return False
def convert_pascal_bbox_to_coco(xmin, ymin, xmax, ymax): """ pascal: top-left-x, top-left-y, x-bottom-right, y-bottom-right coco: top-left-x, top-left-y, width and height """ return [xmin, ymin, xmax - xmin, ymax - ymin]
def schema_choices_helper(field): """ Test custom choices helper """ return [ { "value": "friendly", "label": "Often friendly" }, { "value": "jealous", "label": "Jealous of others" }, { "value": "spits", ...
def find_if_prime_num(check_prime): """ This function checks if any of the numbers represented are prime or not input: (list) check_prime output: (list) is_prime_number """ is_prime_number = [] for num in check_prime: # search for factors, iterating through numbers ranging from 2 to the ...
def marioAlgorithm(total_coins_inserted, coins_in_machine_dict): """ marioAlgorithm(total_coins, coins_dict) --> minimum coins for change """ min_coins_dispensed = [] partial_sum = 0 full_sum = 0 # Sorts the coins based on money value in descending order sorted_coins_in_machine = sorted...
def get_chasm_context(tri_nuc): """Returns the mutation context acording to CHASM. For more information about CHASM's mutation context, look at http://wiki.chasmsoftware.org/index.php/CHASM_Overview. Essentially CHASM uses a few specified di-nucleotide contexts followed by single nucleotide context....
def euclideanGCD( a, b ): """Calculates the Greatest Common Denominator of two integers using the Euclidean algorithm. Arguments should be integers. Returns GCD(a,b) Note: This function will likely hit the recursion limit for big numbers. """ return abs(a) if ( b == 0 ) els...
def tiers_for_dev(dev): """ Returns a tuple of tiers for a given device in ascending order by length. :returns: tuple of tiers """ t1 = dev['region'] t2 = dev['zone'] t3 = dev['ip'] t4 = dev['id'] return ((t1,), (t1, t2), (t1, t2, t3), (t1, t...
def _is_power_of_two(number): """Checks whether a number is power of 2. If a number is power of 2, all the digits of its binary are zero except for the leading digit. For example: 1 -> 1 2 -> 10 4 -> 100 8 -> 1000 16 -> 10000 All the digits after the leading digit are zero after subtract...
def _group_name_from_id(project, group_id): """Build the group name given the project and group ID. :type project: string :param project: The project associated with the group. :type group_id: string :param group_id: The group ID. :rtype: string :returns: The fully qualified name of the g...
def impedance(vp, rho): """ Given Vp and rho, compute impedance. Convert units if necessary. Test this module with: python -m doctest -v impedance.py Args: vp (float): P-wave velocity. rho (float): bulk density. Returns: float. The impedance. Examples: >>>...
def form_name_entries_special(pos, provenance, pw_id, pw_entry, kb_id, kb_entry): """ Create name match entries :param pos: :param pw_id: :param pw_entry: :param kb_id: :param kb_entry: :return: """ entries = [] for pw_name in set(pw_entry['aliases']): entries.append(...
def _wrap(text, width): """Break text into lines of specific width.""" lines = [] pos = 0 while pos < len(text): lines.append(text[pos:pos + width]) pos += width return lines
def get_index_of_smallest(L, i): """Return the index of the smallest element of L. Args: L (list): List we want to analyse. i (int): Index from where we want to start. Returns: int: Index of smallest element of L. """ # The index of the smallest item so far index_of_sm...
def process_text(text): """ process text to remove symbols - remove tags: {spk}, {noise}, {click}, {beep}, <caller>, </caller>, <recipient>, </recipient> - invalid if contains: <bmusic>, <bnoise>, <bspeech>, <foreign>, [utx], +WORD, WOR-, -ORD, ~ WORD, (()), ((Word Word)) - conversion: ...
def cvsecs(*args): """ converts a time to second. Either cvsecs(min, secs) or cvsecs(hours, mins, secs). """ if len(args) == 1: return args[0] elif len(args) == 2: return 60*args[0] + args[1] elif len(args) == 3: return 3600*args[0] + 60*args[1] + args[2]
def port_status_change(port, original): """port_status_change Checks whether a port update is being called for a port status change event. Port activation events are triggered by our own action: if the only change in the port dictionary is activation state, we don't want to do any processing. ...
def nobrackets(v): """ Remove brackets """ return v.replace('[', '').replace(']', '')
def to_bool(bool_str): """Parse the string and return the boolean encoded or raise exception.""" if bool_str.lower() in ['true', 't', '1']: return True elif bool_str.lower() in ['false', 'f', '0']: return False else: return bool_str
def hard_limit(val, limits): """ Check if a value is outside specified limits :param val: value to be tested :param limits: two membered list of lower and upper limit :type val: float :type limits: list of floats :return: 1 if the input is outside the limits, 0 otherwise :retur...
def some(seq): """Return some element of seq that is true.""" for e in seq: if e: return e return False
def add_saved_artists(auths, artists): """ Adds/follows artists. :param auths: dict() being the 'destinations'-tree of the auth object as returned from authorize() :param artists: list() containing the artists IDs to add to the 'destinations' accounts :return: True """ for username in auths:...
def sequences_overlap(true_seq, pred_seq): """ Boolean return value indicates whether or not seqs overlap """ start_contained = (pred_seq['start'] < true_seq['end'] and pred_seq['start'] >= true_seq['start']) end_contained = (pred_seq['end'] > true_seq['start'] and pred_seq['end'] <= true_seq['end']...
def search(keyword_to_queries: dict, keywords: list) -> list: """ Looks up the list of queries that satisfy a keyword. :param keyword_to_queries: a mapping of keywords to query indices :param keywords: a list of keywords to lookup :return: a list of query indices """ query_count = dict() ...
def get_supported_extensions(): """ Returns a list of supported image extensions. """ return ('jpeg', 'jpg', 'png')
def cli_table(table, spl = " ", fill = " ", align = "left"): """ Args: table (List[List[str]]): input data spl (str): splitting string of columns fill (str): string of 1 byte, used to fill the space align (str): left and right is available """ len_row = len(table) len...
def average(x): """This function calculates the average of a list of provided values. :param x: A list of values to be averaged. :type x: List of Integers :return: The average of the provided list. """ return sum(x) * 1.0 / len(x)
def get_unique_el_mapping(data_list): """Map each unique element in the data list to a number/index. """ key2idx = {el: idx for idx, el in enumerate(set(data_list))} idx2key = {v: k for k, v in key2idx.items()} for idx in idx2key.keys(): assert isinstance(idx, int) return key2idx, idx2...
def make_round_pairs(sequence): """ Given a sequence [A, B, C] of size n, creates a new sequence of the same size where each new item is the pair of the item at a given position paired up with next item. Additionally, last item is paired with the first one: [(A, B), (B, C), (C, A)]. :param ...
def subarray(a: list, b: list) -> int: """ Time Complexity: O(n) """ l: int = len(a) hash_table: dict = {a[0] - b[0]: 0} length: int = 0 for i in range(1, l): a[i] += a[i - 1] b[i] += b[i - 1] diff = a[i] - b[i] if diff == 0: length = i + 1 ...
def get_operand_string(mean, std_dev): """ Method to get operand string for Fsl Maths Parameters ---------- mean : string path to img containing mean std_dev : string path to img containing standard deviation Returns ------ op_string : string operand string ...
def pv(flow, n, spot): """PV of cash flow after compounding spot rate over n periods""" return flow / ((1 + spot) ** n)
def runge_kutta4(y, x, dx, f): """computes 4th order Runge-Kutta for dy/dx. Parameters ---------- y : scalar Initial/current value for y x : scalar Initial/current value for x dx : scalar difference in x (e.g. the time step) f : ufunc(y,x) Callable function ...
def heronStep(y, x): """Perform one step of Heron's method for sqrt(y) with guess x.""" return 0.5*(x + y/x)
def point_is_under_triangle(x, y, p0, p1, p2): """Determine whether the vertical line through (x, y, 0) intersects the triangle (p0, p1, p2).""" dX = x - p2[0] dY = y - p2[1] dX21 = p2[0] - p1[0] dY12 = p1[1] - p2[1] # The Barycentric coordinates of (x, y) wrt the triangle. s = dY12 * dX + ...
def find_namespace_vars_usages(analysis, namespace_usage): """ Returns usages of Vars from namespace_usage. It's useful when you want to see Vars (from namespace_usage) being used in your namespace. """ usages = [] for var_qualified_name, var_usages in analysis.get("vindex_usages", {}).items(...
def add_critical_points(points: dict, coord: tuple, ax, stableonly: bool = False): """ Add the critical points to a graph Parameters ---------- points : dict keys are (s,h,z) coordinates, contains information on points coord : tuple tuple of which coordinates...
def Union(List1,List2): """Returns union of two lists""" #----------------------------- # Copy List 1 Into Return List #----------------------------- # Put a copy of List 1 into ReturnList. This gives us the base list to # compare against. ReturnList = List1[:] #-----...
def kernel_mu(n_kernels, manual=False): """ get mu for each guassian kernel, Mu is the middele of each bin :param n_kernels: number of kernels( including exact match). first one is the exact match :return: mus, a list of mu """ mus = [1] # exact match if n_kernels == 1: return mus b...
def SquishHash(s): """ SquishHash() is derived from the hashpjw() function by Peter J. Weinberger of AT&T Bell Labs. https://en.wikipedia.org/wiki/PJW_hash_function """ h = 0 for f in s: h = (h << 4) + ord(f.lower()) g = h & 0xf0000000 if g != 0: h |= g >> ...
def stripnl(string): """Strip the final newline from <string>. It is an error if <string> does not end with a newline character, except for the empty string, which is okay. >>> stripnl('') '' >>> stripnl('he\\nllo\\n') 'he\\nllo' >>> try: ... stripnl('hello') ... except Runti...
def listify(item, delimiter=","): """Used for taking character (usually comma)-separated string lists and returning an actual list, or the empty list. Useful for environment parsing. Sure, you could pass it integer zero and get [] back. Don't. """ if not item: return [] if type(ite...
def _get_charset(message): """Return charset, given a http.client.HTTPMessage""" if not message["content-type"] or not "charset=" in message["content-type"]: # utter guesswork return "utf-8" charset = message["content-type"].split("charset=")[1] return charset.split(";")[0]
def replace_it_in_list(original: list): """ This function replace all the 'it' to 'something' because 'it' is to general in knowledge. :param original: A list of strings to be replaced. :return: A list of strings after the replacement. """ result = [] for i in original: word = i.spli...
def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0
def _linear_annealing(init, fin, step, annealing_steps): """Linear annealing of a parameter. Linearly increase parameter from value 'init' to 'fin' over number of iterations specified by 'annealing_steps'""" if annealing_steps == 0: return fin assert fin > init, 'Final value should be ...
def get_field(key_value_pair_list, key): """ Given a list of key-value pairs (dicts with keys 'key' and 'value'), find the entry that has the provided `key` and return its value. If no `key` is found, return None. It assumes that each `key` only appears one in `key_value_pair_list`, s...
def get_squares(num): """ Get the first n triangular numbers. """ return [int(i ** 2) for i in range(1, num + 1)]
def get_media_id_from_url(anilist_url): """ get media id from url used to strip an anilist url for the media id specifically """ # initialize media id based off url media_id = 0 if 'anilist' in anilist_url: try: media_id = int(anilist_url.split('anilist')[-1].split('/')[2]) ...
def hk_aocs_modes(bits: list) -> bytes: """ First bit should be on the left, bitfield is read from left to right """ enabled_bits = 0 bits.reverse() for i in range(len(bits)): enabled_bits |= bits[i] << i return enabled_bits.to_bytes(1, byteorder='big')
def get_best_v_for_gnh_tb(sorted_degrees, sorted_nen_counts): """ """ sub_list = [sorted_nen_counts[0][0]] min_count = sorted_nen_counts[0][1] for (v, count) in sorted_nen_counts[1:]: if count != min_count: break sub_list.append(v) for v, deg in sorted_degrees: ...