content
stringlengths
42
6.51k
def merge_wv_t1_eng(where_str_tokens, NLq): """ Almost copied of SQLNet. The main purpose is pad blank line while combining tokens. """ nlq = NLq.lower() where_str_tokens = [tok.lower() for tok in where_str_tokens] alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789$' special = {'-LRB-': '(', '-RRB-': ')', '-LSB-': '[', '-RSB-': ']', '``': '"', '\'\'': '"', } # '--': '\u2013'} # this generate error for test 5661 case. ret = '' double_quote_appear = 0 for raw_w_token in where_str_tokens: # if '' (empty string) of None, continue if not raw_w_token: continue # Change the special characters w_token = special.get(raw_w_token, raw_w_token) # maybe necessary for some case? # check the double quote if w_token == '"': double_quote_appear = 1 - double_quote_appear # Check whether ret is empty. ret is selected where condition. if len(ret) == 0: pass # Check blank character. elif len(ret) > 0 and ret + ' ' + w_token in nlq: # Pad ' ' if ret + ' ' is part of nlq. ret = ret + ' ' elif len(ret) > 0 and ret + w_token in nlq: pass # already in good form. Later, ret + w_token will performed. # Below for unnatural question I guess. Is it likely to appear? elif w_token == '"': if double_quote_appear: ret = ret + ' ' # pad blank line between next token when " because in this case, it is of closing apperas # for the case of opening, no blank line. elif w_token[0] not in alphabet: pass # non alphabet one does not pad blank line. # when previous character is the special case. elif (ret[-1] not in ['(', '/', '\u2013', '#', '$', '&']) and (ret[-1] != '"' or not double_quote_appear): ret = ret + ' ' ret = ret + w_token return ret.strip()
def cmake_quote_path(value): """ cmake_quote_path(value) -> str Return a quoted form of the given value that is suitable for use in CMake language files. """ # CMake has a bug in it's Makefile generator that doesn't properly quote # strings it generates. So instead of using proper quoting, we just use "/" # style paths. Currently, we only handle escaping backslashes. value = value.replace("\\", "/") return value
def capitalize_text(text): """ Converte una stringa in miniscolo con le iniziali in maiuscolo :param text: stringa da convertire :return: stringa convertita """ array_string = text.lower().split(' ') for i, tmp_name in enumerate(array_string): array_string[i] = tmp_name.capitalize() return ' '.join(array_string)
def etag(obj): """Return the ETag of an object. It is a known bug that the S3 API returns ETags wrapped in quotes see https://github.com/aws/aws-sdk-net/issue/815""" etag = obj['ETag'] if etag[0] == '"': return etag[1:-1] return etag
def baseHtml(title, body): """return base html document with css style.""" html = '<html>\n<head>\n<title>%s</title>\n<link href="class.css" type="te' html += 'xt/css" rel="stylesheet"/>\n</head>\n<body>\n%s\n</body>\n</html>' return html % (title, body)
def camelize(text): """Returns Node names such as i64 -> R64 and less_than -> LessThan.""" return "".join([w.lower().capitalize() for w in text.split("_")])
def redshift_str2num(z: str): """ Converts the redshift of the snapshot from text to numerical, in a format compatible with the file names. E.g. float z = 2.16 <--- str z = 'z002p160'. """ z = z.strip('z').replace('p', '.') return round(float(z), 3)
def op_help(oper, left_op, right_op): """Helper method does math on operands and returns them""" if oper == '+': return left_op + right_op elif oper == '-': return left_op - right_op elif oper == '*': return left_op * right_op else: return left_op / right_op
def compute_induced_subgraph(graph, subgraph_nodes): """Compute the induced subgraph formed by a subset of the vertices in a graph. :arg graph: A :class:`collections.abc.Mapping` representing a directed graph. The dictionary contains one key representing each node in the graph, and this key maps to a :class:`collections.abc.Set` of nodes that are connected to the node by outgoing edges. :arg subgraph_nodes: A :class:`collections.abc.Set` containing a subset of the graph nodes in the graph. :returns: A :class:`dict` representing the induced subgraph formed by the subset of the vertices included in `subgraph_nodes`. .. versionadded:: 2020.2 """ new_graph = {} for node, children in graph.items(): if node in subgraph_nodes: new_graph[node] = children & subgraph_nodes return new_graph
def int_depth(h_int: list, thickness: float): """ Computes depth to the interface for a three layer model. :param h_int: depth to to first interface :param thickness: thickness :return: d_interface: interface depths """ d_interface = h_int d_interface.append(d_interface[0] + thickness) return d_interface
def isfloat(s): """True if argument can be converted to float""" try: float(s) return True except ValueError: pass return False
def adjust_filename_to_globs(filename, globs): """ Adjusts a given filename so it ends with the proper extension """ if globs: # If given use file extensions globs possible_fns = [] # Loop over globs, if the current filenames extensions matches # a given glob, the filename is returned as is, otherwise # the extension of the first glob is added at the end of filename for glob in globs: if glob is not None: extension = glob[1:] if filename[len(filename) - len(extension):].lower() != extension.lower(): possible_fns.append("%s%s" % (filename, glob[1:])) else: return filename # matching extension is returned immediately return possible_fns[0] # otherwise add extension of the first filter else: # If no globs are given, return filename as is return filename
def newline(value, arg): """ Adds a newline to the value once after every arg characters """ assert (arg > 0) new_value = "" for i in range(0, len(value)): new_value += value[i] if (i % arg == 0 and i != 0): # insert newline new_value += " " return new_value
def key_value_string(obj: dict) -> str: """ Dump a dict object into a string representation of key-value pairs """ return ", ".join(f"{k}={v}" for k, v in sorted(obj.items()))
def haproxy_flatten(d, separator='.'): """ haproxy_flatten a dictionary `d` by joining nested keys with `separator`. Slightly modified from <http://codereview.stackexchange.com/a/21035>. >>> haproxy_flatten({'eggs': 'spam', 'sausage': {'eggs': 'bacon'}, 'spam': {'bacon': {'sausage': 'spam'}}}) {'spam.bacon.sausage': 'spam', 'eggs': 'spam', 'sausage.eggs': 'bacon'} """ def items(): for k, v in d.items(): try: for sub_k, sub_v in haproxy_flatten(v, separator).items(): yield separator.join([k, sub_k]), sub_v except AttributeError: yield k, v return dict(items())
def LLTR2domain(lowerleft, topright): """Convert the two pairs of (lower, left), (top, right) in (lat, lon) into the four pairs of (lat, lon) of the corners """ xa, ya = lowerleft xb, yb = topright domain = [(xa, ya), (xa, yb), (xb, yb), (xb, ya)] return domain
def json_init(request, options, configuration): """The main daemon is telling us the relevant cli options """ global greeting greeting = request['params']['options']['greeting'] return "ok"
def format_cnpj(cnpj): """ Formats the CNPJ as 'xx.xxx.xxx/xxxx-xx'. Parameter: cnpj -- The cpf value. It must contain 14 digits. Return: The formatted CNPJ. """ return cnpj[0:2] + '.' + cnpj[2:5] + '.' + cnpj[5:8] + '/' + cnpj[8:12] + '-' + cnpj[12:14]
def ubfx(value, lsb, width): """Unsigned Bitfield Extract""" return (value >> lsb) & ((1 << width) - 1)
def sort_priority(metadata): """ Function to fetch priority of tables from each item in the configuration """ try: return int(metadata['priority']) except KeyError: return 0
def merge(lst1, lst2): """Merges two sorted lists into a single sorted list. Returns new list. lst1 and lst2 are destroyed in the process.""" result = [] while lst1 or lst2: if not lst1: return result + lst2 elif not lst2: return result + lst1 if lst1[0] < lst2[0]: # Note: pop(0) may be slow -- this isn't optimized code. result.append(lst1.pop(0)) else: result.append(lst2.pop(0)) return result
def is_vip(badges): """ Returns True if input contains key 'vip' """ if 'vip' in badges: return True else: return False
def recreate_tags_from_list(list_of_tags): """Recreate tags from a list of tuples into the Amazon Tag format. Args: list_of_tags (list): List of tuples. Basic Usage: >>> list_of_tags = [('Env', 'Development')] >>> recreate_tags_from_list(list_of_tags) [ { "Value": "Development", "Key": "Env" } ] Returns: List """ tags = list() i = 0 for i in range(len(list_of_tags)): key_name = list_of_tags[i][0] key_val = list_of_tags[i][1] tags.append( { 'Key': key_name, 'Value': key_val } ) return tags
def str2bool(v): """For making the ``ArgumentParser`` understand boolean values""" return v.lower() in ("yes", "true", "t", "1")
def create_vocabulary(dataset, terminal_token='<e>'): """Map each token in the dataset to a unique integer id. :param dataset a 2-d array, contains sequences of tokens. A token can be a word or a character, depending on the problem. :param terminal_token (Optional). If specified, will be added to the vocabulary with id=0. :returns a tuple of vocabulary (a map from token to unique id) and reversed vocabulary (a map from unique ids to tokens). """ vocabulary = {} reverse_vocabulary = [] if terminal_token is not None: vocabulary[terminal_token] = 0 reverse_vocabulary.append(terminal_token) for sample in dataset: for token in sample: if not token in vocabulary: vocabulary[token] = len(vocabulary) reverse_vocabulary.append(token) return vocabulary, reverse_vocabulary
def fg(text, color): """Set text to foregound color.""" return "\33[38;5;" + str(color) + "m" + text + "\33[0m"
def naka_rushton_no_b(c, a, c50, n): """ Naka-Rushton equation for modeling contrast-response functions. Do not fit baseline firing rate (b). Typical for pyramidal cells. Where: c = contrast a = Rmax (max firing rate) c50 = contrast response at 50% n = exponent """ return (a*(c**n)/((c50**n)+(c**n)))
def _authorisation(auth): """Check username/password for basic authentication""" if not auth: return False user = auth.username password = auth.password credentials = {'Alice': 'secret', 'Bob': 'supersecret'} try: truepass = credentials[user] except KeyError: return False if truepass == password: return True else: return False
def gql_issues(fragment): """ Return the GraphQL issues query """ return f''' query ($where: IssueWhere!, $first: PageSize!, $skip: Int!) {{ data: issues(where: $where, first: $first, skip: $skip) {{ {fragment} }} }} '''
def check_numbers_unique(number_list: list) -> bool: """ Checks whether numbers in list are all unique >>> check_numbers_unique([1, 2, 3]) True >>> check_numbers_unique([1, 2, 2]) False """ number_set = set() for number in number_list: if number not in number_set: if number not in [' ', '*']: number_set.add(number) else: return False return True
def __get_total_response_time(meta_datas_expanded): """ caculate total response time of all meta_datas """ try: response_time = 0 for meta_data in meta_datas_expanded: response_time += meta_data["stat"]["response_time_ms"] return "{:.2f}".format(response_time) except TypeError: # failure exists return "N/A"
def _as_stac_instruments(value: str): """ >>> _as_stac_instruments('TM') ['tm'] >>> _as_stac_instruments('OLI') ['oli'] >>> _as_stac_instruments('ETM+') ['etm'] >>> _as_stac_instruments('OLI_TIRS') ['oli', 'tirs'] """ return [i.strip("+-").lower() for i in value.split("_")]
def get_module_properties(properties): """ Get dict of properties for output module. Args: properties (list): list of properties Returns: (dict): dict with prop, der and contrib """ module_props = dict(property=None, derivative=None, contributions=None) for prop in properties: if prop.startswith("property"): module_props["property"] = prop elif prop.startswith("derivative"): module_props["derivative"] = prop elif prop.startswith("contributions"): module_props["contributions"] = prop return module_props
def convert_time(milliseconds): """ Convert milliseconds to minutes and seconds. Parameters ---------- milliseconds : int The time expressed in milliseconds. Return ------ minutes : int The minutes. seconds : int The seconds. """ minutes = milliseconds // 60 seconds = milliseconds % 60 return minutes, seconds
def get_top_tags(twlst): """ return the top user mentions and hashtags in :param twlst: list of dict of tweets :return list of hashtags, list of user mentions """ if isinstance(twlst[0], dict): hashlst: dict = {} mentionlst: dict = {} for tw in twlst: if 'hashes' in tw: for x in tw['hashes']: if str(x).lower() in hashlst: hashlst[str(x).lower()] += 1 else: hashlst[str(x).lower()] = 1 if 'mentions' in tw: for x in tw['mentions']: if str(x).lower() in mentionlst: mentionlst[str(x).lower()] += 1 else: mentionlst[str(x).lower()] = 1 hashlst = {k: hashlst[k] for k in sorted(hashlst, key=lambda x: hashlst[x], reverse=True)} mentionlst = {k: mentionlst[k] for k in sorted(mentionlst, key=lambda x: mentionlst[x], reverse=True)} return hashlst, mentionlst
def rivers_with_station(stations): """ Given a list of station objects, returns a set with the names of the rivers with a monitoring station. As the container is a set, there are no duplicates. """ stationed_rivers = set() for station in stations: if station.river: stationed_rivers.add(station.river) return stationed_rivers
def linear_search(lst: list, value: object) -> int: """ Return the index <i> of the first occurance of <value> in the list <lst>, else return -1. >>> linear_search([1, 2, 3, 4], 3) 2 >>> linear_search([1, 2, 3, 4], 5) -1 >>> linear_search([1, 2, 3, 4], 4) 3 >>> linear_search([1, 2, 3, 4], 1) 0 """ i = 0 lst_length = len(lst) while i != lst_length and value != lst[i]: i += 1 if i == lst_length: return -1 else: return i
def clean_strokes(sample_strokes, factor=100): """Cut irrelevant end points, scale to pixel space and store as integer.""" # Useful function for exporting data to .json format. copy_stroke = [] added_final = False for j in range(len(sample_strokes)): finish_flag = int(sample_strokes[j][4]) if finish_flag == 0: copy_stroke.append([ int(round(sample_strokes[j][0] * factor)), int(round(sample_strokes[j][1] * factor)), int(sample_strokes[j][2]), int(sample_strokes[j][3]), finish_flag ]) else: copy_stroke.append([0, 0, 0, 0, 1]) added_final = True break if not added_final: copy_stroke.append([0, 0, 0, 0, 1]) return copy_stroke
def getStats(err): """Computes the average translation and rotation within a sequence (across subsequences of diff lengths).""" t_err = 0 r_err = 0 for e in err: t_err += e[2] r_err += e[1] t_err /= float(len(err)) r_err /= float(len(err)) return t_err, r_err
def validate_passwords(password_list): """ Find valid passwords with min and max count """ count = 0 for password in password_list: if (password["min"] <= password["password"].count(password["char"]) <= password["max"]): count += 1 return count
def minutes_to_seconds( minutes: str ) -> int: """Converts minutes to seconds.""" return int(minutes)*60
def word_probabilities(counts, total_spams, total_non_spams, k=0.5): """turn the word_counts into a list of triplets w, p(w | spam) and p(w | ~spam)""" return [ ( w, (spam + k) / (total_spams + 2 * k), (non_spam + k) / (total_non_spams + 2 * k), ) for w, (spam, non_spam) in counts.items() ]
def boolean_string(s: str) -> bool: """ Checks whether a boolean command line argument is `True` or `False`. Parameters ---------- s: str The command line argument to be checked. Returns ------- bool_argument: bool Whether the argument is `True` or `False` Raises ------ ValueError If the input is not 'True' nor 'False' """ if s not in {'False', 'True'}: raise ValueError('Not a valid boolean string') return s == 'True'
def _validate_name(name): """ Validates the given name. Parameters ---------- name : `None` or `str` A command's respective name. Returns ------- name : `None` or `str` The validated name. Raises ------ TypeError If `name` is not given as `None` neither as `str` instance. """ if name is not None: name_type = name.__class__ if name_type is str: pass elif issubclass(name_type, str): name = str(name) else: raise TypeError(f'`name` can be only given as `None` or as `str` instance, got {name_type.__name__}; ' f'{name!r}.') return name
def roc(tests=[]): """ Returns the ROC curve as an iterator of (x, y)-points, for the given list of (TP, TN, FP, FN)-tuples. The x-axis represents FPR = the false positive rate (1 - specificity). The y-axis represents TPR = the true positive rate. """ x = FPR = lambda TP, TN, FP, FN: float(FP) / ((FP + TN) or 1) y = TPR = lambda TP, TN, FP, FN: float(TP) / ((TP + FN) or 1) return sorted([(0.0, 0.0), (1.0, 1.0)] + [(x(*m), y(*m)) for m in tests])
def ascent_set(t): """ Return the ascent set of a standard tableau ``t`` (encoded as a sorted list). The *ascent set* of a standard tableau `t` is defined as the set of all entries `i` of `t` such that the number `i+1` either appears to the right of `i` or appears in a row above `i` or does not appear in `t` at all. EXAMPLES:: sage: from sage.combinat.chas.fsym import ascent_set sage: t = StandardTableau([[1,3,4,7],[2,5,6],[8]]) sage: ascent_set(t) [2, 3, 5, 6, 8] sage: ascent_set(StandardTableau([])) [] sage: ascent_set(StandardTableau([[1, 2, 3]])) [1, 2, 3] sage: ascent_set(StandardTableau([[1, 2, 4], [3]])) [1, 3, 4] sage: ascent_set([[1, 3, 5], [2, 4]]) [2, 4, 5] """ row_locations = {} for (i, row) in enumerate(t): for entry in row: row_locations[entry] = i n = len(row_locations) if not n: return [] ascents = [n] for i in range(1, n): # ascent means i+1 appears to the right or above x = row_locations[i] u = row_locations[i + 1] if u <= x: ascents.append(i) return sorted(ascents)
def compare_two_data_lists(data1, data2): """ Gets two lists and returns set difference of the two lists. But if one of them is None (file loading error) then the return value is None """ set_difference = None if data1 is None or data2 is None: set_difference = None else: set_difference = len(set(data1).difference(data2)) return set_difference
def rotate_clockwise(shape): """ Rotates a matrix clockwise """ return [[shape[y][x] for y in range(len(shape))] for x in range(len(shape[0]) - 1, -1, -1)]
def add(x, y): """An addition endpoint.""" return {'result': x + y}
def _lower_if_str(item): """ Try to convert item to lowercase, if it is string. Args: item (obj): Str, unicode or any other object. Returns: obj: ``item.lower()`` if `item` is ``str`` or ``unicode``, else just \ `item` itself. """ if isinstance(item, str): return item.lower() return item
def ris_excludeValue_check(fieldsTuple, itemType_value): """ params: fieldsTuple, tuple. itemType_value, str. return: fieldValue_dict, {} """ # ris_element = fieldsTuple[0] exclude_value_list = fieldsTuple[2] fieldValue_dict = {} # for exclude_value in exclude_value_list: if itemType_value in exclude_value: if ris_element == "CY" and itemType_value == "conferencePaper": fieldValue_dict["C1"] = False elif ris_element == "NV" and itemType_value == "bookSection": fieldValue_dict["IS"] = False elif ris_element == "SE" and itemType_value == "case": fieldValue_dict["SE"] = True pass elif ris_element == "VL" and itemType_value == "patent": fieldValue_dict["VL"] = True pass elif ris_element == "VL" and itemType_value == "webpage": fieldValue_dict["VL"] = True pass else: pass elif itemType_value not in exclude_value_list: fieldValue_dict[ris_element] = False else: pass # # return fieldValue_dict
def get_vep_variant(chrom='1', pos='1', ref='A', alt='G', annotation="ADK"): """ Return a variant dictionary """ variant_id = '_'.join([chrom, pos, ref, alt]) variant = { "CHROM":chrom, "POS":pos, "INFO":"Annotation={0}".format(annotation), 'vep_info':{ 'A': [{ "Gene": annotation, "Consequence": 'transcript_ablation' }] }, "variant_id": variant_id } return variant
def underscored(string): """Convert string from 'string with whitespaces' to 'string_with_whitespaces'""" assert isinstance(string, str) return string.replace(' ', '_')
def RPL_TRACECONNECTING(sender, receipient, message): """ Reply Code 201 """ return "<" + sender + ">: " + message
def get_value_from_xml_string(xml_text, node_name): """ Author : Niket Shinde :param xml: :param node_name: :return: """ #print("Inside function get value from xml" + xml_text) start_node_name = "<" + node_name + ">" str_position = xml_text.find(start_node_name) + len(start_node_name) end_node_name = "</" + node_name + ">" end_position = xml_text.find(end_node_name) customer_id = xml_text[str_position:end_position] return customer_id
def _update_stats(stats, train_loss=None, train_accuracy=None, test_loss=None, test_accuracy=None, test_confusion_matrix=None): """ Utility function for collecting stats """ if train_loss: stats['train_loss'].append(train_loss) if train_accuracy: stats['train_accuracy'].append(train_accuracy) if test_loss: stats['test_loss'].append(test_loss) if test_accuracy: stats['test_accuracy'].append(test_accuracy) if test_confusion_matrix is not None: stats['test_confusion_matrix'].append(test_confusion_matrix) return stats
def factorial(n: int) -> int: """ Calculate the factorial of a positive integer https://en.wikipedia.org/wiki/Factorial >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral values >>> factorial(-1) Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if not isinstance(n, int): raise ValueError("factorial() only accepts integral values") if n < 0: raise ValueError("factorial() not defined for negative values") return 1 if n == 0 or n == 1 else n * factorial(n - 1)
def pretty_string_time(t): """Custom printing of elapsed time""" if t > 4000: s = 't=%.1fh' % (t / 3600) elif t > 300: s = 't=%.0fm' % (t / 60) else: s = 't=%.0fs' % (t) return s
def _IsBuildRunning(build_data): """Checks whether the build is in progress on buildbot. Presence of currentStep element in build JSON indicates build is in progress. Args: build_data: A dictionary with build data, loaded from buildbot JSON API. Returns: True if build is in progress, otherwise False. """ current_step = build_data.get('currentStep') if (current_step and current_step.get('isStarted') and current_step.get('results') is None): return True return False
def n_letter_words(all_words, n): """ Given a collection of words, return the ones that are three letters @param all_words is the string containing all words @returns a list of three-letter words """ res = [] all_words = all_words.split(" ") for word in all_words: if len(word) == n: res.append(word) return res
def _assign_numbers(dic: dict) -> dict: """Private function for assign numbers values to dictionary :param dic: report dictionary :type dic: dict :return: report dictionary :rtype: dict """ for k, v in dic.items(): try: if '.' in v: dic[k] = float(v) else: dic[k] = int(v) except ValueError: pass return dic
def get_target_key(stream_name, object_format, key_stem, prefix="", naming_convention=None): """Creates and returns an S3 key for the message""" return f"{prefix}{stream_name}/{key_stem}.{object_format}"
def scale_yaxis(dataset, scale): """The dataset supplied is scaled with the supplied scale. The scaled dataset is returned.""" result = {} result["data"] = [x / scale["scale"] for x in dataset] result["format"] = scale["label"] return result
def option_from_template(text: str, value: str): """Helper function which generates the option block for modals / views""" return {"text": {"type": "plain_text", "text": str(text), "emoji": True}, "value": str(value)}
def reduce_matrix(M, p, is_noise=False): """ Reduces an NxN matrix over finite field Z/pZ. """ for i, row in enumerate(M): for j, element in enumerate(row): if is_noise: if element < 0 and abs(element) < p: continue M[i][j] = element % p return M
def utf8(array): """Preserves byte strings, converts Unicode into UTF-8. Args: array (bytearray or str) : input array of bytes or chars Returns: UTF-8 encoded bytearray """ retval = None if isinstance(array, bytes) is True: # No need to convert in this case retval = array else: retval = array.encode("utf-8") return retval
def pad_batch(batch_tokens): """Pads a batch of tokens. Args: batch_tokens: A list of list of strings. Returns: batch_tokens: A list of right-padded list of strings. lengths: A list of int containing the length of each sequence. """ max_length = 0 for tokens in batch_tokens: max_length = max(max_length, len(tokens)) lengths = [] for tokens in batch_tokens: length = len(tokens) tokens += [""] * (max_length - length) lengths.append(length) return batch_tokens, lengths
def almost_equal(a, b, rel_tol=1e-09, abs_tol=0.0): """A function for testing approximate equality of two numbers. Same as math.isclose in Python v3.5 (and newer) https://www.python.org/dev/peps/pep-0485 """ return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def _is_map_type(column_type: str) -> bool: """ Given column_type string returns boolean value if given string is for MapType. :param column_type: string description of column type :return: boolean - MapType or not. """ if column_type.find("map<") == -1: return False else: return True
def _redact_arg(arg: str, s3_config: dict) -> str: """Process one argument for _redact_keys""" for config in s3_config.values(): for mode in ['read', 'write']: if mode in config: for name in ['access_key', 'secret_key']: key = config[mode].get(name) if key and (arg == key or arg.endswith('=' + key)): return arg[:-len(key)] + 'REDACTED' return arg
def format_IPv6(host_address): """Format IPv6 host address """ if host_address: if not "]" in host_address: host_address = "[{0}]".format(host_address) return host_address
def is_valid(sides): """ For a shape to be a triangle at all, all sides have to be of length > 0, and the sum of the lengths of any two sides must be greater than or equal to the length of the third side. :param sides: :return: """ # 1 - all sides have to be of length > 0: if sum(sides) <= 0: return False # 2 - the sum of the lengths of any two sides must be greater than or equal # to the length of the third side: if sides[0] + sides[1] < sides[2]: return False if sides[2] + sides[1] < sides[0]: return False if sides[0] + sides[2] < sides[1]: return False return True
def find_peak(list_of_integers): """ Function that finds a peak in a list of unsorted integers. Args: list_of_integers (int): Unrdered integer list to find the peak Returns: The peak value """ if len(list_of_integers) == 0: return None if len(list_of_integers) == 1: return list_of_integers[0] if list_of_integers[1] <= list_of_integers[0]: return list_of_integers[0] if list_of_integers[-1] >= list_of_integers[-2]: return list_of_integers[-1] mid = len(list_of_integers) // 2 if list_of_integers[mid] >= list_of_integers[mid - 1] \ and list_of_integers[mid] >= list_of_integers[mid + 1]: return list_of_integers[mid] if list_of_integers[mid + 1] > list_of_integers[mid]: return(find_peak(list_of_integers[mid + 1:len(list_of_integers)])) if list_of_integers[mid - 1] > list_of_integers[mid]: return(find_peak(list_of_integers[0:mid]))
def infile_check(filename, testfile, num_s, num_e): """See if a testfile is in any line of a file""" with open(filename, 'rt', encoding='utf-8') as x: for i in x: # print(i) sample_test = i[num_s:num_e] # print(sample_test) if testfile == sample_test: return i[4] return '-'
def normalize_score(score, mean, std): """ Normalizes the score by centering it at 0.5 and scale it by 2 standard deviations. Values below 0 or above 1 are clipped. :param score: The score to standardize. :param mean: The mean score for this subject. :param std: The standard deviation of scores for the subject. :return: The score centered at 0.5 and scaled by 2 standard deviations. """ score -= mean if std != 0: score /= std*2 # We don't want to clip to much of the distribution score += 0.5 if score < 0: score = 0 elif score > 1: score = 1 return score
def lispi(a): """for splitting user input""" a = int(a) a_1 = (a)//10 a_2 = (a)%10 return a_1,a_2
def attack_succcess_probability(atk, df): """Dictionary with pre-calculated probabilities for each combination of dice Parameters ---------- atk : int Number of dice the attacker has df : int Number of dice the defender has Returns ------- float """ return { 2: { 1: 0.83796296, 2: 0.44367284, 3: 0.15200617, 4: 0.03587963, 5: 0.00610497, 6: 0.00076625, 7: 0.00007095, 8: 0.00000473, }, 3: { 1: 0.97299383, 2: 0.77854938, 3: 0.45357510, 4: 0.19170096, 5: 0.06071269, 6: 0.01487860, 7: 0.00288998, 8: 0.00045192, }, 4: { 1: 0.99729938, 2: 0.93923611, 3: 0.74283050, 4: 0.45952825, 5: 0.22044235, 6: 0.08342284, 7: 0.02544975, 8: 0.00637948, }, 5: { 1: 0.99984997, 2: 0.98794010, 3: 0.90934714, 4: 0.71807842, 5: 0.46365360, 6: 0.24244910, 7: 0.10362599, 8: 0.03674187, }, 6: { 1: 0.99999643, 2: 0.99821685, 3: 0.97529981, 4: 0.88395347, 5: 0.69961639, 6: 0.46673060, 7: 0.25998382, 8: 0.12150697, }, 7: { 1: 1.00000000, 2: 0.99980134, 3: 0.99466336, 4: 0.96153588, 5: 0.86237652, 6: 0.68516499, 7: 0.46913917, 8: 0.27437553, }, 8: { 1: 1.00000000, 2: 0.99998345, 3: 0.99906917, 4: 0.98953404, 5: 0.94773146, 6: 0.84387382, 7: 0.67345564, 8: 0.47109073, }, }[atk][df]
def filter_blank_targets(rows): """Filter data points against blank targets. Returns: rows with blank targets removed """ rows_filtered = [] for row in rows: if row['Target'] == 'blank': # Verify this is inactive assert float(row['median']) == -4 else: # Keep it rows_filtered += [row] return rows_filtered
def getCircle(x0, y0, radius): """ http://en.wikipedia.org/wiki/Midpoint_circle_algorithm public static void DrawCircle(int x0, int y0, int radius) { int x = radius, y = 0; int radiusError = 1-x; while(x >= y) { DrawPixel(x + x0, y + y0); DrawPixel(y + x0, x + y0); DrawPixel(-x + x0, y + y0); DrawPixel(-y + x0, x + y0); DrawPixel(-x + x0, -y + y0); DrawPixel(-y + x0, -x + y0); DrawPixel(x + x0, -y + y0); DrawPixel(y + x0, -x + y0); y++; if (radiusError<0) { radiusError += 2 * y + 1; } else { x--; radiusError += 2 * (y - x + 1); } } } # Get a bitmapped circle as runlengths. >>> getCircle(0,0,5) {0: [-5, 5], 1: [-5, 5], 2: [-5, 5], 3: [-4, 4], 4: [-3, 3], 5: [-2, 2], -2: [-5, 5], -5: [-2, 2], -4: [-3, 3], -3: [-4, 4], -1: [-5, 5]} """ points = {} x = radius y = 0 radiusError = 1-x while x >= y: points[y + y0] = [-x + x0, x + x0] points[x + y0] = [-y + x0, y + x0] points[-y + y0] = [-x + x0, x + x0] points[-x + y0] = [-y + x0, y + x0] y += 1 if (radiusError<0): radiusError += 2 * y + 1 else: x -= 1 radiusError += 2 * (y - x + 1) return points
def find_profile (profiles, chrom, start_bp, end_bp): """ Find a profile for a given chromosome that spans a given range of bp positions """ if chrom in profiles.keys(): for el in profiles[chrom]: if el[0] == start_bp and el[1] == end_bp: return [el[2], el[3]] return None
def set_cache_readonly(readonly=True): """Set the flag controlling writes to the CRDS cache.""" global _CRDS_CACHE_READONLY _CRDS_CACHE_READONLY = readonly return _CRDS_CACHE_READONLY
def divide(x, y): """ Divides two floats where the second must be non-zero, otherwise a ZeroDivisionError is raise. :type x: float :param x: numerator :type y: float != 0 :param y: denominator :rtype: float """ if y != 0: return x / y else: raise ZeroDivisionError
def canGetExactChange(targetMoney, denominations): # Write your code here """ use memoization, dp """ # memoization mem = {} # helper function def helper(target): if target in mem: return mem[target] if target not in mem: mem[target] = False for d in denominations: if d > target: continue if target % d == 0 or helper(target-d): mem[target] = True break return mem[target] return helper(targetMoney)
def returns_lists(cells=16, actions=4): """Initialize returns list. Each state has four possible actions. Args: cells ([type]): Array with cells in grid actions ([type]): Array with possible actions Returns: [type]: Rewards dictionary """ # Each state has four possible actions to take def create_array(n, lst): for i in range(n): lst.append(str(i)) return lst possible_states = [] possible_states = create_array(cells, possible_states) possible_actions = [] possible_actions = create_array(actions, possible_actions) returns = {} for state in possible_states: for action in possible_actions: returns[state+", "+action] = [] return returns
def str_truncate(text: str, width: int = 64, ellipsis: str = "...") -> str: """Shorten a string (with an ellipsis) if it is longer than certain length.""" assert width >= 0 if len(text) <= width: return text if len(ellipsis) > width: ellipsis = ellipsis[:width] return text[:max(0, (width - len(ellipsis)))] + ellipsis
def flatten( l, max_depth = None, ltypes = ( list, tuple ) ): """flatten( sequence[, max_depth[, ltypes]] ) => sequence Flatten every sequence in "l" whose type is contained in "ltypes" to "max_depth" levels down the tree. See the module documentation for a complete description of this function. The sequence returned has the same type as the input sequence. """ if max_depth is None: make_flat = lambda x: True else: make_flat = lambda x: max_depth > len( x ) if callable( ltypes ): is_sequence = ltypes else: is_sequence = lambda x: isinstance( x, ltypes ) r = list() s = list() s.append(( 0, l )) while s: i, l = s.pop() while i < len( l ): while is_sequence( l[i] ): if not l[i]: break elif make_flat( s ): s.append(( i + 1, l )) l = l[i] i = 0 else: r.append( l[i] ) break else: r.append( l[i] ) i += 1 try: return type(l)(r) except TypeError: return r
def str2latitute(value): """convert a str to valid latitude""" if "." not in value: value = value[:2] + "." + value[2:] return float(value)
def listify(string_or_list): """Takes a string or a list and converts strings to one item lists""" if hasattr(string_or_list, 'startswith'): return [string_or_list] else: return string_or_list
def is_power_of_two(n): """ Check whether n is a power of 2 """ return (n != 0) and (n & (n - 1) == 0)
def pixeltocomplex(xpos, ypos, xinterval, yinterval, resolution): """ Uses linear interpolation to convert an image coordinate to its complex value. """ re = (xpos / resolution[0]) * (xinterval[1] - xinterval[0]) + xinterval[0] im = (ypos / resolution[1]) * (yinterval[1] - yinterval[0]) + yinterval[0] return complex(re, -im)
def wordify(string): """Replace non-word chars [-. ] with underscores [_]""" return string.replace("-", "_").replace(".", " ").replace(" ", "_")
def cm2pt(cm=1): """2.54cm => 72pt (1 inch)""" return float(cm) * 72.0 / 2.54
def isfloat(value): """ Determine if value is a float Parameters ---------- value : Value """ try: float_val = float(value) if float_val == value or str(float_val) == value: return True else: return False except ValueError: return False
def josephus(num, k): """ recursive implementation of Josephus problem num - the number of people standing in the circle k - the position of the person who is to be killed return the safe position who will survive the execution """ if num == 1: return 1 return (josephus(num - 1, k) + k - 1) % num + 1
def check_positive_integer(value, parameter_name='value'): """This function checks whether the given value is a positive integer. Parameters ---------- value: numeric, Value to check. parameter_name: str, The name of the indices array, which is printed in case of error. Returns ------- value: int, Checked and converted int. """ int_value = int(value) if value < 0 or value != int_value: raise ValueError('The parameter `' + str(parameter_name) + '` must be a positive integer.') return value
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() # print("Text: ", text) if not text: return [] tokens = text.split() # print("tokens : ", tokens) return tokens
def simple_score(correlation, sharpe, drawdown, alpha, sensitivity, out=None): """ Calculate a simple score on a scale of 1 to 10 based on the given metrics. Each metric is given 2 points. If alpha is zero, then the score is zero since you have made no positive returns correlation correlation of strategy, between 1 and -1 sharpe sharpe ratio drawdown max drawdown percentage alpha excess returns sensitivity price sensitivity based on open=high or open=low prices out output format. returns score if None else the list of points for any other argument """ # A list to hold points for each of the metric points = [0, 0, 0, 0, 0] correlation = abs(correlation) drawdown = abs(drawdown) if correlation < 0.1: points[0] = 2 else: points[0] = 2 * (1 - correlation) if sharpe > 0: points[1] = min(2, sharpe) if abs(drawdown) < 0.05: points[2] = 2 else: points[2] = max(0, 2 - ((drawdown - 0.05) * 0.25 * 100)) if alpha > 0: points[3] = min(2, alpha * 100) if sensitivity < 0.1: points[4] = 2 else: points[4] = max(0, (0.3 - sensitivity) * 10) if out == "list": return points else: return 0 if alpha <= 0 else sum(points)
def HOF_atoms(at): """ Returns the heat of formation of the element. Parameters: at (char): Symbol of the element values (dict): Values of the control variables Returns: HOF_atoms (float): Heat of formation of the element """ h = 6.626070040*(10**-34) #6.626070040d-34 Ry = 10973731.568508 #10973731.568508d0 c = 299792458 #299792458d0 N_avo = 6.02214179000000*(10**+23) #6.02214179000000d+23 au2kcm = 2 * Ry * h * c * N_avo / 4184 kcm2au = 1 / au2kcm hof_dict_1 = {"H": 51.63, "Li": 37.69, "Be": 76.48, "B": 136.2, "C": 169.98, \ "N": 112.53, "O": 58.99 , "F": 18.47, "Na": 25.69, "Mg": 34.87, \ "Al": 78.23, "Si": 106.6, "P": 75.42, "S": 65.66, "Cl": 28.59, \ "K": 21.48303059, "Ca": 42.38503824, "Fe": 98.7373, "Ga": 64.763384321, \ "Ge": 89.354, "As": 68.86, "Se": 57.8991, "Br": 28.1836, "I": 25.62} # if values["hof_C_hydrocarbon"]=="true": # new_val = {"C": 170.11} # hof_dict_1.update(new_val) #case ('K ') # todo collect reference for 3-rd row from Sambit # case ('Br') !Phys. Chem. Chem. Phys., 2015, 17, 3584--3598 # case ('I') ! JANAF # many other cases have numbers commented out...take a look at OG f90 file, thanks if at in hof_dict_1: HOF_atoms = hof_dict_1[at] * kcm2au return(HOF_atoms) else: # equivalent to case default with open("Thermochemistry.out", "a") as ther_chem: ther_chem.write("Error: unknown element type encoutered in HOF_atoms: " + str(at)+ " \n")
def fix_timecols(data): """Update and fix old errors in the timecols item of old data dictionaries""" if "timecols" not in data: return new_timecols = {} # some old pickles have timecols as tuples: if not isinstance(data["timecols"], dict): data["timecols"] = dict(data["timecols"]) for col, tcol in data["timecols"].items(): if col.endswith("-x") and tcol.endswith("-y"): new_timecols[tcol] = col else: new_timecols[col] = tcol data["timecols"] = new_timecols return data
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if not ints: return None min_int = max_int = ints[0] for integer in ints: if integer > max_int: max_int = integer elif integer < min_int: min_int = integer return min_int, max_int