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 = {'-L...
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,...
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()...
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...
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] + thi...
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...
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 += " " retu...
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'}}}) {'s...
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] ...
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) [ { ...
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...
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 ...
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 KeyE...
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: ...
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) excep...
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 propert...
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 = milliseco...
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 'hash...
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_...
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,...
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_f...
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), ) ...
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 ...
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 a...
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:...
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...
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...
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): ...
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...
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...
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_...
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_accura...
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: fa...
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....
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(wo...
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) ...
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 % ...
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 retv...
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 = m...
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 els...
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) ...
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(si...
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:...
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: ...
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 ...
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 { ...
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...
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, ...
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 ZeroDivision...
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 >...
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 acti...
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, (w...
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. ...
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] r...
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: ...
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...
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...
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 correlatio...
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 ...
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"]...
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...