content
stringlengths
42
6.51k
def getTooltipString(description): """Ensures that tooltips are shown with newlines. """ newDescription = "" if not description == "": newDescription = "<FONT>" newDescription += description newDescription += "</FONT>" return newDescription
def dr_hill_zero_background(x, theta, eta, kappa): """dr hill zero background Parameters ---------- x : int theta : float eta : float kappa : float Returns ------- float (theta* x**eta) / (kappa**eta + x**eta) """ return (theta * x**eta) / (kappa**eta + x**eta)
def insert_in_front(val, seq): """ >>> insert_in_front(5, [1, 3, 4, 6]) [5, 1, 3, 4, 6] >>> insert_in_front(5, (1, 3, 4, 6)) (5, 1, 3, 4, 6) >>> insert_in_front('x', 'abc') 'xabc' """ if type(seq) == list: seq = [val] + seq return seq elif type(seq) == tuple: seq = (val,) + seq return seq elif type(seq) == str: seq = str(val) + seq return seq
def filter_frontier(frontier, pred_fns, cfg_pred_fns=None): """Filter out points from the frontier that don't pass all the pred_fns. If a pred_fn is None, ignore that metric. """ new_frontier = [] for result in frontier: cfg, qos = result keep = True if not all(f(x) for x, f in zip(qos, pred_fns) if f is not None): keep = False if cfg_pred_fns is not None: if not all(f(x) for x, f in zip(cfg, cfg_pred_fns) if f is not None): keep = False if keep: new_frontier.append(result) return new_frontier
def merge(left, right): """Merges two sorted lists. Args: left: A sorted list. right: A sorted list. Returns: The sorted list resulting from merging the two sorted sublists. Requires: left and right are sorted. """ items = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: items.append(left[i]) i = i + 1 else: items.append(right[j]) j = j + 1 if i < len(left): items.extend(left[i:]) elif j < len(right): items.extend(right[j:]) return items
def check_equal(iterator): """ returns true if all items in iterator are equal, otherwise returns false """ iterator = iter(iterator) try: first = next(iterator) except StopIteration: return True return all(first == rest for rest in iterator)
def get_names(title): """ Recieves a title string and returns all the possible usages of the project name. """ if not title: return None canvas = title.strip().lower() return { "project_title": canvas.title(), "project_cammel": canvas.title().replace(" ", ""), "project_snake": canvas.replace(" ", "_"), "project_kebab": canvas.replace(" ", "-") }
def optiC1(tau,w,s): """Compute the optimal consumption of young generation Args: tau (float): percentage of contribution of the wage of the young agent w (float): wage s (float): savings Returns: (float): optimal consumption of young generation """ return (1-tau)*w-s
def foldl(function, list, initial): """ Given a function, a list, and initial accumulator, fold (reduce) each item into the accumulator from the left using function(accumulator, item) """ for item in list: initial = function(initial, item) return initial
def bitWrite(x, n, b): #pylint: disable-msg=invalid-name """ Based on the Arduino bitWrite function, changes a specific bit of a value to 0 or 1. The return value is the original value with the changed bit. This function is written for use with 8-bit shift registers :param x: numeric value :param n: position to change starting with least-significant (right-most) bit as 0 :param b: value to write (0 or 1) """ if b == 1: x |= 1<<n & 255 else: x &= ~(1 << n) & 255 return x
def is_odd(number): """ *Determine if the number is odd or not* **Key Arguments:** - ``number`` -- number to be tested for 'odd'ness Returns: - True or False -- depending on whether the arugment is odd or even """ if number % 2 == 0: return False else: return True
def answer_is_type(answer, target_answer_type): """ :param answer: :param target_answer_type: :return: true if the answer type matches given input 'RepeatingAnswer' question type return 'answers' as an object, and dict for all other question types. """ answer_type = answer['type'] if isinstance(answer, dict) else answer.type return answer_type == target_answer_type.lower()
def get_experiment_name(model, dataset, optimizer): """ Name where the experiment's results are saved :param model: 'vgg', 'vggnonorm', 'resnet' or 'lstm' :param dataset: 'cifar10' or 'cifar100' :param optimizer: 'sgdm', 'ssgd' or 'sssgd' :return: The name of the experiment """ return model + '-' + dataset + '-' + optimizer + '/'
def yr2sec(time): """Converts time from years to seconds.""" return time * 60.0 * 60.0 * 24.0 * 365.25
def _issues_choice_callback(enum, _, param, value): """Translate the given value to enum representation.""" if value is None: return return getattr(enum, value)
def mel2hz(mel): """Convert a value in Mels to Hertz :param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise. :returns: a value in Hertz. If an array was passed in, an identical sized array is returned. """ return 700 * (10**(mel / 2595.0) - 1)
def are_relatively_prime(a, b): """Return ``True`` if ``a`` and ``b`` are two relatively prime numbers. Two numbers are relatively prime if they share no common factors, i.e. there is no integer (except 1) that divides both. """ for n in range(2, min(a, b) + 1): if a % n == b % n == 0: return False return True
def round_down(value, multiple): """Return value rounded down to closest multiple not zero.""" return max((value - (value % multiple)), multiple)
def freeze(x): """Attempts to make x immutable by converting it into a *frozen datum*. Input can be str, bool, set, frozenset, list, tuple, None, and any nesting of those. Output will consist of str, bool, frozenset, tuple, and None only. """ if isinstance(x, str): # Assume that strings are immutable. return x elif isinstance(x, bool): # Bools too return x elif isinstance(x, (set, frozenset)): return frozenset(freeze(v) for v in x) elif isinstance(x, (list, tuple)): return tuple(freeze(v) for v in x) elif x is None: return None else: raise TypeError("Value cannot be frozen for use in an environment: %r" % x)
def v3ToStr(v3): """ convert a vbase3 vector to a string like v0,v1,v2 :param v3: :return: """ return ','.join(str(e) for e in v3)
def strip_suffix(name, split='_'): """ Returns the portion of name minus the last element separated by the splitter character :param name: str, name to strip the suffix from :param split: str, split character :return: str """ if not name.count(split): return name return name.replace(split + name.split(split)[-1], '')
def hex_to_rgb(value): """In: hex(#ffffff). Out: tuple(255, 255, 255)""" value = value.lstrip('#') rgb = tuple(int(value[i:i + 2], 16) for i in (0, 2, 4)) return rgb
def surfaceZetaFormatToTextureFormat(fmt, swizzled, is_float): """Convert nv2a zeta format to the equivalent Texture format.""" if fmt == 0x1: # Z16 if is_float: return 0x2D if swizzled else 0x31 else: return 0x2C if swizzled else 0x30 elif fmt == 0x2: # Z24S8 if is_float: return 0x2B if swizzled else 0x2F else: return 0x2A if swizzled else 0x2E else: raise Exception("Unknown zeta fmt %d (0x%X) %s %s" % (fmt, fmt, "float" if is_float else "fixed", "swizzled" if swizzled else "unswizzled"))
def count_levels(orgao, splitter): """ Return the number of levels in the `orgao` (split by `splitter`). """ return len(orgao.split(splitter))
def remove_opened_position(pre_ticker_list, opened_position_ticker_list): """ Return a list of tickers that do not have any position opened. """ ticker_list = pre_ticker_list for pre_ticker in pre_ticker_list: for opened_position_ticker in opened_position_ticker_list: if pre_ticker == opened_position_ticker: ticker_list.remove(opened_position_ticker) return ticker_list
def imt_check(grade_list_idx, grade_list_i, grade_list_j): """ A check used in imt table generation """ return ((grade_list_idx == abs(grade_list_i - grade_list_j)) and (grade_list_i != 0) and (grade_list_j != 0))
def assignFirstFive(l=['A', 'B', 'C', 'D', 'E']): """ task 0.5.19 use the list 'l' in and express that uses range and zip, but not using a comprehension """ return list(zip(range(len(l)), l))
def is_challenge_config_yaml_html_field_valid( yaml_file_data, key, base_location ): """ Arguments: yaml_file_data {dict} -- challenge config yaml dict key {string} -- key of the validation field base_location {string} -- path of extracted config zip Returns: is_valid {boolean} -- flag for field validation is success message {string} -- error message if any """ value = yaml_file_data.get(key) message = "" is_valid = False if value: is_valid = True else: message = "ERROR: There is no key for {} in YAML file".format(key) return is_valid, message
def fact(n): """ calculate n! iteratively """ result = 1 if n > 1: for f in range(2, n + 1): result *= f return result
def bisection( f, a, b, TOL=1e-5, NMAX=500 ): """ INPUT : - Function - Lower Bound - Upper Bound - OPTIONAL: Tolerance - OPTIONAL: Maximum Number of Iterations RETURN: - Solution - Residual - # of Iterations """ n=1 # Counter res = [] # Residual iter_conv = [] # Iterative convergance while( n <= NMAX ): # Determine midpoint p = (a+b)/2.0 res.append( f(p) ) # Evaluate residual # Check for convergence if (abs( res[-1] ) < TOL) or ( (b-a)/2.0 < TOL ): # Return solution return (p, res, n) else: n = n + 1 # Increment counter if (f(p)*f(a) > 0): # Check for signs a = p else: b = p return False # No solution found within iteration limit
def PathCost(ni, nf): """The incremental cost to go from node ni to an adjacent node nf""" #ni, nf = node objects return 1.0
def get_coloured_text_string(text, colour): """ Wrap a string with some unicode to colour it in the terminal. :param text: The text block that we want to explain. :type text: string, required :param colour: The name of the colour you want encoded :type colour: string, required :return: The colour encoded text :rtype: string """ if colour=="red": return ("\033[31m" + text + "\033[0m") if colour=="green": return ("\033[32m" + text + "\033[0m") if colour=="yellow": return ("\033[33m" + text + "\033[0m") if colour=="blue": return ("\033[34m" + text + "\033[0m") if colour=="purple": return ("\033[35m" + text + "\033[0m") if colour=="cyan": return ("\033[36m" + text + "\033[0m") if colour=="white": return ("\033[37m" + text + "\033[0m") return text
def _move_right(p, index): """exchange blank position with the tile on the right""" _p = list(p) _p[index], _p[index + 1] = _p[index + 1], _p[index] return tuple(_p)
def convertToInt(s): """ Convert to string to int. Protect against bad input. @param s: Input string @return: integer value. If bad return 0. """ try: value = int(s) except ValueError: value = 0 return value
def _is_zero_length(_element): """This function checks to see if an element has a zero length. :param _element: The element of which the length will be checked :returns: Boolean value stating whether or not the length of the element is zero """ return True if len(_element) == 0 else False
def transform_ranges(ranges): """ Transform sequence of ranges into a list of sorted integers. Parameteres ----------- ranges : str ranges separated by colon (,) e.g.: 100,1-5,2,300,200-202 Returns list of integers In the example above we would get [1, 2, 3, 4, 5, 100, 200, 201, 202, 300] ------- """ if not ranges: return [] ids = set() ranges = ranges.split(',') for range_ in ranges: el = range_.split('-') if len(el) == 1: ids.add(int(el[0])) else: # take care of negative left limit a, b = '-'.join(el[:-1]), el[-1] [ids.add(i) for i in range(int(a), int(b) + 1)] ids = sorted(list(ids)) return ids
def is_restart_command(command_text: str) -> bool: """ >>> is_restart_command("restart") True >>> is_restart_command("restart game") True >>> is_restart_command("take lamp") False """ return command_text.startswith("restart")
def strip(s, chars=None): """strip(s [,chars]) -> string Return a copy of the string s with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping. """ return s.strip(chars)
def detectsubstitutions(args): """Detect substitutions specified on the commandline. This method will be called from the hooks within the applications.py module. This is where the applications specific code should be placed so that Longbow can handle substitutions. """ # Initialise variables. removelist = [] sub = {} for index, item in enumerate(args): if item == "-var" or item == "-v": sub[args[index + 1]] = args[index + 2] removelist.append(item) removelist.append(args[index + 1]) removelist.append(args[index + 2]) for item in removelist: args.remove(item) return sub
def search_vowels(word): """Print symbols""" vowels = set('aeoui') unique_words = set(vowels).intersection(set(word)) print(unique_words) return sorted(vowels)
def dict_to_feature(feature_dict, keys, max_value=None): """Extract values from dict""" feature = [] for key, val in feature_dict.items(): # First level if key not in keys: continue if val is None or val == "auto" or key == "autotuning" or val == "": continue if isinstance(val, dict): feature.append(dict_to_feature(val, max_value)) else: feature.append(float(val)) # normalization, should not matter in tree models if max_value is not None: norm_feature = [] for f, mv in zip(feature, max_value): norm_feature.append(f / mv) feature = norm_feature return feature
def confirm_env_action(msg, skip=False): """Confirm an action on an environment. :param env: Environment object :type env: EnvironmentEntity :param msg: Message to display when asking for input. :type msg: str :param skip: Whether or not to skip bypass :type skip: bool :returns: Whether or not remove is confirmed. :rtype: bool """ confirmed = skip if not confirmed: msg = '{} (y/n) --> '.format(msg) resp = '' while (resp != 'y' and resp != 'n'): resp = input(msg).lower() confirmed = (resp == 'y') return confirmed
def _validate_raid_5(logical_disk, unassigned_pd, no_of_pds): """Checks if RAID 5 logical drive creation with requested size is possible This method finds a list of suitable unassigned physical drives which can be used to create a logical volume of requested size :param logical_disk: The logical disk dictionary from raid config :param unassigned_pd: The sorted list of unassigned physical drives :param no_of_pds: The 'number_of_physical_disks' if user has specified in target raid configuration, else default value is False :returns: A list of suitable physical drives for logical volume creation """ # RAID 5 can be with 3 or 4 disks. Out of a list of pds [a,b,c,d] # (a,b,c), or (b,c,d) or (a,b,c,d) are the possible combinations # # case 1: a:100, b:100, c:400 # result: raid 5: 200 gb # # case 2: a:100, b:200, c:200 gb # result: raid 5: 200 gb # # case 3: a:100, b:100, c:100, d:400 # result: raid 5: 300 gb if no_of_pds: tries = len(unassigned_pd) - no_of_pds for i in range(tries + 1): max_size = float(unassigned_pd[i][1]) * (no_of_pds - 1) if max_size >= logical_disk['size_gb']: return unassigned_pd[i:i + no_of_pds] # Check if user did not specify number of disks else: disk_count = 3 while disk_count <= len(unassigned_pd): for i in range(len(unassigned_pd) - disk_count + 1): max_size = float(unassigned_pd[i][1]) * (disk_count - 1) if max_size >= logical_disk['size_gb']: return unassigned_pd[i:i + disk_count] disk_count += 1 return []
def extract_turls(indata): """ Extract TURLs from indata for direct i/o files. :param indata: list of FileSpec. :return: comma-separated list of turls (string). """ turls = "" for f in indata: if f.status == 'remote_io': turls += f.turl if not turls else ",%s" % f.turl return turls
def pmul(p, n): """Return the multiple of the given probabilty.""" return 1.0 - (1.0 - p) ** n
def mapFromTo(x, a, b, c, d): """map() function of javascript""" y = (float(x) - float(a)) / (float(b) - float(a)) * \ (float(d) - float(c)) + float(c) return y
def read(var): """Read the contents from a file""" with open(var) as fvar: return fvar.read()
def isclass(object): """Return true if the object is a class.""" return hasattr(object, '__metaclass__') and not hasattr(object, '__class__')
def stripToNone(s): """ strips and return None if string is empty """ if s is None: return s = s.strip() if s == '': return None return s
def make_dic(doc_id=None, root=None, date=None, author=None, text=None, favorite=None): """make dictionary form argument and return dictionary Keyword Arguments: doc_id {int} -- documnet ID (default: {None}) root {string} -- xml file name (default: {None}) date {string} -- date of document (default: {None}) author {string} -- author of document (default: {None}) text {string} -- text of document (default: {None}) favorite {string} -- favorite of document (default: {None}) Returns: dictionary -- document data in dictionary """ return { 'docID': doc_id, 'root': root, 'date': date, 'author': author, 'text': text, 'favorite': favorite }
def gen_imagesrc(d, l): """ Produces the HTML code for that set of images. d is a dict containing the name, date, location, directory, and list of pictures. l is 1 if this is a sub page, and 0 if this is home. """ name = d['name'] date = d['date'] location = d['location'] directory = d['directory'] files = d['pics'] if (l == 1): p = '<a class="nav" href="index.html">Go Home</a>' else: p = '<a class="nav" href="'+directory+'.html">Go to page</a>' srcd = '<div class="image_set"><div class="left"><h2 class="title">'+name+'</h2><p class="date">'+date+'</p><p class="location">'+location+'</p>'+p+'</div><div class="images">' for i in files: srcd = srcd + '<a href="'+directory+'/original/'+i+'"><img src="'+directory+'/final/'+i+'" class="img"/></a>' scrd = srcd + '</div></div>' return scrd
def MinimalRnaalifoldParser(lines): """MinimalRnaalifoldParser. returns lists of sequence, structure_string, energy """ res = [] if lines: for i in range(0,len(lines),2): seq = lines[i].strip() struct,energy = lines[i+1].split(" (") energy = float(energy.split('=')[0].strip(' \n)')) res.append([seq,struct,energy]) return res
def greater_difference(min_num, val, max_num): """returns the greater difference between a value and two numbers :param min_num (int) : a number to check val (int) : the number to compare to other params max_num (int) : a number to check :return absolute value of greatest difference between two compared numbers""" if abs(max_num - val) > abs(min_num - val): return abs(max_num - val) else: return abs(min_num - val)
def format_message(message, prefix=None, why=None): """Format a message, along with the prefix and exception if provided :param message: the message to print :type message: str :param prefix: optional prefix to the message :type prefix: str :param why: optional exception to display. Defaults to None :type why: str :rtype: str """ buf = [] if prefix is not None: buf.append(prefix) buf.append(message) if why is not None: buf.append(str(why)) return ': '.join(buf)
def combine(func, *arrays): """ Combines n arrays by adding the elements at the same index together in the new array Arguments: func: function that takes in the n elements at each index and combines them *arrays: N arrays to combine Returns: A new array where all elements are the combination of the elements at the same index in the source arrays using func """ return [func(elements) for elements in zip(*arrays)]
def create_index_dict(board): """ Creates a dictionary from values to indices """ index_dict = {} for i, row in enumerate(board): for j, elem in enumerate(row): if elem not in index_dict: index_dict[elem] = (i, j) return index_dict
def sanitize_mapping_file(data, headers): """Clean the strings in the mapping file for use with javascript Inputs: data: list of lists with the mapping file data headers: list of strings with the mapping file headers Outputs: s_data: sanitized version of the input mapping file data s_headers: sanitized version of the input mapping file headers This function will remove all the ocurrences of characters like ' or ". """ all_lines = [headers] + data out_lines = [] # replace single and double quotes with escaped versions of them for line in all_lines: out_lines.append([element.replace("'","").replace('"','') for element in line]) return out_lines[1::], out_lines[0]
def next_position(board, column): """Return the next availabe position in a column # Arguments board: matrix, required column: int (0 to 6) - required - Index of the column # Return Index (row) of availabe position # Exception IndexError: `column` argument out of range. """ if column < 0 or column > 6: raise IndexError('Column out of range.') for i, value in enumerate(board[column]): if value == 0: return i
def exclude_keys(d, keys): """Return a new dictionary excluding all `keys`.""" return {k: v for k, v in d.items() if k not in keys}
def RoundRobin(stats): """ receives a lists of arm pulling results and return a number of arm to pull just for testing""" k = len(stats) n = sum(s[0] for s in stats) # total number of pulls return n % k
def remove_short(tokens, minsize=3): """Remove tokens smaller than `minsize` chars, which is 3 by default.""" return [token for token in tokens if len(token) >= minsize]
def _compute_n_zeros_ones(c): """Step 3: Compute number of zeros & ones.""" # Compute ascii's binary string, e.g. 0b100. bin_c = bin(ord(c)) # Count how many ones in binary string. bin_str = bin_c[2:] return bin_str.count('0'), bin_str.count('1')
def check_seg(segl): """check the segmentation format -> take the largest segmentation""" checked = segl.copy() # take the longest if we have multiple polygons ..? if len(segl) > 1: maxlen = 0 for loc_seg in segl: if len(loc_seg) > maxlen: maxlen = len(loc_seg) checked = [loc_seg] return checked
def _convert_line(line): """Ignore comments(#) and strip values from columns""" if not line.strip() or line.startswith('#'): return None, None from_node, to_node = line.split() return from_node.strip(), to_node.strip()
def read_bedfile(handle): """ Read the bed file We are only interested in the transcript_id and exon_nr """ include = set() for line in handle: name = line.strip('\n').split('\t')[3] transcript_id, exon_nr = name.split(':') include.add((transcript_id, exon_nr)) return include
def get_context_order(k): """ :param k: length of kmer :return: list of characters of each nt position """ context_order = [str(x + 1) for x in range(k)] return context_order
def entry_is_a_postal_address(result): """ The LPI dataset includes entries for address assets that cannot receive post such as car parks and streets. These should not appear in the address picker. Such entries have a POSTAL_ADDRESS_CODE of 'N'. Return boolean true if an entry is a "real" postable address. """ return result['LPI']['POSTAL_ADDRESS_CODE'] != 'N'
def analyze_dataflow(group, dataflow, dependencies): """ return the updated dependency set """ local = set([]) outputs = set([]) temps = set([]) for reads, writes in reversed(dataflow): local = local.union(reads) for read in writes: if read in dependencies: outputs.add(read) else: temps.add(read) # compute the inputs inputs = local.difference(outputs).difference(temps) group["OUTPUTS"] = list(outputs) group["INPUTS"] = list(inputs) group["TEMPS"] = list(temps) return dependencies.union(inputs)
def from_bytes(bs): """Unpacks an unsigned int from a big-endian bytestring.""" return int.from_bytes(bs, "big")
def _format_decimal_coords(ra, dec): """ Print *decimal degree* RA/Dec values in an IPAC-parseable form """ return '{0} {1:+}'.format(ra, dec)
def pair_in_collection(pair, pair_collection, have_direction=True): """ Check if a pair is in a collection or not. :param pair: A tuple :param pair_set: A collection of tuple :param have_direction if true (a,b) is different from (b,a) otherwise consider them as same one :return: boolean """ if have_direction: return pair in pair_collection else: reversed_pair = (pair[0], pair[1]) return pair in pair_collection or reversed_pair in pair_collection
def replace_variable_chars(data): """Replace all characters found in the R variable in obfuscated script""" data = data.replace(b'%r:~0,1%', b'J') data = data.replace(b'%r:~5,1%', b'G') data = data.replace(b'%r:~1,1%', b'g') data = data.replace(b'%r:~2,1%', b'i') data = data.replace(b'%r:~16,1%', b'I') data = data.replace(b'%r:~4,1%', b't') data = data.replace(b'%r:~6,1%', b'X') data = data.replace(b'%r:~7,1%', b'z') data = data.replace(b'%r:~14,1%', b'S') data = data.replace(b'%r:~8,1%', b's') data = data.replace(b'%r:~9,1%', b'w') data = data.replace(b'%r:~10,1%', b'b') data = data.replace(b'%r:~11,1%', b'h') data = data.replace(b'%r:~15,1%', b'H') data = data.replace(b'%r:~12,1%', b'm') data = data.replace(b'%r:~13,1%', b'u') data = data.replace(b'%r:~17,1%', b'O') return data
def _hash_clause(clause): """ _hash_clause(clause : list) return (key : string) Creates a unique hash string of the given clause. It is used to identify redundant clauses. Returns the hash value of the given clause. """ key = "" sorted_clause = clause[:] sorted_clause.sort() for literal in sorted_clause: key += ".{0:d}".format(literal) return key
def editor_valid(enough_edits, account_old_enough, not_blocked, ignore_wp_blocks): """ Check for the eligibility criteria laid out in the terms of service. Note that we won't prohibit signups or applications on this basis. Coordinators have discretion to approve people who are near the cutoff. """ if enough_edits and account_old_enough and (not_blocked or ignore_wp_blocks): return True else: return False
def get_unused_options(cfg_dict, options): """ Returns the unused keys in a configuration dictionary. An unused key is a key that is not seen in *options*. Parameters ---------- cfg_dict : dict options : :py:class:`~enrich2.plugins.options.Options` Returns ------- `set` Set of unused keys. """ unused = set() option_keys = set(options.keys()) for key in cfg_dict.keys(): if key not in option_keys: unused.add(key) return unused
def get_num_classes(labels): """Gets the total number of classes. # Arguments labels: list, label values. There should be at lease one sample for values in the range (0, num_classes -1) # Returns int, total number of classes. # Raises ValueError: if any label value in the range(0, num_classes - 1) is missing or if number of classes is <= 1. """ num_classes = max(labels) + 1 missing_classes = [i for i in range(num_classes) if i not in labels] if len(missing_classes): raise ValueError('Missing samples with label value(s) ' '{missing_classes}. Please make sure you have ' 'at least one sample for every label value ' 'in the range(0, {max_class})'.format( missing_classes=missing_classes, max_class=num_classes - 1)) if num_classes <= 1: raise ValueError('Invalid number of labels: {num_classes}.' 'Please make sure there are at least two classes ' 'of samples'.format(num_classes=num_classes)) return num_classes
def is_edge(s, t, k): """There is an edge from s to t if there is a length k suffix of s that matches a length k prefix as t (and s != t). """ if s == t: return False else: return (s[1][-k:] == t[1][:k])
def emphasize(content=None): """Emphasize tags.""" return content if content else ''
def get_task_error(dd): """Get target error not knowing the gender, modeled through a Gaussian Mixure model""" mm = 0.046 return dd * mm
def top_files(query, files, idfs, n): """ Given a `query` (a set of words), `files` (a dictionary mapping names of files to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the filenames of the the `n` top files that match the query, ranked according to tf-idf. """ tf_idf=dict() for file in files: tf_idf_values =0 for word in query: tf = files[file].count(word) if word in idfs: tf_idf_values += (tf * idfs[word]) else: print("##Please Note: Some words in the query were not present in the idfs.") tf_idf[file]=tf_idf_values return sorted(tf_idf, key=lambda x: tf_idf[x], reverse=True)[:n]
def percent_formatter(x, pos): """Return tick label for growth percent graph.""" return str(int(x)) + '%'
def remove_doublequotes(x:list): """ removes double quotes from list """ x_cleaned=[el.replace("'",'') for el in x] return x_cleaned
def dict_reduce(method, *dicts): """make new dict by performing reduce per key,value on list of dicts""" # no action if one dict; error if zero. if len(dicts) < 2: return dicts[0] # assume all dicts have identical keys new_dict = {} for key,value in dicts[0].items(): new_value = value for dict_ in dicts[1:]: new_value = method(value, dict_[key]) new_dict[key] = new_value return new_dict
def _extract_hashtag(entities): """Extract hashtags.""" htags = [] for htag in entities['entities'].get('hashtags'): htags.append(htag.get('text')) if htags: return htags return None
def StringToFloat4(value): """Convert a float value into a string with four decimal places.""" return '%.4f' % value
def get_threshold_bounds(min_threshold, max_threshold): """ Gets bounds on the threshold for the minimization process. Calculates the bounds in a way that would leave a gap between the possible optimized threshold and the tensor max values. We use min_threshold as lower-bound to prevent the selected threshold from being zero or negative. Args: min_threshold: minimal threshold to use if threshold is too small (not used for this method). max_threshold: maximal threshold to be used in quantization. Returns: An array with a pair of (lbound, ubound) on the quantization threshold limit values. """ max_threshold = max(min_threshold, max_threshold) return [(min_threshold, 2 * max_threshold)]
def _get_workspace_size_define_macro(pool_name: str, model_name="default") -> str: """This function converts pool names to compiler generated workspace pool size macros""" prefix = "TVMGEN_" + model_name.upper() + "_" postfix = "_WORKSPACE_POOL_SIZE" return prefix + pool_name.upper() + postfix
def errormsg(e): """Generates an error message as a string""" return "ERROR: " + str(e)
def key_from_image_name(image_name): """ >>> key_from_image_name('shipwright/blah:1234') '1234' """ return image_name.split(':', 1)[1]
def find_command_end(command, start=0): """find the next '\n' that is not preceeded by '\\', or return the last valid position (length-1)""" length = len(command) end = start-1 while 1: start = end + 1 end = command.find('\n',start) if end < 0: return length-1 # not in command elif end > start and command[end-1] == '\\': if length > end+1 and command[start] == '#' \ and command[end+1] != '#': return end # since comments cannot wrap else: continue return end # found
def check_number(number): """This function checks the input value is correct or not and return the floating value if correct input""" try: float_val = float(number) except ValueError: return None else: return float_val
def ackermann_fast(m: int, n: int) -> int: """Ackermann number. """ while m >= 4: if n == 0: n = 1 else: n = ackermann_fast(m, n - 1) m -= 1 if m == 3: return (1 << n + 3) - 3 elif m == 2: return (n << 1) + 3 elif m == 1: return n + 2 else: return n + 1
def resort_amplitudes_by_dataset_hash( n_grp, n_dst, dataset_hash, real_group_amps, ): """Sorted the real amplitudes into the order that they will be returned by the optimiser""" sorted_group_amps = [] i_cnt = 0 for i_grp in range(n_grp): for _ in range(n_dst): i_dst = dataset_hash[i_cnt] i_cnt += 1 sorted_group_amps.append(real_group_amps[i_grp*n_dst+i_dst]) return sorted_group_amps
def lerp(first, second, ratio): """Interpolate between two tensors.""" return first * (1 - ratio) + second * ratio
def myfunc(x): """ Generic function. Parameters ---------- x: float or array_like The value or array at which to calculate the function Examples -------- Execution on a float >>> from newton_raphson import * >>> myfunc(3.0) 11.0 Execution on a SciPy array_like >>> a = np.linspace(0,10,10) >>> myfunc(a) array([ -4. , -0.54320988, 5.38271605, 13.77777778, 24.64197531, 37.97530864, 53.77777778, 72.04938272, 92.79012346, 116. ]) """ return x**2+2*x-4
def is_iterable(l): """ >>> is_iterable(7) False >>> is_iterable([7]) True >>> is_iterable(tuple([7])) True >>> is_iterable(set([7])) True >>> is_iterable('abc') False >>> d = {7:None} >>> is_iterable(d) True """ return hasattr(l,"__iter__")
def get_keys(keys_in_values_file, config_file_keys): """ Get keys from values file present in config file """ values_file_keys = [] for key in keys_in_values_file: if key in config_file_keys: values_file_keys.append(key) return values_file_keys
def make_divisible(v, divisor, min_value=None): """ This function taken from tf code repository. It ensures that the return value is divisible by 8. """ if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v
def make_course_abbreviation_help(common_abbrevs: dict) -> str: """This is a helper function to make a help string of available course names and their abbreviations """ result_per_line, sorted_list = [], [] abbrevs = {v: k for k, v in common_abbrevs.items()} sorted_list = sorted([item for item in abbrevs.items()], key=lambda tpl: tpl[0]) for course_name, abbreviations in sorted_list: result_per_line.append(course_name.upper()) for a in abbreviations: result_per_line.append(" " + a) result_per_line.append('') return '\n'.join(result_per_line).strip()
def isnum(number): """Check if number.""" try: int(number) return True except ValueError: return False