content
stringlengths
42
6.51k
def get_docker_tag(platform: str, registry: str) -> str: """:return: docker tag to be used for the container""" platform = platform if any(x in platform for x in ['build.', 'publish.']) else 'build.{}'.format(platform) if not registry: registry = "mxnet_local" return "{0}/{1}".format(registry, platform)
def _truncate(s: str, max_length: int) -> str: """Returns the input string s truncated to be at most max_length characters long. """ return s if len(s) <= max_length else s[0:max_length]
def add_anchors(pattern): """If there's no explicit start and end line symbols it is necessary to add the corresponding regexes to the beggining and end of the string. :param pattern: A regular expression. :type pattern: str """ # Start line. pattern = pattern[1:] if pattern.startswith('^') else '.*' + pattern # End line. pattern = pattern[:-1] if pattern.endswith('$') else pattern + '.*' return pattern
def invalid_br_vsby(v): """Checks if visibility is inconsistent with BR""" return not 0.6 < v < 6.1
def unlist(_list): """ if list is of length 1, return only the first item :arg list _list: a python list """ if len(_list) == 1: return _list[0] else: return _list
def mean(data): """ This is used to find the mean in a set of data. The mean is commonly referred to as the 'average'.""" data = data sum = 0 for x in data: sum += x return sum/len(data) def __repr__(): "Mean(enter data here)"
def get_stat( dance, player, stat ): """ Accepts a bin representing the player and a string representing the stat and returns the stat's value. """ return dance[ str(player) ][ str(stat) ]
def check_in_data(var, data): """ Check, if var in data dictionary or not """ if var not in data: # print(f"Info : Key error for { var }") data[var] = "" return data[var]
def get_descriptors_text(dl): """ Helper function that separates text descriptors from the mixture of text and uris that is returned from Agritriop Parameters ---------- dl : list Descriptor list. Returns ------- list list of text descritors only. """ return list(filter(lambda x: not x.startswith('http') , dl))
def is_prime(x): """Assumes x is a nonnegative int Returns True if x is prime; False otherwise""" if x <= 2: return False for i in range(2, x): if x%i == 0: return False return True
def nesting_level(x): """Calculate nesting level of a list of objects. To convert between sparse and dense representations of topological features, we need to determine the nesting level of an input list. The nesting level is defined as the maximum number of times we can recurse into the object while still obtaining lists. Parameters ---------- x : list Input list of objects. Returns ------- int Nesting level of `x`. If `x` has no well-defined nesting level, for example because `x` is not a list of something, will return `0`. Notes ----- This function is implemented recursively. It is therefore a bad idea to apply it to objects with an extremely high nesting level. Examples -------- >>> nesting_level([1, 2, 3]) 1 >>> nesting_level([[1, 2], [3, 4]]) 2 """ # This is really only supposed to work with lists. Anything fancier, # for example a `torch.tensor`, can already be used as a dense data # structure. if not isinstance(x, list): return 0 # Empty lists have a nesting level of 1. if len(x) == 0: return 1 else: return max(nesting_level(y) for y in x) + 1
def copy_rate(sent1, sent2): """ copy rate between two sentences. In particular, the proportion of sentence 1 that are copied from sentence 2. Input: sent1, sent2: two sentence strings (generated summary, source). Output: score: copy rate on unigrams. """ sent1_split = set(sent1.split()) sent2_split = set(sent2.split()) intersection = sent1_split.intersection(sent2_split) # recall = len(intersection) / len(sent2_split) precision = len(intersection) / len(sent1_split) # union = sent1_split.union(sent2_split) # jacd = 1 - len(intersection) / len(union) # jacquard distance # score = stats.hmean([recall, precision]) # F1 score (need to import scipy.stats.hmean) # score = 2 * recall * precision / (recall + precision) if recall != 0 and precision != 0 else 0 # F1 score return precision
def determinant(point1, point2, point3): """ Compute the determinant of three points, to determine the turn direction, as a 3x3 matrix: [p1(x) p1(y) 1] [p2(x) p2(y) 1] [p3(x) p3(y) 1] :param point1: the first point coordinates as a [x,y] list :param point2: the second point coordinates as a [x,y] list :param point3: the third point coordinates as a [x,y] list :return: a value >0 if counter-clockwise, <0 if clockwise or =0 if collinear """ return (point2[0] - point1[0]) * (point3[1] - point1[1]) \ - (point2[1] - point1[1]) * (point3[0] - point1[0])
def quorum_check(value_x, value_y, value_z, delta_max): """ Quorum Checking function Requires 3 input values and a max allowed delta between sensors as args. Checks all 3 values against each other and max delta to determine if sensor has failed or is way out of agreement with the other two. Returns a "Return Code" and a value. Return Codes: 0 - All sensors agree, 1 - sensor x out of spec, 2 - sensor y out of spec, 3 - sensor z out of spec, 4 - no sensors agree, you should error out/email/alarm/etc. 5 - sensors agree in pairs but spread across all 3 exceeds delta """ # Reset values agree_xy = False agree_xz = False agree_yz = False x_min = value_x - delta_max x_max = value_x + delta_max y_min = value_y - delta_max y_max = value_y + delta_max # Check for agreement between pairs if x_min <= value_y <= x_max: agree_xy = True if x_min <= value_z <= x_max: agree_xz = True if y_min <= value_z <= y_max: agree_yz = True # Evaluate if all sensors either disagree or agree if not (agree_xy) and not (agree_xz) and not (agree_yz): val = 0 return_val = [4, val] return return_val # Set this to return error code stating none of the sensors agree if agree_xy and agree_xz and agree_yz: val = (value_x + value_y + value_z) / 3 val = round(val, 1) return_val = [0, val] return ( return_val # Set this to return all good code and average of all 3 sensors ) # Catch edge case of agreement between two separate pairs but not the third. # For this case also return an average of all 3. if ( (agree_xy and agree_yz and not agree_xz) or (agree_yz and agree_xz and not agree_xy) or (agree_xy and agree_xz and not agree_yz) ): val = (value_x + value_y + value_z) / 3 val = round(val, 1) return_val = [5, val] return return_val # Set this to return all large spread code and average of all 3 sensors # If we flow through all the previous checks, identify which sensor is out of line with quorum. if agree_xy and not agree_yz and not agree_xz: val = (value_x + value_y) / 2 val = round(val, 1) return_val = [3, val] return return_val # Set this to return one bad sensor code for sensor z and average of 2 remaining sensors if not agree_xy and agree_yz and not agree_xz: val = (value_y + value_z) / 2 val = round(val, 1) return_val = [1, val] return return_val # Set this to return one bad sensor code for sensor x and average of 2 remaining sensors if not agree_xy and not agree_yz and agree_xz: val = (value_x + value_z) / 2 val = round(val, 1) return_val = [2, val] return return_val
def bit_mask(start, stop): """Return a number with all it's bits from `start` to `stop` set to 1.""" number_of_set_bits = stop - start + 1 return ((1 << number_of_set_bits) - 1) << start
def shiftRow(s): """ShiftRow function""" return [s[0], s[1], s[3], s[2]]
def revert_dictionary(dictionary): """Given a dictionary revert it's mapping :param dictionary: A dictionary to be reverted :returns: A dictionary with the keys and values reverted """ return {v: k for k, v in dictionary.items()}
def speech_response(output, endsession): """ create a simple json response """ return { 'outputSpeech': { 'type': 'PlainText', 'text': output }, 'shouldEndSession': endsession }
def clean_comment(comment): """Remove comment formatting. Strip a comment down and turn it into a standalone human readable sentence. Examples: Strip down a comment >>> clean_comment("# hello world") "Hello world" Args: comment (str): Comment to clean Returns: str: Cleaned sentence """ return comment.strip("# ").capitalize()
def countchanges(hunk): """hunk -> (n+,n-)""" add = len([h for h in hunk if h[0] == '+']) rem = len([h for h in hunk if h[0] == '-']) return add, rem
def format_exc_for_journald(ex, indent_lines=False): """ Journald removes leading whitespace from every line, making it very hard to read python traceback messages. This tricks journald into not removing leading whitespace by adding a dot at the beginning of every line :param ex: Error lines :param indent_lines: If indentation of lines should be present or not :type indent_lines: bool """ result = '' for line in ex.splitlines(): if indent_lines: result += ". " + line + "\n" else: result += "." + line + "\n" return result.rstrip()
def are_all_terms_fixed_numbers(sequence: str): """ This method checks whither the sequence consists of numbers (i.e. no patterns) sequence: A string that contains a comma seperated numbers returns: True if the sequence contains numbers only, False otherwise. """ seq_terms = sequence.split(",") for term in seq_terms: if not str(term).strip().lstrip("+-").isdigit(): return False return True
def _errors_to_text(errors): """Turn a resolution errors trace into a list of text.""" texts = [] for err in errors: texts.append('Server {} {} port {} answered {}'.format(err[0], 'TCP' if err[1] else 'UDP', err[2], err[3])) return texts
def merge_two_dicts(x, y): """Copied from https://stackoverflow.com/a/26853961/4386191""" z = x.copy() # start with x's keys and values z.update(y) # modifies z with y's keys and values & returns None return z
def merge(left, right): """Merge sort merging function.""" left_index, right_index = 0, 0 result = [] while left_index < len(left) and right_index < len(right): if left[left_index] < right[right_index]: result.append(left[left_index]) left_index += 1 else: result.append(right[right_index]) right_index += 1 result += left[left_index:] result += right[right_index:] return result
def __get_wind_adjustment(wind_speed): """ Calculate the wind adjustment value by wind speed :param float wind_speed: :return: """ if wind_speed < 0: raise ValueError('wind speed cannot be negative') if 0 <= wind_speed <= 12: wind = 1 elif 13 <= wind_speed <= 25: wind = 2 else: wind = 0 return wind
def _extract_match(toc, index, seperator=','): """ Extracts a path between seperators (,) :toc (str) Table of contents :index (int) Index of match returns full path from match """ length = len(toc) start_index = index while toc[start_index] != seperator and start_index >= 0: start_index -= 1 end_index = index while toc[end_index] != seperator and end_index < length - 1: end_index += 1 if end_index == length - 1: end_index += 1 match = toc[start_index+1:end_index].replace(seperator, '') return match
def removeEmptyElements(list): """ Remove empty elements from a list ( [''] ), preserve the order of the non-null elements. """ tmpList = [] for element in list: if element: tmpList.append(element) return tmpList
def get_letter_from_index(index: int) -> str: """Gets the nth letter in the alphabet Parameters ---------- index : int Position in the alphabet Returns ------- str Letter at given position in the alphabet """ return chr(ord("@") + index)
def billetes_verdes(cant): """ Str -> num :param cant: valor de una cantidad en euros :return: los billetes >>> billetes_verdes('434') '2 billetes de 200 1 billete de 20 euros 1 billete de 10 euros 2 monedas de 2 euros' >>> billetes_verdes('626') '3 billetes de 200 1 billete de 20 euros 3 monedas de 2 euros' >>> billetes_verdes('1298') '6 billetes de 200 4 billete de 20 euros 1 billete de 10 euros 4 monedas de 2 euros' """ billetes_200 = int(cant) // 200 new_1 = int(cant) % 200 billetes_20 = new_1 // 20 new_2 = new_1 % 20 billetes_10 = new_2 // 10 new_3 = new_2 % 10 monedas_2 = new_3 // 2 new_4 = new_3 % 2 mensaje = '' if (billetes_200): mensaje += str(billetes_200) + ' billetes de 200 ' if (billetes_20): mensaje += str(billetes_20) + ' billete de 20 euros ' if (billetes_10): mensaje += str(billetes_10) + ' billete de 10 euros ' if (monedas_2): mensaje += str(monedas_2) + ' monedas de 2 euros' return ('%s' % mensaje.rstrip('\n'))
def second_word(s): """Returns the second word of `s`, regardless of how many spaces are before it. Parameters ---------- s : str Returns ------- second_w : str The second word of `s`. """ # Initialisations s_list = list(s) for i in range(1, len(s)): if s_list[i] != " " and s_list[i-1] == " ": for j in range(i, len(s)): if s_list[j] == " ": second_w = "".join(s_list[i:j]) return second_w second_w = "".join(s_list[i:]) return second_w
def _get_metric_value(nested_dict, metric_name): """Gets the value of the named metric from a slice's metrics.""" for key in nested_dict: if metric_name in nested_dict[key]['']: typed_value = nested_dict[key][''][metric_name] if 'doubleValue' in typed_value: return typed_value['doubleValue'] if 'boundedValue' in typed_value: return typed_value['boundedValue']['value'] raise ValueError('Unsupported value type: %s' % typed_value) else: raise ValueError('Key %s not found in %s' % (metric_name, list(nested_dict[key][''].keys())))
def _store_chunks_in_order(seen: str, unseen: str, seen_first: bool) -> list: """ Save two strings (a 'seen' and an 'unseen' string) in an array where the 'seen' string is the first element if the seen_first parameter is True. @param seen: The 'seen' string @param unseen: The 'unseen' string @return: An array where either the seen or unseen strings are the first/second element depending on the value of the seen_first parameter. """ if seen_first: return [seen, unseen] else: return [unseen, seen]
def is_tuner(x): """ Whether or not x is a tuner object (or just a config object). """ return x is not None and hasattr(x, 'iter_params')
def handle_value(data): """ Take a non-string scalar value and turns it into yamelish. Return a tuple: yamelish (string), whether this string is a block (boolean) """ return str(data), False
def pixel_to_world(geo_trans, x, y): """Return the top-left world coordinate of the pixel :param geo_trans: geo transformation :type geo_trans: tuple with six values :param x: :param y: :return: """ return geo_trans[0] + (x * geo_trans[1]), geo_trans[3] + (y * geo_trans[5])
def _set_default_capacitance( subcategory_id: int, style_id: int, ) -> float: """Set the default value of the capacitance. :param subcategory_id: :param style_id: :return: _capacitance :rtype: float :raises: KeyError if passed a subcategory ID outside the bounds. :raises: IndexError if passed a style ID outside the bounds when subcategory ID is equal to three. """ _capacitance = { 1: 0.15e-6, 2: 0.061e-6, 3: [0.027e-6, 0.033e-6], 4: 0.14e-6, 5: 0.33e-6, 6: 0.14e-6, 7: 300e-12, 8: 160e-12, 9: 30e-12, 10: 3300e-12, 11: 81e-12, 12: 1e-6, 13: 20e-6, 14: 1700e-6, 15: 1600e-6, 16: 0.0, 17: 0.0, 18: 0.0, 19: 0.0, }[subcategory_id] if subcategory_id == 3: _capacitance = _capacitance[style_id - 1] return _capacitance
def is_in(x, l): """Transforms into set and checks existence Given an element `x` and an array-like `l`, this function turns `l` into a set and checks the existence of `x` in `l`. Parameters -------- x : any l : array-like Returns -------- bool """ return x in set(l)
def split_kwargs(relaxation_kwds): """Split relaxation keywords to keywords for optimizer and others""" optimizer_keys_list = [ 'step_method', 'linesearch', 'eta_max', 'eta', 'm', 'linesearch_first' ] optimizer_kwargs = { k:relaxation_kwds.pop(k) for k in optimizer_keys_list if k in relaxation_kwds } if 'm' in optimizer_kwargs: optimizer_kwargs['momentum'] = optimizer_kwargs.pop('m') return optimizer_kwargs, relaxation_kwds
def casa_argv(argv): """ Processes casarun arguments into C-style argv list. Modifies the argv from a casarun script to a classic argv list such that the returned argv[0] is the casarun scriptname. Parameters ---------- argv : list of str Argument list. Returns ------- sargv Script name plus optional arguments Notes ----- Does not depend on CASA being present. """ if False: lines = os.popen("casarun -c","r").readlines() n = int(lines[len(lines)-1].strip()) else: n = argv.index('-c') + 1 return argv[n:]
def from_tags(tags): """Transform the boto way of having tags into a dictionnary""" return {e['Key']: e['Value'] for e in tags}
def ascii2int(str, base=10, int=int): """ Convert a string to an integer. Works like int() except that in case of an error no exception raised but 0 is returned; this makes it useful in conjunction with map(). """ try: return int(str, base) except: return 0
def is_straight(pips): """Return True if hand is a straight. Compare card pip values are in decending order. Hand is presorted. """ return (pips[0] == pips[1] + 1 == pips[2] + 2 == pips[3] + 3 == pips[4] + 4)
def vector2d(vector): """ return a 2d vector """ return (float(vector[0]), float(vector[1]))
def getkey(value, key): """\ Fetch a key from a value. Useful for cases such as dicts which have '-' and ' ' in the key name, which Django can't cope with via the standard '.' lookup. """ try: return value[key] except KeyError: return ""
def romi(total_revenue, total_marketing_costs): """Return the Return on Marketing Investment (ROMI). Args: total_revenue (float): Total revenue generated. total_marketing_costs (float): Total marketing costs Returns: Return on Marketing Investment (float) or (ROMI). """ return ((total_revenue - total_marketing_costs) / total_marketing_costs) * 100
def path2fname(path): """ Split path into file name and folder ========== =============================================================== Input Meaning ---------- --------------------------------------------------------------- path Path to a file [string], e.g. 'C:\\Users\\SPAD-FCS\\file.ext' ========== =============================================================== ========== =============================================================== Output Meaning ---------- --------------------------------------------------------------- fname File name, e.g. 'file.ext' folderName Folder name, e.g. 'C:\\Users\\SPAD-FCS\\' ========== =============================================================== """ fname = path.split('\\')[-1] folderName = '\\'.join(path.split('\\')[0:-1]) + '\\' return fname, folderName
def find_key(d, nested_key): """Attempt to find key in dict, where key may be nested key1.key2...""" keys = nested_key.split('.') key = keys[0] return (d[key] if len(keys) == 1 and key in d else None if len(keys) == 1 and key not in d else None if not isinstance(d[key], dict) else find_key(d[key], '.'.join(keys[1:])) if key in d else None)
def round_filters(filters, multiplier, divisor=8, min_width=None): """Calculate and round number of filters based on width multiplier.""" if not multiplier: return filters filters *= multiplier min_width = min_width or divisor new_filters = max(min_width, int(filters + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_filters < 0.9 * filters: new_filters += divisor return int(new_filters)
def validate_key(data, key): """ Validates that a key exists or not """ try: return data[key[0]] except Exception as e: return "NAN"
def linearize(a, b, y): """Generates linearization constraints for the product y = ab. Parameters ---------- a : str First factor. b : str Second factor. y : Product. Returns ------- List[str] A list holding the three linearization constraints. """ force_zero_a = "- %s + %s >= 0" % (y, a) force_zero_b = "- %s + %s >= 0" % (y, b) force_one = "- %s + %s + %s <= 1" % (y, a, b) return [force_zero_a, force_zero_b, force_one]
def de_dupe_list(input): """de-dupe a list, preserving order. """ sam_fh = [] for x in input: if x not in sam_fh: sam_fh.append(x) return sam_fh
def mean(val_a, val_b): """ A function returning the mean of both values. This function is redeveloped so as to be called as choice_func in the function "values_as_slop()" (see below) in external projects. Parameters ---------- val_a : float First value. val_b : float Second value. Returns ------- float: mean of both values. """ return (val_a + val_b) / 2
def fit_function(x, a, b): """ This function ... :param x: :param a: :param b: :return: """ return a * x + b
def list_intersection(a, b): """ Find the first element in the intersection of two lists """ result = list(set(a).intersection(set(b))) return result[0] if result else None
def encode(num, alphabet): """Encode a positive number into Base X and return the string. Arguments: - `num`: The number to encode - `alphabet`: The alphabet to use for encoding """ if num == 0: return alphabet[0] arr = [] arr_append = arr.append # Extract bound-method for faster access. _divmod = divmod # Access to locals is faster. base = len(alphabet) while num: num, rem = _divmod(num, base) arr_append(alphabet[rem]) arr.reverse() return "".join(arr)
def escape(inp, quote='"'): """ Escape `quote` in string `inp`. Example usage:: >>> escape('hello "') 'hello \\"' >>> escape('hello \\"') 'hello \\\\"' Args: inp (str): String in which `quote` will be escaped. quote (char, default "): Specify which character will be escaped. Returns: str: Escaped string. """ output = "" for c in inp: if c == quote: output += '\\' output += c return output
def sortkey(d): """Split d on "_", reverse and return as a tuple.""" parts=d.split("_") parts.reverse() return tuple(parts)
def _strip_sort_key(the_dict): """ The sort key is prepended to the each of the values in this list of dictionaries. But that sort key shouldn't remain a part of the dictionary, so remove it. It's separated from the name by a colon. """ new_dict = {} for k, v in the_dict.items(): new_list = [] for item in v: tup = item.rpartition(":") new_list.append(tup[2]) new_dict[k] = new_list return new_dict
def encode_var_int(number): """ Returns a bytearray encoding the given number. """ buf = bytearray() shift = 1 while True: buf.append(number & 0x7F) number -= buf[-1] if number == 0: buf[-1] |= 0x80 break number -= shift number >>= 7 shift += 7 return buf
def calc_jac_titles(title1, title2): """ Identify titles for jaccard similarity (used in calculate_jaccard) """ countIntersection = 0 for token in title2: if token in title1: countIntersection += 1 countUnion = len(title1) + len(title2) - countIntersection return countIntersection / countUnion
def is_summary(number): """ Takes a number as input Identifies a sentence as part of the summery or not """ if number != 0: return 'yes' else: return 'no'
def eq_by(f, value_1, value_2): """Check if two values are equal when applying f on both of them.""" return f(value_1) == f(value_2)
def _neighboring_points(o_index, i_index, e_len, f_len): """ A function that returns list of neighboring points in an alignment matrix for a given alignment (pair of indexes) """ result = [] if o_index > 0: result.append((o_index - 1, i_index)) if i_index > 0: result.append((o_index, i_index - 1)) if o_index < e_len - 1: result.append((o_index + 1, i_index)) if i_index < f_len - 1: result.append((o_index, i_index + 1)) if o_index > 0 and i_index > 0: result.append((o_index - 1, i_index - 1)) if o_index > 0 and i_index < f_len - 1: result.append((o_index - 1, i_index + 1)) if o_index < e_len - 1 and i_index > 0: result.append((o_index + 1, i_index - 1)) if o_index < e_len - 1 and i_index < f_len - 1: result.append((o_index + 1, i_index + 1)) return result
def _to_map(keys, vals): """Attach the keys from the file header to the values. Both are assumed to be in the order read from the input file""" return {k: v for k, v in zip(keys, vals) if v is not None and v != ''}
def dictSave(d,fname=None): """format a dictionary to text. If no fname given, just print.""" out="" for k in sorted(d.keys()): if type(d[k])==str: out+='%s = "%s"\n'%(k,str(d[k])) else: out+="%s = %s\n"%(k,str(d[k])) if fname==None: print(out) else: #debug("writing configuration file") f=open(fname,'w') f.write(out) f.close() return out
def remove_comments(lines, token='#'): """ Generator. Strips comments and whitespace from input lines. """ l = [] for line in lines: s = line.split(token, 1)[0].strip() if s != '': l.append(s) return l
def _deep_value(*args, **kwargs): """ Drills down into tree using the keys """ node, keys = args[0], args[1:] for key in keys: node = node.get(key, {}) default = kwargs.get('default', {}) if node in ({}, [], None): node = default return node
def get_list_index_or_none_if_out_of_range(imageList, index): """ This function... :param imageList: :param index: :return: """ if index < len(imageList): return imageList[index] else: return None
def human_format(num): """ Convert <num> into human form (round it and add a suffix) """ magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 # add more suffixes if you need them return '%.3f%s' % (num, ['', 'K', 'M', 'B', 'T', 'Q'][magnitude])
def append_s(value): """ Adds the possessive s after a string. value = 'Hans' becomes Hans' and value = 'Susi' becomes Susi's """ if value.endswith('s'): return u"{0}'".format(value) else: return u"{0}'s".format(value)
def html_list_element(content): """Creates an html list element from the given content :returns: html list element as string """ return "<li>" + content + "</li>"
def namestr(object): """This method returns the string name of a python object. :param object: The object that should be used :type object: Python object :returns: Object name as string """ for n,v in globals().items(): if v == object: return n return None
def caseless_uniq(un_uniqed_files): """ Given a list, return a list of unique strings, and a list of duplicates. This is a caseless comparison, so 'Test' and 'test' are considered duplicates. """ lower_files = [] # Use this to allow for easy use of the 'in' keyword unique_files = [] # Guaranteed case insensitive unique filtered = [] # any duplicates from the input for aFile in un_uniqed_files: if aFile.lower() in lower_files: filtered.append(aFile) else: unique_files.append(aFile) lower_files.append(aFile.lower()) return (unique_files, filtered)
def bubble_sort(input_data): """Implementation of the bubble sort algorithm, employs an enhancement where the inner loops keep track of the last sorted element as described in the video below. (https://www.youtube.com/watch?v=6Gv8vg0kcHc) The input_data is sorted in-place, this is dangerous to do """ is_sorted = False last_unsorted_index = len(input_data) - 1 while not is_sorted: is_sorted = True for curr_index in range(last_unsorted_index): curr_element = input_data[curr_index] # be sure to not go out of bounds in the loop since we are accessing # the next element, happens at the edge of the list next_index = curr_index + 1 next_element = input_data[next_index] # swap the elements that are not in order if curr_element > next_element: input_data[curr_index], input_data[next_index] =\ input_data[next_index], input_data[curr_index] is_sorted = False # as we loop everytime, the last elements of the list will be in order # this is explained in the video in the docstring above last_unsorted_index -= 1 return input_data
def getDigitsFromStr(string:str,withDigitPoint:bool = False): """ Extract number from a string. Return a list whose element is strings that is number. Parameters ---------- string : str The string that may contain numbers. withDigitPoint : bool Use true is the numbers are float. False if all numbers are int. Returns ------- strList : list A list whose elements are string that can be converted into numbers. """ import re if withDigitPoint: strList = re.findall(r"\d+\.?\d*",string) else: strList = re.findall(r"\d+\d*",string) return strList
def period_contribution(x): """ Turns period--1, 2, 3, OT, etc--into # of seconds elapsed in game until start. :param x: str or int, 1, 2, 3, etc :return: int, number of seconds elapsed until start of specified period """ try: x = int(x) return 1200 * (x - 1) except ValueError: return 3600 if x == 'OT' else 3900
def AND(p: bool, q: bool) -> bool: """ Conjunction operator used in propositional logic """ return bool(p and q)
def first(value): """Returns the first item in a list.""" try: return value[0] except IndexError: return ''
def get_accuracy_count(data_list, optimal_distance): """ Processes data list from file to find accuracy count. Returns accuracy count. """ count = sum(1 for i in data_list if optimal_distance in i) return count
def bottom_up_mscs(seq: list) -> tuple: """Dynamic programming bottom-up algorithm which finds the sub-sequence of seq, such that the sum of the elements of that sub-sequence is maximal. Let sum[k] denote the max contiguous sequence ending at k. So, we have: sum[0] = seq[0] sum[k + 1] = max(seq[k], sum[k] + seq[k]) To keep track where the max contiguous subsequence starts, we use a list. Time complexity: O(n). Space complexity: O(n).""" indices = [0] * len(seq) _sum = [0] * len(seq) _sum[0] = seq[0] _max = _sum[0] start = end = 0 for i in range(1, len(seq)): if _sum[i - 1] > 0: _sum[i] = _sum[i - 1] + seq[i] indices[i] = indices[i - 1] else: _sum[i] = seq[i] indices[i] = i if _sum[i] > _max: _max = _sum[i] end = i start = indices[i] return _max, start, end
def _unquote(tk): """Remove quotes from a string. Perform required substitutions. - Enclosing quotes are removed - SQL-like escape sequence in single quotes are replaced by their value (i.e: 'abc''def' => abc'def) """ if not tk: return tk if tk[0] == tk[-1] == '"': return tk[1:-1] if tk[0] == tk[-1] == "'": return tk[1:-1].replace("''","'") return tk
def get_local_name(full_name): """ Removes namespace part of the name. Namespaces can appear in 2 forms: {full.namespace.com}name, and prefix:name. Both cases are handled correctly here. """ full_name = full_name[full_name.find('}')+1:] full_name = full_name[full_name.find(':')+1:] return full_name
def fib(n : int) -> int: """precondition: n >= 0 """ if n == 0: return 1 elif n == 1: return 1 else: return fib(n-2) + fib(n-1)
def _get_config(path, value): """ Create config where specified key path leads to value :type path: collections.Sequence[six.text_type] :type value: object :rtype: collections.Mapping """ config = {} for step in reversed(path): config = {step: config or value} return config
def IS_ARRAY(expression): """ Determines if the operand is an array. Returns a boolean. See https://docs.mongodb.com/manual/reference/operator/aggregation/isArray/ for more details :param expression: Any valid expression. :return: Aggregation operator """ return {'$isArray': expression}
def py_str(x): """convert c string back to python string""" return x.decode('utf-8')
def borr(registers, a, b, c): """(bitwise OR register) stores into register C the result of the bitwise OR of register A and register B.""" registers[c] = registers[a] | registers[b] return registers
def get_path_to_service(service_id): """In lieu of a url-reversing mechanism for routes in the app""" return '/app/index.html#/service/%d' % service_id
def dblp_key_extract(entry): """Return dblp key if the bibtex key is already a DBLP one, otherwise return none.""" if entry["ID"].startswith("DBLP:"): return entry["ID"][5:] else: return None
def circulator(circList, entry, limit): """ This method will wrap a list overwriting at the beginning when limit is reached. Args ---- circList: list initial list entry: any item to add to list limit: int size limit for circular list Returns ------- circList: list updated list """ circList.append(entry) if len(circList) > limit: circList.pop(0) return circList
def find_diff_indexes_and_lenght_on_same_size_values(value_one, value_two): """Find the diff indexes and lenght of the difference, as follows below, and return on an array of diffs. Some more details follows below:""" """(a) on the first different char in a sequence, save that index on a buffer along with the sequence lenght (only 1 for now)""" """(b) on the successive different chars in a sequence, increment the lenght of the sequence on the buffer""" """(c) on the first equal char after a sequence of differences, add the buffer to our list and reset it if needed""" current_diff = None diffs = [] for char_index in range(len(value_one)): if value_one[char_index] != value_two[char_index]: if not current_diff: ## (a) situation, as above (this comment won't generate docs!) current_diff = {"diff_start":char_index, "chain":1} else: ## (b) situation, as above (this comment won't generate docs!) current_diff["chain"] += 1 else: if current_diff: ## (c) situation, as above (this comment won't generate docs!) diffs.append(current_diff) current_diff = None ## Let's not forget to append anything that has remained on the buffer (this comment won't generate docs!) if current_diff: diffs.append(current_diff) current_diff = None return diffs
def nil_eq(a, b): """Implementation of `equal` (only use with Nil types).""" return a is None and b is None
def _get_vault_path(device_uuid): """Generate full vault path for a given block device UUID :param: device_uuid: String of the device UUID :returns: str: Path to vault resource for device """ # return '{}/{}'.format( # socket.gethostname(), # device_uuid # ) return device_uuid
def sfx(uri: str) -> str: """ Add a separator to a uri if none exists. Note: This should only be used with module id's -- it is not uncommon to use partial prefixes, e.g. PREFIX bfo: http://purl.obolibrary.org/obo/BFO_ :param uri: uri to be suffixed :return: URI with suffix """ return str(uri) + ('' if uri.endswith(('/', '#', '_', ':')) else '/')
def xy_to_xyz(x, y): """Convert `xyY` to `xyz`.""" return [x / y, 1, (1 - x - y) / y]
def _transform_summarized_rep(summarized_rep): """change around the keys of the summarized_representation dictionary This makes them more readable This function makes strong assumptions about what the keys look like (see PooledVentralStreams.summarize_representation for more info on this): a single string or tuples of the form `(a, b)`, `(a, b, c), or `((a, b, c), d)`, where all of `a,b,c,d` are strings or ints. We convert them as follows (single strings are untouched): - `(a, b) -> error_a_b` - `(a, b, c) -> error_a_scale_b_band_c` - `((a, b, c), d) -> error_a_scale_b_band_c_d` Parameters ---------- summarized_rep : dict the dictionary whose keys we want to remap. Returns ------- summarized_rep : dict dictionary with keys remapped """ new_summarized_rep = {} for k, v in summarized_rep.items(): if not isinstance(k, tuple): new_summarized_rep["error_" + k] = v elif isinstance(k[0], tuple): new_summarized_rep["error_scale_{}_band_{}_{}".format(*k[0], k[1])] = v else: if len(k) == 2: new_summarized_rep["error_scale_{}_band_{}".format(*k)] = v else: new_summarized_rep['error_' + '_'.join(k)] = v return new_summarized_rep
def strp(value, form): """ Helper function to safely create datetime objects from strings :return: datetime - parsed datetime object """ # pylint: disable=broad-except from datetime import datetime def_value = datetime.utcfromtimestamp(0) try: return datetime.strptime(value, form) except TypeError: try: from time import strptime return datetime(*(strptime(value, form)[0:6])) except ValueError: return def_value except Exception: return def_value
def control_game(cmd): """ returns state based on command """ if cmd.lower() in ("y", "yes"): action = "pictures" else: action = "game" return action
def decompose_seconds(seconds): """ Descomponer una cantidad de segundos en horas, minutos y segundos. :param seconds: :return: """ h = int(seconds // 3600) m = int(seconds % 3600 // 60) s = int(seconds % 60) ms = int((seconds - int(seconds)) * 1000) return h, m, s, ms