content
stringlengths
42
6.51k
def service_update_flags( #pylint: disable=too-many-arguments target_rep_size=None, instance_count=None, rep_restart_wait=None, quorum_loss_wait=None, standby_rep_keep=None, min_rep_size=None, placement_constraints=None, placement_policy=None, correlation=None, metrics=None, move_cost=None): """Calculate an integer representation of flag arguments for updating stateful services""" flag_sum = 0 if (target_rep_size is not None) or (instance_count is not None): flag_sum += 1 if rep_restart_wait is not None: flag_sum += 2 if quorum_loss_wait is not None: flag_sum += 4 if standby_rep_keep is not None: flag_sum += 8 if min_rep_size is not None: flag_sum += 16 if placement_constraints is not None: flag_sum += 32 if placement_policy is not None: flag_sum += 64 if correlation is not None: flag_sum += 128 if metrics is not None: flag_sum += 256 if move_cost is not None: flag_sum += 512 return flag_sum
def vowel_count(phrase): """Return frequency map of vowels, case-insensitive. >>> vowel_count('rithm school') {'i': 1, 'o': 2} >>> vowel_count('HOW ARE YOU? i am great!') {'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1} """ # MUCH quicker way: VOWELS = set("aeiou") vowel = {"a", "e", "i", "o", "u"} answer = {} lower_phrase = phrase.lower() for ltr in lower_phrase: if ltr in vowel: if ltr in answer: answer[ltr] = answer[ltr] + 1 else: answer[ltr] = 1 return answer # for ltr in phrase: # if ltr in VOWELS: # counter[ltr] = counter.get(ltr, 0) + 1
def calc_t_ramp(t_int, n_reset, t_frame): """Calculates the ramp time -- or the integration time plus overhead for resets. Parameters ---------- t_int : float Integration time (in seconds). n_reset : int Rest frames per integration t_frame : float Frame time (in seconds). Returns ------- t_ramp : float Ramp time (in seconds). """ t_ramp = t_int + (n_reset - 1)*t_frame return t_ramp
def combine_quality( dqarr1, dqarr2 ): """ Combines two data quality arrays to make a third. The bitwise nature of the data quality flags means that two arrays can be combined without needing to know the meaning of the underlying flags. :Parameters: dqarr1: numpy array or None numpy array which represents a dq plane (or part of it). Can be None if there is no data quality information. dqarr2: numpy array or None numpy array which represents another dq plane (or part of it). Can be None if there is no data quality information. :Returns: newdq: numpy array numpy array containing a combination of both DQ arrays. Can be None if both of the input arrays are None. """ # Check which of the arrays are defined. if dqarr1 is not None and dqarr2 is not None: # There are two quality arrays - merge them. # The bitwise OR operation combines the effect of the flags # without the need to know what they mean. newdq = dqarr1 | dqarr2 elif dqarr1 is not None: # Only array 1 is defined - return it. newdq = dqarr1 elif dqarr2 is not None: # Only array 2 is defined - return it. newdq = dqarr2 else: # Neither array is defined - return None. newdq = None return newdq
def twos_comp(val, bits): """compute the 2's complement of int value val""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val # return positive value as is
def encode_query(parsed_query): """ Take a parsed query and encode it to a query string. """ def escape_parens(value): return value.replace('(', '\\(').replace(')', '\\)') encoded_clauses = [] for clause in parsed_query['clauses']: type = clause['type'] text = escape_parens(clause['text']) encoded_clause = '{}({})'.format(type, text) encoded_clauses.append(encoded_clause) return ' '.join(encoded_clauses)
def sort_models_topologically(models): """Sort models topologically so that parents will precede children.""" models = set(models) seen = set() ordering = [] def dfs(model): if model in models and model not in seen: seen.add(model) for child_model in model._meta.reverse_relations.values(): dfs(child_model) ordering.append(model) # parent will follow descendants # order models by name and table initially to guarantee a total ordering names = lambda m: (m._meta.model_name, m._meta.db_table) for m in sorted(models, key=names, reverse=True): dfs(m) return list(reversed(ordering))
def dna_starts_with(dna, pattern): """ Return True if 'dna' starts with 'pattern' """ # Sanitize input dna = dna.upper() pattern = pattern.upper() if not (set(dna) <= set('CGTA')): raise ValueError('DNA contains garbage: %s' % set(dna)) if not (set(pattern) <= set('CGTA')): raise ValueError('Pattern contains unexpected nucleotides: %s' % set(dna)) # Pattern is too large if len(pattern) > len(dna): return False return pattern == dna[:len(pattern)]
def remove_dollars(text): """remove dollars from start/end of text""" while text.startswith("$"): text = text[1:] while text.endswith("$"): text = text[0:-1] return text
def negate_conf(c): """Negate a line of configuration.""" return "no %s" % c
def oldWikiWordToLabel(word): """ Strip '[' and ']' if non camelcase word and return it """ if word.startswith(u"[") and word.endswith(u"]"): return word[1:-1] return word
def get_invalid_request_param(message): """ Returns error response for invalid request parameters :param str error: message :return: error_response :rtype: object """ error_response = {"status": 400, "data": [], "message": message} return error_response
def map_value_in_list_to_dictionary_key(event, mapping_dict_with_lists, existing_column, new_column, allow_nulls, passthrough): """ Maps a value from a list back to the key. Useful to map values to categories. :param event: A dictionary :param mapping_dict_with_lists: A mapping dict with lists in the values such as {"baked good": ["cake", "croissant"]} :param existing_column: The column with the existing data :param new_column: The name of the new column for the added data :param allow_nulls: True if the existing column can have NULL. If set to False NULLs will throw an error :param passthrough: True if we should pass through a value of the existing column when there is no mapping value in the list :return: An altered event Examples: .. code-block:: python # Example #1 event = {'_metadata': {'event_type': 'MY_SCHEMA.MY_TABLE'}, 'a_field': 1} event = map_value_in_list_to_dictionary_key(event, mapping_dict_with_lists={'1-3': [1, 2, 3], '4-6': [4, 5, 6]}, existing_column='a_field', new_column='a_mapped_field', allow_nulls=False, passthrough=False) event = {'_metadata': {'event_type': 'MY_SCHEMA.MY_TABLE'}, 'a_field': 1, 'a_mapped_field': '1-3'} # Example #2 event = {'_metadata': {'event_type': 'MY_SCHEMA.MY_TABLE'}, 'a_field': 7} event = map_value_in_list_to_dictionary_key(event, mapping_dict_with_lists={'1-3': [1, 2, 3], '4-6': [4, 5, 6]}, existing_column='a_field', new_column='a_mapped_field', allow_nulls=False, passthrough=False) Exception: Missing map_list transform MY_SCHEMA.MY_TABLE a_field """ func_name = 'map_list transform ' + event['_metadata']['event_type'] + ' ' + existing_column existing_column_value = event[existing_column] event[new_column] = None for k, v in mapping_dict_with_lists.items(): if existing_column_value in v: event[new_column] = k if event[new_column] is not None: return event elif passthrough: event[new_column] = existing_column_value elif allow_nulls: return event else: raise Exception('Missing %s' % func_name) return event
def product_trial_rate(number_of_first_time_purchases, total_purchasers): """Returns the percentage of customers who trialled a product for the first time during a period. Args: number_of_first_time_purchases (int): Total number of unique first-time purchasers during a period. total_purchasers (int): Total number of unique purchasers during a period. Returns: Percentage of customers who purchased product for the first time during a period. """ return (number_of_first_time_purchases / total_purchasers) * 100
def fibonacci_sum_squares(n: int): """ Computes the last digit of F0^2 + F1^2 + ... + Fn^2. :param n: the sequence size of Fibonacci numbers :return: the last digit of the sum of squares Example 1: 0+1+1+4+9+25+64+169=273 >>> fibonacci_sum_squares(7) 3 Example 2: F73 = 1,052,478,208,141,359,608,061,842,155,201 >>> fibonacci_sum_squares(73) 1 """ n %= 60 if n < 2: return n fibonacci = [0, 1] fibonacci_sq_sum = 0 for i in range(2, n + 1): last_digit = (fibonacci[i - 1] + fibonacci[i - 2]) % 10 fibonacci.append(last_digit) for num in fibonacci: fibonacci_sq_sum += num**2 % 10 fibonacci_sq_sum %= 10 return fibonacci_sq_sum
def card(n): """Return the playing card numeral as a string for a positive n <= 13.""" assert type(n) == int and n > 0 and n <= 13, "Bad card n" specials = {1: 'A', 11: 'J', 12: 'Q', 13: 'K'} return specials.get(n, str(n))
def parse_csv_value(s): """Parse and convert value to suitable types Args: s (str): value on csv Returns: Suitable value (int, float, str, bool or None) """ try: return int(s) except (OverflowError, ValueError): try: return float(s) except (OverflowError, ValueError): pass lower = s.lower() if lower in ("false", "true"): return "true" == lower elif lower in ("", "none", "null"): return None else: return s
def convexHull(points): """ Compute the convex hull of the given {points} """ # set up the two corners p_min = [] p_max = [] # zip all the points together, forming as many streams of coordinates as there are # dimensions for axis in zip(*points): # store the minimum value in p_min p_min.append(min(axis)) # and the maximum value in p_max p_max.append(max(axis)) # all done return p_min, p_max
def example_func(x: str = 'Hello', y: bool = True, z: float = 12.1) -> str: """ A test function :param x: The exxxx param :param y: The whyyyyyyy param :return: A string showing all values, repeated 10x to test long return values (Should be truncated to 256 chars) """ return f'x is: {x}, y is: {str(y)}, and z is: {str(z)}'*10
def is_anti_symmetric(L): """ Returns True if the input matrix is anti-symmetric, False otherwise. """ result = len(L) == len(L[0]) for i in range(len(L)): for j in range(len(L)): result *= L[i][j] == -L[j][i] return result
def is_correct_educator_name(text): """ Checks if the text is correct :param text: input text :type text: str :return: True or False :rtype: bool """ return text.replace(".", "").replace("-", "").replace(" ", "").isalnum()
def extract(string, start='(', stop=')', firststop=True): """ Return substring between `start` and first/last `stop` characters Args: string (string): the string to extract from start (string): the left delimiter string stop (string): the right delimiter string firststop (bool): if True extract to the rightmost stop Returns: the extracted string """ try: if firststop: extracted = string[string.index(start) + len(start) : string.index(stop)] else: extracted = string[string.index(start) + len(start) : string.rindex(stop)] except ValueError: if start == stop == "'": start = stop = '"' elif start == stop == '"': start = stop = "'" try: if firststop: extracted = string[string.index(start) + len(start) : string.index(stop)] else: extracted = string[string.index(start) + len(start) : string.rindex(stop)] except ValueError: extracted = '' return extracted
def check_dynamic_shape(shape): """ Function Description: check dynamic shpae Parameter: shape:shape Return Value: False or True """ dynamic_shape = False for item in shape: if item is None or isinstance(item, str): dynamic_shape = True break return dynamic_shape
def subnet_str(cidr): """Convert the cidr string to x.x.x.x_y format :param cidr: CIDR in x.x.x.x/y format """ if cidr is None: return None return cidr.replace("/", "_")
def convertHtml(text): """A few HTML encodings replacements. &amp;#39; to ' &amp;quot; to " """ return text.replace('&amp;#39;', "'").replace('&amp;quot;', '"')
def parse_globus_url(url): """Parse a Globus URL string of the format: globus://<UUID Endpoint>:<Path> globus://ddb59aef-6d04-11e5-ba46-22000b92c6ec:/share/godata/file1.txt returns a dict of the format: { 'endpoint': 'ddb59aef-6d04-11e5-ba46-22000b92c6ec' 'path': '/share/godata/file1.txt' } Raises ValueError if invalid format """ if 'globus://' not in url: raise ValueError('url "{}" did not start with "globus://"'.format(url)) url_chunks = url.replace('globus://', '').split(':') if len(url_chunks) < 2: raise ValueError('Unable to find ":" to split path from endpoint for ' '{}'.format(url)) if len(url_chunks[0]) != 36: raise ValueError('Malformed Globus endpoint UUID does not' 'contain 36 characters: {}' ''.format(url_chunks[0])) return url_chunks[0], ':'.join(url_chunks[1:])
def calcBotFinalReward(top_action, bot_aspect_action, bot_opinion_action, gold_labels, bot_bias = 0.): """ Final bottom reward, using tagging sequence matching. """ lenth = len(top_action) r = [0. for j in range(len(bot_aspect_action))] j = 0 for i in range(lenth): if top_action[i] > 0: r[j] = -1.0 for label in gold_labels: if label['type'] == top_action[i]: ok = True for t in range(lenth): if label['aspect_tags'][t] != bot_aspect_action[j][t] or label['opinion_tags'][t] != bot_opinion_action[j][t]: ok = False break if ok: r[j] = 1 # negative reward if there are impossible results # 1) if either beginning tag of aspect or opinion span is absent or there is more than 1 of either if bot_aspect_action[j].count(2) !=1: r[j] -= 0.2 if bot_opinion_action[j].count(2) !=1: r[j] -= 0.2 # 2) if no aspect or opinion span detected or more than 1 of either is detected aspect_cnt = 0 prev_aspect = False for k, aspect_k in enumerate(bot_aspect_action[j]): if aspect_k > 0: prev_aspect = True if k == len(bot_aspect_action[j]) - 1: aspect_cnt += 1 elif aspect_k == 0: if prev_aspect: aspect_cnt += 1 prev_aspect = False if aspect_cnt > 1: break opinion_cnt = 0 prev_opinion = False for k, opinion_k in enumerate(bot_opinion_action[j]): if opinion_k > 0: prev_opinion = True if k == len(bot_opinion_action[j]) - 1: opinion_cnt += 1 elif opinion_k == 0: if prev_opinion: opinion_cnt += 1 prev_opinion = False if opinion_cnt > 1: break if aspect_cnt != 1: r[j] -= 0.2 if opinion_cnt != 1: r[j] -= 0.2 j += 1 for j in range(len(bot_aspect_action)): r[j] -= bot_bias return r
def format_if(value, format_kwargs): """Apply format args to value if value or return value as is.""" if not value: return value return value.format_map(format_kwargs)
def current_data_indexes(data, two_columns_argument): """ Transform the columns argument to the indexes of data tuple. Parameters ---------- data : tuple A value returned by the get_data() function. two_columns_argument : list A list which contains two indexes of used columns - columns argument. Returns ------- tuple A tuple which contains two indexes. """ first_index = -1 second_index = -1 for index, column_data in enumerate(data): if two_columns_argument[0] == column_data[0]: first_index = index if two_columns_argument[1] == column_data[0]: second_index = index return first_index, second_index
def gibberish(*args): """Concatenate strings in *args together.""" # Initialize an empty string: hodgepodge hodgepodge='' # Concatenate the strings in args for word in args: hodgepodge += word # Return hodgepodge return hodgepodge
def _rstrip_underscored_part(string): """Remove part after rightmost underscore in string if such a part exists.""" underscore_ind = string.rfind('_') if underscore_ind != -1: return string[:underscore_ind] return string
def update_flag(key_press, current_flag, flags): """Handle key press from cv2.waitKey() for capturing frames :param key_press: output from `cv2.waitKey()` :param current_flag: value of 'flag' holding previous key press :param flags: dictionary mapping key presses to class labels :return: new flag value """ if key_press < 0 or chr(key_press) not in flags.keys(): return current_flag key_press = chr(key_press) for k in flags.keys(): if k == key_press and k == current_flag: print(f'Stop capturing for {flags[k]}') return None elif k == key_press: print(f'Capturing for {flags[k]}') return k
def year_range(entry): """Show an interval of employment in years.""" val = "" if entry.get("start_date") is None or entry["start_date"]["year"]["value"] is None: val = "unknown" else: val = entry["start_date"]["year"]["value"] val += "-" if entry.get("end_date") is None or entry["end_date"]["year"]["value"] is None: val += "present" else: val += entry["end_date"]["year"]["value"] return val
def get_obj_value(data_obj, attr, default=None): """Get dict's key or object's attribute with given attr""" if isinstance(data_obj, dict): return data_obj.get(attr, default) return getattr(data_obj, attr, default)
def apply_downsampling(seq, step, filter_global=False, filter_local=False, **kwargs): """ Apply Down Samplings Args. ----- - seq : list [e.g. np.ndarray(), pd.DataFrame] - step : integer, Spaceing between values Return. ------- - lsit of donwsampled `seq` """ seq_list = [] # Apply filters [whole sequence] if not isinstance(filter_global, bool): seq = filter_global(seq, **kwargs) for start in range(step): if not isinstance(filter_local, bool): # Apply local filter seq_new = filter_local(seq, start, step=step, **kwargs) else: seq_new = seq[start::step] seq_list.append(seq_new) return seq_list
def _to(l): """To Converts all addresses passed, whether strings or lists, into one singular list Arguments: l (list(str|str[])): The list of addresses or lists of addresses Returns: list """ # Init the return list lRet = [] # Go through each item in the list for m in l: # If we got a list if isinstance(m, (list,tuple)): lRet.extend(m) # Else, we got one address else: lRet.append(m) # Return the full list return lRet
def construct_yaml_fields(signatures, function_operation_id_root, file_operation_id_root, server_root_url): """ Parse the signatures of functions to a dictionary that is used to generate yaml files. f = {0: {'name': 'linear-regression', 'request_method': 'post', 'doc_string': 'this is a doc string', 'operation_id': 'cloudmesh.linear_regression', 'paras': { 'file_name': {'name': 'file_name', 'type': 'string'}, 'intercept': {'name': 'intercept', 'type': 'int'} }}} """ table_yaml = {} count = 0 for i, class_i in signatures.items(): # build the yaml information table for class constructor count += 1 class_i_name = class_i['class_name'] constructor_yaml_info = {} constructor_yaml_info['name'] = class_i_name + '_constructor' constructor_yaml_info['request_method'] = 'post' constructor_yaml_info['doc_string'] = 'this is a doc string' constructor_yaml_info['operation_id'] = function_operation_id_root + '.' + \ class_i_name + '_constructor' constructor_yaml_info['paras'] = {} for init_para_name, init_para_type in class_i['constructor'].items(): constructor_yaml_info['paras'][init_para_name] = { 'name': init_para_name, 'type': init_para_type} table_yaml[count] = constructor_yaml_info # build the yaml information table for class members for member_name, parameters in class_i['members'].items(): count += 1 if (member_name != 'property'): member_yaml_info = {} member_yaml_info['name'] = class_i_name + '_' + member_name member_yaml_info['request_method'] = 'post' member_yaml_info['doc_string'] = 'this is a doc string' member_yaml_info['operation_id'] = function_operation_id_root + '.' + \ class_i_name + '_' + member_name member_yaml_info['paras'] = {} for member_para_name, member_para_type in parameters.items(): member_yaml_info['paras'][member_para_name] = { 'name': member_para_name, 'type': member_para_type} table_yaml[count] = member_yaml_info res = {'header': {'server_url': server_root_url}, 'functions': table_yaml, 'files':{'operation_id':file_operation_id_root} } return res
def get_item_properties(item, fields, mixed_case_fields=[]): """Return a tuple containing the item properties. :param item: a single item resource (e.g. Server, Tenant, etc) :param fields: tuple of strings with the desired field names :param mixed_case_fields: tuple of field names to preserve case """ row = [] for field in fields: if field in mixed_case_fields: field_name = field.replace(' ', '_') else: field_name = field.lower().replace(' ', '_') if not hasattr(item, field_name) and isinstance(item, dict): data = item[field_name] else: data = getattr(item, field_name, '') if data is None: data = '' row.append(data) return tuple(row)
def map_loc_genes(gene_list): """Map gene names beginning with 'LOC'. See https://www.biostars.org/p/129299/ : these are genes with no published symbol, and thus have the format 'LOC' + Entrez ID. """ gene_map = {} unmatched = [] for gene in gene_list: if gene.startswith('LOC'): gene_map[gene] = gene.replace('LOC', '') else: unmatched.append(gene) return gene_map, unmatched
def flatten_tests(test_classes): """ >>> test_classes = {x: [x] for x in range(5)} >>> flatten_tests(test_classes) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] >>> test_classes = {x: [x + 1, x + 2] for x in range(2)} >>> flatten_tests(test_classes) [(0, 1), (0, 2), (1, 2), (1, 3)] """ tests = [] for class_name, test_names in test_classes.items(): tests += [(class_name, test_name) for test_name in test_names] return tests
def get_end_time(op): """Return the end time string of the operation.""" return op.get('metadata', {}).get('endTime')
def tablero_a_cadena(tablero): """ (str) -> str convierte el tablero a una cadena >>>tablero_a_cadena(tablero) [ ['t', 'k', 'a', 'q', 'r', 'a', 'k', 't'], ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'], ['T', 'K', 'A', 'R', 'Q', 'A', 'K', 'T'] ] :param tablero: Representacion visual del juego en una (matriz) :return: cadena que representa las casillas del tablero """ cadena = "" for fila in tablero: cadena += str(fila) + "\n" return cadena
def create_python_command(args): """Create python shell command with args""" return "python {}".format(" ".join(args))
def SBATCH_Config(object): """Simple data type that holds a dict data member and has a to_str() method.""" settings = ["begin", "constraint", "cpus-per-task", # min. CPUs per task on one node "error", # stderr filename "job-name", "mail-type", "mem", # memory per node (MB) "mem-per-cpu", "mincpus", # min. CPUs per node "nodes", # min. nodes "ntasks", # number of tasks that will be launched "output", # stdout filename "partition", # partition(s) to submit to "time", # time limit ] forbidden_settings = ["chdir", ] def __init__(self, config_dict): self._cgf = config_dict def to_str(self): """Convert configuration to string, which can be written in bash scripts.""" pass def __str__(self): return self.to_str()
def qualify(path: str) -> str: """Add the scheme to a file path, if required.""" if path.startswith("/"): return f"file://{path}" else: return path
def _canonical_machine_name(machine): """Handle the .comlab -> .cs DNS change, mapping old results to the new names.""" return machine.replace('.comlab.ox.ac.uk', '.cs.ox.ac.uk')
def sahovnica_n(n_vrstic): """ vrni string, ki bo narisal sahovnico v velikost n_vrstic""" # BEGIN SOLUTION result = '' # END SOLUTION return result
def secToHHMMSS(seconds): """ Converts input seconds into the desired output display format. Rounds to the nearest second. """ rndSec = int(seconds + 0.5) # rounded seconds hrs = int(rndSec / 3600) min = int((rndSec - hrs * 3600) / 60) sec = rndSec - hrs * 3600 - min * 60 return str(hrs).zfill(2) + ":" + str(min).zfill(2) + ":" + str(sec).zfill(2) + ".0000000"
def clean_inputs(word): """ cleans inputs in case of blanks or all spaces """ invalid_tems = [None, ' ', '', '\t', '\n'] if word in invalid_tems: return None else: return word
def settings_outside_clinical_bounds(cir, isf, sbr): """ Identifies whether any of the settings are outside clinical bounds (based on medical advisory) Parameters ---------- cir: float carb to insulin ratio for the particular scenario isf: float insulin sensitivity factor for the particular scenario sbr:float scheduled basal rate for the particular scenario Returns ------- a boolean for whether any of the settings fall outside of the clinical bounds criteria as defined in the function """ return ( (float(isf) < 10) | (float(isf) > 500) | (float(cir) < 2) | (float(cir) > 150) | (float(sbr) < 0.05) | (float(sbr) > 30) )
def conv_lin(a, b=1.0, c=0.0, inverse=False): """Simple linear transform will I think store parameters against each sensor then they are handy >>> conv_lin(4,2,3) 11 >>> conv_lin(11,2,3.0,True) 4.0 >>>""" if inverse is False: return a * b + c else: return (a - c) / b
def from_literal(tup): """Convert from simple literal form to the more uniform typestruct.""" def expand(vals): return [from_literal(x) for x in vals] def union(vals): if not isinstance(vals, tuple): vals = (vals,) v = expand(vals) return frozenset(v) if not isinstance(tup, tuple): return ('prim', tup) elif isinstance(tup[0], str): tag, *vals = tup if tag == 'prim': return tup elif tag == 'tuple': params = tuple(expand(vals)) return (tag, params) elif tag == 'map': k, v = vals return (tag, (union(k), union(v))) else: vals, = vals # pylint: disable=self-assigning-variable return (tag, union(vals)) else: return tuple(expand(tup))
def _service_account_email(project_id, service_account_id): """Return full service account email.""" return '%s@%s.iam.gserviceaccount.com' % (service_account_id, project_id)
def remove_subtitle(title): """Strip a book's subtitle (if it exists). For example, 'A Book: Why Not?' becomes 'A Book'.""" if ':' in title: return title[:title.index(':')].strip() else: return title
def overlap(start1, end1, start2, end2, tolerance=0): """Check that range (start1, end1) overlaps with (start2, end2).""" # Taken from https://nedbatchelder.com/blog/201310/range_overlap_in_two_compares.html return end1 + tolerance >= start2 and end2 + tolerance >= start1
def get_start_end(sequence, skiplist=['-','?']): """Return position of first and last character which is not in skiplist. Skiplist defaults to ['-','?']).""" length=len(sequence) if length==0: return None,None end=length-1 while end>=0 and (sequence[end] in skiplist): end-=1 start=0 while start<length and (sequence[start] in skiplist): start+=1 if start==length and end==-1: # empty sequence return -1,-1 else: return start,end
def rec_cmp_prereleases(one, two): """Recursive function that compares two version strings represented as lists to determine which takes precedence. If it is the left argument ("one"), the result will be a 1. If the righthand argument wins ("two"), the result will be a 2. If the two are equivalent (i.e. are the same string), the result is a 0. :param one: left-hand version str :param two: right-hand version str :return: 0, 1, or 2 :rtype: int """ if one == two: return 0 # if either has reached its zenith of productivity, the other has won. # # (Note that this is only correct in the context of there being conditionals in # the cmp_prerelease function that already handle the case in which one # version string has a prerelease and the other one doesn't! This recursive # comparator function won't ever be invoked in that situation.) if len(one) == 0: return 2 elif len(two) == 0: return 1 # ok so we still have two values to compare. # try to make ints; if we fail, then we have ASCII. cmp_strs = {} cmp_ints = {} try: cmp_ints[1] = int(one[0]) except ValueError: cmp_strs[1] = one[0] try: cmp_ints[2] = int(two[0]) except ValueError: cmp_strs[2] = two[0] if len(cmp_strs)==2: # if the two strings are equivalent, recurse down further. # if not, declare a winner by ASCII value. if cmp_strs[1] == cmp_strs[2]: return rec_cmp_prereleases(one[1:], two[1:]) elif cmp_strs[1] > cmp_strs[2]: return 1 elif cmp_strs[1] < cmp_strs[2]: return 2 elif len(cmp_ints)==2: # if the two integers are equivalent, recurse down further. # otherwise, declare a winner by integer value. if cmp_ints[1] == cmp_ints[2]: return rec_cmp_prereleases(one[1:], two[1:]) elif cmp_ints[1] > cmp_ints[2]: return 1 elif cmp_ints[1] < cmp_ints[2]: return 2 # Apples and oranges: ASCII always wins. return list(cmp_strs.keys())[0]
def strtobool(value): """ This method convert string to bool. Return False for values of the keywords "false" "f" "no" "n" "off" "0" or 0. Or, return True for values of the keywords "true" "t" "yes" "y" "on" "1" or 1. Or, othres return None. Args: value : string value Return: Return False for values of the keywords "false" "f" "no" "n" "off" "0" or 0. Or, return True for values of the keywords "true" "t" "yes" "y" "on" "1" or 1. Or, othres return None. Raises: TypeError : The type of parameter is not string. ValueError : The parameter value can not be interpreted as a bool value. """ if type(value) is not str and value not in [0, 1]: raise TypeError("The type of parameter value must be string.") ret_value = None if value.lower() in ["false", "f", "no", "n", "off", "0"] or value == 0: ret_value = False elif value.lower() in ["true", "t", "yes", "y", "on", "1"] or value == 1: ret_value = True else: raise ValueError("not supported bool value.") return ret_value
def manual_sentence_spelling(x, spelling_dictionary): """ Applies spelling on an entire string, if x is a key of the spelling_dictionary. :param x: (string) sentence to potentially be corrected :param spelling_dictionary: correction map :return: the sentence corrected """ if x in spelling_dictionary: return spelling_dictionary[x] else: return x
def _to_bytes(string): """ Convert string to bytes. """ if not isinstance(string, (str, bytes)): # pragma: no cover string = str(string) return string if isinstance(string, bytes) else string.encode('utf-8')
def get_backend_properties_url(config, backend_type, hub=None): """ Util method to get backend properties url """ hub = config.get('hub', hub) if hub: return '/Network/{}/devices/{}/properties'.format(hub, backend_type) return '/Backends/{}/properties'.format(backend_type)
def get_mail_port(protocol): """ This returns the server port to use for POP retrieval of mails :param protocol: The protocol to be used to fetch emails - IMAP or POP3 :type protocol: basestring :return: Returns the correct port for either POP3 or POP3 over SSL :rtype: int """ if protocol == 'POP3': port = 995 elif 'IMAP' == protocol: port = 993 else: raise Exception("Invalid options passed to get_mail_port") return port
def mask_list(mask): """Return the list of set bits in a mask as integers.""" set_bits = [] for position, bit in enumerate(reversed(bin(mask)[2:])): if bit == "1": set_bits.append(int("1{}".format("0" * position), base=2)) return set_bits
def stock_list(listOfArt: list, listOfCat: list) -> str: """ You will be given a stocklist (e.g. : L) and a list of categories in capital letters e.g : M = {"A", "B", "C", "W"} or M = ["A", "B", "C", "W"] or ... and your task is to find all the books of L with codes belonging to each category of M and to sum their quantity according to each category. """ result = '' if not listOfArt: return result for cat in listOfCat: total = 0 for art in listOfArt: if cat in art[0]: total += int(art.split(' ')[1]) if result != '': result += ' - ({} : {})'.format(cat, total) else: result += '({} : {})'.format(cat, total) return result
def get_title(file): """ Returns a string containing the title for the given file. Args: file(dict): Describes the file. Returns: String representing the title. """ # Use the track title. As a fallback, use the display title. title = file.get("track_and_facet_info", {}).get("track_title", file["display_title"]) return title
def make_attr_name(name): """Converts name to pep8_style Upper case letters are replaced with their lower-case equivalent optionally preceded by '_' if one of the following conditions is met: * it was preceded by a lower case letter * it is preceded by an upper case letter and followed by a lower-case one As a result:: make_attr_name('aName') == 'a_name' make_attr_name('ABCName') == 'abc_name' make_attr_name('Name') == 'name' """ if name.islower(): result = name else: result = [] l0 = '' # char already added l1 = '' # char yet to be added for c in name: if c.islower(): if l1.isupper(): if l0.isupper() or l0.islower(): # ABc -> a_bc # aBc -> a_bc result.append('_') result.append(l1.lower()) else: # _Bc -> _bc result.append(l1.lower()) else: result.append(l1) else: # same rules for upper or non-letter if l1.isupper(): if l0.isupper(): # ABC -> ab... # AB_ -> ab_ result.append(l1.lower()) elif l0.islower(): # aBC -> a_b... # aB_ -> a_b_ result.append('_') result.append(l1.lower()) else: # _BC -> _b... # _B_ -> _b_ result.append(l1.lower()) else: result.append(l1) l0 = l1 l1 = c # name finishes with upper rules if l1.isupper(): if l0.isupper(): # AB -> ab result.append(l1.lower()) elif l0.islower(): # aB -> a_b result.append('_') result.append(l1.lower()) else: # _B -> _b result.append(l1.lower()) else: result.append(l1) result = ''.join(result) return result
def template_alternate_precedence(trace, event_set): """ precedence(A, B) template indicates that event B should occur only if event A has occurred before. Alternate condition: "events must alternate without repetitions of these events in between" :param trace: :param event_set: :return: """ # exactly 2 event assert (len(event_set) == 2) event_1 = event_set[0] event_2 = event_set[1] if event_2 in trace: if event_1 in trace: # Go through two lists, one by one # first events pos must be before 2nd lists first pos etc... # A -> A -> B -> A -> B # efficiency check event_1_count = len(trace[event_1]) event_2_count = len(trace[event_2]) # There has to be more or same amount of event A's compared to B's if event_2_count > event_1_count: return 0, False event_1_positions = trace[event_1] event_2_positions = trace[event_2] # Go through all event 2's, check that there is respective event 1. # Find largest event 1 position, which is smaller than event 2 position # implementation # Check 1-forward, the 1-forward has to be greater than event 2 and current one has to be smaller than event2 event_1_ind = 0 for i, pos2 in enumerate(event_2_positions): # find first in event_2_positions, it has to be before next in event_1_positions while True: if event_1_ind >= len(event_1_positions): # out of preceding events, but there are still event 2's remaining. return -1, False next_event_1_pos = None if event_1_ind < len(event_1_positions) - 1: next_event_1_pos = event_1_positions[event_1_ind + 1] event_1_pos = event_1_positions[event_1_ind] if next_event_1_pos: if event_1_pos < pos2 and next_event_1_pos > pos2: # found the largest preceding event event_1_ind += 1 break elif event_1_pos > pos2 and next_event_1_pos > pos2: # no event larger return -1, False else: event_1_ind += 1 else: # if no next event, check if current is smaller if event_1_pos < pos2: event_1_ind += 1 break else: return -1, False # since there is no smaller remaining event count = len(event_2_positions) return count, False else: # impossible because there has to be at least one event1 with event2 return -1, False return 0, True
def ak_expected(): """ Fixture to create example cosine coefficients """ return [6, -1]
def ensure_list(value): """Wrap value in list if it is not one.""" if value is None: return [] return value if isinstance(value, list) else [value]
def find_by_id(object_id, items): """ Find an object given its ID from a list of items """ for item in items: if object_id == item["id"]: return item raise Exception(f"Item with {object_id} not found")
def overall_accuracy_calc(TP, POP): """ Calculate overall accuracy. :param TP: true positive :type TP : dict :param POP: population :type POP:int :return: overall_accuracy as float """ try: overall_accuracy = sum(TP.values()) / POP return overall_accuracy except Exception: return "None"
def check_letter(row, col, board): """ check cell in row and col to see if it's a head letter of a word :param row: row starting from 0 :param col: col starting from 0 :param board: a list consists of 0 and 1 converted from original board :return: head_value 0 not a head letter 1 or 0b01 is a head letter of a word across 2 or 0b10 is a head letter of a word down 3 or 0b11 is a head letter for both a word across and a word down """ # check 11 pattern for first row and first column # check 011 pattern for other rows and columns assert row <= len(board) - 1 assert col <= len(board[0]) - 1 head_value = 0 if board[row][col] == "1": # check down word if row == 0: if board[row+1][col] == "1": head_value += 2 elif board[row-1][col] == "0" and board[row+1][col] == "1": head_value += 2 # check across word if col == 0: if board[row][col+1] == "1": head_value += 1 elif board[row][col-1] == "0" and board[row][col+1] == "1": head_value += 1 return head_value
def merge(items1, items2): """Merge given lists of items, each assumed to already be in sorted order, and return a new list containing all items in sorted order. DONE: Running time: O(n), since the lists are iterated over and merged in linear time. DONE: Memory usage: O(n), since an auxiliary list is created.""" sorted_list = [] i, j = 0, 0 # DONE: Repeat until one list is empty while i < len(items1) and j < len(items2): # DONE: Find minimum item in both lists and append it to new list if items1[i] <= items2[j]: sorted_list.append(items1[i]) i += 1 else: sorted_list.append(items2[j]) j += 1 # DONE: Append remaining items in non-empty list to new list if i < len(items1): sorted_list.extend(items1[i:]) elif j < len(items2): sorted_list.extend(items2[j:]) return sorted_list
def _strip_to_integer(trigger): """Return only the integer part of a string.""" return int("".join([x for x in trigger if x.isdigit()]))
def add_frame_div_parent(cell_info): """ Adds the frame a cells parent divides on to cell info. Args: cell_info (dict): dict that maps cells to cell info Returns: dict: cell info with added frame_div_parent """ new_info = cell_info.copy() for info in new_info.values(): if info['parent']: parent = info['parent'] info['frame_div_parent'] = new_info[parent]['frame_div'] else: info['frame_div_parent'] = None return new_info
def get_race_infos(results): """ Returns general information for the race """ race = {} race["league_name"] = results["league_name"] race["start_time"] = results["start_time"] race["track_id"] = results["track"]["track_id"] race["track_name"] = results["track"]["track_name"] race["config_name"] = results["track"]["config_name"] return race
def subarray_slice(index, num_items): """ Returns a slice that selects for selecting a chunk out of an array @param index: Which chunk to select @param num_items: Number of items in a chunk @return A slice for selecting index*num_items to (index+1)*num_items """ return slice(index * num_items, (index+1) * num_items)
def fno_to_na(fno): """Convert an fno to an NA. Parameters ---------- fno : `float` focal ratio Returns ------- `float` NA. The NA of the system. """ return 1 / (2 * fno)
def child_request_dict(ts_epoch): """A child request represented as a dictionary.""" return { "system": "child_system", "system_version": "1.0.0", "instance_name": "default", "namespace": "ns", "command": "say", "id": "58542eb571afd47ead90d25f", "parameters": {}, "comment": "bye!", "output": "nested output", "output_type": "STRING", "status": "CREATED", "hidden": True, "command_type": "ACTION", "created_at": ts_epoch, "updated_at": ts_epoch, "status_updated_at": ts_epoch, "error_class": None, "metadata": {"child": "stuff"}, "has_parent": True, "requester": "user", }
def _hyperparameters_to_cmd_args(hyperparameters): """ Converts our hyperparameters, in json format, into key-value pair suitable for passing to our training algorithm. """ cmd_args_list = [] for key, value in hyperparameters.items(): cmd_args_list.append('--{}'.format(key)) cmd_args_list.append(value) return cmd_args_list
def clean_text(text): """ Cleans words of newline character. """ cleaned_text = [] for line in text: cleaned_word = line.replace('\n', '') if len(line) >= 5: cleaned_text.append(cleaned_word) return cleaned_text
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 get_module_name(name): """Gets the name according to the config parser.""" return name.split('.')[0]
def position_similarity(el1, el2, seq1, seq2): """ Get the normalized inverted movement cost for for between `el1` and `el2` on the `seq2` iterable. The function is used to get a value describing how far two words are in a phrase (as list, as in ``string.split(' ')`` or, in our case through :func:`search.utils.tokenize`). Moves are relative to el1 on seq1, which `should` be the longest set for the function to work properly. .. warning:: The function is currently broken and always returns 1, making the position inside the matching string irrelevant. .. note:: The given strings **MUST** be inside the corresponding list. Arguments: el1 (any): element of the ``seq1`` iterable el2 (any): element of the ``seq2`` iterable seq1 (iterable): iterable allowing the ``index`` method containing the `el1` element. seq2 (iterable): iterable allowing the ``index`` method containing the `el2` element. Returns: float: value ``0 -> 1`` representing how far the two words are, where ``1`` represent the closest(same position) and tending to zero the farthest on the maximum available moves possible on ``seq1``. """ return 1 # FIXME: Something's wrong here. # Function left `on hold` with a return 1 since we need a value and 1 # should be the default value for "everything is where is supposed to be" # ------------------------------------------------------------------------- # The function SHOULD return a value representing a ratio of word (el1) # position inside the sequence that contains it (seq1) relative to the # other element (el2) on its sequence (seq2). # The reason for this function to exist is to have a value that tells the # rest of the search algoritm how much an element is offset relative to # the supposed position, allowing the search to give more weight to # queries that are written exactly as they are found, while i.e. inverted # order should have little less weight. # The idea is to have a 1 when: # * len(seq1) == len(seq2) AND indexes of elements are the same: # 'hi, hello there', 'yo, hello world' -> ('there', 'world') # * lengths are different BUT the el1 is proportionally at about the same # position in seq1 as el2 is on el2: # 'hello world, 'hello there, how are you' -> ('world', 'are') # meaning that the elements are more or less in the same "spot". # * one of the two sequences have length 1: # should be irrelevant any type of calculus since the relative position # of such word will be 0 (index/length) or the reciprocal will be 1 # (1 - idx/len) # # All other cases should return a value between 1 and ->0, tending toward # 0 the more the longest sequence is long. # ========================================================================= long_, short = seq1, seq2 el_long, el_short = el1, el2 len_long, len_short = len(seq1), len(seq2) if len_long == 1 or len_short == 1: # useless to count as this would # * cause a ZeroDivisionError (no moves available) # * return 1 in any case since the algorithm NEEDS to return 1 if one # of the two sequence is of len 1 return 1 if len_short > len_long: # Reverse if needed # NOTE: This should be ok and would prevent dumbness when setting up # the function call long_, short = short, long_ el_long, el_short = el_short, el_long len_long, len_short = len_short, len_long long_idx = long_.index(el_long) short_idx = short.index(el_short) moves = abs(long_idx - short_idx) max_moves = utils.max_distance(long_, word_index=long_idx) return abs(1 - (moves / max_moves))
def _get_block_sizes_v2(resnet_size): """Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resnet_size: The number of convolutional layers needed in the model. Returns: A list of block sizes to use in building the model. Raises: KeyError: if invalid resnet_size is received. Remarks: Used in gt_ressize_dependent_params_v2. """ choices = { 18: [2, 2, 2, 2], 34: [3, 4, 6, 3], 50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3], 200: [3, 24, 36, 3], } try: return choices[resnet_size] except KeyError: err = ('Could not find layers for selected Resnet v2 size.\n' 'Size received: {}; sizes allowed: {}.'.format( resnet_size, choices.keys())) raise ValueError(err)
def _unicode(s): """ A helper function for converting to Unicode """ if isinstance(s, str): return s elif isinstance(s, bytes): return s.decode('utf-8') else: raise ValueError("Expected unicode or ascii string, got %s" % type(s))
def _validate_as_instance(item, target_type): """ Validates that the item is an instance of the target_type and if not, checks whether the item is the Parameters ---------- item : target_type target_type : type Returns ------- target_type the item as an instance of the target type Raises ------ TypeError if the passed item isn't either target_type or an instance thereof """ if not isinstance(item, target_type): try: item = _validate_as_instance(item(), target_type) except: raise TypeError( "{} can't be parsed as a {}.".format(item, target_type) ) return item
def dict2str(data): """ Create a string with a whitespace and newline delimited text from a dictionary. For example, this: {'cpu': '1100', 'ram': '640', 'smp': 'auto'} becomes: cpu 1100 ram 640 smp auto cpu 2200 ram 1024 """ result = '' for k in data: if data[k] != None: result += '%s %s\n' % (str(k), str(data[k])) else: result += '%s\n' % str(k) return result
def restoreString(s, indices): """ :type s: str :type indices: List[int] :rtype: str """ shuffle_str = "" for i in range(len(indices)): shuffle_str += s[indices.index(i)] return shuffle_str
def check_instructors(instructors): """ 'instructor' must be a non-empty comma-separated list of quoted names, e.g. ['First name', 'Second name', ...']. Do not use 'TBD' or other placeholders. """ # YAML automatically loads list-like strings as lists. return isinstance(instructors, list) and len(instructors) > 0
def occurrences(x, lst): """Count the number of occurrences of x in lst.""" return len(list(filter(lambda e: x == e, lst)))
def is_symmetric(A): """Tells whether a matrix is a symmetric matrix or not. Args ---- A (compulsory) A matrix. Returns ------- bool True if the matrix is a diagonal matrix, False otherwise. """ for i in range(len(A)): for j in range(len(A[0])): try: if A[i][j] != A[j][i]: return False except IndexError: #Would happen if matrix is not square. return False return True
def getExtension(fname): """ Gets extension from the file name. Returns without the dot (.) """ a = fname.rfind('.') return fname[a+1:]
def same_notebook_code(nb1, nb2): """ Return true of the code cells of notebook objects `nb1` and `nb2` are the same. """ # Notebooks do not match of the number of cells differ if len(nb1['cells']) != len(nb2['cells']): return False # Iterate over cells in nb1 for n in range(len(nb1['cells'])): # Notebooks do not match if corresponding cells have different # types if nb1['cells'][n]['cell_type'] != nb2['cells'][n]['cell_type']: return False # Notebooks do not match if source of corresponding code cells # differ if nb1['cells'][n]['cell_type'] == 'code' and \ nb1['cells'][n]['source'] != nb2['cells'][n]['source']: return False return True
def calculate_pizzas_recursive(participants, n_pizza_types, pizza_types): """ This function calculates the order list for pizzas, for a given number of participants. Recursive See: https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/ """ # No participants left if(n_pizza_types <= 0 or participants <= 0): return 0, None # If weight of the nth item is more than Knapsack of capacity # W, then this item cannot be included in the optimal solution if(pizza_types[-1] > participants): return calculate_pizzas_recursive(participants, n_pizza_types-1, pizza_types[:-1]) # If it fits: Always do a binary split to include it or not # By doing so, the case where no element at all is a solution is checked, # which seems quite senseless # A lot of stuff is calculated way to often by doing so temp, temp_idx = calculate_pizzas_recursive(participants-pizza_types[-1], n_pizza_types-1, pizza_types[:-1]) last_element_included = pizza_types[-1] + temp last_element_not_included, _ = calculate_pizzas_recursive(participants, n_pizza_types-1, pizza_types[:-1]) # Return the maximum of both cases because: # The maximum can never be exceed, so this is save, but the higher # the closer the addition until the maximum worked then if last_element_included >= last_element_not_included: print(n_pizza_types-1) return last_element_included, n_pizza_types-1 else: return last_element_not_included, None
def factors(number): """Give a list of all the facotrs of given natural number.""" if number > 1: return [i for i in range(1, number) if number % i == 0] elif number == 1: return [] else: raise ValueError("Requires a Natural number")
def crop_list(timelist, min_len): """ Crop out items shorter than min len """ croped_list = [] for i in timelist: # Don't keep items if start time shifted forward # by min length, is greater than end time. if i[0].shift(minutes=+min_len) <= i[1]: croped_list.append(i) return croped_list
def _num_requests_needed(num_repos, factor=2, wiggle_room=100): """ Helper function to estimate the minimum number of API requests needed """ return num_repos * factor + wiggle_room
def count_bits(n): """ Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative. """ result = "" f_num = f"{n:08b}" for el in f_num: if el == "1": result += el return len(result)
def escape(inp, char_pairs): """Escape reserved characters specified in the list of tuples `char_pairs` Parameters ---------- inp : str Input string chair_pairs : list List of tuples of (character, escape sequence for character) Returns ------- str Escaped output See also -------- unescape_GFF3 """ for char_, repl in char_pairs: inp = inp.replace(char_, repl) return inp