content
stringlengths
42
6.51k
def build_speechlet_response(title, output, reprompt_text, should_end_session): """ Build a response containing both speech and a card """ return { 'outputSpeech': { 'type': 'PlainText', 'text': output }, 'card': { 'type': 'Simple', 'title'...
def _stringify_tensor(obj): """Try to stringify a tensor.""" if hasattr(obj, 'name'): return str(obj.name) else: return str(obj)
def decode_to_unicode(data): """Recursively decodes byte strings to unicode""" if isinstance(data, bytes): return data.decode('utf-8') elif isinstance(data, dict): return dict((decode_to_unicode(k), decode_to_unicode(v)) for k, v in data.items()) elif isinstance(data, list): ...
def validate_resource_noun(resource_noun: str) -> bool: """Validates resource noun. Args: resource_noun: resource noun to validate Returns: bool: True if no errors raised Raises: ValueError: If resource noun not supported. """ if resource_noun: return True ra...
def pairs2map( pairs, key_col=0, value_col=1): """Converts a list of key value pairs to a dictionary. @type pairs: array @param pairs: an array of key value paris, representing a map as a list of tuples. @type key_col: mixed @param key_col: the column that contains the key (defa...
def robust_join(s, sep=','): """Join an iterable converting each element to str first.""" return sep.join([str(e) for e in s])
def get_resort_test(files): """Re-sort the files under data path. :param files: file list :type files: list :return: alphabetic orders :rtype: list """ name_dict = {} for sample in files: name = sample.lower() name_dict[name] = sample re_file = [name_dict[s] for s in...
def _normalize_vendor(vendor): """Return a canonical name for a type of database.""" if not vendor: return "db" # should this ever happen? if "sqlite" in vendor: return "sqlite" if "postgres" in vendor or vendor == "psycopg2": return "postgresql" return vendor
def get_contain_flag(correct_entity_group, source_dependence): """determine whether correct_entity_group is included in source_dependence""" contain_flag = True for inline_entity in correct_entity_group: if inline_entity not in source_dependence: contain_flag = False break ...
def unique(iterable): """Remove duplicates from `iterable`.""" return type(iterable)(x for x in dict.fromkeys(iterable))
def check_for_wrong_schema(error): """ Checks if column does not exist """ return "UndefinedColumn" in str(error)
def is_power_of_2(num : int) -> bool: """ Finds whether a number is a power of 2. Parameters: num: the number to be checked Returns: True if number is a power of 2, otherwise False """ if num <= 0: raise ValueError else: if num & (num - 1) == 0: ...
def remove_identical_kinetics(k_list): """ removes all identical kinetics entries in k_list takes in a list of kinetics entries returns the list with the identical kinetics entries removed does this based on strings, which should be fine for this specifically, since we shouldn't have any id...
def _is_subpath(path, ancestors): """Determines if path is a subdirectory of one of the ancestors""" for ancestor in ancestors: if path == ancestor: return True if not ancestor.endswith("/"): ancestor += "/" if path.startswith(ancestor): return True ...
def _chr(i): """Converts an int to 1-char byte string. This function is used for python2 and python3 compatibility. See http://python-future.org/compatible_idioms.html#byte-string-literals Args: i: The integer to convert. Returns: A 1-char byte string with the input value as the b...
def GetResourceIdFromString(setting): """Returns the resource id from the setting path. A setting path should start with following syntax: [organizations|folders|projects]/{resource_id}/settings/{setting_name}/value Args: setting: A String that contains the setting path """ return setting.split('/')[1...
def html_color_to_rgb(hexcolor): """Convert #RRGGBB to an (R, G, B) tuple.""" if not hexcolor.startswith('#'): raise ValueError(f"Invalid color string '{hexcolor}' (should start with '#')") hexcolor = hexcolor[1:] if len(hexcolor) not in {3, 6}: raise ValueError(f"'#{hexcolor}'' is no...
def _calculateRankForStats(wins: int, losses: int, ties: int) -> int: """ Calculates the rank for single gameType. Returns 0 if gameType is any """ return (wins * 1) + (losses * -1) + (ties * 0)
def make_pairs_for_model(model_num=0): """ Create a list of pairs of model nums; play every model nearby, then every other model after that, then every fifth, etc. Returns a list like [[N, N-1], [N, N-2], ... , [N, N-12], ... , [N, N-50]] """ if model_num == 0: return pairs = [] pai...
def _str_eval_break(eval, act, ctxt) : """Passes through [break] so that the writer can handle the formatting code.""" return ["[break]"]
def TimeStr(ms): """ Returns a time string """ s=ms/1000 m,s=divmod(s,60) h,m=divmod(m,60) d,h=divmod(h,24) if m > 0: return "%d Min %d Sec" % (m,s) else: return "%d Seconds" % (s)
def text_box_end_pos(pos, text_box, border=0): """ Calculates end pos for a text box for cv2 images. :param pos: Position of text (same as for cv2 image) :param text_box: Size of text (same as for cv2 image) :param border: Outside padding of textbox :return box_end_pos: End xy coordinates for t...
def insensitive_glob(value, prefix="*."): """ Convert an extension to a case-insensitive glob. """ return prefix + "".join(f"[{v.lower()}{v.upper()}]" for v in value)
def add_dict(left, right): """Merge two dictionaries by adding common items. Parameters ---------- left: dict Left dictionary. right Right dictionary Returns ------- dict Resulting dictionary """ return {k: left.get(k, 0) + right.get(k, 0) for k in le...
def _intersect(lst_a, lst_b): """ return the intersection of two lists """ return list(set(lst_a) & set(lst_b))
def trade_normalize_slot_name(name: str) -> str: """Normalizes the slot name as in TRADE. Extracted from get_slot_information in https://github.com/jasonwu0731/trade-dst/blob/master/utils/utils_multiWOZ_DST.py. """ if "book" not in name: return name.replace(" ", "").lower() return name.lowe...
def count_models(hyper_params): """ Given a hyper_params dict, this function will return the maximum number of models that can be built out of all the combination of hyper-parameters. :param hyper_params: dict containing parameter name and a list of values to iterate over :return: max_model_number:...
def _breakLineSplitPos (text, maxWidth): """ Get position for text splitting. """ if len (text) < maxWidth: return len (text) lastSplitPos = None for i in range (1, len (text)): if text[i] == " " or text[i] == "\t" or text[i] == "\n": if (i >= maxWidth): ...
def quote(string): """Add quotes to the beginning and the end of a string if not already present.""" string_elements = [] if not string.startswith('\''): string_elements.append('\'') string_elements.append(string) if not string.endswith('\''): string_elements.append('\'') return ...
def splitBinNum(binNum): """Split an alternate block number into latitude and longitude parts. Args: binNum (int): Alternative block number Returns: :tuple Tuple: 1. (int) Latitude portion of the alternate block number. Example: ``614123`` => ``614`` 2....
def tohex(s): """Convert a string to hexadecimal""" return ''.join([hex(ord(c))[2:].zfill(2) for c in s])
def resolve_thumbnail(url_id, requested_size='original'): """Format the properties of the ``resolve_thumbnail`` event. :param url_id: the resolve ID of the URL that was resolved :type url_id: str :param requested_size: Thumbnails can be requested in different sizes, log which...
def get_required_values(generator, field): """Get required values for a generator from the field. If required value is a function, calls it with field as argument. If required value is a string, simply fetch the value from the field and return. """ # FIXME: avoid abbreviations rt = {} i...
def get_significant_count(values): """removes leading zero's from the list.""" count = len(values) i = count - 1 while count and not values[i]: i -= 1 count -= 1 return count
def top_files(query, files, idfs, n): """ Given a `query` (a set of words), `files` (a dictionary mapping names of files to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the filenames of the the `n` top files that match the query, ranked accord...
def get_asn_via_macaddress(flow_asn_macaddr, d_mapping_macaddress_member_asn): """ Lookup mac2asn -- get and transform mac address to same format as mac2as mapping data :param flow_asn_macaddr: :return: """ flow_mac2asn = 'UNKNOWN' if flow_asn_macaddr in d_mapping_macaddress_member_asn: ...
def default_input(input, default=None): """Process the keyword input in the function. Args: input: Keyword input for the function. Return: `default` when input is `None`, otherwise `input`. """ if input is None: return default else: return input
def RPL_TRACELINK(sender, receipient, message): """ Reply Code 200 """ return "<" + sender + ">: " + message
def app_name(experiment_uuid): """Convert a UUID to a valid Heroku app name.""" return "dlgr-" + experiment_uuid[:8]
def __format_size(file_size): """ Format file size information depending on the amount of bytes. """ file_size = int(file_size) list_units = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] list_index = 0 while file_size > 1000: file_size = float(file_size) / 1000 l...
def is_tune_grid_search(obj): """Checks if obj is a dictionary returned by tune.grid_search. Returns bool. """ return isinstance( obj, dict) and len(obj) == 1 and "grid_search" in obj and isinstance( obj["grid_search"], list)
def count_trees(tree_map, down, right): """Count number of trees encountered in tree_map, with down, right steps.""" column = 0 trees = 0 for index, row in enumerate(tree_map[::down]): if row[column] == '#': trees += 1 column = (column + right) % len(row) return trees
def topsort(edge_dict, root=None): """ List of nodes in topological sort order from edge dict where key = rv and value = list of rv's children """ queue = [] if root is not None: queue = [root] else: for rv in edge_dict.keys(): prior=True for p in edge_dict.keys(): if rv in edge_dict[p]: prior...
def merge_bytes(*args): """Returns a single list of bytes from given bytes and list of bytes. Arguments: *args -- bytes and list of bytes to merge """ result = [] for arg in args: if type(arg) in [list, tuple]: result.extend(arg) else: result.append(arg) ...
def compare_keywords(new_keywords, old_keywords): """compares two lists of keywords, and returns True if they are the same.""" if len(new_keywords) != len(old_keywords): return False for keyword in new_keywords: found_it = False for old_keyword in old_keywords: if old_key...
def myfloat(value, prec=4): """ round and return float """ return round(float(value), prec)
def rocket_mode(new_mode=None): """set mode if new_mode is defined. return current mode.""" global _rocket_mode if new_mode is not None: _rocket_mode = new_mode return _rocket_mode
def build_compare_words(lookup, compareto, jenkin_build_terms): """ :param lookup: :param compareto: :param jenkin_build_terms: :return: """ result = False if compareto: if "-" in compareto: compareto = compareto.replace("-", "_") if " " in compareto: ...
def _identifier_split(identifier): """Return (name, start, end) string tuple from an identifier (PRIVATE).""" id, loc, strand = identifier.split(":") start, end = map(int, loc.split("-")) start -= 1 return id, start, end, strand
def str_to_bool(value: str) -> bool: """Deduce boolean value from string. Credits: flask-restful""" if not value: raise ValueError("boolean type must be non-null") value = value.lower() if value in ('true', 'yes', '1',): return True if value in ('false', 'no', '0',): retu...
def v4_tail(iterable, n): """Return the last n items of given iterable. For the second bonus we were supposed to make our function work with any kind of iterable. We could just convert the incoming iterable to a listself. But this might not be a good idea. If someone calls our function with a very...
def make_score(word, score): """Return a wordscore list from two strings that can be used by the solver's reduce function. e.g. word='later' and score='21011' would give [['l', 2], ['a', 1], ['t', 0], ['e', 1], ['r', 1]] """ return [[l, int(s)] for l, s in zip(word, score)]
def max_continuous_interval(int_list): """ The size of the longest continuous number sequence in a list """ int_list = sorted(int_list) if not int_list: return 0 max_size = 1 first, last = int_list[0], int_list[0] for number in int_list[1:]: if number == last + 1: ...
def _clean(txt): """Replace all whitespace with a single space.""" return " ".join(txt.split()).strip()
def alphabetical_value(name): """ Returns the alphabetical value of a name as described in the problem statement. """ return sum([ord(c) - 64 for c in list(str(name))])
def get_level(*var_arr): """ :param vars: :return: [None,None,1] -> 3 [1,1,1] -> 3 [1,1,None] -> 2 """ level = -1 for index, var in enumerate(var_arr): if var is not None: level = index + 1 return level
def render_boolean(value, title, show_false=False): """Returns a HMTL snippet which can be inserted as True/False symbol. """ return { 'boolean_value': value, 'title': title, 'show_false': show_false }
def from_datastore(entity): """Translates Datastore results into the format expected by the application. Datastore typically returns: [Entity{key: (kind, id), prop: val, ...}] This returns: [ name, street, city, state, zip, open_hr, close_hr, phone, drink, rating, website ] where n...
def check_filename_by_pattern(filename, include=None, exclude=None): """Check whether filename contain specific pattern. Parameters ---------- filename : str Filename to be checked. include : list List of allowed patterns. exclude : list List of not allowed patterns. ...
def get_triangle_number(n): """ A triangle number is a number who has for value the sum of the n first positives integers. This function return the n-th triangle number. """ return (n*(n+1))//2
def scale(x,range1=(0,0),range2=(0,0)): """ Linear scaling for a value x """ return range2[0]*(1 - (x-range1[0]) / (range1[1]-range1[0])) + range2[1]*((x-range1[0]) / (range1[1]-range1[0]))
def label_selectors(labels): """ :param labels: dictionary containing k, v :return: string of k8s labels """ return ",".join(["%s=%s" % (k, v) for k, v in labels.items()])
def solver_handler(arg): """Check if an object is a Handler and if so, solve it.""" if getattr(arg,'_is_Handler',False): return arg.solve else: return arg
def remove_0x_head(s): """ Better use from django_eth_events.utils import remove_0x_head, because in pyEthereum version <= 1.6.1 is bugged for Python3 """ return s[2:] if s[:2] in (b'0x', '0x') else s
def prefix_spaces(s: str) -> int: """Count number of prefix spaces in a string.""" count = 0 for x in s: if x != ' ': return count count += 1 return count
def string_dlt_to_dlt(dlt_str_rep): """ Return dictionary/list/tuple from given string representation of dictionary/list/tuple Parameters ---------- dlt_str_rep : str '[]' Examples -------- >>> string_dlt_to_dlt("") Traceback (most recent call last): ... SyntaxErr...
def pkt_line(data): """Wrap data in a pkt-line. Args: data: The data to wrap, as a str or None. Returns: The data prefixed with its length in pkt-line format; if data was None, returns the flush-pkt ('0000'). """ if data is None: return b'0000' return ('%04x' % (len(data) ...
def is_pdf(file_path): """ Checks whether the file is a pdf. """ import mimetypes type = mimetypes.guess_type(file_path)[0] return type and type == 'application/pdf'
def predictXVal(y, params): """ Predicts the x-axis value of a given y-axis value that belongs to a curve given its parameters @param y: y-axis value of the points to be estimated @param params: (tuple) of the lane line fitted parameters """ a, b, c = params return a*y**2 + b*y + c
def _strip_header(doc): """Strip Matlab header and splash info off doc. Searches for the tag 'NIPYPE' in the doc and returns everyting after that. """ hdr = 'NIPYPE' # There's some weird cruft at the end of the docstring, almost looks like # the hex for the escape character 0x1b. cruft = '...
def remove_none_from_list(lst: list): """ Create a new list from the given one without `None` entries. :param lst: list to remove the `None` entries from :return: list without `None` entries from """ return [item for item in lst if item is not None]
def aggregate_results(results, callback_per_result=None): """ Aggregate results :param results: dict as from test_results() :returns: tuple (num_tests, num_errors, num_failures) """ sum_tests = sum_errors = sum_failures = 0 for name in sorted(results.keys()): (num_tests, num_errors,...
def has_auxiliary(heat_type): """Determines if the heating type has aux capability Parameters ---------- heat_type : str The name of the heat type Returns ------- boolean """ if heat_type == "heat_pump_electric_backup": return True return False
def convert_progress_bar(value): """ Converts float value in database to progress percentage use in progress bar. Args: value (float): The float value that you want to convert Returns: float: The converted value that will use in progress bar. """ if type(value) is not float: ...
def bits_diff(bits_a, bits_b): """Returns the Hamming distance between two bitstrings. Parameters ---------- bits_a : Tuple[int] The first string. bits_b : Tuple[int] The second string. Returns ------- int The number of bits that differ. """ return sum(...
def analyze_drift( datadrift: dict, ) -> bool: """Analyze the Evidently drift report and return a true/false value indicating whether data drift was detected. Args: datadrift: datadrift dictionary created by evidently """ drift = datadrift["data_drift"]["data"]["metrics"]["dataset_drift...
def sf_trans_to_sf_percent(sf_trans_since_BB, sf_start_t, age_of_universe): """Takes a sf_trans_since_BB and translates it to a percentage.""" return (sf_trans_since_BB - sf_start_t)/(age_of_universe - sf_start_t)
def get_p(k, var): """ In the numpy implementation the probability of success is needed, so this returns to probability of success. """ return k/float(var)
def replace(board, old, replaceWith): """ Replaces a character in the board. replace(LIST, CHARACTER, CHARACTER TO REPLACE IT WITH) >>> replace(["A", "B"], "B", "X") ["A", "X"] """ # Loops through every index of the board for x in range(len(board)): # If the current ind...
def str_cvt_lower(s): """konversi besar->kecil""" return s.lower()
def is_master_manifest(manifest_content): """ Parse the m3u8 manifest to see if this is the master manifest that points to other manifests. :param manifest_content: :return: True if it's the master manifest """ manifest_lines = manifest_content.split('\n') for line in manifest_lines: ...
def check_new_adjacents(row, col, seat_map): """ Return the no. of adjacent seats occupied """ occupied = 0 # ttb = top to bottom, ltr = left to right directions = ((-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1)) for direction in directions: pos = (col + direction[0], ...
def _check_coords_range(selected_range, coordinate, full_range): """Check that the coordinates range arguments follow the expected pattern in the **import_mrms_grib** function.""" if selected_range is None: return sorted(full_range) if not isinstance(selected_range, (list, tuple)): if...
def origin_fun(x,case=1): """ Some functions defined on [0,1] to be expanded by Fourier basis :param x:The point where the function need to be evaluated :param case: Considered case :return: Corresponding function value """ if case==1: return 32*x*x*(1-x)*(1-x) if case==2: ...
def TurkeyFilter(c): """Returns True if color can be classified as a shade of turkey""" if (c[2] > c[0]) and (c[1] > c[0]) and (c[2] == c[1]): return True else: return False
def get_sharenums(tw_vectors): """ :param tw_vectors: See ``allmydata.interfaces.TestAndWriteVectorsForShares``. :return set[int]: The share numbers which the given test/write vectors would write to. """ return set( sharenum for (sharenum, (test, data, new_length)) i...
def strtobool(s): """ @returns: Boolean version of s @type s: unicode @rtype: bool """ return s in (u"True", u"true", u"t")
def damerau_levenshtein(s1, s2, cost): """Calculates the Damerau-Levenshtein distance between two strings. The Levenshtein distance says the minimum number of single-character edits (i.e. insertions, deletions, swap or substitution) required to change one string to the other. The idea is to reserve...
def convert_value_to_query_param(key: str, value): """ Convert key/value pairs to a string suitable for query parameters eg {'type': 'organisation'} becomes type=organisation eg {'type': ['organisation', 'organisation']} becomes type=organisation&type=organisation """ if value is None: r...
def bit_flip(bit): """Do a bit flip""" if bit == '1': return '0' else: return '1'
def jaccard_set(list1, list2): """Define Jaccard Similarity function for two sets""" intersection = len(list(set(list1).intersection(list2))) union = (len(list1) + len(list2)) - intersection return float(intersection) / union
def local(public_repo_name): """Return local form of public repo name. Aptly REST API interprets '_' as '/' in repo names. :param public_repo_name: The name of the repo (e.g. a4pizza/base) """ return public_repo_name.replace('/', '_')
def remove_extra_spaces(text: str) -> str: """Remove extranious spaces.""" template = [('\r', ' '), ('\n', ' '), ('\t', ' ')] for token, replacement in template: text.replace(token, replacement) return ' '.join( text.split() )
def split_cmp_command(cmd, remove_quotes=True): """ Splits a command line. @param cmd command line @param remove_quotes True by default @return list """ if isinstance(cmd, str): spl = cmd.split() res = [] for s in spl: ...
def assign_crn_species(crn, signals): """ Returns types of species in a given CRN. On the types of species in an implementation CRN: - Signal species are implementation species that (are supposed to) correspond to formal species in a formal CRN. - Fuel species are implementation speci...
def primes(limit): """ Get all primes below a limit """ if limit < 2: return [] prime = [True for i in range(limit + 1)] result = [] for i in range(2, limit + 1): if prime[i]: result.append(i) for j in range(2, limit // i + 1): if i...
def gcd(a, b): """ Euclidean alg """ r = {0: a, 1: b} # remainders q = {} # quotients m = 1 while r[m] != 0: q[m] = r[m - 1] // r[m] r[m + 1] = r[m - 1] - (q[m] * r[m]) m += 1 m -= 1 return r[m]
def _check_pandas_installed(strict=True): """Aux function.""" try: import pandas return pandas except ImportError: if strict is True: raise RuntimeError('For this functionality to work, the Pandas ' 'library is required.') else: ...
def check_container(container, _type) -> tuple: """ Given a container object, check and see if the contents match the specified type If the test fails, return the offending type, false flag and the offending index """ if not(hasattr(container, '__iter__')): raise ValueError( ...
def dcu(d1, d2): """Dict copy & update, returning the new dictionary""" rval = d1.copy() rval.update(d2) return rval