content
stringlengths
42
6.51k
def get_available_username(user_profile): """ Determines the username based on information available from slack. First information is used in the following order: 1) display_name, 2) real_name :param user_profile: Slack user_profile dict :return: human-readable username """ display_name = user_profile["display_name_normalized"] if display_name: return display_name real_name = user_profile["real_name_normalized"] if real_name: return real_name raise ValueError("User Profile data missing name information")
def _TypeMismatch(a, b): """The entries at the same position in A and B have differing types.""" return 'Types do not match, %s v. %s' % (str(a), str(b))
def get_python_exec(py_num: float, is_py2: bool = False) -> str: """ Get python executable Args: py_num(float): Python version X.Y is_py2(bool): for python 2 version, Set True if the returned result should have python2 or False for python. Returns: str: python executable """ if py_num < 3: if is_py2: py_str = "2" else: py_str = "" else: py_str = "3" return f"python{py_str}"
def step_function(x: float): """ Mathematical step function A type of indicatio function/characteristic function. """ return 1.0 if x >= 0 else 0.0
def mosek_test_tags(mosek_required = True): """Returns the test tags necessary for properly running MOSEK tests. By default, sets mosek_required=True, which will require that the supplied tag filters include "mosek". MOSEK checks a license file outside the workspace, so tests that use MOSEK must have the tag "no-sandbox". """ nominal_tags = [ "no-sandbox", ] if mosek_required: return nominal_tags + ["mosek"] else: return nominal_tags
def _DictToString(dictionary): """Convert a dictionary to a space separated 'key=value' string. Args: dictionary: the key-value dictionary to be convert Returns: a string representing the dictionary """ dict_str = ' '.join(' {key}={value}'.format(key=key, value=value) for key, value in sorted(dictionary.items())) return dict_str
def are_n(n): """A bit of grammar. This function returns a string with the appropriate singular or plural present indicative form of 'to be', along with 'n'.""" choices = ['are no', 'is 1', f'are {n}'] if n < 2: return choices[n] else: return choices[2]
def parse_content_type(c): """ A simple parser for content-type values. Returns a (type, subtype, parameters) tuple, where type and subtype are strings, and parameters is a dict. If the string could not be parsed, return None. E.g. the following string: text/html; charset=UTF-8 Returns: ("text", "html", {"charset": "UTF-8"}) """ parts = c.split(";", 1) ts = parts[0].split("/", 1) if len(ts) != 2: return None d = {} if len(parts) == 2: for i in parts[1].split(";"): clause = i.split("=", 1) if len(clause) == 2: d[clause[0].strip()] = clause[1].strip() return ts[0].lower(), ts[1].lower(), d
def chopping(long_string): """ Twitch won't let you send messages > 500 :param long_string: :return: """ texts = [] start, index = 0, 0 while index >= 0: index = long_string.find(',', start + 450) if index > 0: texts.append(long_string[start:index]) else: texts.append(long_string[start:]) break start = index return texts
def remove_start_end_blanks(regex, list_span): """ if regex starts with \n and end with multiple spaces shortens the spans of the corresponing length""" if regex[0:2]==r"\n": list_span = [(x[0]+1, x[1]) for x in list_span] if regex[-2:] == " ": list_span = [(x[0], x[1]-2) for x in list_span] return list_span
def concatenateString(data, delimiter='\t'): """ Concatenate string list by using proviced delimeter Args: data: list of strings delimiter: symbol, default to ' ', used to separate text Returns: Concatenated strings separated by delimeter """ return delimiter.join(data)
def _filter_match_all(elements, keywords): """ Returns the elements for which all keywords are contained. :param elements: a list of strings to filter :param keywords: a tuple containing keywords that should all be included :return: matching matching elements """ matching = [] for elem in elements: if all(keyword in elem for keyword in keywords): matching.append(elem) return matching
def find_largest_digit(n): """ :param n: The integer that is given :return: The largest digit of the integer """ if n < 0: n = -n if 0 < n < 10: # Base case return n else: if n % 10 > n // 10 % 10: # n % 10 is the first digit counted from right side of the integer # n // 10 % 10 is the second digit counted from right side of the integer return find_largest_digit(n//10 + (n % 10 - n // 10 % 10)) # n // 10 is to reduce the number of digits from right side # (n % 10 - n // 10 % 10) is the difference between the two number # Adding the difference to keep the larger digit in the integer else: return find_largest_digit(n // 10)
def extract_attribute_ids(geographical_type_id, attributes): """PointSource-specific version of util.extract_attribute_ids() (q.v.)""" id_name = 'NPDES' if geographical_type_id == 'Facility' else geographical_type_id return [attribute[id_name] for attribute in attributes]
def promote_columns(columns, default): """ Promotes `columns` to a list of columns. - None returns `default` - single string returns a list containing that string - tuple of strings returns a list of string Parameters ---------- columns : str or list of str or None Table columns default : list of str Default columns Returns ------- list of str List of columns """ if columns is None: if not isinstance(default, list): raise TypeError("'default' must be a list") return default elif isinstance(columns, (tuple, list)): for c in columns: if not isinstance(c, str): raise TypeError("columns must be a list of strings") return list(columns) elif isinstance(columns, str): return [columns] raise TypeError("'columns' must be a string or a list of strings")
def countRunningCoresCondorStatus(status_dict): """ Counts the cores in the status dictionary The status is redundant in part but necessary to handle correctly partitionable slots which are 1 glidein but may have some running cores and some idle cores @param status_dict: a dictionary with the Machines to count @type status_dict: str """ count = 0 # The loop will skip elements where Cpus or TotalSlotCpus are not defined for collector_name in status_dict: for glidein_name, glidein_details in status_dict[collector_name].fetchStored().items(): if not glidein_details.get("PartitionableSlot", False): count += glidein_details.get("Cpus", 0) return count
def trim_sequence( seq:str, maxlen:int, align:str="end") -> str: """ Trim `seq` to at most `maxlen` characters using `align` strategy Parameters ---------- seq : str The (amino acid) sequence maxlen : int The maximum length align : str The strategy for trimming the string. Valid options are `start`, `end`, and `center` Returns ------- trimmed_seq : str The trimmed string. In case `seq` was already an appropriate length, it will not be changed. So `trimmed_seq` could be shorter than `maxlen`. """ seq_len = len(seq) assert maxlen <= seq_len if align == "end": return seq[-maxlen:] elif align == "start": return seq[0:maxlen] elif align == "center": dl = seq_len - maxlen n_left = dl // 2 + dl % 2 n_right = seq_len - dl // 2 return seq[n_left:n_right] else: raise ValueError("align can be of: end, start or center")
def capwords(s, sep=None): """capwords(s [,sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words. """ if sep is None: sep = ' ' return sep.join(x.capitalize() for x in s.split(sep)) #return (sep or ' ').join(x.capitalize() for x in s.split(sep))
def get_tp_fp_fn(gold_annotation, candidate_annotation): """ Get the true positive, false positive, and false negative for the sets :param gold_annotation: :param candidate_annotation: :return: """ tp, fp, fn = 0., 0., 0. for c in candidate_annotation: if c in gold_annotation: tp += 1 else: fp += 1 for g in gold_annotation: if g not in candidate_annotation: fn += 1 # How to handle empty gold and candidate sets? return {"true_positive": tp, "false_positive": fp, "false_negative": fn}
def _check_need_broadcast(shape1, shape2): """Returns True if broadcast is necessary for batchmatmul.""" return shape1[:-2] != shape2[:-2]
def find_longest_substring(s: str, k: int) -> str: """ Speed: ~O(N) Memory: ~O(1) :param s: :param k: :return: """ # longest substring (found) lss = "" # current longest substring c_lss = "" # current list of characters for the current longest substring c_c = [] i = 0 for i, c in enumerate(s): # current character is in list of characters of the current substring ? if c in c_c: # if yes, increase/update current substring c_lss += c else: # else # Can we add the new character in the current substring ? if len(c_c) < k: # if yes: increase/updating the current substring c_lss += c else: # else => compare the current result (substring) & start a new substring research # compare the current substring with the longest substring found as far # Current substring is larger ? if len(c_lss) > len(lss): # if yes: update the longest substring lss = c_lss # in any case => start a new substring research # first element is: the last character of the previous current substring c_c = [c_lss[-1]] c_lss = c_lss[-1] + c # Early exit: at this moment, can we found a larger substring ? if (len(s) - i + len(c_lss)) <= len(lss): break # add the new character in list of current character for substring c_c += [c] # perform a last comparaison for current substring if len(c_lss) > len(lss): lss = c_lss # print(len(s) - i - 1) return lss
def perimeter_square(n): """ Take the length of the side of a square and calculate the perimeter, given by 4*n. """ perimeter = 4*n return perimeter
def join_schema_func(func): """Join the schema and function, if needed, to form a qualified name :param func: a schema, function tuple, or just an unqualified function name :returns: a possibly-qualified schema.function string """ if isinstance(func, tuple): return "%s.%s" % func else: return func
def escape_backticks(text: str) -> str: """Replace backticks with a homoglyph to prevent text in codeblocks and inline code segments from escaping. """ return text.replace("\N{GRAVE ACCENT}", "\N{MODIFIER LETTER GRAVE ACCENT}")
def lix(n_words, n_long_words, n_sents): """ Readability score commonly used in Sweden, whose value estimates the difficulty of reading a foreign text. Higher value => more difficult text. References: https://en.wikipedia.org/wiki/LIX """ return (n_words / n_sents) + (100 * n_long_words / n_words)
def get_tags(data): """ Gets all of the tags in the data >>> get_tags({ \ "paths": { \ "1": {"a": {"tags": ["c"]}, \ "b": {"tags": ["c"]}}, \ "2": {"a": {"tags": ["b"]}, \ "d": {}}, \ "3": {"c": {"tags": ["d", "e"]}} \ } \ }) ['', 'b', 'c', 'd', 'e'] """ tags = set() for methods in data["paths"].values(): for method in methods.values(): if type(method) is list: continue tags |= set(method.get("tags", [""])) return sorted(list(tags))
def get_star_index_files(path:str, with_sjdb_files:bool=False): """ Find the file names necessary for a STAR index rooted at path. Parameters ---------- path: string the path to the directory containing the STAR index with_sjdb_files: bool whether to include the splice junction database files in the returned list Returns ------- star_index_files: list of strings the complete paths to all of the files expected for a STAR index rooted at path (include sjdb/exon files, if specified) """ import os star_files = [ "chrLength.txt", "chrNameLength.txt", "chrName.txt", "chrStart.txt", "Genome", "genomeParameters.txt", "SA", "SAindex" ] sjdb_files = [ "exonGeTrInfo.tab", "exonInfo.tab", "geneInfo.tab", "sjdbInfo.txt", "sjdbList.fromGTF.out.tab", "sjdbList.out.tab", "transcriptInfo.tab" ] if with_sjdb_files: sf = star_files + sjdb_files else: sf = star_files star_index_files = [ os.path.join(path, star_file) for star_file in sf] return star_index_files
def data_resource_creator_permissions(creator, resource): """ Assemble a list of all permissions needed to create data on a given resource @param creator User who needs permissions @param resource The resource to grant permissions on @return A list of permissions for creator on resource """ permissions = [] for perm in 'SELECT', 'MODIFY', 'ALTER', 'DROP', 'AUTHORIZE': permissions.append((creator, resource, perm)) if resource.startswith("<keyspace "): permissions.append((creator, resource, 'CREATE')) keyspace = resource[10:-1] # also grant the creator of a ks perms on functions in that ks for perm in 'CREATE', 'ALTER', 'DROP', 'AUTHORIZE', 'EXECUTE': permissions.append((creator, '<all functions in %s>' % keyspace, perm)) return permissions
def getMimeType(content_type): """ Extract MIME-type from Content-Type string and convert it to lower-case. .. deprecated:: 0.4 """ return content_type.partition(";")[0].strip().lower()
def wcs_axis_to_data_axis(wcs_axis, missing_axis): """Converts a wcs axis number to the corresponding data axis number.""" if wcs_axis is None: result = None else: if wcs_axis < 0: wcs_axis = len(missing_axis) + wcs_axis if wcs_axis > len(missing_axis)-1 or wcs_axis < 0: raise IndexError("WCS axis out of range. Number WCS axes = {0}".format( len(missing_axis))) if missing_axis[wcs_axis]: result = None else: data_ordered_wcs_axis = len(missing_axis)-wcs_axis-1 result = data_ordered_wcs_axis-sum(missing_axis[::-1][:data_ordered_wcs_axis]) return result
def types(items): """ Assignment 5 updated """ result = [] for i in items: if isinstance(i, int): i_mall = "The square of {} is {}." result.append(i_mall.format(i, i*i)) elif isinstance(i, str): s_mall = "The secret word is {}." result.append(s_mall.format(i)) elif isinstance(i, list): l_mall = "The list contains {}." result.append(l_mall.format(", ".join(i))) else: pass return " ".join(result)
def strict_exists(l, f): """Takes an iterable of elements, and returns (False, None) if f applied to each element returns False. Otherwise it returns (True, e) where e is the first element for which f returns True. Arguments: - `l`: an iterable of elements - `f`: a function that applies to these elements """ for e in l: if f(e) == True: return (True, e) elif f(e) == False: pass else: raise TypeError("Expected a Boolean") return (False, None)
def sentiment_display(sentiment_score): """ Returns a human readable display value for a sentiment score """ if sentiment_score is None: return None sentiment = 'Neutral' if sentiment_score < 0: sentiment = 'Negative' elif sentiment_score > 0: sentiment = 'Positive' return sentiment
def step_backward(position, panel_l, panel_r, connection_map): """ This function sounds as the character moves from the reflex board to the plug. Its similar to the previous one, but vice versa :param position: Position of the char in the list. :param panel_r: The list that represents the right side of the router :param panel_l: The list that represents the left side of the router :param connection_map: A dictionary showing which characters are attached to each character on the screen :return: Index of the char in left side of router """ holder1 = panel_l[position] holder3 = "" for key, value in connection_map.items(): if value == holder1: holder3 = key break holder4 = panel_r.index(holder3) return [holder4, holder3]
def size (paper): """Returns the size of `paper` as `(nrows, ncols)`.""" nrows = max(y for _, y in paper) + 1 ncols = max(x for x, _ in paper) + 1 return nrows, ncols
def _format_mp4(input_path, offset): """Formats the video to an MP4.""" return offset, ("-f", "mp4",)
def combine_bolds(graph_text): """ Make ID marker bold and remove redundant bold markup between bold elements. """ if graph_text.startswith("("): graph_text = ( graph_text.replace(" ", " ") .replace("(", "**(", 1) .replace(")", ")**", 1) .replace("** **", " ", 1) ) return graph_text
def create_index_card(name: str, text: str, a_href:str, img_href: str, img_alt: str) -> dict: """Return HTML/CSS card created with the information provided.""" return { 'name': name, 'text': text, 'a_href': a_href, 'img_href': img_href, 'img_alt': img_alt }
def isclose(a0, a1, tol=1.0e-4): """ Check if two elements are almost equal with a tolerance. :param a0: number to compare :param a1: number to compare :param tol: The absolute tolerance :return: Returns boolean value if the values are almost equal """ return abs(a0 - a1) < tol
def is_handler_authentication_exempt(handler): """Return True if the endpoint handler is authentication exempt.""" try: is_unauthenticated = handler.__caldera_unauthenticated__ except AttributeError: is_unauthenticated = False return is_unauthenticated
def largest_element(a, loc=False): """ Return the largest element of a sequence a. """ try: Largest_value = a[0] location = 0 for i in range(1,len(a)): if a[i] > Largest_value: Largest_value = a[i] location = i if loc == True: return Largest_value,location else: return Largest_value except TypeError: print("Your types do not match") return except: print("Unexpected error:") raise
def remove_zero_amount_coproducts(db): """Remove coproducts with zero production amounts from ``exchanges``""" for ds in db: ds[u"exchanges"] = [ exc for exc in ds["exchanges"] if (exc["type"] != "production" or exc["amount"]) ] return db
def _convert_lists_to_tuples(node): """Recursively converts all lists to tuples in a nested structure. Recurses into all lists and dictionary values referenced by 'node', converting all lists to tuples. Args: node: A Python structure corresponding to JSON (a dictionary, a list, scalars, and compositions thereof) Returns: A Python structure identical to the input, but with lists replaced by tuples. """ if isinstance(node, dict): return {key: _convert_lists_to_tuples(value) for key, value in node.items()} elif isinstance(node, (list, tuple)): return tuple([_convert_lists_to_tuples(value) for value in node]) else: return node
def build_kde_parameters_matrix(jsons_list): """Contructs the list of good QAOA input parameters from jsons provided.""" good_params_matrix = [] for json in jsons_list: good_params = json["good_params"] good_params_matrix = good_params_matrix + good_params return good_params_matrix
def average_accuracy(y_true, y_pred): """ Compute the average accuracy. .. function:: average_accuracy(y_true, y_pred) :param y_true: The true labels. :type y_true: list(str) :param y_pred: The predicted labels. :type y_pred: list(str) :return: The average accuracy. :rtype: float """ labels = set(y_true) | set(y_pred) pairs = list(zip(y_true, y_pred)) scores = [] for label in labels: true_positive = sum( 1 for pair in pairs if pair == (label, label) ) true_negative = sum( 1 for pair in pairs if pair[0] != label and pair[1] != label ) false_positive = sum( 1 for pair in pairs if pair[0] != label and pair[1] == label ) false_negative = sum( 1 for pair in pairs if pair[0] == label and pair[1] != label ) s = true_positive + true_negative + false_positive + false_negative scores.append((true_positive + true_negative) / s) return sum(scores) / len(scores)
def depolarizing_par_to_eps(alpha, d): """ Convert depolarizing parameter to infidelity. Dugas et al. arXiv:1610.05296v2 contains a nice overview table of common RB paramater conversions. Parameters ---------- alpha (float): depolarizing parameter, also commonly referred to as lambda or p. d (int): dimension of the system, 2 for a single qubit, 4 for two-qubits. Returns ------- eps = (1-alpha)*(d-1)/d """ return (1 - alpha) * (d - 1) / d
def create_labels(sizes): """create labels starting at 0 with specified sizes sizes must be a tuple """ labels = [] for i, size in enumerate(sizes): labels += size*[i] return(labels)
def split_cmd(cmds) -> list: """ Split the commands to the list for subprocess Args: cmds (str): command Returns: command list """ # cmds = shlex.split(cmds) # disable auto removing \ on windows return cmds.split() if isinstance(cmds, str) else list(cmds)
def peak_1d_brute_force(nums): """Find peak by naive iteration. Time complexity: O(n). Space complexity: O(1). """ # Iterate to check element is greater than its neighbors. for i in range(len(nums)): if ((i == 0 or nums[i] >= nums[i - 1]) and (i == len(nums) - 1 or nums[i] >= nums[i + 1])): return i
def is_dna_palindrome(s1, s2): """ (str, str) -> bool Precondition: s1 and s2 only contain characters from 'A', 'T', 'C' or 'G'. is_dna(s1, s2) would return True. Return True iff s1 and s2 form a DNA palindrome. >>> is_dna_palindrome('GATC','CTAG') True >>> is_dna_palindrome('GCCTA','CGGAT') False """ return s1 == s2[::-1]
def mask_dict_password(dictionary, secret='***'): """Replace passwords with a secret in a dictionary.""" d = dictionary.copy() for k in d: if 'password' in k: d[k] = secret return d
def make_flat(folders, paths_flat = None): """ """ if paths_flat is None: paths_flat = dict() parent_id = len(paths_flat) - 1 if paths_flat else None for foldername, subfolders in sorted(folders.items()): paths_flat[len(paths_flat)] = { "id": len(paths_flat), "parent_id": parent_id, "name": foldername } make_flat(subfolders, paths_flat) return paths_flat
def running_step(steps, *argv): """Return true if running any step in arguments. """ for step in argv: if step in steps: return True return False
def is_user(user): """Return ``True`` if passed object is User and ``False`` otherwise.""" return type(user).__name__ == 'User'
def parse_list(spec): """Convert a string specification like 00-04,07,09-12 into a list [0,1,2,3,4,7,9,10,11,12] Args: spec (str): string specification Returns: List[int] Example: >>> parse_list("00-04,07,09-12") [0, 1, 2, 3, 4, 7, 9, 10, 11, 12] >>> parse_list("05-04") Traceback (most recent call last): ... ValueError: In specification 05-04, end should not be smaller than begin """ ret_list = [] for spec_part in spec.split(","): if "-" in spec_part: begin, end = spec_part.split("-") if end < begin: raise ValueError( "In specification %s, end should not be smaller than begin" % spec_part) ret_list += range(int(begin), int(end) + 1) else: ret_list += [int(spec_part)] return ret_list
def wordparamcheck(givenparams, expectedparams): """ New version of the word and parameter check Returned values will be given in a list form OUTPUT = [if it matched, matched index, matched value,\ if the correct num of params given,\ num of params, list of params] """ matchingindex = -1 # set default value to null (= -1) matchedparam = "NULL" for index in range(0, len(expectedparams)): if (len(givenparams) == 1): break elif (expectedparams[index][0] == givenparams[1]): matchingindex = index matchedparam = givenparams[1] break numofparams = len(givenparams) - 2 params = [] matchfound = True correctvalues = False if (matchingindex == -1): matchfound = False correctvalues = False else: if (expectedparams[matchingindex][1] == "more"): if (numofparams > 0): correctvalues = True params = givenparams del params[0] del params[0] elif (expectedparams[matchingindex][1] == "none"): if (numofparams == 0): correctvalues = True params = ["NULL"] elif (expectedparams[matchingindex][1] == "optional"): if (numofparams >= 0): correctvalues = True params = givenparams del params[0] del params[0] elif (expectedparams[matchingindex][1] == "skip"): params = ["NULL"] correctvalues = True else: matchfound = False correctvalues = False params = ["NULL"] matchedparam = "INVALID" output = [matchfound, matchingindex, matchedparam, correctvalues, numofparams, params] return output
def filter_pairs(pairs, genes): """ :param pairs: :param genes: :return: Limit only to pairsi n the genes """ return [p for p in pairs if p[0] in genes and p[1] in genes]
def number_of_common_3grams(string1, string2): """ Return the number of common tri-grams in two strings """ # Pure Python implementation: no numpy tri_grams = set(zip(string1, string1[1:], string1[2:])) tri_grams = tri_grams.intersection(zip(string2, string2[1:], string2[2:])) return len(tri_grams)
def degrees_to_cardinal(degree: float): """ """ dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"] index = int((degree + 11.25)/22.5) return dirs[index % 16]
def slashAtTheEnd(url): """ Adds a slash at the end of given url if it is missing there. :param url: url to check and update :returns: updated url """ return url if url.endswith('/') else url + '/'
def do_sql(conn, stmt, dry_run, *vals): """ run stmt on sqlite connection conn """ print(stmt, vals) if dry_run == 0: return conn.execute(stmt, vals) else: return []
def resize_by_ratio(size): """ Resize the size according to the imagenet training ratio. """ resize = round(256 / 224 * size / 2) * 2 return resize
def wheel(pos): """ Wheel is a width of a single rainbow line Input a value 0 to 255 to get a color value. The colours are a transition r - g - b - back to r. """ if pos < 0 or pos > 255: return 0, 0, 0, 0 if pos < 85: return 255 - pos * 3, pos * 3, 0, 0 if pos < 170: pos -= 85 return 0, 255 - pos * 3, pos * 3, 0 pos -= 170 return pos * 3, 0, 255 - pos * 3, 0
def get_players_to_sell(players): """ Provides a list of players that, if I have, I should consider selling for money reasons :param players: list of players :return: list of players """ if not isinstance(players, list): raise ValueError('expected list') return [player for player in players if player[11] < -100]
def plain(text): """Remove boldface formatting from text.""" import re return re.sub('.\b', '', text)
def prod(x): """Compute the product of a sequence.""" out = 1 for a in x: out *= a return out
def gen_matrix(e): """ Generating new matrix. @param e The width and height of the matrix is 2^e. @return New 2x2 to 2^e x 2^e matrix list. """ if e < 1: return None m_list = [[[1, 2], [3, 0]]] _b = m_list[0] for n in range(1, e): m = m_list[n - 1] m_list.append([ [4 * i + _b[0][0] for i in m[0]] + [4 * i + _b[0][1] for i in m[0]], [4 * i + _b[0][0] for i in m[1]] + [4 * i + _b[0][1] for i in m[1]], [4 * i + _b[1][0] for i in m[0]] + [4 * i + _b[1][1] for i in m[0]], [4 * i + _b[1][0] for i in m[1]] + [4 * i + _b[1][1] for i in m[1]], ]) return m_list
def readBit(integer, position): """ :param integer: :return boolean: Description: This function will take in an integer and a position value. The return will be a boolean based on whether the bit is 1 or 0 at the requested position of the integer. Example: integer = 252, which in binary is 1010 1010. This is a byte, where the LSB is at position 0 and the MSB is at position 7. With the above integer, position 1 is 1, position 3 is 0, and position 4 is 1 and so on. """ # Left shifts 0x01 by the position number, which is then AND'd with the absolute value of the passed integer, # This resulting value is then right shifted by the position. # This basically is how you can 'capture' the bit at a certain location and return its value as a boolean return ((0x01 << position) & abs(integer)) >> position
def search(nums, target): """ Search in given rotated sorted array :param nums: given array :type nums: list[int] :param target: target number :type target: int :return: index of target :rtype: int """ left = 0 right = len(nums) - 1 while left + 1 < right: mid = (left + right) // 2 if nums[mid] == target: return mid # find local sorted array elif nums[left] < nums[mid]: if nums[left] <= target < nums[mid]: right = mid else: left = mid else: if nums[mid] < target <= nums[right]: left = mid else: right = mid if left < len(nums) and nums[left] == target: return left elif right >= 0 and nums[right] == target: return right else: return -1
def fc_wwn_to_string(wwn): """Convert FC WWN to string without colons. :param wwn: FC WWN :return: FC WWN without colons """ return wwn.replace(":", "")
def is_power_of_two(num): """Checks whether num is a power of two. Args: num: A positive integer. Returns: True if num is a power of two. """ return ((num & (num - 1)) == 0) and num > 0
def anno_parser(annos_str): """Parse annotation from string to list.""" annos = [] for anno_str in annos_str: anno = list(map(int, anno_str.strip().split(','))) annos.append(anno) return annos
def pascal_triangle(n: int): """ Print pascal's triangle for n rows """ def moving_sum(arr: list): """moving sum sub-routine""" n = len(arr) if n <= 1: return arr out = [] for i in range(0, n-1): out.append(arr[i]+arr[i+1]) return out if n == 0: row = [1] if n == 1: row = [1, 1] else: row = [1] + moving_sum(pascal_triangle(n-1)) + [1] print(row) return row
def extended_gcd(a, b): """returns gcd(a, b), s, r s.t. a * s + b * r == gcd(a, b)""" s, old_s = 0, 1 r, old_r = b, a while r: q = old_r // r old_r, r = r, old_r - q * r old_s, s = s, old_s - q * s return old_r, old_s, (old_r - old_s * a) // b if b else 0
def isunauthenticated(f): """Decorator to mark authentication-non-required. Checks to see if the function is marked as not requiring authentication with the @unauthenticated decorator. Returns True if decorator is set to True, False otherwise. """ return getattr(f, 'unauthenticated', False)
def pluralize(word, count): """Make a word plural by adding an *s* if `count` != 1. Parameters ---------- word : :class:`~python:str` the word count : :class:`~python:int` the word count Returns ------- :class:`~python:str` """ return word if count == 1 else word + 's'
def _get_request_value(request, value_name, default=''): """Helper method to get header values from a request's GET/POST dict, if present.""" if request is not None: if request.method == 'GET': return request.GET.get(value_name, default) elif request.method == 'POST': return request.POST.get(value_name, default) return default
def _validate_pipeline_runtime(primary_pipeline: dict, runtime: str) -> bool: """ Generic pipelines do not have a persisted runtime type, and can be run on any runtime Runtime specific pipeline have a runtime type, and con only be run on matching runtime """ is_valid = False pipeline_runtime = primary_pipeline["app_data"].get("runtime") if not pipeline_runtime: is_valid = True else: if runtime and pipeline_runtime == runtime: is_valid = True return is_valid
def add_metadata_columns_to_schema(schema_message): """Metadata _sdc columns according to the stitch documentation at https://www.stitchdata.com/docs/data-structure/integration-schemas#sdc-columns Metadata columns gives information about data injections """ extended_schema_message = schema_message extended_schema_message['schema']['properties']['_sdc_extracted_at'] = {'type': ['null', 'string'], 'format': 'date-time'} extended_schema_message['schema']['properties']['_sdc_batched_at'] = {'type': ['null', 'string'], 'format': 'date-time'} extended_schema_message['schema']['properties']['_sdc_deleted_at'] = { 'type': ['null', 'string']} return extended_schema_message
def do_right(value, width=80): """Right-justifies the value in a field of a given width.""" return value.rjust(width)
def check_double_entries(entries): """ Process a list of tuples of filenames and corresponding hash for double hashes. `entries`: the list of entries with their hashes returns: a dictionary containing double entries by hash """ hashes = dict() for entry in entries: h = entry[1] if h not in hashes: hashes[h] = [] hashes[h].append(entry) double_hashes = dict() for (key, entrylist) in hashes.items(): if len(entrylist) > 1: double_hashes[key] = entrylist return double_hashes
def remove_extra_raw_data_fields(raw_line): """Used for filter() to ignore time-sensitive lines in report JSON files. :param raw_line: A line to filter :return: True if no time-sensitive fields are present in the line """ if 'grade_released_date' in raw_line: return False if 'last_update' in raw_line: return False if 'date:' in raw_line: return False return True
def geojson_driver_args(distribution): """ Construct driver args for a GeoJSON distribution. """ url = distribution.get("downloadURL") or distribution.get("accessURL") if not url: raise KeyError(f"A download URL was not found for {str(distribution)}") return {"urlpath": url}
def get_scale_offsets(scaled_w, scaled_h, origin_w, origin_h, offset_l, offset_t, offset_w, offset_h): """ Inverts scaling offsets (kind of like inverting the scaling itself, really). Calculates the scale offsets necessary to scale back to its original form an image that was scaled to the specified dimensions using the specified offsets. """ # input parameters scaled = [scaled_w, scaled_h] origin = [origin_w, origin_h] scaled_off = [offset_l, offset_t, offset_w, offset_h] # source offsets, from lengths (w / h) to crop-style (negative values) for i, (org_l, off_l) in enumerate(zip(origin, scaled_off[:2]), 2): # If the input is positive, it represents a length, rather than a crop- # style offset from the bottom right. Even if the output from this code # is positive, however, it must always be a crop-style offset, so there # won't be any special treatment required. if scaled_off[i] > 0: scaled_off[i] -= org_l - off_l # the actual scaling of the offsets scales = 2 * [scale / original for original, scale in zip(origin, scaled)] off = [-offset * scale for offset, scale in zip(scaled_off, scales * 2)] # target offsets, from crop-style to lengths for i, (scaled_l, off_l) in enumerate(zip(scaled, off[:2]), 2): # The input must be a crop-style offset from the bottom right, even if # it happens to be positive. I could process only the positive values, # but because I like consistency, I decided to convert all values from # crop-style offsets to represent a length, regardless of whether it's # really necessary. off[i] += scaled_l - off_l return tuple(off)
def format_names_and_descriptions(objects, name_attr='name', description_attr='description'): """Format a table with names on the left and descriptions on the right.""" pairs = [] for o in objects: name = getattr(o, name_attr) description = getattr(o, description_attr) pairs.append((name, description)) # deterministic order pairs = sorted(pairs, key=lambda p: p[0]) # add headers if there's anything in the list if len(pairs) > 0: pairs = [("Name", "Description"), ("====", "===========")] + pairs # format as table max_name_len = 0 for pair in pairs: max_name_len = max(len(pair[0]), max_name_len) table = "" for pair in pairs: if pair[0] == pair[1]: # skip useless description line = pair[0] else: line = pair[0].ljust(max_name_len) + " " + pair[1] table = table + line + "\n" if table == "": return "\n" else: return table
def _filter_files(adir, filenames, filecnt, file_type, ffilter): """ Filter files by file type(filter function) then returns matching files and cumulated count. """ rfiles = ffilter(adir, filenames) filecnt += len(rfiles) return rfiles, filecnt
def _swap_labelmap_dict(labelmap_dict): """Swaps keys and labels in labelmap. Args: labelmap_dict: Input dictionary. Returns: A dictionary mapping class name to class numerical id. """ return {v:k for k, v in labelmap_dict.items()}
def fahrenheit2kelvin(theta): """Convert temperature in Fahrenheit to Kelvin""" return 5./9 * (theta - 32) + 273.15
def pick_bball_game(p): """ prob_game1 = p prob_game2 = P(make 1+2) + P(make 1+3) + P(make 2+3) + P(make 1+2+3) prob_game2 = p*p*(1-p) + p*(1-p)*p + (1-p)*p*p + p*p*p prob_game2 = p**2 - p**3 + p**2 - p**3 + p**2 - p**3 + p**3 prob_game2 = 3 * p ** 2 - 2 * p ** 3 prob_game1 > prob_game2 p > 3 * p ** 2 - 2 * p ** 3 1 > 3 * p - 2 * p ** 2 2 * p ** 2 - 3 * p + 1 > 0 (p - 1) * (2 * p - 1) > 0 p < 1, both terms must be negative (2 * p - 1) < 0 p < 0.5 """ if p == 0 or p == 1 or p == 0.5: return 0 elif p < 0.5: return 1 else: return 2
def format_user_outputs(user: dict = {}) -> dict: """Take GitHub API user data and format to expected context outputs Args: user (dict): user data returned from GitHub API Returns: (dict): user object formatted to expected context outputs """ ec_user = { 'Login': user.get('login'), 'ID': user.get('id'), 'NodeID': user.get('node_id'), 'Type': user.get('type'), 'SiteAdmin': user.get('site_admin') } return ec_user
def _map_response_description(item): """ struct like {(1,2):'3'} """ key, value = item return "{} : {} : {}".format(key[0], key[1], value)
def abbreviate_statement(text): """Depending on the type of statement, abbreviate it to two letters and add a trailing underscore so it can be used as the first prefix of a title for an SQL table. """ if text.find('income-statement') != -1: text = 'income statement' return text elif text.find('balance-sheet') != -1: text = 'balance sheet' return text elif text.find('cash-flow') != -1: text = 'cash flow' return text else: text = 'unknown' return text
def D(x, y): """D code generator""" return (y << 5) | x
def apply_ticket_permissions(env, req, tickets): """Apply permissions to a set of milestone tickets as returned by `get_tickets_for_milestone()`.""" return [t for t in tickets if 'TICKET_VIEW' in req.perm('ticket', t['id'])]
def separator(sep): """Returns separator from G_OPT_F_SEP appropriately converted to character. >>> separator('pipe') '|' >>> separator('comma') ',' If the string does not match any of the separator keywords, it is returned as is: >>> separator(', ') ', ' :param str separator: character or separator keyword :return: separator character """ if sep == "pipe": return "|" elif sep == "comma": return "," elif sep == "space": return " " elif sep == "tab" or sep == "\\t": return "\t" elif sep == "newline" or sep == "\\n": return "\n" return sep
def strip(s): """strip(s) -> string Return a copy of the string s with leading and trailing whitespace removed. """ return s.strip()
def extract_course(transcript, course): """ (str, int) -> str Return a string containing a course code, course mark and final mark, in that order. The second argument specifies the order in which the course appears in the transcript. >>> extract_course('MAT,90,94,ENG,92,NE,CHM,80,85', 2) 'ENG,92,NE' >>> extract_course('MAT,90,94,ENG,92,NE,CHM,80,85', 4) '' """ if 1 <= course < 4: index = 0; if course == 2: index = 10; elif course == 3: index = 20 return transcript[index: index + 9] else: return ''
def comparison_count_sort(unordered_lst): """Sorts a list by comparison counting. pre: unordered_lst is an unordered list of numbers post: sorted_lst which comprises of unordered_lst's elements sorted in an increasing order. """ lst_size = len(unordered_lst) # create a list of counts, and a list to create a sorted list # append zeros to count_lst and sorted_lst to make them of lst_size count_lst = [0 for i in range(lst_size)] sorted_lst = [0 for i in range(lst_size)] # count how many numbers are smaller/greater than each number for i in range(lst_size - 1): for j in range(i + 1, lst_size): # increase count of item which is larger if unordered_lst[i] < unordered_lst[j]: count_lst[j] += 1 else: count_lst[i] += 1 #assign values to sorted_lst by index based on their count_lst values for i in range(lst_size): sorted_lst[count_lst[i]] = unordered_lst[i] return sorted_lst
def windows_folder(folder): """ Modify foders from files in a dataframe\ To be used with pandas .apply() """ folder = str(folder).replace("\\", "/") return folder
def _permute(c, p): """Returns the permutation of the given 32-bit or 64-bit code with the specified permutation table.""" # NOTE: only difference between 32 & 64 bit permutations # is that len(p)==8 for 32 bit, and len(p)==16 for 64 bit. out = 0 for r in p: out |= r[c&0xf] c >>= 4 return out