content
stringlengths
42
6.51k
def parse_uint(data_obj, factor=1): """convert bytes (as unsigned integer) and factor to float""" decimal_places = -int(f'{factor:e}'.split('e')[-1]) return round(int.from_bytes(data_obj, "little", signed=False) * factor, decimal_places)
def noamwd_decay(step, warmup_steps, model_size, rate, decay_steps, start_step=0): """Learning rate schedule optimized for huge batches """ return ( model_size ** (-0.5) * min(step ** (-0.5), step * warmup_steps**(-1.5)) * rate ** (max(step - start_step + decay_steps, 0) // decay_steps))
def remove_suffix(text, suffix): # type: (str, str) -> str """Remove suffix from text if any""" if text.endswith(suffix): return text[:len(text)-len(suffix)] return text
def process_vector_args(args): """ A helper function to process vector arguments so callables can take vectors or individual components. Essentially unravels the arguments. """ new_args = [] for arg in args: if hasattr(arg, 'shape') and len(arg.shape) > 0: shape = arg.shape if (min(shape) != 1 and len(shape) == 2) or len(shape) > 2: raise AttributeError("Arguments should only contain vectors") for i in range(max(shape)): if len(shape) == 1: new_args.append(arg[i]) elif shape[0] == 1: new_args.append(arg[0, i]) elif shape[1] == 1: new_args.append(arg[i, 0]) elif isinstance(arg, (list, tuple)): for element in arg: if isinstance(element, (list, tuple)): raise AttributeError("Arguments should not be nested " + "lists/tuples") new_args.append(element) else: # hope it's atomic! new_args.append(arg) return tuple(new_args)
def is_palindrome(string): """Check if string is a Palindrome. Args: string (str): String. Returns: bool: Return True if string is a palindrome and False if not. """ string = string.strip() if string == string[::-1]: return True else: return False
def split(container, count): """ split the jobs for parallel run """ return [container[_i::count] for _i in range(count)]
def clamp(value, value_max=1, value_min=0): """Clamp between values.""" return max(min(value, value_max), value_min)
def uniqify(s): """Remove duplicates and sort the result list.""" return sorted(set(s))
def func_x_a_p_kwargs(x, a=2, *, p="p", **kwargs): """func. Parameters ---------- x: float a: int p: str kwargs: dict Returns ------- x: float a: int p: str kwargs: dict """ return x, None, a, None, None, p, None, kwargs
def do_boxes_intersect(box, *other_boxes): """Whether the first box intersects with any of the others. :param tuple box: box described by coordinates of upper left corner and width, height by ((x,y),(w,h)) with x, y, w, h integers :param list other_boxes: list of other boxes of the form ((x,y), (width,height)) :return: bool """ ((x, y), (w, h)) = box for ((other_x, other_y), (other_w, other_h)) in other_boxes: # pt lies in box? if ((other_x <= x <= other_x + other_w) or (x <= other_x <= x + w)) and \ ((other_y <= y <= other_y + other_h) or (y <= other_y <= y + h)): return True return False
def node_list_to_node_name_list(node_list): """Converts a node list into a list of the corresponding node names.""" node_name_list = [] for n in node_list: node_name_list.append(n.get_name()) return node_name_list
def f1(gt_s, gt_e, pr_s, pr_e): """ Evaluate F1 score of a predicted span over a ground truth span. Args: gt_s: index of the ground truth start position gt_e: index of the ground truth end position pr_s: index of the predicted start position pr_e: index of the predicted end position """ gt = {idx for idx in range(gt_s, gt_e+1)} pr = {idx for idx in range(pr_s, pr_e+1)} intersection = gt.intersection(pr) prec = 1. * len(intersection) / len(pr) rec = 1. * len(intersection) / len(gt) f1_score = (2. * prec * rec) / (prec+rec) if prec+rec != 0. else 0. return f1_score
def decrypt_key(e1, modulus): """Works out the decryption key Inputs - e and the modulus both integers Outputs - The decryption key""" d = 1 #Setting d to 1 finished = False #To check if we found a value for d while finished != True: #We check to see if we have a value for d newD = e1 * d #Works out the remainder using the equation ed (mod modulus) = 1 finalD = newD % modulus if finalD == 1: #If the remainder is 1 we have a value for d!! finished = True else: d = d + 1 return d
def _fullname(o): """Return the fully-qualified name of a function.""" return o.__module__ + "." + o.__name__ if o.__module__ else o.__name__
def qubits(circ): """ Args: circ(list(list(tuple))): Circuit Returns: list: The list of qubits appearing in the circuit. """ qs = [] for c in circ: for g in c: qs += list(g) qs = list(set(qs)) return qs
def strip_quotes(value): """strip both single or double quotes""" value = value.strip() if "\"" in value: return value.strip("\"") elif "\'" in value: return value.strip("\'") else: return value
def GetAllCombinations(choices, noDups=1, which=0): """ Does the combinatorial explosion of the possible combinations of the elements of _choices_. **Arguments** - choices: sequence of sequences with the elements to be enumerated - noDups: (optional) if this is nonzero, results with duplicates, e.g. (1,1,0), will not be generated - which: used in recursion **Returns** a list of lists >>> GetAllCombinations([(0,),(1,),(2,)]) [[0, 1, 2]] >>> GetAllCombinations([(0,),(1,3),(2,)]) [[0, 1, 2], [0, 3, 2]] >>> GetAllCombinations([(0,1),(1,3),(2,)]) [[0, 1, 2], [0, 3, 2], [1, 3, 2]] """ if which >= len(choices): res = [] elif which == len(choices) - 1: res = [[x] for x in choices[which]] else: res = [] tmp = GetAllCombinations(choices, noDups=noDups, which=which + 1) for thing in choices[which]: for other in tmp: if not noDups or thing not in other: res.append([thing] + other) return res
def generate_payload(data_file): """ Generate a list of payloads to import into deep lynx Args data_file (string): location of file to read Return payload (dictionary): a dictionary of payloads to import into deep lynx e.g. {metatype: list(payload)} """ payload = dict() return payload
def humanReadable(n): """Given an int, e.g. 52071886 returns a human readable string 5.2M ref: http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size """ #DROPPING the human readable part and just moving to millions # for unit in ['','K','M','B','T','P','E','Z']: # if abs(n) < 1000.0: # return "%3.1f%s" % (n, unit) # n /= 1000.0 # return "%.1f%s" % (num, 'Y') return "%.1f" % (n/1000000.0)
def definition_area(t, x): """ for the initial value x0 = 1 this ODE only has a solution for x in (-sqrt(2),sqrt(2)). Therefore the ode is only defined in a certain area. :param t: time :param x: x value :return: slope dx/dt """ dx = t * x ** 2 return dx
def split_list(doc_list, n_groups): """ Args: doc_list (list): is a list of documents to be split up n_groups (int): is the number of groups to split the doc_list into Returns: split_lists (list): a list of n_groups which are approximately equal in length, as a necessary step prior to multiprocessing """ avg = len(doc_list) / float(n_groups) split_lists = [] last = 0.0 while last < len(doc_list): split_lists.append(doc_list[int(last):int(last + avg)]) last += avg return split_lists
def url_has(url, wordlist): """True iff wordlist intersect url is not empty.""" for word in wordlist: if word in url: return True return False
def calc_dh(eta): """Calculate the first derivative of the interpolation function Args: eta: the phase field Returns: the value of dh """ return 30 * eta ** 2 * (eta - 1) ** 2
def parse_secs_to_str(duration: int = 0) -> str: """ Do the reverse operation of :py:func:`parse_str_to_secs`. Parse a number of seconds to a human-readable string. The string has the form XdXhXmXs. 0 units are removed. :param int duration: The duration, in seconds. :return: A formatted string containing the duration. :rtype: :py:class:`str` >>> parse_secs_to_str(3601) '1h1s' """ secs, mins, hours, days = 0, 0, 0, 0 result = '' secs = duration % 60 mins = (duration % 3600) // 60 hours = (duration % 86400) // 3600 days = duration // 86400 result += '%dd' % days if days else '' result += '%dh' % hours if hours else '' result += '%dm' % mins if mins else '' result += '%ds' % secs if secs else '' if not result: result = '0s' return result
def step_anneal(base_lr, global_step, anneal_rate=0.98, anneal_interval=30000): """ Annealing learning rate by steps :param base_lr: base learning rate :type base_lr: float :param global_step: global training steps :type global_step: int :param anneal_rate: rate of annealing :type anneal_rate: float :param anneal_interval: interval steps of annealing :type anneal_interval: int :return: scheduled learning rate :rtype: float """ lr = base_lr * anneal_rate ** (global_step // anneal_interval) return lr
def shape_select(dict_sizes, max_size): """takes a dict in parameter, returns list of shapes\ of blocker of at most max size""" shapes = [] for size in dict_sizes: if size is not None and max_size is not None and size <= max_size: for item in dict_sizes[size]: shapes.append(item) return shapes
def gff3plsorting(gff_file, outgff_file): """ """ inputs = [gff_file] outputs = [outgff_file] options = { 'cores': 1, 'memory': '4g', 'account': 'NChain', 'walltime': '01:00:00' } spec = ''' /home/marnit/bin/gff3sort.pl --chr_order natural {infile} > {outfile} '''.format(infile=gff_file, outfile=outgff_file) return inputs, outputs, options, spec
def get_scores(data: dict) -> list: """Get a list of all scores.""" return data.get('scores', [])
def set_attribute(t, key: str, data): """ Set an attribute on a callable. Mainly used with decorators to allow the decorators to store data onto the callable :param t: the callable to store data onto :param key: the key of the data, the attributes name. :param data: the data to set, the attributes value :return: the callable after the modification :exception RuntimeError - Raised if a non callable is given as `t` """ if not callable(t): raise RuntimeError("Trying to annotate " + t) setattr(t, key, data) return t
def find_interval(x, partition, endpoints=True): """ find_interval -> i If endpoints is True, "i" will be the index for which applies partition[i] < x < partition[i+1], if such an index exists. -1 otherwise If endpoints is False, "i" will be the smallest index for which applies x < partition[i]. If no such index exists "i" will be set to len(partition) """ for i in range(0, len(partition)): if x < partition[i]: return i-1 if endpoints else i return -1 if endpoints else len(partition)
def _image_mode(backup_mode): """True if backup is image type.""" return backup_mode == 'image'
def isblank(s): """Is this whitespace or an empty string?""" if isinstance(s, str): if not s: return True else: return s.isspace() else: return False
def strip_comments(content): """Manual striping of comments from file content. Many localized content pages contain original English content in comments. These comments have to be stripped out before analyzing the links. Doing this using regular expression is difficult. Even the grep tool is not suitable for this use case. NOTE: We strived to preserve line numbers when producing the resulted text. This can be useful in future if we want to print out the line numbers for bad links. """ result = [] in_comment = False for line in content: idx1 = line.find("<!--") idx2 = line.find("-->") if not in_comment: # only care if new comment started if idx1 < 0: result.append(line) continue # single line comment if idx2 > 0: result.append(line[:idx1] + line[idx2+4:]) continue result.append(line[:idx1]) in_comment = True continue # already in comment block if idx2 < 0: # ignore whole line result.append("") continue result.append(line[idx2+4:]) in_comment = False return result
def burn_in_scaling(cur_batch, burn_in, power): """ ---------- Author: Damon Gwinn (gwinndr) ---------- - Returns the darknet burn in scaling - Designed to be used with torch.optim.LambdaLR - Scaling formula is (cur_batch / burn_in)^power ---------- """ return pow(cur_batch / burn_in, power);
def login(i): """ Input: { (sudo) - if 'yes', add sudo } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ import os s='docker login' if i.get('sudo','')=='yes': s='sudo '+s os.system(s) return {'return':0}
def _parse_userinfo(userinfo): """Try to split the URL's userinfo (the part between :// and @) into fields separated by :. If anything looks wrong, remind user to percent-encode values.""" if hasattr(userinfo, 'split'): parts = userinfo.split(u':', 1) if len(parts) == 2: return parts raise ValueError('Could not parse user/key in store-URL. Note that values have to be percent-encoded, eg. with urllib.quote_plus().')
def is_valid_interval(x): """ Returns true iff x is a well-shaped concrete time interval (i.e. has valid beginning and end). """ try: return hasattr(x, "hasBeginning") and len(x.hasBeginning) > 0 and \ len(x.hasBeginning[0].inTimePosition) > 0 and \ len(x.hasBeginning[0].inTimePosition[0].numericPosition) > 0 and hasattr(x, "hasEnd") and \ len(x.hasEnd) > 0 and len(x.hasEnd[0].inTimePosition) > 0 and \ len(x.hasEnd[0].inTimePosition[0].numericPosition) > 0 and \ x.hasBeginning[0].inTimePosition[0].numericPosition < x.hasEnd[0].inTimePosition[0].numericPosition except TypeError: return False
def find_duo_maps(dict_A, dict_B): """This function finds the maps that are to be combined. Expected inputs are: dict_A and dict_B: dictionaries""" maps_A = list(dict_A.keys()) maps_B = list(dict_B.keys()) maps_to_combine = list(set(maps_A) & set(maps_B)) maps_to_combine.remove('meta') print("Map(s) that occur(s) in both sources:\n{}".format(maps_to_combine)) return maps_to_combine
def deindented_source(src): """De-indent source if all lines indented. This is necessary before parsing with ast.parse to avoid "unexpected indent" syntax errors if the function is not module-scope in its original implementation (e.g., staticmethods encapsulated in classes). Parameters ---------- src : str input source Returns ------- str : de-indented source; the first character of at least one line is non-whitespace, and all other lines are deindented by the same """ lines = src.splitlines() n_chars = float("inf") for line in lines: len_line = len(line) idx = 0 # we're Python 3, so we assume you're not mixing tabs and spaces while idx < n_chars and idx < len_line and line[idx] in [" ", '\t']: idx += 1 if len_line > idx: n_chars = min(idx, n_chars) lines = [line[n_chars:] for line in lines] src = "\n".join(lines) return src
def is_suffix_of(suffix, trace) -> bool: """ Args: suffix: target suffix trace: trace in question Returns: True if suffix is the suffix of trace. """ if len(trace) < len(suffix): return False else: return trace[-len(suffix):] == suffix
def is_palindrome(word): """ :returns: True if <word> is a palindrome :param str word: a string """ return word == word[::-1]
def day2k_to_date(day2k): """Convert integer day number since 2000-01-01 to date as (year, month, day) tuple. """ # ref: https://en.wikipedia.org/wiki/Julian_day#Julian_or_Gregorian_calendar_from_Julian_day_number # Gregorian date formula applied since 1582-10-15 # Julian date formula applied until 1582-10-04 d__ = int(day2k) + 2451545 f__ = d__ + 1401 # Julian calender if d__ > 2299160: # Gregorian calender f__ += (((4 * d__ + 274277) // 146097) * 3) // 4 - 38 e__ = 4 * f__ + 3 h__ = 5 * ((e__ % 1461) // 4) + 2 day = (h__ % 153) // 5 + 1 month = (h__ // 153 + 2) % 12 + 1 year = e__ // 1461 - 4716 + (14 - month) // 12 return year, month, day
def _func_and(current, checks): """Implementation of And.""" return all(check(current) for check in checks)
def evaluate_f1(tp: int, fp: int, fn: int) -> float: """F1-score. *F1-score* $=\dfrac{2TP}{2TP + FP + FN}$ Args: tp: True Positives fp: False Positives fn: False Negatives """ try: return 2 * tp / (2 * tp + fp + fn) except ZeroDivisionError: return 0.0
def match_to_schema(_dict, requested_key): """ Match the schema supplied with the response to return the data we requested. :param _dict: :param requested_key: :return: """ if _dict.get(requested_key) is not None: return _dict[requested_key] for valid_key in _dict: if valid_key == requested_key: if not isinstance(_dict.get(valid_key), dict): return _dict[valid_key] else: continue elif valid_key != requested_key and isinstance(_dict.get(valid_key), dict): return match_to_schema(_dict[valid_key], requested_key) return None
def get_metric(dataset_name): """tbd""" if dataset_name in ['esol', 'freesolv', 'lipophilicity']: return 'rmse' elif dataset_name in ['qm7', 'qm8', 'qm9', 'qm9_gdb']: return 'mae' else: raise ValueError(dataset_name)
def hermiteInterpolate(v0, v1, v2, v3, alpha, tension, bias): """ Hermite interpolator. Allows better control of the bends in the spline by providing two parameters to adjust them: * tension: 1 for high tension, 0 for normal tension and -1 for low tension. * bias: 1 for bias towards the next segment, 0 for even bias, -1 for bias towards the previous segment. Using 0 bias gives a cardinal spline with just tension, using both 0 tension and 0 bias gives a Catmul-Rom spline. """ alpha2 = alpha * alpha alpha3 = alpha2 * alpha m0 = (((v1 - v0) * (1 - tension)) * (1 + bias)) / 2.0 m0 += (((v2 - v1) * (1 - tension)) * (1 - bias)) / 2.0 m1 = (((v2 - v1) * (1 - tension)) * (1 + bias)) / 2.0 m1 += (((v3 - v2) * (1 - tension)) * (1 - bias)) / 2.0 a0 = 2 * alpha3 - 3 * alpha2 + 1 a1 = alpha3 - 2 * alpha2 + alpha a2 = alpha3 - alpha2 a3 = -2 * alpha3 + 3 * alpha2 return a0 * v1 + a1 * m0 + a2 * m1 + a3 * v2
def is_ontology_metadata(convention, metadatum): """Check if metadata is ontology from metadata convention """ try: return bool(convention["properties"][metadatum]["ontology"]) except KeyError: return False
def build_query_for_indicators(indicators): """Builds an Elasticsearch query for Yeti indicator patterns. Prepends and appends .* to the regex to be able to search within a field. Returns: The resulting ES query string. """ query = [] for domain in indicators: query.append('domain:/.*{0:s}.*/'.format(domain['pattern'])) return ' OR '.join(query)
def unitarity_fn(x, baseline, amplitude, unitarity): """ Fitting function for unitarity randomized benchmarking, equation (8) of [ECN] :param numpy.ndarray x: Independent variable :param float baseline: Offset value :param float amplitude: Amplitude of exponential decay :param float decay: Decay parameter :return: Fit function """ return baseline + amplitude * unitarity ** (x-1)
def reverse_array(orig): """ Returns a list in reversed order Mutable? """ new = [] while len(orig) > 1: new.insert(0, orig[0]) orig.pop(0) return new
def is_part_of_group(settings_file, campaign_id): """Checks whether a campaign is part of a group. Args: settings_file (dict): Settings file for the project campaign_id (int): Id of campaign which is to be checked Returns: bool: True if campaign part of any group else False """ campaignGroups = settings_file.get("campaignGroups") if campaignGroups and str(campaign_id) in campaignGroups: return True return False
def CreateNameToSymbolInfo(symbol_infos): """Create a dict {name: symbol_info, ...}. Args: symbol_infos: iterable of SymbolInfo instances Returns: a dict {name: symbol_info, ...} """ return {symbol_info.name: symbol_info for symbol_info in symbol_infos}
def find_largest_digit_helper(n, largest_digit): """ This function helps find the largest digit in the number. :param n: the number used to find the largest digit :param largest_digit: stores the largest digit in the number, the default value is 0. :return: the largest digit in the number """ if n == 0: return largest_digit else: if n < 0: n = n * (-1) digit = n % 10 if digit > largest_digit: largest_digit = digit n = n//10 return find_largest_digit_helper(n, largest_digit)
def filter_zones(item, correct_prefixes, wrong_prefixes, zone) -> bool: """Return true for item in zone.""" name, _ = item for pre in wrong_prefixes: if name.startswith(pre): return False for pre in correct_prefixes: if name.startswith(pre): return True return zone == "main"
def cloudfront_restriction_type(restriction_type): """ Property: GeoRestriction.RestrictionType """ valid_values = ["none", "blacklist", "whitelist"] if restriction_type not in valid_values: raise ValueError( 'RestrictionType must be one of: "%s"' % (", ".join(valid_values)) ) return restriction_type
def check_percentages(percentages): """ Check percentages for validity percentages is an array where each array element is either a percentage value or None. The percentage values must add up to no more than 100.0. Negative values count as positive. If there are no None-values and the percentages do not add up to 100.0, they are rescaled so that they do. None-values stay None The result is a copy of percentages were all values that are not None are floats and may have been rescaled. """ # check that sum of percentages is not more than 100% try: given_values = [abs(value) for value in percentages if value is not None] percentage_sum = sum(given_values) except ValueError: print >> sys.stderr, "Percentages are in incompatible formats" sys.exit(1) if percentage_sum > 100.0: print >> sys.stderr, "Percentages add up to more than a hundred" sys.exit(1) # make everything that's not None into floats, rescale if applicable if len(percentages) == len(given_values): # no None-values # convert all values to float and rescale if necessary try: percentages = [abs((float(percentage) * (100.0 / percentage_sum))) for percentage in percentages] except ValueError: print >> sys.stderr, "Percentages cannot be converted to float" sys.exit(1) else: for i, percentage in enumerate(percentages): if percentage is not None: try: percentages[i] = abs(float(percentage)) except ValueError: print >> sys.stderr, \ "Percentages cannot be converted to float" sys.exit(1) return percentages
def get_cache_key(key): """ Generates a prefixed cache-key for ultimatethumb. """ return 'ultimatethumb:{0}'.format(key)
def formActions( primaryButton="", button2=False, button3=False, button4=False, button5=False, inlineHelpText=False, blockHelpText=False): """ *Generate a formActions - TBS style* **Key Arguments:** - ``primaryButton`` -- the primary button - ``button2`` -- another button - ``button3`` -- another button - ``button4`` -- another button - ``button5`` -- another button - ``inlineHelpText`` -- inline and block level support for help text that appears around form controls - ``blockHelpText`` -- a longer block of help text that breaks onto a new line and may extend beyond one line **Return:** - ``formActions`` -- the formActions """ falseList = [primaryButton, button2, button3, button4, button5, inlineHelpText] for i in range(len(falseList)): if not falseList[i]: falseList[i] = "" [primaryButton, button2, button3, button4, button5, inlineHelpText] = falseList if inlineHelpText: inlineHelpText = """<span class="help-inline">%(inlineHelpText)s</span>""" % locals( ) else: inlineHelpText = "" if blockHelpText: blockHelpText = """<span class="help-block">%(blockHelpText)s</span>""" % locals( ) else: blockHelpText = "" formActions = """ <div class="form-actions"> %(primaryButton)s %(button2)s %(button3)s %(button4)s %(button5)s </div>%(inlineHelpText)s%(blockHelpText)s""" % locals() return formActions
def test_inp(test_obj, test_if, name_inp, value=False): """ Test a value if it returns false raise an exception :param: test_obj Object to be tested. :param:test_if The input that is tested to be equal as. (in int, str, double etc) :param: value Bool, if True the exception also shows test_obj not recommended for long lists. :param: name_inp String, the informal name of the object shown in exception. """ assert isinstance(name_inp, str) try: assert isinstance(test_obj, test_if) except AssertionError: if not isinstance(test_if, tuple): if not value: raise TypeError( 'Expected %s for %s but got %s' % (test_if.__name__, name_inp, test_obj.__class__.__name__) ) else: raise TypeError( 'Expected %s for %s but got type %s with' ' value: %s' % (test_if.__name__, name_inp, test_obj.__class__.__name__, test_obj) ) else: test_if = [i.__name__ for i in test_if] if not value: raise TypeError( 'Expected %s for %s but got %s' % (', '.join(test_if), name_inp, test_obj.__class__.__name__) ) else: raise TypeError( 'Expected %s for %s but got type %s with' ' value: %s' % (', '.join(test_if), name_inp, test_obj.__class__.__name__, test_obj) ) return None
def checker(wordlist, filename): """ Return if the file matches all words in the word list """ content = open(filename).read().lower().split() return all(word in content for word in wordlist)
def getTags(src): """ It is a function to get sentence tags with {'B', 'M', 'E', 'S'}. :param src: :return: tags list """ tags = [] if len(src) == 1: tags = ['S'] elif len(src) == 2: tags = ['B', 'E'] else: m_num = len(src) - 2 tags.append('B') tags.extend(['M'] * m_num) tags.append('S') return tags
def _collapse(values): """Collapse multiple values to a colon-separated list of values""" if isinstance(values, str): return values if values is None: return "all" if isinstance(values, list): return ";".join([_collapse(v) for v in values]) return str(values)
def unknown_els(dim): """ The elements of the "unknown" basis. Just returns an empty list. Parameters ---------- dim : int The dimension of the basis (doesn't really matter). Returns ------- list """ assert(dim == 0), "Unknown basis must have dimension 0!" return []
def pgcd(a, b): """ [description] calculate the greatest common divisor of a and b :param a: it is an Int :param b: it is an Int :return: a -> it is an Int """ while b != 0: a, b = b, a % b return a
def sumSquares(upperLimit): """ Returns the sum of squares from [1, upperLimit] --param upperLimit : integer --return sum of squares : integer """ squares = [x**2 for x in range(1,upperLimit+1)] return sum(squares)
def count_words(words): """You are given a string words. Count the number of unique words that starts with lower letter. Count the number of unique words that starts with Upper letter. And return a list contains the two counts and the length of the string words. If two words are same, count them as one. If two words are different, count them as two. Example: count_words("You are given a string of words") == [6,1, 31] count_words("Please write some Some unit unit tests") == [4, 2, 38] """ words = str(words) splitted_words = words.split() #print(splitted_words) number_of_words = len(words) # The Third Requirement lower_letters_words = [] upper_letters_words = [] lower_letters_counter = 0 # The first Requirement upper_letters_counter = 0 # The second Requirement for word in splitted_words: first_letter = word[0] if first_letter.isupper(): if word in upper_letters_words: continue upper_letters_counter += 1 upper_letters_words.append(word) elif first_letter.islower(): if word in lower_letters_words: continue lower_letters_counter += 1 lower_letters_words.append(word) final_answer = [lower_letters_counter, upper_letters_counter, number_of_words] #print(final_answer) return final_answer
def __format_float(value): """Format float in scientific notation, 6 decimal places. :param value: :return: """ return '{:.6e}'.format(float(value))
def _le_to_uint(val): """Returns the unsigned integer represented by the given byte array in little-endian format. Args: val: Byte array in little-endian format that represents an unsigned integer. Returns: The unsigned integer represented by the byte array ``val``. """ return int.from_bytes(val, byteorder='little')
def perfect_score(student_info): """ :param student_info: list of [<student name>, <score>] lists :return: first `[<student name>, 100]` or `[]` if no student score of 100 is found. """ # for name, score in student_info: # if score == 100: for student in student_info: # print("boop", student) if student[1] == 100: return student return []
def subexpr_before_unbalanced(expr, ltok, rtok): """Obtains the expression prior to last unbalanced left token.""" subexpr, _, post = expr.rpartition(ltok) nrtoks_in_post = post.count(rtok) while nrtoks_in_post != 0: for i in range(nrtoks_in_post): subexpr, _, post = subexpr.rpartition(ltok) nrtoks_in_post = post.count(rtok) _, _, subexpr = subexpr.rpartition(rtok) _, _, subexpr = subexpr.rpartition(ltok) return subexpr
def get_slu_type(cfg): """ Reads the SLU type from the configuration. """ return cfg['SLU']['type']
def elvis_operator(operator, receiver, expr): """:yaql:operator ?. Evaluates expr on receiver if receiver isn't null and returns the result. If receiver is null returns null. :signature: receiver?.expr :arg receiver: object to evaluate expression :argType receiver: any :arg expr: expression :argType expr: expression that can be evaluated as a method :returnType: expression result or null .. code:: yaql> [0, 1]?.select($+1) [1, 2] yaql> null?.select($+1) null """ if receiver is None: return None return operator(receiver, expr)
def roundup_16(x): """Rounds up the given value to the next multiple of 16.""" remainder = x % 16 if remainder != 0: x += 16 - remainder return x
def relabel_prometheus(job_config): """Get some prometheus configuration labels.""" relabel = { 'path': '__metrics_path__', 'scheme': '__scheme__', } labels = { relabel[key]: value for key, value in job_config.items() if key in relabel.keys() } # parse __param_ parameters for param, value in job_config.get('params', {}).items(): labels['__param_%s' % (param,)] = value return labels
def find_header(blockquote): """Find attributes in a blockquote if they are defined on a header that is the first thing in the block quote. Returns the attributes, a list [id, classes, kvs] where id = str, classes = list, kvs = list of key, value pairs """ if blockquote[0]['t'] == 'Header': level, attr, inline = blockquote[0]['c'] return level, attr, inline
def reader(start_sinogram=0, end_sinogram=0, step_sinogram=1, start_projection=0, end_projection=0, step_projection=1, sinograms_per_chunk=0, projections_per_chunk=0): """ Function to expose input tomography array parameters in function pipeline GUI Parameters ---------- start_sinogram : int Start for sinogram processing end_sinogram : int End for sinogram processing step_sinogram : int Step for sinogram processing start_projection : int Start for projection processing end_projection : int End for projection processing step_projection : int Step for projection processing sinograms_per_chunk : int Number of sinograms processed at one time. Limited by machine memory size Returns ------- tuple, tuple, int: Arguments rearranged into tuples to feed into reconstruction """ return (start_projection, end_projection, step_projection), (start_sinogram, end_sinogram, step_sinogram), \ sinograms_per_chunk, projections_per_chunk
def split_off_attrib(xpath): """ Splits off attribute of the given xpath (part after @) :param xpath: str of the xpath to split up """ split_xpath = xpath.split('/@') assert len(split_xpath) == 2, f"Splitting off attribute failed for: '{split_xpath}'" return tuple(split_xpath)
def _create_file_name_from_complex_index(complex_): """Create a file name from a complex index.""" choice = "".join([str(int(x)) for x in complex_[1]]) if len(complex_) == 3: file_name = f"{complex_[0]}_{choice}_{complex_[2]}.parquet" elif len(complex_) == 2: file_name = f"{complex_[0]}_{choice}.parquet" else: raise NotImplementedError return file_name
def parseInt(value, ret=0): """ Parses a value as int. This function works similar to its JavaScript-pendant, and performs checks to parse most of a string value as integer. :param value: The value that should be parsed as integer. :param ret: The default return value if no integer could be parsed. :return: Either the parse value as int, or ret if parsing not possible. """ if value is None: return ret if not isinstance(value, str): value = str(value) conv = "" value = value.strip() for ch in value: if ch not in "+-0123456789": break conv += ch try: return int(conv) except ValueError: return ret
def fibonacci_smaller_than(limit): """Return Fibonacci series up to limit""" result = [] previous_number, current_number = 0, 1 while previous_number < limit: result.append(previous_number) previous_number, current_number = current_number, previous_number + current_number return result
def math_map_list(values, toMin=0, toMax=1): """ Maps the values of a list from a minimum value to a maximum value. ---------- values : list to be mapped ---------- toMin : minimum value of the list's target range (default = 0) toMax : maximum value of the list's target range (default = 1) """ minValue = min(values) maxValue = max(values) delta = maxValue - minValue deltaTarget = toMax - toMin newValues = [toMin +(value-minValue)*deltaTarget/delta for value in values] return newValues
def compare_listener(current_listener, new_listener): """ Compare two listeners. :param current_listener: :param new_listener: :return: """ modified_listener = {} # Port if current_listener['Port'] != new_listener['Port']: modified_listener['Port'] = new_listener['Port'] # Protocol if current_listener['Protocol'] != new_listener['Protocol']: modified_listener['Protocol'] = new_listener['Protocol'] # If Protocol is HTTPS, check additional attributes if current_listener['Protocol'] == 'HTTPS' and new_listener['Protocol'] == 'HTTPS': # Cert if current_listener['SslPolicy'] != new_listener['SslPolicy']: modified_listener['SslPolicy'] = new_listener['SslPolicy'] if current_listener['Certificates'][0]['CertificateArn'] != new_listener['Certificates'][0]['CertificateArn']: modified_listener['Certificates'] = [] modified_listener['Certificates'].append({}) modified_listener['Certificates'][0]['CertificateArn'] = new_listener['Certificates'][0]['CertificateArn'] elif current_listener['Protocol'] != 'HTTPS' and new_listener['Protocol'] == 'HTTPS': modified_listener['SslPolicy'] = new_listener['SslPolicy'] modified_listener['Certificates'] = [] modified_listener['Certificates'].append({}) modified_listener['Certificates'][0]['CertificateArn'] = new_listener['Certificates'][0]['CertificateArn'] # Default action # We wont worry about the Action Type because it is always 'forward' if current_listener['DefaultActions'][0]['TargetGroupArn'] != new_listener['DefaultActions'][0]['TargetGroupArn']: modified_listener['DefaultActions'] = [] modified_listener['DefaultActions'].append({}) modified_listener['DefaultActions'][0]['TargetGroupArn'] = new_listener['DefaultActions'][0]['TargetGroupArn'] modified_listener['DefaultActions'][0]['Type'] = 'forward' if modified_listener: return modified_listener else: return None
def get_cluster_from_pattern(pattern, clusters): """ Helper function to return the cluster a pattern is in Args: pattern: A tuple of three values clusters: A list of lists of patterns Returns: The list containing the pattern """ for cluster in clusters: if pattern in cluster: return cluster else: raise RuntimeError("Pattern not found in cluster")
def timestampToSubscribers(response): """ Create a dictionary that links a timestamp to subscribers. Makes it easier to batch up messages to send to subscribers. {123456789.123: [subA, ..., subN]} :return: """ timestamp_to_subscribers = {} # matches subscribers to their current place in kinesis stream for established_subscriber in response: stream_event, subscriber = established_subscriber['event_name'].split( '_subscriber_' ) approximate_arrival_timestamp = established_subscriber[ 'approximate_arrival_timestamp' ] if approximate_arrival_timestamp not in timestamp_to_subscribers: timestamp_to_subscribers[approximate_arrival_timestamp] = [] timestamp_to_subscribers[approximate_arrival_timestamp].append( subscriber) else: timestamp_to_subscribers[approximate_arrival_timestamp].append( subscriber) return timestamp_to_subscribers
def memdiff_search(bytes1, bytes2): """ Use binary searching to find the offset of the first difference between two strings. :param bytes1: The original sequence of bytes :param bytes2: A sequence of bytes to compare with bytes1 :type bytes1: str :type bytes2: str :rtype: int offset of the first location a and b differ, None if strings match """ # Prevent infinite recursion on inputs with length of one half = (len(bytes1) // 2) or 1 # Compare first half of the string if bytes1[:half] != bytes2[:half]: # Have we found the first diff? if bytes1[0] != bytes2[0]: return 0 return memdiff_search(bytes1[:half], bytes2[:half]) # Compare second half of the string if bytes1[half:] != bytes2[half:]: return memdiff_search(bytes1[half:], bytes2[half:]) + half
def parse_block(block, metric=[], labels={}): """Parse_block. Parse a 'block' of results (a level of a for example) and transform into a suitable list with labels and all """ result = [] # Give a dict of lists of labels which will be concatenated into a single # label per item. These could be static or based on the response data labels = {"app": ["example", "random_numbers"], "env": ["TEST"]} # .items() converts a dict to a list of key-value tuples for key, value in block.items(): # At this point we have e.g. key-value pair # "smalls: {'first': 3, 'second': 18}" based on the data for n_key, n_value in value.items(): # And here "first: 3" # Append the list with the metric "prefixes", keys, # labels and value # # e.g. "example1", "random", "smalls", "first", labels, 5 result.append((metric + [key] + [n_key], labels, n_value)) return result
def is_valid_address(address): """check ip-address is valid""" if address.find('.') != -1: addr_list = address.split('.') if len(addr_list) != 4: return False for each_num in addr_list: if not each_num.isdigit(): return False if int(each_num) > 255: return False return True return False
def matrix_sum(matrix): """ Matrix_sum: has one required parameter of a matrix (an array of arrays). This function will then sum the total of each row or each array within the matrix and return the results per row as a single array. """ output = [] for i in range(len(matrix)): counter = 0 for j in range(len(matrix[i])): counter += matrix[i][j] output.append(counter) return output
def cipher(word): """ :param word: the word to decipher to "ave" :return: the number used for encryption """ word = word.lower() return ord(word[0]) % 97
def populate_albums_table(db_session, artist_id, l): """Save the list of albums in the albums table.""" if not l: # list is empty return False #print list c = db_session.cursor() c.execute("""DELETE FROM albums WHERE artist_id = ?""", [artist_id]) for album_list in l: c.execute("""INSERT INTO albums (artist_id, album_id, name, year, precise_rating) VALUES (?,?,?,?,?)""", album_list) db_session.commit() c.close() return True
def leap_year(year, calendar='standard'): """Determine if year is a leap year""" leap = False if ((calendar in ['standard', 'gregorian', 'proleptic_gregorian', 'julian']) and (year % 4 == 0)): leap = True if ((calendar == 'proleptic_gregorian') and (year % 100 == 0) and (year % 400 != 0)): leap = False elif ((calendar in ['standard', 'gregorian']) and (year % 100 == 0) and (year % 400 != 0) and (year < 1583)): leap = False return leap
def _block_to_bed_line(block): """ tchrom, trun, trun + size, tstrand, qchrom, qrun, qrun + size, qstrand, chain_id + '.' + str(bc), chain_score :param block: :return: """ return '{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n'.format(*block)
def split_by_cleaning(value, split_by_char=','): """ The method returns elements from a string value by deleting extra spaces :param value: A string value :param split_by_char: A character in the value to split :return: list of split elements """ elements = value.strip().strip(split_by_char).split(split_by_char) return [element.strip() for element in elements if element.strip()]
def parse_by_suffix(input_string, suffix, start_char=" "): """searches through input_string until it finds the suffix. Walks backwards from the suffix and returns everything in the string between suffix and the end_char""" end = input_string.find(suffix) start = end while input_string[start] != start_char: start -= 1 return input_string[start+1:end]
def diR_calc(i,vt,v,winv,Rf,Lf,wbase): """Calcluate derivative of inverter branch current - real component - iR""" diR = (1/Lf)*(-Rf*i.real - v.real + vt.real) + (winv/wbase)*i.imag return diR
def query_for_users_annotations(userid): """Return an Elasticsearch query for all the given user's annotations.""" return { "query": { "filtered": { "filter": { "bool": { "must": [{"term": {"user": userid.lower()}}] } } } } }
def convertHLAToIEDB(h): """Takes format A*1234 or A_1234 and returns A*12:34""" return 'HLA-' + h[:4].replace('_', '*') + ':' + h[4:]
def add_suffix(event, fields, suffix, separator='_'): """ Adds a suffix to a field or list of fields :param event: A dict with the entire event :param field_or_field_list: A single field or list of fields for which to add a suffix :param suffix: The suffix to add to the fields :param separator: The character to place between the name and the suffix :return: An altered event with the altered field names Examples: .. code-block:: python # Example #1 event = {'a_field': 'a_value'} event = add_suffix(event, fields='a_field', suffix='an_ending') event = {'a_field_an_ending': 'a_value'} # Example #2 event = {'a_field': 'a_value'} event = add_suffix(event, fields='a_field', suffix='an_ending', separator='---') event = {'a_field---an_ending': 'a_value'} # Example #3 event = {'a_field': 'a_value', 'another_field': 'another_value'} event = add_suffix(event, fields=['a_field', 'another_field'], suffix='an_ending') event = {'a_field_an_ending': 'a_value', 'another_field_an_ending': 'another_value'} """ if type(fields) is not list: fields = [fields] for k, v in event.items(): if k in fields: event[k + separator + suffix] = event[k] del event[k] return event
def _get_severity_filter_value(severity_arg): """Converts single str to upper case. If given list of strs, converts all to upper case.""" if severity_arg: return ( [severity_arg.upper()] if isinstance(severity_arg, str) else list(map(lambda x: x.upper(), severity_arg)) )