content
stringlengths
42
6.51k
def unique_fname(full_path: str) -> str: """Get unique file name for given full path to MELD data file. The return format is '[dialog]_[utterance]'. :param full_path: full path to MELD .mp4 data file :return: unique id of data file (only unique within dataset directory) """ fname = full_path.split(...
def get_only_word(line) -> str: """ Given the line that consists of only one word, return that word in lowercase with no additional whitespace :param line: The string representation of the line :return: The lowercase, trimmed content of the given line """ return line.strip().lower()
def fixed_version(num): """ Decode a fixed 16:16 bit floating point number into a version code. :param num: fixed 16:16 floating point number as a 32-bit unsigned integer :return: version number (float) """ return float("{:04x}.{:04x}".format(num >> 16, num & 0x0000ffff))
def urwid_to_click(color): """convert urwid color name to click color name """ col = color.split()[-1] if col == 'brown': return 'yellow' if col == 'grey': return 'white' return col
def dailyTemperatures(T): """ :type T: List[int] :rtype: List[int] """ res = [0]*len(T) stack = [] for index, value in enumerate(T): while stack and T[stack[-1]] < value: stack_pop = stack.pop() res[stack_pop] = index - stack_pop stack.append(index) ...
def filter_files_on_mdtm(remote_tstamps, local_tstamps=None): """ Compare two timestamps dictionaries for files for files changed Filenames are basenames Positional arguments: - remote_tstamps: dict: A dictionary {filename: {'ftp_mdtm' : timestamp, ... }, ...} - local_tstamps: di...
def rankieToCelcius(rankie:float, ndigits = 2)->float: """ Convert a given value from Rankine to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Celsius """ return round((float(rankie) -...
def _host_dhcp(fixed_ip_ref): """Return a host string for an address""" instance_ref = fixed_ip_ref['instance'] return "%s,%s.novalocal,%s" % (instance_ref['mac_address'], instance_ref['hostname'], fixed_ip_ref['address'])
def tupleize(element, ignore_types=(str, bytes)): """Cast a single element to a tuple.""" if hasattr(element, '__iter__') and not isinstance(element, ignore_types): return element else: return tuple((element,))
def consoO(R,s,tau,w): """Compute the consumption of the old agents Args: R (float): gross return on saving s (float): savings tau (float): percentage of contribution of the wage of the young agent w (float): wage Returns: (float...
def getset_item(obj, item, set=None): """ Get `item` in either a dict or a list `obj` If `set` is specified, `item` in `obj` will be set to `set`s value """ # We don't know whether path elements are strings or ints, so try both for func in [lambda x: x, int]: try: item = func...
def update_running_average(running_average, n, new_obs): """Updates a running average while avoiding large values and provoke overflow. Parameters ---------- cumulative_avg: value of the cumulative average so far n: Number of samples including new observation new_obs: New observation""" a =...
def wrap(n, maxValue): """Auxiliary function to wrap an integer on maxValue. Examples: >>> # For positives: wrap(n, maxValue) = n % maxValue >>> [ wrap(i,3) for i in range(9) ] [0, 1, 2, 0, 1, 2, 0, 1, 2] >>> # For negatives, the pattern is continued in a natura...
def list_to_csv(args): """ Convert a list to a string csv. """ args = map(str, args) args = ",".join(args) return args
def get_p_inf(clusters, shape): """ Returns the probability for a lattice site to be part of the infinite cluster. :param clusters: List cluster sizes. :param shape: Tuple with the shape of the lattice (row first). :return float: Probability for any site to be part of the infinite cluster. ...
def geometry_to_xyz(geometry: list) -> str: """ Creates a string with the .xyz format from a list that represents the geometry Parameters ---------- geometry : list A list returned representing the geometry. Example: [('H', (0.0, 0.0, 0.0)), ('H', (0.0, 0.0, 1.6))] Returns ---------- A string with the ...
def remove_overlap(reg1, reg2, spacer=0): """ Remove overlap between two regions. e.g. [10, 30], [20, 40] returns [10, 20], [30, 40] """ regions = sorted([sorted(reg1), sorted(reg2)]) try: if regions[0][1] - regions[1][0] >= spacer: coords = sorted(reg1 + reg2) re...
def get_type(type_arg): """get the type from type:arg format | str --> str""" return type_arg.partition(':')[0].strip(' ')
def merge_sort(array): """ Sort array in ascending order by merge sort Merge Sort is a Divide and Conquer algorithm. Conceptually, a merge sort works as follows: 1. Divide the unsorted list into n sub-lists, each containing one element (a list of one element is considered sorted). 2. Repe...
def linear_search(array: list): """Find and return the greatest value with a linear search""" maxValue = array[0] for number in array[1:]: if number > maxValue: maxValue = number return maxValue
def _interpret_arg_mode(arg, default="auto"): """ >>> _interpret_arg_mode("Str") 'string' """ if arg is None: arg = default if arg == "auto" or arg == "eval" or arg == "string": return arg # optimization for interned strings rarg = str(arg).strip().lower() if rarg in ...
def hex_to_rgb(hex_string): """Return a tuple of red, green and blue components for the color given as #rrggbb. """ assert len(hex_string) in (4, 7), "Hex color format is not correct." if len(hex_string) == 4: return tuple(int(c * 2, 16) for c in hex_string[1:]) return tuple(int(hex_stri...
def detect_overlap(coords1, coords2): """ Returns `True` if `coords1` overlaps with `coords2`. :param coords1: `list` of two `int` numbers representing **start**, **end** coordinates of a feature :param coords2: `list` of two `int` numbers representing **start**, **end** coordinates of a feature """...
def decode_int_keys(o): """Decode a JSON object while converting string int keys to ints. Inspired by: https://stackoverflow.com/a/48401729 """ def decode_int(string): try: return int(string) except ValueError: return string if isinstance(o, dict): r...
def getSum(a, b): """ a XOR b is the sum a AND b is the carry If there is a nonzero carry, add the carry to the sum and shift the carry to the left. Repeat until the carry is zero. """ sum = a ^ b carry = a & b while carry: sum ^= carry carry <<= 1 retur...
def _py3_compat_decode(item_out_of_redis): """Py3 redis returns bytes, so we must handle the decode.""" if not isinstance(item_out_of_redis, str): return item_out_of_redis.decode('utf-8') return item_out_of_redis
def solution1(s): """ Inefficient solution by myself --- Runtime: 628ms --- :type s: str :rtype: int """ count = len(s) for i in range(len(s)): for j in range(i + 2, len(s) + 1): cur_slice = s[i:j] if cur_slice == cur_slice[::-1]: ...
def filter_cars(car_list: list, year: int) -> list: """Filter cars by year.""" result = [] for car in car_list: if car["year"] < year: result.append(car) return result
def gather_lists(list_): """ Concatenate all the sublists of L and return the result. @param list[list[object]] list_: list of lists to concatenate @rtype: list[object] >>> gather_lists([[1, 2], [3, 4, 5]]) [1, 2, 3, 4, 5] >>> gather_lists([[6, 7], [8], [9, 10, 11]]) [6, 7, 8, 9, 10, 1...
def elo(old, exp, score, k=32): """ Calculate the new Elo rating for a player :param old: The previous Elo rating :param exp: The expected score for this match :param score: The actual score for this match :param k: The k-factor for Elo (default: 32) """ return old + k * (score - exp)
def previous_item(some_list, current_index): """ Returns the previous element of the list using the current index if it exists. Otherwise returns an empty string. """ try: return some_list[int(current_index) - 1] # access the previous element except: return ''
def make_album(artist, title, tracks=''): """Build a dictionary describing a music album.""" album = {'artist_name': artist, 'album_title': title} if tracks: album['tracks'] = tracks return album
def evaluate_term(term): """Converts a term dictionary into a string like "field=^value".""" operator = '=' # This list contains the characters signifying their search modifier in the # order they are listed in the enum. char_list = ['', '*', '>', ']', '<', '[', '^', '!'] if 'modifier' in term....
def levenshtein(top_string, bot_string): """ The Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (i.e. insertions, deletions or substitutions) required ...
def list_break(l, n=2): """ Group a list into consecutive n-tuples. Incomplete tuples are NOT discarded list_break([1,2,3,4,5], 2) => [[1, 2], [3, 4], [5]] list_break([1,2,3,4,5], 6) => [[1, 2, 3, 4, 5]] https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks """ n...
def result(score): """ Returns a string indicating the result of a game https://www.gokgs.com/json/dataTypes.html#score """ if type(score) == float: if score > 0: out = "Black + " + str(score) else: out = "White + " + str(-score) else: out = score ...
def prod(iterable): """Computes the product of all items in iterable.""" prod = 1 for item in iterable: prod *= item return prod
def squash_int_range(ilist): """Takes a list of integers and squashes consecutive values into a string range. Returned list contains mix of strings and ints. """ irange = [] rstart = None rprev = None sorted(ilist) for i, value in enumerate(ilist): if rstart is None: ...
def configureBeam(x, y, z, szNm): """configureBeam(x,y,z, szNm) Create xtraParams entries to configure the beam for the simulation. Input: x, y, z - positions of the beam in meters szNm - the beam diameter in nm (converted to m internally)""" return { "PosX" : x, "PosY" : y, "PosZ": z, "nmSize": sz...
def is_prime(n): """Return boolean if argument is prime number. >>> is_prime(10) False >>> is_prime(7) True """ if n < 2: return False if n == 2: return True if not n & 1: return False for x in range(3, int(n**0.5) + 1, 2): if n % x == 0: ...
def gcd(x, y): """ greatest common divisor of x and y """ while y: x, y = y, x % y return x
def shutdown_hook(f): """Tag a function or method as a shutdown hook.""" def _(): f._nvim_shutdown_hook = True f._nvim_bind = True return f
def get_column_name(row, columns): """ For cases where there is a variation on a particular column name. Final column in list must be the default name. """ for col in columns: if row.get(col): return col return columns[-1]
def sanitize_parameter_overrides(parameter_overrides): """ Get sanitized parameter override values based on if the workflow went via a guided deploy to set the parameter overrides for deployment. If a guided deploy was followed the parameter overrides consists of additional information such as if a give...
def subtract(d1, d2): """Subtracts two dictionaries. Returns a new dictionary containing all the keys from d1 that are not in d2. """ d = {} for key in d1: if key not in d2: d[key] = d1[key] return d
def argflatten(arg_list): """Some list arguments is actually a list of lists. A simple routine to faltten list of lists to a simple list Parameters ========== arg_list: list of lists Value of a list argument needs to be flatten Return ====== arg_as_list: list The flatte...
def distance(duration, speed, fly, rest): """ >>> distance(1000, 14, 10, 127) 1120 >>> distance(1000, 16, 11, 162) 1056 >>> distance(10, 1, 20, 7) 10 """ time = 0 distance = 0 flying = True while time < duration: if flying: flight_time = min(fly, dur...
def tree_right_side_view(root): """ https://leetcode.com/discuss/interview-question/1467470/Facebook-phone-interview Question 2 Args: root: Returns: right side view """ ret = [] if not root: return ret q = [root] while q: ret.append(0) for _ in ra...
def is_palindrome(string: str): """ Determine if a string is a palindrome using recursion. """ if string == '': return True first, last = string[0], string[-1] return (first == last) and is_palindrome(string[1:-1])
def aggregate_position_order(buys: list, sells: list): """ Aggregate the amount field for orders with multiple fills :param buys: a list of buy orders :param sells: a list of sell orders :return: 2 lists containing aggregated amounts for buy and sell orders. """ aggregated_buys = [] aggr...
def rest(array): """Return all but the first element of `array`. Args: array (list): List to process. Returns: list: Rest of the list. Example: >>> rest([1, 2, 3, 4]) [2, 3, 4] See Also: - :func:`rest` (main definition) - :func:`tail` (alias) ...
def is_subset_of(value, subset): """Check if a variable is a subset.""" return set(value) >= set(subset)
def is_iterable(param): """ is iterable :param param: :return: """ try: iter(param) return True except TypeError: return False
def make_token(name, value=''): """Make a token with name and optional value.""" return {'name': name, 'value': value}
def class_name(obj): """ Returns the class name of an object""" return obj.__class__.__name__
def minutes_to_time(minutes_past_midnight): """ Reformat a decimal 'minutes past midnight' to a time string rounded to the nearest second """ hours, remainder = divmod(minutes_past_midnight * 60, 3600) minutes, seconds = divmod(remainder, 60) return '{:02.0f}:{:02.0f}:{:02.0f}'.format(hours,...
def rgb_to_hex(r, g, b, a = 255): """Converts a 8-bit RGBA color to a single integer matching (0xRRGGBBAA). Args: r (int): Red color channel g (int): Green color channel b (int): Blue color channel a (int, optional): Alpha color channel. Defaults to 255. Returns: in...
def getrank(level: int) -> str: """gets rank of a tool""" rank = "impossible" if level >= 200: rank = "netherite" elif level >= 150: rank = "diamond" elif level >= 100: rank = "gold" elif level >= 50: rank = "iron" elif level >= 25: rank ...
def set_background(dark_enabled): """Set the background styles.""" if dark_enabled: # noqa: DAR101, DAR201 return {'background-color': '#303030', 'color': 'white', 'height': '100vh'} return {'background-color': 'white', 'color': 'black', 'height': '100vh'}
def sublist_name_from_connection_id(conn_name, subconn_name): """ Removes prefixed parent_connection_id from connection_id as introduced by sesam 2019.09 :param conn_name: list connection name aka parent_connection_id :param subconn_name: subconnection name aka connection_id """ return conn_...
def compute_most_frequent_repeat_unit(sequence, repeat_unit_size, min_occurrences=3, min_fraction_bases_covered=0.8): """Return the most frequent repeat unit of the given size within the given sequence. Args: sequence (str): a sequence of dna bases repeat_unit_size (int): exact repeat unit size...
def get_monitoring_status(code): """Get monitoring status from code.""" monitoring_status = {0: "Monitored", 1: "Not monitored"} if code in monitoring_status: return monitoring_status[code] + " (" + str(code) + ")" return "Unknown ({})".format(str(code))
def gcd(a,b): """gcd(a,b) returns the greatest common divisor of the integers a and b.""" a = abs(a); b = abs(b) while (a > 0): b = b % a tmp=a; a=b; b=tmp return b
def parse(puzzle_input): """Parse input - break into lines""" return list(filter(bool,puzzle_input.splitlines(False)))
def pretty_size_print(num_bytes): """ Output number of bytes in a human readable format """ if num_bytes is None: return KiB = 1024 MiB = KiB * KiB GiB = KiB * MiB TiB = KiB * GiB PiB = KiB * TiB EiB = KiB * PiB ZiB = KiB * EiB YiB = KiB * ZiB if num_bytes >...
def lerp(x, x0, x1, y0, y1): """Linear interpolation of a value y within y0, y1 given a value x within x0, x1. """ return y0+(x-x0)*((y1-y0)/(x1-x0))
def _split(value): """Split input/output value into two values.""" if isinstance(value, str): # iterable, but not meant for splitting return value, value try: invalue, outvalue = value except TypeError: invalue = outvalue = value except ValueError: raise Value...
def get_image_set_from_skpdiff(skpdiff_records): """Get the set of all images references in the given records. @param skpdiff_records An array of records, which are dictionary objects. """ expected_set = frozenset([r['baselinePath'] for r in skpdiff_records]) actual_set = frozenset([r['testPath'] f...
def repr_func(func): """Attempts to return a representative document of a function/method.""" try: if hasattr(func, "im_self"): im_self = func.im_self full_class_name = str(im_self.__class__) func_name = func.__name__ return ".".join([full_class_name, func...
def check_add_additional_end_lines(value): """Uses to check the additional lines passed to Material and Multimaterial classes are correctly formatted""" if value is not None: string_codes = ["mcnp", "serpent", "shift", "fispact"] if not isinstance(value, dict): raise ValueError(...
def disp_to_depth(disp, min_depth=0.1, max_depth=100.0): """Convert network's sigmoid output into depth prediction The formula for this conversion is given in the 'additional considerations' section of the paper. """ min_disp = 1 / max_depth max_disp = 1 / min_depth scaled_disp = min_disp + ...
def to_language(locale): """ Turn a locale name (en_US) into a language name (en-us). Extracted `from Django <https://github.com/django/django/blob/e74b3d724e5ddfef96d1d66bd1c58e7aae26fc85/django/utils/translation/__init__.py#L265-L271>`_. """ p = locale.find("_") if p >= 0: return locale[:p].lower() ...
def fort_range(*args): """Specify a range Fortran style. For instance, fort_range(1,3) equals range(1,4). """ if len(args) == 2: return range(args[0], args[1]+1) elif len(args) == 3: return range(args[0], args[1]+1, args[2]) else: raise IndexError
def is_anagram_hashmap(s, t): """ Determine whether or not teo given strings are anagram by counting characters Time Complexity: O(n) :param s: source string :type s: str :param t: target string :type t: str :return: whether or not teo given strings are anagram :rtype: bool ...
def check_unique(lst: list, num=9) -> bool: """ Function check if in list of N values aren't any repetition of elements. It there are function return False. True otherwise. >>> check_unique(['1', '2', '3', '4', '5', '6', '7', '*', '*']) True >>> check_unique(['1', '2', '3', '4', '4', '6', '7', '...
def check_module_installed(name): """Check whether a module is available for import. Args: name (str): module name Returns: bool: Whether the module can be imported """ from importlib import import_module try: import_module(name) except ImportError: return...
def listify(string_or_list): """ return a list if the input is a string, if not: returns the input as it was Args: string_or_list (str or any): Returns: A list if the input is a string, if not: returns the input as it was Note: - allows user to use a string as an argument ...
def greet(name): """ Greets a person with their name capitalized. :param name: a string. :return: greets that name, capitalized and ends with an exclamation point. """ return "Hello " + name.capitalize() + "!"
def source_from_url(link): """ Given a link to a website return the source . """ if 'www' in link: source = link.split('.')[1] else: if '.com' in link: source = link.split('.com')[0] else: source = link.split('.')[0] source = source.replace('https...
def vector_dot(vector1=(), vector2=()): """ Computes the dot-product of the input vectors. :param vector1: input vector 1 :type vector1: tuple :param vector2: input vector 2 :type vector2: tuple :return: result of the dot product :rtype: list """ if not vector1 or not vector2: ...
def ifloor(n): """Return the whole part of m/n.""" from math import floor return int(floor(n))
def dollar_signs(value, failure_string='N/A'): """ Converts an integer into the corresponding number of dollar sign symbols. If the submitted value isn't a string, returns the `failure_string` keyword argument. Meant to emulate the illustration of price range on Yelp. """ try: coun...
def top_caller(time_spent_number): """Return a dictionary with time spent for each number. Args: time_spent_number: dictionary with time spent for each number Returns: top_duration: longest duration top_number: number with longest duration """ top_number = None top_durati...
def tuple_to_string(name, results): """Return string from (name, results) tuple""" return name + ' ' + ' '.join([str(x) for x in results])
def parse_token_data(data, token_name): """Reads amount of token from get_data() then return in float. Args: data: data from get_my_token(). token_name: Ex. 'TLM' Returns: amount in float. """ for i in data['tokens']: if token_name in i.values(): retur...
def golf(n, r=1): """Indent only one space would get 3 stars""" for i in str(n): r *= max(int(i), 1) return r
def in_nested_list(nested_list, obj): """return true if the object is an element of <nested_list> or of a nested list """ for elmt in nested_list: if isinstance(elmt, (list, tuple)): if in_nested_list(elmt, obj): return True elif elmt == obj: retur...
def escape_var_name(var_name): """For Pyeda, variable names have to match the expression [a-zA-Z][a-zA-Z0-9_]*. This methods escapes special symbols which don't match this expression. Args: var_name (str): Variable name. Returns: str: Escaped variable name. """ return var_name.replace("#", "___H___").r...
def first_defined_tag(tag_dict, tags, default=''): """ Get first defined tag out of the list in tags. Example usage: tags=['track', 'tracknumber', 'track_number'] To cope with Mutagen's data structures, tag_dict is assumed to be a dictionary of arrays, with only the first element of ...
def _validate_service_identities(value, model): # pylint: disable=unused-argument """Validate service_identities is formatted correctly. :param ServiceIdentities value: A ServiceIdentity list :param rtype: bool """ return all(["ServiceName" in service_identity for service_identity in value])
def signum(x): """cal signum :param x: :return: """ if x > 0: return 1.0 if x < 0: return -1.0 if x == 0: return 0
def display_number(number): """Format number using , as thousands separator.""" return "{:,}".format(number)
def normalize(D, value=1): """normalize. Normalize the coefficients to a maximum magnitude. Parameters ---------- D : dict or subclass of dict. value : float (optional, defaults to 1). Every coefficient value will be normalized such that the coefficient with the maximum magnitu...
def truncate_after(d, n): """Truncate first timestamp dictionary D after N entries.""" sorted_lst = sorted(d.items(), key=lambda a: a[1][0]) return dict(sorted_lst[:n])
def deducirnumero(dedunum): """ Funcion que evalua el numero :return: """ if(dedunum%2 == 0): return "Es par" else: return "Es impar"
def get_market_data_entry(summary, currency): """Converts from Bittrex format to our own.""" return { 'name': summary['MarketName'].replace('%s-' % currency, ''), 'volume': summary['Volume'], # Hope for the best. 'price': summary['Last'] }
def match_context_key(key): """Set the case of a context key appropriately for this project, Roman always uses upper case. >>> match_context_key('aB.$QqZ4nB') 'AB.$QQZ4NB' """ return key.upper()
def summation_i_squared(n): """ Write a function def summation_i_squared(n): that calculates sum_{i=1}^{n} i^2 n is the stopping condition Return the integer value of the sum If n is not a valid number, return None You are not allowed to use any loops """ if type(n) == int and n...
def verse(day): """Produce the verse for the given day""" ordinal = [ 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', ] gifts = [ ...
def create_entities_dict(name, face_entity_list, solid_entity_list, main_object=None): """ Helper method for creating an entities dictionary. :param name: name of the collection of entities :param face_entity_list: [face_entity_1, ..., face_entity_n] :param solid_entity_list: [solid_entity_1, ...,...