content
stringlengths
42
6.51k
def object_info_as_dict(object_info): """Convert a KBase object_info list into a dictionary.""" [ _id, _name, _type, _save, _version, _owner, _ws, _ws_name, _md5, _size, _meta, ] = object_info return dict( ob...
def str_space_to_list(string): """ Converts a spaced string in a list. The string consists of the succession of the elements of the list separated by spaces. :param string: the string to convert. :return: the corresponding list. """ string_list = string.split(" ") list = [] if string_l...
def maximum_value(tab): """ brief: return maximum value of the list args: tab: a list of numeric value expects at leas one positive value return: the max value of the list the index of the max value raises: ValueError if expected a list as input ValueError if no positive value found """ if not(isinstan...
def increment_array_and_count(tag_name, count, word): """ Increment a count within a dictionary or add a new count if necessary """ tag = tag_name try: count[word] += 1 except: count[word] = 1 return tag, count
def LoadCSV(filename): """Load CSV file. Loads a CSV (comma-separated value) file from disk and returns it as a list of rows where each row is a list of values (which are always strings). """ try: with open(filename) as f: rows = [] while 1: line = f....
def lowercase(text): """Return the given text in lowercase.""" lowercase_text = text.lower() return lowercase_text
def groupms_byiconf(microstates, iconfs): """ This function takes in a list of microstates and a list of conformer indicies, divide microstates into two groups: the first one is those contain one of the given conformers, the second one is those contain none of the listed conformers. """ ingroup = []...
def rectangle_clip(recta, rectb): """ Return the clipped rectangle of ``recta`` and ``rectb``. If they do not intersect, ``None`` is returned. >>> rectangle_clip((0, 0, 20, 20), (10, 10, 20, 20)) (10, 10, 10, 10) """ ax, ay, aw, ah = recta bx, by, bw, bh = rectb x = max(ax, bx) ...
def determineDocument(pdf): """ Scans the pdf document for certain text lines and determines the type of investment vehicle traded""" if 'turbop' in pdf or 'turboc' in pdf: return 'certificate' elif 'minil' in pdf: return 'certificate' elif 'call' in pdf or 'put' in pdf: return '...
def fib_table_for(n): """ Returns: fibonacci list [a0, a1, ..., an] Parameter n: the position in the fibonacci sequence Precondition: n >= 0 is an int """ if n == 0: return [1] # if for n==1 is unnecessary fib = [1,1] for k in range(2,n): fib.append(fib[-1] ...
def remove_args(route_title): """ Remove args from title string for display in console | str --> str """ print('Running remove_args') arg_index = route_title.find('(') if arg_index == -1: return route_title return route_title[0:arg_index]
def nested_get(dictionary: dict, keys: list): """Set value to dict for list of nested keys >>> nested_get({'key': {'nested_key': 123}}, keys=['key', 'nested_key']) 123 """ nested_dict = dictionary for key in keys[:-1]: nested_dict = nested_dict[key] return nested_dict.get(keys[-1])
def humanize(memory, suffix="B", kilo=1024): """ Scale memory to its proper format e.g: 1253656 => '1.20 MiB' 1253656678 => '1.17 GiB' """ if kilo == 1000: units = ["", "k", "M", "G", "T", "P"] elif kilo == 1024: units = ["", "Ki", "Mi", "Gi", "Ti", "Pi"] else...
def is_minimum_metric_set(app, expected, collected): """ Determine if the required metrics are found. """ expected = set(expected) collected = set(collected) missing_metrics = expected.difference(collected) if missing_metrics: msg = "Expected metrics not found: {}" app["log...
def _mangle_attr(name): """ Mangle attributes. The resulting name does not startswith an underscore '_'. """ return 'm_' + name
def matrixmult (A, B): """Matrix multiplication function This function returns the product of a matrix multiplication given two matrices. Let the dimension of the matrix A be: m by n, let the dimension of the matrix B be: p by q, multiplication will only possible if n = p, thus creating a matr...
def return_timings(data, trial_type): """ Finds all trials matching the string 'trial_type', retrieves onset in seconds, and returns them as a list. """ data = filter(lambda d: trial_type in d[0], data) onsets = [] for trial in data: onsets.append(trial[5]) return onsets
def clear_bit(int_type, offset): """Return an integer with the bit at 'offset' cleared.""" mask = ~(1 << offset) return int_type & mask
def _next_pow_two(n): """Returns the next power of two greater than or equal to `n`""" i = 1 while i < n: i = i << 1 return i
def _fill_mi_header(row, control_row): """ Forward fill blank entries in row but only inside the same parent index. Used for creating headers in Multiindex. Parameters ---------- row : list List of items in a single row. control_row : list of bool Helps to determine if part...
def reverse_complement(number, length): """ Calculate the reverse complement of a DNA sequence in a binary representation. :arg int number: Binary representation of a DNA sequence. :return: Binary representation of the reverse complement of the sequence corresponding to `number`. :rtype:...
def ucb_air_criterion( num_arms, round_num, beta, max_attainable=False ): """ Computes whether to add a new arm from the current number of arms, the round number, and problem properties using the Arm Introducing Rule (AIR). For more details, refer to Wang et al. 2008, "Algorithms for infinitely many ...
def vectorize(values): """ Takes a value or list of values and returns a single result, joined by "," if necessary. """ if isinstance(values, list): return ','.join(str(v) for v in values) return values
def calculate_handlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ return len(hand) #returns the length of Hand
def build_ui_field(item): """ The function is used to build the description of mongoengine fields depending on the type in the YAML file description. An example of item is given below: {'title': {'required': True, 'type': 'text', 'label': 'Title'}} :param item: :return: string in the follow...
def detect_process_by_name(proc_name, exec_path, port): """Checks if process of given name runs on given ip_address and port. Args: proc_name -- process name, exec_path -- path to executable, port -- process port. """ pids = [] from os import popen for line in popen("ps ax | grep " + pro...
def remove_duplicates(l:list): """ This method can remove duplicates for lists of objects that implement _eq_ but do not implement _hash_. For such cases l = list(set(l)) wont work. """ return [obj for index, obj in enumerate(l) if obj not in l[index + 1:]]
def count_pos(L): """ (list) -> bool Counts the number of negative values in a list and returns True if all elements of L are positive. Restriction: L must be a list with numbers in it """ for i in L: if i <= 0: return False else: continue return T...
def _standardize_keys(zipcounty): """Standardize and keep relevent fields (zip and county).""" standard_area = {} for k, v in zipcounty.items(): if k.replace(' ', '').lower() in ['zip', 'zipcode', 'zip code']: standard_area['zipCode'] = v if k.replace(' ', '').lower() in ['county...
def time(seconds): """ Format time as a string. Parameters: seconds (float): time in seconds """ sec_per_min = 60 sec_per_hour = 60 * 60 sec_per_day = 24 * 60 * 60 if seconds > sec_per_day: return "%.2f days" % (seconds / sec_per_day) elif seconds > sec_per_hour: ...
def convert_to_map(list_str): """ Convert a list of strings (['key', 'value', 'key', 'value', ...]) into {key: value} Parameters ---------- list_str : list, type of element is String list of strings in the format of ['key', 'value', 'key', 'value', ...] Returns ------- key_valu...
def num_bytes_to_str(num_bytes): """Return a number of bytes as a human-readable string.""" for unit in ("B", "KB", "MB", "GB"): if num_bytes < 1024: return "{:.1f} {}".format(num_bytes, unit) num_bytes /= 1024 return "{:.1f} TB".format(num_bytes)
def get_commands_to_config_vrf(delta, vrf): """Gets commands to configure a VRF Args: delta (set): params to be config'd- created in nxos_vrf vrf (str): vrf name Returns: list: ordered list to config a vrf Note: Specific for Ansible module(s). Not to be called otherwi...
def curie_to_str(prefix: str, identifier: str) -> str: """Combine a prefix and identifier into a CURIE string.""" return f"{prefix}:{identifier}"
def median(nums): """ calculates the median of a list of numbers >>> median([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]) 2.5 >>> median([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4.1, 1000000]) 3 >>> median([]) Traceback (most recent call last): ... ValueError: Need a non-empty iterable """ ls = sorted(nums) ...
def integer(number, *args, **kwargs): """Improved int function that can return the correct value of a binary number in twos compliment """ if len(kwargs) > 0 and kwargs['signed'] and number[0] == '1': return -(-(int(number, *args))+(2**len(number))) return int(number, *args)
def normalize(data_list): """ :param data_list: [(x0, y0), (x1, y1), ..., (xn-1, yn-1)] """ x_list = [] y_list = [] for pair in data_list: x_list.append(pair[0]) y_list.append(pair[1]) x_min = min(x_list) x_max = max(x_list) x_range = x_max - x_mi...
def count_mutations(tree, ntaxa): """ Takes pairs of taxa/nodes and alleles, and returns the number of mutations that happened along the tree. Pairs must be ordered in same way as seq-gen output. """ # node/taxon IDs labels = [int(tree[i].split()[0]) for i in range(len(tree))] # cor...
def find_smp_rt(rt1, rt2): """ determine the sample rates - highest and lowest :param rt1: list of the first file :param rt2: list of the second file :return: a tuple with the needed values of the sample rates """ return (min(rt1, rt2), max(rt1, rt2))
def _patsplit(pattern, default): """Split a string into the optional pattern kind prefix and the actual pattern.""" if ':' in pattern: kind, pat = pattern.split(':', 1) if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre', 'listfile', 'listfile0', 'set'): ...
def remove_comments(line): """Remove comments (#) from FIELD, CONFIG, CONTROL lines Also compress any mulitple white spaces. """ line = line.split("#")[0] line = " ".join(line.split()) return line.strip()
def stagger_tuple(elements_list, initial=None): """ Converts a list of objects into a staggered tuple Example: [1, 2, 3, 4, 5] [(1, 2), (2, 3), (3, 4), (4, 5)] """ res = [] previous_element = initial for element in elements_list: if previous_element is not None: ...
def best_match(long_seq, short_seq): """ First, know the len of long_seq and short_seq, and know how many times the long_seq string can loop in order to find out the best match string. Second, for each loop we count how many characters that look the same in each sub string(sub the long_seq) and assi...
def process_singleton_ids(ids, entity): """Returns a single id if len(ids)==1. If len(ids)>1, returns ids (assumed to be a list), or raises a ValueError if the shared functions expect a single id rather than a list for the specified entity. """ if len(ids)==1: ids = ids[0] elif entity=='gbd_...
def InvertDictionary(origin_dict): """Invert the key value mapping in the origin_dict. Given an origin_dict {'key1': {'val1', 'val2'}, 'key2': {'val1', 'val3'}, 'key3': {'val3'}}, the returned inverted dict will be {'val1': {'key1', 'key2'}, 'val2': {'key1'}, 'val3': {'key2', 'key3'}} Args: origin_dict:...
def kebab_case_to_camel_case(s): """ convert a kebab case string to a camel case string A utility function to help convert a kebab case string into a camel case string. This is to help convert directive options typically defined in kebab case to Confluence macro parameters values which are typically...
def walkable(grid_array: list) -> list: """Get a list of all the coordinates that are walkable Args: grid_array (list): map of the terrain Returns: list: all coordinates that are walkable """ walkable = [] for i, row in enumerate(grid_array): for j, cell in enumerate(ro...
def cart_comp(x,y): """ A basic comparison function to insure that layers are selected in terms of larger positive to larger negative """ return int(y-x)
def is_commconnect_form(form): """ Checks if something is a commconnect form, by manually inspecting the deviceID property """ return form.get('form', {}).get('meta', {}).get('deviceID', None) == 'commconnect'
def get_ls(num): """ Get a list of available line styles """ ls = [ ':', '--', '-.', '-', ':', '--', '-.', '-', ':', ':', '--', '-.', '-', ':', '--', '-.', '-', ':' ] return ls[:num]
def __shapes_are_equal(shape1, shape2, named_dim_length): """ compare the shape of two array. zeros in the second arguments are ignored Parameters ---------- shape1 : tuple shape2 : tuple named_dim_length : dict Returns ------- bool True, if both shapes are identica...
def convert_REC_ID_to_DD_ID(REC_ID): """ Convert IDs as they are in RECCON into original Daily Dialog IDs """ split, id = REC_ID.split('_') id = str(int(id) + 1) if split == 'tr': return 'dialogue-'+id elif split == 'va': return 'dialogue-'+str(int(id)+11118) assert(split...
def assemble_config(aggregation_method, task2models): """Assemble the entire config for dumping to JSON. Args: aggregation_method (str): the aggregation method to use during ensemble prediction task2models (dict): mapping from task to the associated ...
def non_modal_batch_melt(Co, Do, F, P): """ non_modal_batch calculates the concentration of a given trace element in a melt produced from non modal batch melting of a source rock as described by Shaw (1970) equation 15. Inputs: Co = Concentration of trace element in the original solid ...
def dataToPixels(z): """ Given a data-point value I{z} along the x (or y) axis, returns the number of pixels from the left (or bottom) of the subplot. """ return 250*(z+1.0)
def get_weight_by_name(module_weights, name): """ Retrieve parameter weight values from result of Module.get_weights() :param module_weights: all weights of a module, returned by Module.get_weights() :param name: :return: """ for w, w_name in module_weights: if name == w_name: ...
def computeBCC(data_str): """ data str= ASCII string XOR each chr in string returns a two char ASCII string """ bcc = 0 for d in data_str: # print d # d = ord(d) # bcc = bcc ^ ord(d) bcc = bcc ^ ord(d) # print bcc bcc = bcc & 1...
def eval_phoneme_duration(phoneme_list, phoneme_dur_parser): """ obtain duration for each phoneme in the phoneme_list :param phoneme_list: a list of phoneme strings :param phoneme_dur_parser: a map from phoneme to its duration :return: a list of (phoneme, duration) pairs example: ...
def minimum(x,y,z): """ Determine the minum of three values min=x if(y<mi): mi=y if(z<mi): mi=z return mi """ return min(min(x,y),z)
def outdegree(graph): """ To find the out degree we need to scan through all the vertices and all the edges associated with that vertex so the time it takes is O(V+E) """ out = [] for i in range(len(graph)): out.append(len(graph[i])) return out
def calculateConsensus(u, d, t, U_sum, D_sum): """ Calcluate consensus score. This is a heuristic for the percentage of the community who finds a term useful. Based on the observation that not every user will vote on a given term, user reptuation is used to estimate consensus. As the number of vot...
def dumb_lp(text): """ :arg text: a String that contains the text that needs to be processed. :returns a list containing keywords extracted from the text """ keywords = [] command_flags = ['get', 'show', 'find', 'tell', 'what', 'how'] command_subjects = ['wea...
def symsplit(item): """ Splits symmetric molecule atom mapping expression into its component parts. Returns a list of atom mappings in the symmetric molecule. For example: symsplit('(abc;cba)') = ['abc','cba'] """ # Removing white space tmp=item.replace(' ','') # checking format ...
def get_keys_of_max_n(dict_obj, n): """Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c'] """ return sorted([ item[0] for item in sorted( d...
def is_valid_time_response(response): """ Returns true if a time response is valid. str -> bool """ try: return float(response) >= 0 except ValueError: return False
def is_posix_path3(my_path): """Return whether or not a given path is Posix-based.""" return "/" in str(my_path)
def find_stop_position(initial_path, starting_position): """Returns a suffix from a given path. :param initial_path: The path for which a suffix is wanted. :param starting_position: The starting position from the suffix. :return: A suffix for a given path. """ if isinstance(initial_path[0][0],...
def shout(word): """Return a string with three exclamation marks""" # Concatenate the strings: shout_word shout_word = word + '!!!' # Replace print with return return(shout_word)
def get_month_days(month_number): """month_number = 1 in January month_number = 12 in December""" month_days = [31,28,31,30,31,30,31,31,30,31,30,31] return month_days[month_number-1]
def _key_is_valid(dictionary, key): """Test that a dictionary key exists and that its value is not blank.""" if key in dictionary: if dictionary[key]: return True return False
def dSigma_dCosT(eNu, cosT): """Return differential cross section in MeV^-2 as a function of the emission angle of the outgoing (detected) particle. Input: eNu: neutrino energy (MeV) cosT: cosine of the angle between neutrino and outgoing (detected) particle """ # Small values of cosT ...
def get_topic_link(text: str) -> str: """ Generate a topic link. A markdown link, text split with dash. Args: text {str} The text value to parse Returns: {str} The parsed text """ return f"{text.lower().replace(' ', '-')}"
def decode( string, dtype='U' ): """ short wrapper to decode byte-strings read from FRBcat """ if 'f' in dtype: if 'null' in string: return float('NaN') return float(string) return string
def series_sum(n): """Return nth item of sum series.""" total = 0 denom = 1 for i in range(n): total += 1 / denom denom += 3 return '{:.2f}'.format(total)
def joinSet(itemSet, removedSet, length): """Join a set with itself and returns the n-element itemsets""" filteredSet = set() flagAddItem = True composed_set = set([i.union(j) for i in itemSet for j in itemSet if len(i.union(j)) == length]) newremovedSet = set() for item ...
def _get(obj, name): """ Get the indexable value with given `name` from `obj`, which may be a `dict` (or subclass) or a non-dict that has a `__getitem__` method. """ try: # try to get value using dict's __getitem__ descriptor first return dict.__getitem__(obj, name) except TypeEr...
def round_digits( v: float, num_digits: int = 2, use_thousands_separator: bool = False ) -> str: """ Round digit returning a string representing the formatted number. :param v: value to convert :param num_digits: number of digits to represent v on None is (Default value = 2) :param ...
def ensure_array(exemplar, item): """Coerces *item* to be an array (linear sequence); if *item* is already an array it is returned unchanged. Otherwise, an array of the same length as exemplar is created which contains *item* at every index. The fresh array is returned. """ try: item[...
def reverse_text_len(width, fs): """Approximation of text length""" return int(width / (0.6 * fs))
def str_to_integer(data): """Convert a stream of bytes representing a number into a single integer.""" value = 0 i = 0 for char in data: value += (char << i) i += 8 return value
def reverseComplement(seq): """ Returns the reverse complement of a DNA sequence, retaining the case of each letter""" complement = "" for base in seq: if base == "A": complement += "T" elif base == "T": complement += "A" elif base == "G": ...
def enthalpy_wall_del(T_0, T_w, C_p): """ Calculates specific enthalpy difference between total conditions and those at the stagnation point of a sphere in supersonic flow. Input variables: T_0 : Gas total temperature T_w : Sphere wall temperature C_p : Specific heat capac...
def vis321(n): """ 0 0 0 0 0 00 0 00 00 00 00 00 Number of Os: 4 6 8""" result = '' return result
def unconvert_from_RGB_255(colors): """ Return a tuple where each element gets divided by 255 Takes a (list of) color tuple(s) where each element is between 0 and 255. Returns the same tuples where each tuple element is normalized to a value between 0 and 1 """ un_rgb_color = (colors[0]/(2...
def storage_descriptor(columns, location): """Dynamically build a Data Catalog storage descriptor with the desired columns and S3 location""" return { "Columns": columns, "Location": location, "InputFormat": "org.apache.hadoop.mapred.TextInputFormat", "OutputFormat": "org.apache....
def is_task_terminal(task): """Return whether a given mesos task is terminal. Terminal states are documented in http://mesos.apache.org/api/latest/java/org/apache/mesos/Protos.TaskState.html :param task: the task to be inspected :returns: a boolean indicating if the task is considered to be in a t...
def findMinHeightTrees(n, edges): """ :type n: int :type edges: List[List[int]] :rtype: List[int] """ if not edges or n==1: return [0] adj=[set() for i in range(n)] for i,j in edges: adj[i].add(j) adj[j].add(i) leaves=[nodeIndex for nodeIndex in range(n) if le...
def get_length_of_missing_array(array_of_arrays): """ Sort the list in ascending order and extract the lengths of each list into another list Loop through the list of lengths searching to the greatest distance between 2 elements if the distance is greater than 1, add 1 to the previous element (or subtra...
def _relative_channels(channels, adjacency): """Renumber channels from absolute indices to relative indices, to match arrays used in the detection code. Parameters ---------- channels : dict A dict {group: list_of_channels} adjacency : dict A dict {group: set_of_neighbors} ...
def get_percentage(num_voters, lang_votes): """Gets percentage sum given list of vote counts and total voters.""" return sum([int(100 * i / num_voters + 0.5) for i in lang_votes])
def merge_dictionaries(a, b, path=None, update=True): """ Merge two dictionaries recursively. From https://stackoverflow.com/a/25270947 """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): ...
def disambiguate_language(text, assumed_languages, db): """ Some Wiktionary links simply point to a term without specifying what language it's in. In that case, we have to guess. The possible languages are: - The language of the Wiktionary it's in - The language of the other term in th...
def depth_first(start, children_func): """Return a depth-first traversal of a tree. Args: start: the root of the tree. children_func: function taking a node to its sequence of children. Returns: a list of nodes in depth-first order """ seen = set() result = [] def traversal(node): if nod...
def _cmp_tm( lhs, rhs ) : """ compare two tm structs """ if lhs[0] != rhs[0] : return False ; if lhs[1] != rhs[1] : return False ; if lhs[2] != rhs[2] : return False ; if lhs[3] != rhs[3] : return False ; if lhs[4] != rhs[4] : return False ; if lhs[5] != rhs[5] : return False ; if...
def get_title_from_content(content): """ Generates a title from the content using the first line and stripping away whitespace and hash signs :content: str :returns: str """ title = content.split('\n', 1)[0].replace('#', '').lstrip()[0:50] return title
def _ensureListOfLists(iterable): """ Given an iterable, make sure it is at least a 2D array (i.e. list of lists): >>> _ensureListOfLists([[1, 2], [3, 4], [5, 6]]) [[1, 2], [3, 4], [5, 6]] >>> _ensureListOfLists([1, 2]) [[1, 2]] >>> _ensureListOfLists(1) [[1]...
def get_box(pts): """Returns tight fitting bounding box (axis aligned) around set of points """ assert len(pts) it = iter(pts) ll = list(next(it)) ur = list(ll[:]) for pt in it: if pt[0] < ll[0]: ll[0] = pt[0] if pt[1] < ll[1]: ll[1] = pt[1] if...
def encode_bool(value: bool) -> bytes: """Encodes a boolean. """ return bytes([int(value)])
def create(row_num, col_num, val = None): """ :param row_num: the number of rows :type row_num: int :param col_num: the number of columns :type col_num: int :param val: the default value to fill the matrix :type val: any (None by default) :return: matrix of rows_num x col_num :rtype: matrix """ matrix = [] ...
def compute_position(positions, total, index, length): """ used to compute the position where the bar will be put """ return positions - total / 2 + length / 2 + index * length