content
stringlengths
42
6.51k
def token_combiner(tokens): """Dummy token combiner.""" return ''.join(tokens)
def slice_to_range(slicer, r_max): """Convert a slice object to the corresponding index list""" step = 1 if slicer.step is None else slicer.step if slicer.start is None: start = r_max - 1 if step < 0 else 0 else: start = slicer.start if slicer.stop is None: stop = -1 if step < 0 else r_max else: stop = slicer.stop # start = 0 if slicer.start is None else slicer.start # stop = r_max if slicer.stop is None else slicer.stop return range(start, stop, step)
def isFile(path: str): """ Check whether path points to a file """ from os.path import isfile return isfile(path)
def _fabric_network_ipam_name(fabric_name, network_type): """ :param fabric_name: string :param network_type: string (One of the constants defined in NetworkType) :return: string """ return '%s-%s-network-ipam' % (fabric_name, network_type)
def path_directories(path_dirs: dict): """ Setting up the desired path directories for each type of file to be converted :return: """ # Setting up the finances trips_tuple = (path_dirs['trips_path'], path_dirs['trips_csv_folder'], path_dirs['trips_sheet_tab'], path_dirs['trips_create_parent_table'] == "True", path_dirs['trips_name']) finances_tuple = (path_dirs['finances_path'], path_dirs['finances_csv_folder'], path_dirs['finances_sheet_tab'], path_dirs['finances_create_parent_table'] == "True", path_dirs['finances_name']) # Creating a dictionary of the tuples of the desired paths with tags path_dict = {trips_tuple: path_dirs['trips_name'], finances_tuple: path_dirs['finances_name']} return path_dict
def filter_running_tasks(tasks): """ Filters those tasks where it's state is TASK_RUNNING. :param tasks: a list of mesos.cli.Task :return filtered: a list of running tasks """ return [task for task in tasks if task['state'] == 'TASK_RUNNING']
def _arithmetic_mean(nums) -> float: """Return arithmetic mean of nums : (a1 + a2 + ... + an)/n""" return sum(nums) / len(nums)
def _backslashreplace_backport(ex): """Replace byte sequences that failed to decode with character escapes. Does the same thing as errors="backslashreplace" from Python 3. Python 2 lacks this functionality out of the box, so we need to backport it. Parameters ---------- ex: UnicodeDecodeError contains arguments of the string and start/end indexes of the bad portion. Returns ------- text: unicode The Unicode string corresponding to the decoding of the bad section. end: int The index from which to continue decoding. Note ---- Works on Py2 only. Py3 already has backslashreplace built-in. """ # # Based on: # https://stackoverflow.com/questions/42860186/exact-equivalent-of-b-decodeutf-8-backslashreplace-in-python-2 # bstr, start, end = ex.object, ex.start, ex.end text = u''.join('\\x{:02x}'.format(ord(c)) for c in bstr[start:end]) return text, end
def sort_dictionary(dictionary: dict, recursive: bool): """ Function to (recursively) sort dictionaries used for package data. This procedure is used to ensure that models always produce the same hash independent of the order of the keys in the dictionaries. Sorting is done by the Python internal sorting methods depending on the data. This means sorting only works for keys with same type and otherwise will throw a TypeError. """ if not isinstance(dictionary, dict): raise TypeError("input is not of type dict") if not isinstance(recursive, bool): raise TypeError("recursive is not of type bool") if recursive: for key, value in dictionary.items(): if isinstance(value, dict): dictionary[key] = sort_dictionary(value, recursive) return dict(sorted(dictionary.items(), key=lambda kv: (kv[0], kv[1])))
def normalize_color(color): """Gets a 3-tuple of RGB ints and return a 3-tuple of unity floats""" return (color[0] / 255.0, color[1] / 255.0, color[2] / 255.0)
def is_nested_dict(item): """ Check if item provides a nested dictionary""" item = next(iter(item.values())) return isinstance(item, dict)
def get_marker(func_item, mark): """ Getting mark which works in various pytest versions """ pytetstmark = [m for m in (getattr(func_item, 'pytestmark', None) or []) if m.name == mark] if pytetstmark: return pytetstmark[0]
def space_tokenizer(sequence): """ Splits sequence based on spaces. """ if sequence: return sequence.split(' ')
def escape_jira_strings(v): """in JIRA ticket body, "{" and "[" are special symbols that need to be escaped""" if type(v) is str: return v.replace(r"{", r"\{").replace(r"[", r"\[") if type(v) is list: return [escape_jira_strings(x) for x in v] return escape_jira_strings(str(v))
def findHomozygotes(diptable={}): """ Given a summary table of diploids, finds those which are homozygous """ mydiptable=diptable homozygouslist=[] mydipkeys=mydiptable.keys() for key in mydipkeys: if key[0]==key[1]: homozygouslist.append(key) homozygtable = {} for key in homozygouslist: homozygtable[key] = mydiptable[key] return homozygtable
def _list_to_tuple(v): """Convert v to a tuple if it is a list.""" if isinstance(v, list): return tuple(v) return v
def _kern_class(class_definition, coverage_glyphs): """Transpose a ttx classDef {glyph_name: idx, glyph_name: idx} --> {idx: [glyph_name, glyph_name]} Classdef 0 is not defined in the font. It is created by subtracting the glyphs found in the lookup coverage against all the glyphs used to define the other classes.""" classes = {} seen_glyphs = set() for glyph, idx in class_definition.items(): if idx not in classes: classes[idx] = [] classes[idx].append(glyph) seen_glyphs.add(glyph) classes[0] = set(coverage_glyphs) - seen_glyphs return classes
def base_url(server, app): """Base URL for the running application.""" return f"http://127.0.0.1:{server['port']}"
def cl_labels(dim): """ Return the classical-basis labels based on a vector dimension. Parameters ---------- dim : int The dimension of the basis to generate labels for (e.g. 2 for a single classical bit). Returns ------- list of strs """ if dim == 0: return [] if dim == 1: return [''] # special case - use empty label instead of "0" return ["%d" % i for i in range(dim)]
def move_point(point): """Move point by it velocity.""" for index, change in enumerate(point['velocity']): point['position'][index] += change return point
def countBits(n): """ :type num: int :rtype: List[int] """ # Approach 1: # res = [0] # for i in range(1, n+1): # res.append(res[i>>1] + (i&1)) # return res # Approach 2: # res = [0] # for i in range(1, n+1): # res.append(res[i&(i-1)] + 1) # return res # Approach 3: # res = [0] # for i in range(1, n+1): # res.append(res[i&(i-1)] + 1) # return res # Approach 4: # res = [0] # for i in range(1, n+1): # res.append(res[i&(i-1)] + 1) # return res # Approach 5: # res = [0] # for i in range(1, n+1): # res.append(res[i&(i-1)] + 1) # return res # Approach 6: # res = [0] # for i in range(1, n+1): # res.append(res[i&(i-1)] + 1) # return res # Approach 7: # res = [0] # for i in range(1, n+1): # res.append(res[i&(i-1)] + 1) # return res # Approach 8: # res = [0] # for i in range(1, n+1): # res.append(res[i&(i-1)] + 1) # return res # Approach 9: res = [0] for i in range(1, n+1): res.append(res[i & (i-1)] + 1) return res
def precision_from_tpr_fpr(tpr, fpr, positive_prior): """ Computes precision for a given positive prevalence from TPR and FPR """ return (positive_prior * tpr) / ((positive_prior * tpr) + ((1 - positive_prior) * fpr))
def remove_timestamp(html_text): """ Return the `html_text` generated attribution stripped from timestamps: the timestamp is wrapped in italic block in the default template. """ return '\n'.join(x for x in html_text.splitlines() if not '<i>' in x)
def utf_encode_list(text): """utf encode every element of a list.""" return [x.encode('utf-8') for x in text]
def SPAlt( ang ): """ Returns list ang cycled such that the ang[2] is the smallest angle """ indexMin = 0 itemMin = 360 for i, item in enumerate( ang ): if (item < itemMin): indexMin = i itemMin = item return ( ang[(indexMin-2)%4:] + ang[:(indexMin-2)%4] )
def handler(context, inputs): """Set a name for a machine :param inputs :param inputs.resourceNames: Contains the original name of the machine. It is supplied from the event data during actual provisioning or from user input for testing purposes. :param inputs.newName: The new machine name to be set. :return The desired machine name. """ old_name = inputs["resourceNames"][0] new_name = inputs["customProperties"]["newName"] #new comment outputs = {} outputs["resourceNames"] = inputs["resourceNames"] outputs["resourceNames"][0] = new_name print("Setting machine name from {0} to {1}".format(old_name, new_name)) return outputs
def _is_internal_name(name): """Determine whether or not *name* is an "__internal" name. :param str name: a name defined in a class ``__dict__`` :return: ``True`` if *name* is an "__internal" name, else ``False`` :rtype: bool """ return name.startswith("__") and not name.endswith("__")
def sphere(ind): """Sphere function defined as: $$ f(x) = \sum_{i=1}^{n} x_i^{2} $$ with a search domain of $-5.12 < x_i < 5.12, 1 \leq i \leq n$. The global minimum is at $f(x_1, ..., x_n) = f(0, ..., 0) = 0. It is continuous, convex and unimodal. """ return sum((x ** 2. for x in ind)),
def get_layer_parents(adjList,lidx): """ Returns parent layer indices for a given layer index. """ # Return all parents (layer indices in list) for layer lidx return [e[0] for e in adjList if e[1]==lidx]
def generate_sql_query_cmd(sql_event_name_condition_arg, sql_event_time_condition_arg): """ The function to generate completed SQL query command. @param sql_event_name_condition_arg The SQL condition of event name. @param sql_event_time_condition_arg The SQL condition of event time. @return The completed SQL query command string. """ #sql_query_cmd = "SELECT ChannelID, StartTime, EndTime FROM (SELECT ClipID, ChannelID, StartTime, EndTime FROM AVClip UNION SELECT ClipID, ChannelID, StartTime, EndTime FROM RecentAVClip) AS AVClipsTable WHERE ClipID IN (SELECT clip_id FROM EventClip WHERE event_his_id IN (SELECT event_his_id FROM EventHistory WHERE " + sql_event_time_condition_arg + " and " + sql_event_name_condition_arg + "))" sql_query_cmd = "SELECT ChannelID, StartTime, EndTime, EventsTable.event_name FROM (SELECT ClipID, ChannelID, StartTime, EndTime FROM AVClip UNION SELECT ClipID, ChannelID, StartTime, EndTime FROM RecentAVClip) AS AVClipsTable, (SELECT EventClip.*, ConditionalEvent.event_name from EventClip, (SELECT event_his_id,event_name FROM EventHistory WHERE " + sql_event_time_condition_arg + " and " + sql_event_name_condition_arg + ") As ConditionalEvent Where EventClip.event_his_id = ConditionalEvent.event_his_id) AS EventsTable WHERE AVClipsTable.ClipID = EventsTable.clip_id" return sql_query_cmd;
def fuzzy_match(pattern, instring, adj_bonus=5, sep_bonus=10, camel_bonus=10, lead_penalty=-3, max_lead_penalty=-9, unmatched_penalty=-1): """Return match boolean and match score. :param pattern: the pattern to be matched :type pattern: ``str`` :param instring: the containing string to search against :type instring: ``str`` :param int adj_bonus: bonus for adjacent matches :param int sep_bonus: bonus if match occurs after a separator :param int camel_bonus: bonus if match is uppercase :param int lead_penalty: penalty applied for each letter before 1st match :param int max_lead_penalty: maximum total ``lead_penalty`` :param int unmatched_penalty: penalty for each unmatched letter :return: 2-tuple with match truthiness at idx 0 and score at idx 1 :rtype: ``tuple`` """ score, p_idx, s_idx, p_len, s_len = 0, 0, 0, len(pattern), len(instring) prev_match, prev_lower = False, False prev_sep = True # so that matching first letter gets sep_bonus best_letter, best_lower, best_letter_idx = None, None, None best_letter_score = 0 matched_indices = [] while s_idx != s_len: p_char = pattern[p_idx] if (p_idx != p_len) else None s_char = instring[s_idx] p_lower = p_char.lower() if p_char else None s_lower, s_upper = s_char.lower(), s_char.upper() next_match = p_char and p_lower == s_lower rematch = best_letter and best_lower == s_lower advanced = next_match and best_letter p_repeat = best_letter and p_char and best_lower == p_lower if advanced or p_repeat: score += best_letter_score matched_indices.append(best_letter_idx) best_letter, best_lower, best_letter_idx = None, None, None best_letter_score = 0 if next_match or rematch: new_score = 0 # apply penalty for each letter before the first match # using max because penalties are negative (so max = smallest) if p_idx == 0: score += max(s_idx * lead_penalty, max_lead_penalty) # apply bonus for consecutive matches if prev_match: new_score += adj_bonus # apply bonus for matches after a separator if prev_sep: new_score += sep_bonus # apply bonus across camelCase boundaries if prev_lower and s_char == s_upper and s_lower != s_upper: new_score += camel_bonus # update pattern index iff the next pattern letter was matched if next_match: p_idx += 1 # update best letter match (may be next or rematch) if new_score >= best_letter_score: # apply penalty for now-skipped letter if best_letter is not None: score += unmatched_penalty best_letter = s_char best_lower = best_letter.lower() best_letter_idx = s_idx best_letter_score = new_score prev_match = True else: score += unmatched_penalty prev_match = False prev_lower = s_char == s_lower and s_lower != s_upper prev_sep = s_char in '_ ' s_idx += 1 if best_letter: score += best_letter_score matched_indices.append(best_letter_idx) return p_idx == p_len, score
def color_name_to_id(color_name: str) -> str: """ map color_name to hex color :param color_name: :return: """ color_id = { 'gray': '#A0A5AA', 'red': '#FA8282', 'orange': '#FA9C3E', 'yellow': '#F2CA00', 'green': '#94BF13', 'blue': '#499DF2', 'purple': '#A18AE6', } try: return color_id[color_name.lower()] except KeyError: raise KeyError('Color name error! Use gray/red/orange/yellow/green/blue/purple')
def GCD(x,y): """Takes two inputs and returns the Greatest common divisor and returns it""" while(y): x, y = y, x % y return x
def is_question(input_string): """ Function to determine if the input contains '?' Function taken from A3 Inputs: string Outputs: string """ if '?' in input_string: output = True return output else: output = False return output
def check_and_fix_names_starting_with_numbers(name): """ Since I3 map names cannot start with a number, add a letter 'a' to any names starting with a number Args: name: The name to check for a beginning number Returns: The new name (unchanged if the name properly started with a letter) """ result = name if name[0].isdigit(): result = "a" + name return result
def count_logistic(x): """Return value of a simple chaotic function.""" val = 3.9 * x * (1-x) return val
def clean_view(view_orig, superunits): """ Define a view of the system that comes from a view of another one. Superunits are cleaned in such a way that no inconsistencies are present in the new view. Args: view_orig (dict): the original view we would like to clean superunits (list): list of the new system's superunits Returns: dict: the new view of the system, where combined superunits are joined with the '+' symbol """ if view_orig is None: return None view = view_orig.copy() allvals = [] for k, val_orig in view_orig.items(): val = [v for v in val_orig] for v in val_orig: if v not in superunits: previous_k = '+'.join(val) if k in view: view.pop(k) else: view.pop(previous_k) val.remove(v) rek = '+'.join(val) view[rek] = val else: allvals.append(v) for k in list(view.keys()): if len(view[k]) == 0: view.pop(k) for k in superunits: if k not in allvals: view[k] = [k] return view
def group_uris(cesnet_groups): """Group URIs fixture.""" return { 'exists': 'urn:geant:cesnet.cz:groupAttributes:f0c14f62-b19c-447e-b044-c3098cebb426?=displayName=example#perun.cesnet.cz', 'new': 'urn:geant:cesnet.cz:groupAttributes:f0c14f62-b19c-447e-b044-c3098c3bb426?=displayName=new#perun.cesnet.cz', 'invalid': 'urn:geant:cesnet.cz:group:f0c14f62-b19c-447e-b044-c3098cebb426#perun.cesnet.cz' }
def transform_json_from_studio_to_vulcan(studio_json): """Transforms a json from the studio format to the vulcan format.""" # Initialize variables vulcan_json = [] # Loop through all studio images for studio_image in studio_json['images']: # Initialize vulcan prediction vulcan_pred = {'outputs': [{'labels': {'discarded': [], 'predicted': []}}]} predicted = [] discarded = [] for metadata in ['location', 'data']: if metadata in studio_image: vulcan_pred[metadata] = studio_image[metadata] # Loop through all studio predictions for studio_pred in studio_image['annotated_regions']: # Build vulcan annotation annotation = { 'label_name': studio_pred['tags'][0], 'score': studio_pred['score'], 'threshold': studio_pred['threshold'] } # Add bounding box if needed if studio_pred['region_type'] == 'Box': annotation['roi'] = { 'bbox': { 'xmin': studio_pred['region']['xmin'], 'xmax': studio_pred['region']['xmax'], 'ymin': studio_pred['region']['ymin'], 'ymax': studio_pred['region']['ymax'] } } # Update json if annotation['score'] >= annotation['threshold']: predicted.append(annotation) else: discarded.append(annotation) # Sort by prediction score of descending order predicted = sorted(predicted, key=lambda k: k['score'], reverse=True) discarded = sorted(discarded, key=lambda k: k['score'], reverse=True) vulcan_pred['outputs'][0]['labels']['predicted'] = predicted vulcan_pred['outputs'][0]['labels']['discarded'] = discarded # Update vulcan json vulcan_json.append(vulcan_pred) return vulcan_json
def cubic_ease_out(p): """Modeled after the cubic y = (x - 1)^3 + 1""" f = p - 1 return (f * f * f) + 1
def make_key(app_id, app_key, task_id): """This is a naming convention for both redis and s3""" return app_id + "/" + app_key + "/" + task_id
def dataset_name_normalization(name: str) -> str: """Normalize a dataset name.""" return name.lower().replace('_', '')
def construct_version_string(major, minor, micro, dev=None): """ Construct version tag: "major.minor.micro" (or if 'dev' is specified: "major.minor.micro-dev"). """ version_tag = f"{major}.{minor}.{micro}" if dev is not None: version_tag += f"-{dev}" return version_tag
def move_to_corner(move): """Take a move ('color', (row,col)). where row, col are 0-indexed (from sgfmill) Figure out which corner it's in Transform it to be in the upper right corner; Returns [corners, move] corners: A list of the indices of the corners it is in (0-3) move: The transformed move """ color, m = move if not m: return (None, move) y, x = m corners = [] if (x >= 9 and y >= 9): corners.append(0) elif (x >= 9 and y <= 9): corners.append(1) elif (x <= 9 and y <= 9): corners.append(2) elif (x <= 9 and y >= 9): corners.append(3) y -= 9 x -= 9 y = abs(y) x = abs(x) y += 9 x += 9 return [corners, (color, (y, x))]
def processPupil(pupil_positions, pupil_coulmn, recStartTimeAlt, filterForConf, confidence_threshold): """extract the pupil data from the eye traker to get standar deviation, mean, and filter the dataset""" diameters = [] frames = [] timeStamps = [] simpleTimeStamps = [] confidence = [] confidenceThreshold = 0.1 if filterForConf: confidenceThreshold = confidence_threshold for row in pupil_positions: timeStamp = float(row[0]) if (float(row[3]) > confidenceThreshold): timeStamps.append(timeStamp) simpleTimeStamps.append(timeStamp-recStartTimeAlt) frames.append(int(row[1])) confidence.append(float(row[3])) diameters.append(float(row[pupil_coulmn])) return diameters, timeStamps, frames, simpleTimeStamps, confidence
def expand_dict(info): """ converts a dictionary with keys of the for a:b to a dictionary of dictionaries. Also expands strings with ',' separated substring to a list of strings. :param info: dictionary :return: dictionary of dictionaries """ res = {} for key, val in info.items(): a, b = key.split(':') if len(val) == 1: val = val[0] if ',' in val: val = [v.strip() for v in val.split(',')] else: if b == 'tag': val = val[0] else: val = ','.join(val) if val == 'False': val = False elif val == 'True': val = True try: res[a][b] = val except KeyError: res[a] = {b: val} return res
def all_but_axis(i, axis, num_axes): """ Return a slice covering all combinations with coordinate i along axis. (Effectively the hyperplane perpendicular to axis at i.) """ the_slice = () for j in range(num_axes): if j == axis: the_slice = the_slice + (i, ) else: the_slice = the_slice + (slice(None), ) return the_slice
def rgb(value, minimum, maximum): """ Calculates an rgb color of a value depending of the minimum and maximum values. Parameters ---------- value: float or int minimum: float or int maximum: float or int Returns ------- rgb: tuple """ value = float(value) minimum = float(minimum) maximum = float(maximum) if minimum == maximum: ratio = 0 else: ratio = 2 * (value - minimum) / (maximum - minimum) b = int(max(0, 255 * (1 - ratio))) r = int(max(0, 255 * (ratio - 1))) g = 255 - b - r return r / 255.0, g / 255.0, b / 255.0
def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> rankine_to_kelvin(0) 0.0 >>> rankine_to_kelvin(20.0) 11.11 >>> rankine_to_kelvin("40") 22.22 >>> rankine_to_kelvin("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) * 5 / 9), ndigits)
def chain_remaining_sets(first, prev, remaining_sets): """ Search remaining_sets for candidates that can chain with prev, recursively, until all sets have been used to take exactly 1 candidate from first: if len(remaining_sets) == 1, we must close the chain with first two digits of first prev: must chain with last two digits of prev remaining_sets: the sets we can use to look for the next chain element return: None if there is no closed-loop chain, otherwise the array making the chain """ new_prefix = prev % 100 for index, candidate_set in enumerate(remaining_sets): for candidate in candidate_set: if candidate // 100 == new_prefix: # This could work. Check if it can form a chain if len(remaining_sets) == 1: if candidate % 100 == first // 100: # We found a chain! return [candidate] else: # Recurse to see if this candidate works out down the line sub_chain = chain_remaining_sets(first, candidate, remaining_sets[:index] + remaining_sets[index+1:]) if sub_chain: return [candidate] + sub_chain return None
def index2string(index): """ Convert an int to string Parameter --------- index: int index to be converted Return ------ string: string string corresponding to the string """ if index == 0: string = 'BENIGN' elif index == 1: string = 'FTP-Patator' elif index == 2: string = 'SSH-Patator' elif index == 3: string = 'DoS Hulk' elif index == 4: string = 'DoS GoldenEye' elif index == 5: string = 'DoS slowloris' elif index == 6: string = 'DoS Slowhttptest' elif index == 7: string = 'Heartbleed' elif index == 8: string = 'Web Attack Brute Force' elif index == 9: string = 'Web Attack XSS' elif index == 10: string = 'Web Attack Sql Injection' elif index == 11: string = 'Infiltration' elif index == 12: string = 'Bot' elif index == 13: string = 'PortScan' elif index == 14: string = 'DDoS' else: print("[ERROR] Cannot convert {}".format(index)) string = 'Error' return string
def get_value(state: dict, key: str): """ get the value of a given key in the state :param state: the dict :param key: key, can be a path like color/r :return: the value if found or None """ k = key.split("/", 1) if len(k) > 1: if k[0] not in state: return None else: return get_value(state[k[0]], k[1]) else: if key in state: return state[key] return None
def tract_id_equals(tract_id, geo_id): """ Determines if a 11-digit GEOID (from the US census files) refers to the same place as a six-digit Chicago census tract ID. :param tract_id: A 6-digit Chicago census tract ID (i.e., '821402') :param geo_id: An 11-digit GEOID from the US Census "Gazetteer" files (i.e., '17031821402') :return: True if equivalent, False otherwise """ return geo_id.startswith("1703") and tract_id == geo_id[-6:]
def req_yaml_template(pip=False, version=True, build=False): """ Builds a template string for requirement lines in the YAML format. :pip: [bool] Whether to build a Conda requirement line or a pip line :version: [bool] Includes the version template :build: [bool] Includes the build template. Makes version "=*" if the `version` is False for Conda packages. :returns: [str] The requirement string template. """ template_str = '{name}' if version: template_str += '=={version}' if pip else '={version}' if build and not pip: if not version: template_str += '=*' template_str += '={build_string}' return template_str
def reverse_map(k_map): """ Return the reversed map from k_map Change each 1 by 0, and each 0 by a 1 """ r_map = [] for line in k_map: r_line = [] for case in line: r_line.append(not case) r_map.append(r_line) return r_map
def deg2dmm(degrees: float, latlon: str) -> str: """ Convert decimal degrees to degrees decimal minutes string. :param float degrees: degrees :param str latlon: "lat" or "lon" :return: degrees as dm.m formatted string :rtype: str """ if not isinstance(degrees, (float, int)): return "" negative = degrees < 0 degrees = abs(degrees) degrees, minutes = divmod(degrees * 60, 60) if negative: sfx = "S" if latlon == "lat" else "W" else: sfx = "N" if latlon == "lat" else "E" return str(int(degrees)) + "\u00b0" + str(round(minutes, 5)) + "\u2032" + sfx
def is_identifier_match(identifier: str, project: dict) -> bool: """ Determines whether or not the specified identifier matches any of the criteria of the given project context data values and returns the result as a boolean. """ matches = ( '{:.0f}'.format(project.get('index', -1) + 1), project.get('uid', ''), project.get('name', '') ) return next( (True for m in matches if identifier == m), False )
def _fix_slice(slc): """ Fix up a slc object to be tuple of slices. slc = None is treated as no slc slc is container and each element is converted into a slice object None is treated as slice(None) Parameters ---------- slc : None or sequence of tuples Range of values for slicing data in each axis. ((start_1, end_1, step_1), ... , (start_N, end_N, step_N)) defines slicing parameters for each axis of the data matrix. """ if slc is None: return None # need arr shape to create slice fixed_slc = list() for s in slc: if not isinstance(s, slice): # create slice object if s is None or isinstance(s, int): # slice(None) is equivalent to np.s_[:] # numpy will return an int when only an int is passed to np.s_[] s = slice(s) else: s = slice(*s) fixed_slc.append(s) return tuple(fixed_slc)
def _update(s, _lambda, P): """ Update ``P`` such that for the updated `P'` `P' v = e_{s}`. """ k = min([j for j in range(s, len(_lambda)) if _lambda[j] != 0]) for r in range(len(_lambda)): if r != k: P[r] = [P[r][j] - (P[k][j] * _lambda[r]) / _lambda[k] for j in range(len(P[r]))] P[k] = [P[k][j] / _lambda[k] for j in range(len(P[k]))] P[k], P[s] = P[s], P[k] return P
def create_gap_from_distmat(matrix, s, t): """Creates gapped strings based on distance matrix.""" gapped_s, gapped_t = '', '' i, j = len(s), len(t) while (i > 0 and j > 0): left = matrix[i][j - 1] up = matrix[i - 1][j] diag = matrix[i - 1][j - 1] best = min(left, up, diag) if matrix[i][j] == best: # match gapped_s = s[i - 1] + gapped_s gapped_t = t[j - 1] + gapped_t i -= 1 j -= 1 elif (best == left and best == up) or (best != left and best != up): # mismatch gapped_s = s[i - 1] + gapped_s gapped_t = t[j - 1] + gapped_t i -= 1 j -= 1 elif best != left and best == up: # gap in second string gapped_s = s[i - 1] + gapped_s gapped_t = '-' + gapped_t i -= 1 elif best == left and best != up: # gap in first string gapped_s = '-' + gapped_s gapped_t = t[j - 1] + gapped_t j -= 1 else: print('shouldnt get here') # pragma: no cover return 0 # pragma: no cover return gapped_s, gapped_t
def clean(input_list, exclude_list=[]): """Returns list with digits, numberwords and useless words from list of key phrases removed Inputs: input_list -- List of strings containing key phrases to be processed exclude_list -- List of strings containing words to be removed Output: output_list -- List of key phrases with words from exclude_list removed """ nums = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten' 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen' 'eighteen', 'nineteen', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninty', 'hundred'] stopwords = ['mhm', 'yeah', 'um', 'ah', 'a', 'the', 'o.k.', 'your', 'hm', 'oh' 'okay', 'my', 'that', 'i', 'alright', 'bye', 'uh', 'i i', 'oh'] if not exclude_list: exclude_list = nums + stopwords output_list = [] for phrase in input_list[:]: split_phrase = phrase.split(' ') for word in split_phrase[:]: if word.lower() in exclude_list or word.isdigit(): split_phrase.remove(word) new_phrase = ' '.join(split_phrase) if new_phrase is '': continue else: output_list.append(new_phrase.lower()) return output_list
def simpsons_diversity_index(*args): """ From https://en.wikipedia.org/wiki/Diversity_index#Simpson_index The measure equals the probability that two entities taken at random from the dataset of interest represent the same type. """ if len(args) < 2: return 0 def __n_times_n_minus_1(number): return number * (number - 1) try: return int( round( ( 1.0 - ( float(sum(map(__n_times_n_minus_1, args))) / float(sum(args) * (sum(args) - 1)) ) ) * 100.0 ) ) except ZeroDivisionError: return 0
def dict_map_leaves(nested_dicts, func_to_call): """ Applies a given callable to the leaves of a given tree / set of nested dictionaries, returning the result (without modifying the original dictionary) :param nested_dicts: Nested dictionaries to traverse :param func_to_call: Function to call on the 'leaves' of those nested dictionaries :return: Result of the transformation (dict) Note that this and all the functions above use the exact same algorithm/pattern for tree traversal. We could reduce duplication by refactoring it into a function, but that might make the code less readable. """ to_update = dict(nested_dicts) for k, v in nested_dicts.items(): if isinstance(v, dict): to_update[k] = dict_map_leaves(v, func_to_call) else: to_update[k] = func_to_call(v) return to_update
def grid_contains_point(point_coord, grid_list_coord): """ Identify if a point is within a grid of coordinates Args: point_coord ([lat,lon]): Coordinates of a point grid_list_coord (list): List of grid centroids Returns: tuple: (boolean) is contained in point , and an exit message if false """ is_contained = True exit_msg = None if float(point_coord[0]) > max(grid_list_coord[0]): exit_msg = 'Simulation terminated: One or more sites is too ' + \ 'far North and is outside the spatial bounds of ' + \ 'your grid data!' is_contained = False if float(point_coord[0]) < min(grid_list_coord[0]): exit_msg = 'Simulation terminated: One or more sites is too ' + \ 'far South and is outside the spatial bounds of ' + \ 'your grid data!' is_contained = False if float(point_coord[1]) > max(grid_list_coord[1]): exit_msg = 'Simulation terminated: One or more sites is too ' + \ 'far East and is outside the spatial bounds of ' + \ 'your grid data!' is_contained = False if float(point_coord[1]) < min(grid_list_coord[1]): exit_msg = 'Simulation terminated: One or more sites is too ' + \ 'far West and is outside the spatial bounds of ' + \ 'your grid data!' is_contained = False return is_contained, exit_msg
def shift(g, d, n): """Shift a list of the given value""" return g[n:] + g[:n], d[n:] + d[:n]
def dict_to_filter_params(d, prefix=''): """ Translate a dictionary of attributes to a nested set of parameters suitable for QuerySet filtering. For example: { "name": "Foo", "rack": { "facility_id": "R101" } } Becomes: { "name": "Foo", "rack__facility_id": "R101" } And can be employed as filter parameters: Device.objects.filter(**dict_to_filter(attrs_dict)) """ params = {} for key, val in d.items(): k = prefix + key if isinstance(val, dict): params.update(dict_to_filter_params(val, k + '__')) else: params[k] = val return params
def partition_strict(function, items): """Like 'partition' but returns two lists instead of lazy iterators. Should be faster than partition because it only goes through 'items' once. >>> is_odd = lambda x : (x % 2) >>> partition_strict(is_odd, [1, 2, 3, 4, 5, 6]) ([1, 3, 5], [2, 4, 6]) """ left = [] right = [] for item in items: (left if function(item) else right).append(item) return (left, right)
def filter_query(filter_dict, required_keys): """Ensure that the dict has all of the information available. If not, return what does""" if not isinstance(filter_dict, dict): raise TypeError("dict_list is not a list. Please try again") if not isinstance(required_keys, list): raise TypeError("dict_list is not a list. Please try again") available = [] for k,v in filter_dict.items(): # print(k, v) if k in required_keys: available.append(k) return available
def _GetBuildProperty(build_properties, property_name): """Get the specified build property from the build properties dictionary. Example property names are Chromium OS Version ('branch'), Chromium OS Version ('buildspec_version'), and GIT Revision ('git_revision'). Args: build_properties: The properties dictionary for the build. property_name: The name of the build property. Returns: A string containing the property value. """ for property_list in build_properties: if property_name in property_list: property_value = property_list[1] break else: property_value = None print(' Warning: Build properties has no %s property.' % property_name) return property_value
def _Append(text): """Inserts a space to text if it is not empty and returns it.""" if not text: return '' if text[-1].isspace(): return text return ' ' + text
def find(d, value): """ Look for the first key correspondind to value `value` in dictionnary `d` """ for (k, v) in d.items(): if v == value: return k
def display_binary_4bit(num: int): """Displays the binary string representation for a given integer. If the number is within 4 bits, the output will be 4 binary digits; if the number is 8 bits then 8 binary digits will be the output. Examples: >>> display_binary_4bit(151)\n '10010111' >>> display_binary_4bit(11)\n '1011' """ return format(num, "04b")
def xor_bytes(bts1: bytes, bts2: bytes) -> bytes: """Make a xor by bytes @param bts1: @param bts2: @return: """ return bytes([byte1 ^ byte2 for byte1, byte2 in zip(bts1, bts2)])
def get_perfdata(label, value, uom, warn, crit, _min, _max): """Returns 'label'=value[UOM];[warn];[crit];[min];[max] """ msg = "'{}'={}".format(label, value) if uom is not None: msg += uom msg += ';' if warn is not None: msg += str(warn) msg += ';' if crit is not None: msg += str(crit) msg += ';' if _min is not None: msg += str(_min) msg += ';' if _max is not None: msg += str(_max) msg += ' ' return msg
def my_sqrt(x): """ :type x: int :rtype: int """ if x <= 1: return x l, r = 0, x while l + 1 < r: mid = l + (r - l) // 2 if mid * mid <= x < (mid + 1) * (mid + 1): return mid elif mid * mid > x: r = mid else: l = mid
def URL(s): """ take an input string and replace spaces with %20""" return s.replace(" ", "%20")
def check_online(device): """Home Assistant Logic for Determining Device Availability""" return 'offline' not in device
def get_precision(tp, fp): """ This function returns the precision for indels by size. :param tp: Number of true positives :type tp: int :param fp: Number of false positives :type fp: int :return: The precision, (tp) / (tp+fp) :rtype: float """ if tp + fp == 0: return 'NaN' else: return format(round(100 * (float(tp) / (tp + fp)), 2), '.2f')
def __discretizePoints(x,cut_points): """ Function to discretize a vector given a list of cutpoints. This function dicretizes a vector given the list of points to cut :param x: a vector composed by real numbers :param cut_points:a list with the points at which the vector has to be cut :return: A factor with the discretization """ vCat = [1] * len(x) for i in range(0, len(x)): for j in range(0, len(cut_points)): if (float(x[i]) >= cut_points[j][0] and float(x[i]) <= cut_points[j][1]): vCat[i] = cut_points[j] return (vCat)
def sdiv(a: float, b: float) -> float: """Returns the quotient of a and b, or 0 if b is 0.""" return 0 if b == 0 else a / b
def fix_indent(rating): """Fixes the spacing between the moveset rating and the moves Returns three spaces if the rating is one character, two if it is two characters (A-, B-, etc) """ if len(rating) == 1: return ' ' * 3 else: return ' ' * 2
def filled(f,d): """ Check if a field exists in a dictionary, and if that field is not None or the empty string. """ return f in d and d[f] is not None and d[f] != ""
def gaps(ranges): """Get a list with the size of the gaps between the ranges """ gaps = [] for cur, nxt in zip(ranges[:-1], ranges[1:]): gaps.append(nxt[0] - cur[1]) # 1: end, 0: start return gaps
def get_collection_for_lingsync_doc(doc): """A LingSync document is identified by its `collection` attribute, which is valuated by a string like 'sessions', or 'datums'. Sometimes, however, there is no `collection` attribute and the `fieldDBtype` attribute is used and evaluates to a capitalized, singular analog, e.g., 'Session' or 'Datum'. This function returns a collection value for a LingSync document. """ type2collection = { 'Session': 'sessions', 'Corpus': 'private_corpuses', # or 'corpuses'? 'Datum': 'datums' } collection = doc.get('collection') if not collection: fieldDBtype = doc.get('fieldDBtype') if fieldDBtype: collection = type2collection.get(fieldDBtype) return collection
def extract_port_from_name(name, default_port): """ extractPortFromName takes a string in the form `id:port` and returns the ID and the port If there's no `:`, the default port is returned """ idx = name.rfind(":") if idx >= 0: return name[:idx], name[idx+1:] return name, default_port
def eta( r_net_day, evaporative_fraction, temperature): """ eta( r_net_day, evaporative_fraction, temperature) """ t_celsius = temperature - 273.15 latent = 86400.0/((2.501-0.002361*t_celsius)*pow(10,6)) result = r_net_day * evaporative_fraction * latent return result
def Mcnu_to_M(Mc, nu): """Convert chirp mass and symmetric mass ratio to total mass""" return Mc*nu**(-3./5.)
def italic(s): """Return the string italicized. Source: http://stackoverflow.com/a/16264094/2570866 :param s: :type s: str :return: :rtype: str """ return r'\textit{' + s + '}'
def _gaussian_gradients(x, y, a, sigma, mu): """Compute weight deltas""" sig2 = sigma**2 delta_b = (mu / sig2) - (y / sig2) * (2 * sig2 + 1 - y**2 + mu * y) delta_a = (1 / a) + delta_b * x return delta_a, delta_b
def suzuki_trotter(trotter_order, trotter_steps): """ Generate trotterization coefficients for a given number of Trotter steps. U = exp(A + B) is approximated as exp(w1*o1)exp(w2*o2)... This method returns a list [(w1, o1), (w2, o2), ... , (wm, om)] of tuples where o=0 corresponds to the A operator, o=1 corresponds to the B operator, and w is the coefficient in the exponential. For example, a second order Suzuki-Trotter approximation to exp(A + B) results in the following [(0.5/trotter_steps, 0), (1/trotteri_steps, 1), (0.5/trotter_steps, 0)] * trotter_steps. :param int trotter_order: order of Suzuki-Trotter approximation :param int trotter_steps: number of steps in the approximation :returns: List of tuples corresponding to the coefficient and operator type: o=0 is A and o=1 is B. :rtype: list """ p1 = p2 = p4 = p5 = 1.0 / (4 - (4 ** (1. / 3))) p3 = 1 - 4 * p1 trotter_dict = {1: [(1, 0), (1, 1)], 2: [(0.5, 0), (1, 1), (0.5, 0)], 3: [(7.0 / 24, 0), (2.0 / 3.0, 1), (3.0 / 4.0, 0), (-2.0 / 3.0, 1), (-1.0 / 24, 0), (1.0, 1)], 4: [(p5 / 2, 0), (p5, 1), (p5 / 2, 0), (p4 / 2, 0), (p4, 1), (p4 / 2, 0), (p3 / 2, 0), (p3, 1), (p3 / 2, 0), (p2 / 2, 0), (p2, 1), (p2 / 2, 0), (p1 / 2, 0), (p1, 1), (p1 / 2, 0)]} order_slices = [(x0 / trotter_steps, x1) for x0, x1 in trotter_dict[trotter_order]] order_slices = order_slices * trotter_steps return order_slices
def map_to_range(start_val, current_range_min, current_range_max, wanted_range_min, wanted_range_max): """Maps x and y from a range to another, desired range""" out_range = wanted_range_max - wanted_range_min in_range = current_range_max - current_range_min in_val = start_val - current_range_min val=(float(in_val)/in_range)*out_range out_val = wanted_range_min+val return out_val
def reflexive_missing_elements(relation, set): """Returns missing elements to a reflexive relation""" missingElements = [] for element in set: if [element, element] not in relation: missingElements.append((element,element)) return missingElements
def RGB2HEX(color): """In: RGB color array Out: HEX string""" return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))
def is_def_arg_private(arg_name): """Return a boolean indicating if the argument name is private.""" return arg_name.startswith("_")
def output_list(master_list): """Removes the extra brackets when outputting a list of lists into a csv file. Args: masterList: input list of lists Returns: list: output list """ output = [] for item in master_list: # check if item is a list if isinstance(item, list): # Append each item inside the list of list for i in output_list(item): output.append(i) # Otherwise just append the item (if not inside list of list) else: output.append(item) # return a single list without the nested lists return output
def RPL_ADMINLOC1(sender, receipient, message): """ Reply Code 257 """ return "<" + sender + ">: " + message
def estimate_coef(clear_x, clear_y): """ Linear regression function. :param clear_x: cleared_x :type clear_x : list :param clear_y: cleared_y :type clear_y : list :return: [slope,intercept] """ try: n = len(clear_x) mean_x = sum(clear_x) / n mean_y = sum(clear_y) / n SS_xy = 0 SS_xx = 0 for index, item in enumerate(clear_x): SS_xx += item**2 SS_xy += item * clear_y[index] SS_xx -= n * (mean_x)**2 SS_xy -= n * mean_x * mean_y B1 = SS_xy / SS_xx B0 = mean_y - B1 * mean_x return [B1, B0] except (TypeError, ZeroDivisionError, OverflowError, ValueError): return [0, 0]
def generate_spec(key_condictions): """get mongo query filter by recursion key_condictions is a list of (key, value, direction) >>> generate_spec([ ... ('a', '10', 1), ... ('b', '20', 0), ... ]) {'$or': [{'$and': [{'a': '10'}, {'b': {'$lt': '20'}}]}, {'a': {'$gt': '10'}}]} """ if not key_condictions: return {} key, value, direction = key_condictions[0] gt_or_lt = '$gt' if direction == 1 else '$lt' next_ordering = generate_spec(key_condictions[1:]) if next_ordering: return {'$or': [{'$and': [{key: value}, next_ordering]}, {key: {gt_or_lt: value}}]} else: return {key: {gt_or_lt: value}}
def skip_material(mtl: int) -> int: """Computes the next material index with respect to default avatar skin indices. Args: mtl (int): The current material index. Returns: int: The next material index to be used. """ if mtl == 1 or mtl == 6: return mtl + 2 return mtl + 1
def add_dict(dict1, dict2): """ Add two dictionaries together. Parameters ---------- dict1 : dict First dictionary to add. dict2 : dict Second dictionary to add. Returns ------- dict The sum of the two dictionaries. Examples -------- >>> add_dict({1: 2, 3: 4}, {1: 3, 5: 6}) {1: 5, 3: 4, 5: 6} """ # Need to copy dictionaries to prevent changing der for original variables dict1 = dict(dict1) dict2 = dict(dict2) for key in dict2: if key in dict1: dict2[key] = dict2[key] + dict1[key] return {**dict1, **dict2}