content
stringlengths
42
6.51k
def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ return { x: hand[x] - word.count(x) if x in word else hand[x] for x in hand if (hand.get(x,0) - word.count(x)) > 0 }
def _formulate_smt_constraints_final_layer( z3_optimizer, smt_output, delta, label_index): """Formulates smt constraints using the logits in the final layer. Generates constraints by setting the logit corresponding to label_index to be more than the rest of the logits by an amount delta for the forward pass of a masked image. Args: z3_optimizer: instance of z3.Optimizer, z3 optimizer. smt_output: list of z3.ExprRef with length num_output. delta: float, masked logit for the label is greater than the rest of the masked logits by delta. label_index: int, index of the label of the training image. Returns: z3 optimizer with added smt constraints. """ for i, output in enumerate(smt_output): if i != label_index: z3_optimizer.solver.add(smt_output[label_index] - output > delta) return z3_optimizer
def conddb_url(api=''): """Return CondDB URL for given API name""" return 'http://cms-conddb.cern.ch/%s' % api
def calc_montage_horizontal(border_size, *frames): """Return total[], pos1[], pos2[], ... for a horizontal montage. Usage example: >>> calc_montage_horizontal(1, [2,1], [3,2]) ([8, 4], [1, 1], [4, 1]) """ num_frames = len(frames) total_width = sum(f[0] for f in frames) + (border_size * num_frames + 1) max_height = max(f[1] for f in frames) total_height = max_height + (2 * border_size) x = border_size pos_list = [] for f in frames: y = border_size + (max_height - f[1]) // 2 pos_list.append([x, y]) x += f[0] + border_size result = [[total_width, total_height]] result.extend(pos_list) return tuple(result)
def get_class_name(name): """ tries to return a CamelCased class name as good as poosible capitalize split at underscores "_" and capitelize the following letter merge this_is_Test => ThisIsTest test => Test testone => Testone """ #print("class_name: " + "".join([c.capitalize() for c in name.split("_")])) return "".join([c.capitalize() for c in name.split("_")])
def getAccentedVocal(vocal, acc_type="g"): """ It returns given vocal with grave or acute accent """ vocals = {'a': {'g': u'\xe0', 'a': u'\xe1'}, 'e': {'g': u'\xe8', 'a': u'\xe9'}, 'i': {'g': u'\xec', 'a': u'\xed'}, 'o': {'g': u'\xf2', 'a': u'\xf3'}, 'u': {'g': u'\xf9', 'a': u'\xfa'}} return vocals[vocal][acc_type]
def _MillerRabin(n: int, a: int) -> bool: """ Miller-Rabin test with base a Args: n (int): number to test a (int): base Returns: bool: result """ d = n - 1 while (d & 1) == 0: d >>= 1 t = pow(a, d, n) while d != n - 1 and t != n - 1 and t != 1: t = (t * t) % n d <<= 1 return t == n - 1 or (d & 1) == 1
def get_overspending_handling(data, category): """ Find the overspendingHandling for a category in a month """ for subcategory in data: if subcategory["categoryId"] == category: if "overspendingHandling" in subcategory: return subcategory["overspendingHandling"] else: return None return None
def smoothed_relative_freq(n_focus, n_ref, size_focus, size_ref, N=1): """Simple maths method for finding relative frequency of a word in the focus corpus compared to the reference corpus. Frequencies are calculated per million and N is the smoothing parameter (default N = 1). Args: n_focus (int): Number of target words in focus corpus n_ref (int): Number of target words in reference corpus size_focus (int): Size of focus corpus size_ref (int): Size of reference corpus N (int, optional): Smoothing parameter Returns: float """ f_focus = n_focus * 1.0e6 / size_focus f_ref = n_ref * 1.0e6 / size_ref return (f_focus + N) / (f_ref + N)
def __splitTime(sec): """Returns time in the format H:MM:SS @rtype: str @return: Time in the format H:MM:SS""" min, sec = divmod(sec, 60) hour, min = divmod(min, 60) return (hour, min, sec)
def check_order_history_product(order_list, username): """ check order history and returns products same as\ or similar to the given username ordered """ category_purchased = set() product_ids = set() for order in order_list: if order['username'] == username: category_purchased.add(order['category']) for order in order_list: if order['category'] in category_purchased: product_id = order['product_id'] product_ids.add(product_id) return product_ids
def _h_n_linear_geometry(bond_distance: float, n_hydrogens: int): # coverage: ignore """Create a geometry of evenly-spaced hydrogen atoms along the Z-axis appropriate for consumption by MolecularData.""" return [('H', (0, 0, i * bond_distance)) for i in range(n_hydrogens)]
def product_code(d, i, r): """Get product code :param d: Report definition :type d: Dict :param i: Item definition :type i: Dict :param r: Meter reading :type r: usage.reading.Reading :return: product code from item :rtype: String """ return i.get('product_code', '')
def complement(intervals, first=None, last=None): """complement a list of intervals with intervals not in list. >>> complement([(10,20), (15,40)]) [] >>> complement([(10,20), (30,40)]) [(20, 30)] >>> complement([(10,20), (30,40)], first=5) [(5, 10), (20, 30)] Arguments --------- intervals : list List of intervals first : int First position. If given, the interval from `first` to the first position in `intervals` is added. last : int Last position. If given, the interval from the last position in `intervals` to `last` is added. Returns ------- intervals : list A new list of intervals """ if len(intervals) == 0: if first is not None and last is not None: return [(first, last)] else: return [] new_intervals = [] intervals.sort() last_from, last_to = intervals[0] if first is not None and first < last_from: new_intervals.append((first, last_from)) for this_from, this_to in intervals: if this_from > last_to: new_intervals.append((last_to, this_from)) last_from = this_from last_to = max(last_to, this_to) if last and last > last_to: new_intervals.append((last_to, last)) return new_intervals
def similarL1(a, b): """ get similar between a string and a string in a list :param a: String :param b: List of strings :return: boolean """ for x in b: if x.lower() in a.lower(): return True return False
def step_schedule_with_warmup(step, step_size, warmup_steps=0, hold_max_steps=0, lr_start=1e-4, lr_max=1e-3, step_decay=.5): """ Create a schedule with a step decrease preceded by a warmup period during which the learning rate increases linearly between {lr_start} and {lr_max}. """ if step < warmup_steps: lr = (lr_max - lr_start) / warmup_steps * step + lr_start elif step < warmup_steps + hold_max_steps: lr = lr_max else: lr = lr_max * step_decay**((step - warmup_steps - hold_max_steps)//step_size) return lr
def parse_line(line): """return the index and direct links described by a string representing a pipe""" k, v = line.strip().split(' <-> ') return k, v.split(', ')
def uvm_object_value_str(v): """ Function- uvm_object_value_str Args: v (object): Object to convert to string. Returns: str: Inst ID for `UVMObject`, otherwise uses str() """ if v is None: return "<null>" res = "" if hasattr(v, 'get_inst_id'): res = "{}".format(v.get_inst_id()) res = "@" + res else: res = str(v) return res
def climbStairs(n, dic = {0:0,1:1,2:2}): """ LeetCode-Problem: You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Solution: Exploring all possible ways to climb the stairs in 1 or 2 steps. And using the dictionary to keep record of the paths we already explored. """ if n in dic.keys(): return dic[n] else: dic[n] = climbStairs(n-1,dic) + climbStairs(n-2,dic) return dic[n]
def check_unique_list(input): """ Given a list, check if it is equal to a sorted list containing 1-9 Return True if the given list is unique, False otherwise """ # convert list string into list of int and sort it int_list = list(map(int, input)) int_list.sort() return int_list == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def _pad(data): """Pad the data to encrypt to be a multiple of 16.""" # return data if no padding is required if len(data) % 16 == 0: return data # subtract one byte that should be the 0x80 # if 0 bytes of padding are required, it means only # a single \x80 is required. padding_required = 15 - (len(data) % 16) data = "%s\x80" % data data = "%s%s" % (data, "\x00" * padding_required) return data
def get_names_from_lines(lines, frac_len, type_function): """Take list of lines read from a file, keep the first fract_len elements, remove the end of line character at the end of each element and convert it to the type definded by function. """ return [type_function(line[:-1]) for line in lines[:frac_len]]
def bitparity(x): """return the bit parity of the word 'x'. """ assert x >= 0, "bitparity(x) requires integer x >= 0" while x > 0xffffffff: x = (x >> 32) ^ (x & 0xffffffff) x ^= x >> 16 x ^= x >> 8 x ^= x >> 4 return (0x6996 >> (x & 15)) & 1
def clean_laughs(text): """ Removes laughs. Parameters ---------- text : str Returns ------- str """ laughs = ['ah', 'eh', 'he' 'ih', 'hi', 'oh'] vowels = ['a', 'e', 'i', 'o', 'u'] text_words = text.split() new_words = [word for word in text_words if word.lower() not in laughs] new_text = ' '.join(new_words) for i in new_words: j = i.lower() for k in vowels: if ('h' in j) and (len(j) >= 4): if (len(j) - 2) <= (j.count(k) + j.count('h')): new_text = new_text.replace(i, '') return new_text
def get_ngrams(s, ngmin, ngmax, separator="", bos="<", eos=">", suffix="", flatten=True): """ For the given sequence s. Return all ngrams in range ngmin-ngmax. spearator is useful for readability bos/eos symbols are added to indicate beginning and end of seqence suffix is an arbitrary string useful for distinguishing in case differernt types of ngrams are used if flatten is false, a list of lists is returned where the first element contains the ngrams of size ngmin and the last contains the ngrams of size ngmax """ # return a single dummy feature if there are no applicable ngrams # probably resulting in a mojority-class classifier if ngmax == 0 or (ngmax - ngmin < 0) : return ['__dummy__'] ngrams = [[] for x in range(1, ngmax + 1)] s = [bos] + s + [eos] for i, ch in enumerate(s): for ngsize in range(ngmin, ngmax + 1): if (i + ngsize) <= len(s): ngrams[ngsize - 1].append( separator.join(s[i:i+ngsize]) + suffix) if flatten: ngrams = [ng for nglist in ngrams for ng in nglist] return ngrams
def extinction_law(a, b, Rv = 3.1): """Eqn 1 from Cardelli 1989""" a_lam_aV = a + b / Rv return a_lam_aV
def base_b(n: int, b: int): """ Return the string representation of n in base-b. Example: base_b(11, 3) = '102' """ e = n // b q = n % b if n == 0: return '0' elif e == 0: return str(q) else: return base_b(e, b) + str(q)
def read_singles(singles_file): """ Read the table of reads per gene and return a dictionary """ if not singles_file: return None counts = {} try: for line in open(singles_file): spl = line.strip().split() try: counts[spl[0]] = sum([int(k) for k in spl[1:]]) except ValueError: pass except IOError: return None return counts
def splituser(host): """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" user, delim, host = host.rpartition('@') return (user if delim else None), host
def getNegativeSamples(outsideWordIdx, dataset, K): """ Samples K indexes which are not the outsideWordIdx """ negSampleWordIndices = [None] * K for k in range(K): newidx = dataset.sampleTokenIdx() while newidx == outsideWordIdx: newidx = dataset.sampleTokenIdx() negSampleWordIndices[k] = newidx return negSampleWordIndices
def rubygems_api_url(name, version=None): """ Return a package API data URL given a name, an optional version and a base repo API URL. For instance: >>> url = rubygems_api_url(name='turbolinks', version='1.0.2') >>> assert url == 'https://rubygems.org/api/v2/rubygems/turbolinks/versions/1.0.2.json' If no version, we return: >>> url = rubygems_api_url(name='turbolinks') >>> assert url == 'https://rubygems.org/api/v1/versions/turbolinks.json' Things we could return: a summary for the latest version, with deps https://rubygems.org/api/v1/gems/mqlight.json """ if not name: return if version: return f'https://rubygems.org/api/v2/rubygems/{name}/versions/{version}.json' else: return f'https://rubygems.org/api/v1/versions/{name}.json'
def cache_clear_mutation(dataset_id): """Update the draft HEAD reference to an new git commit id (hexsha).""" return { 'query': 'mutation ($datasetId: ID!) { cacheClear(datasetId: $datasetId) }', 'variables': {'datasetId': dataset_id} }
def get_service_name(pod_name): """Returns the service name from the pod name.""" return pod_name[:-6]
def compact_dict_none(dct): """ Compacts a dct by removing pairs with a None value. Other nil values pass :param dct: :return: The filtered dict """ return dict(filter(lambda key_value: key_value[1] != None, dct.items()))
def version_is_locked(version): """ Determine if a version is locked """ return getattr(version, "versionlock", None)
def solution(array): """ Finds the smallest positive integer not in array. The smallest possible answer is 1. :param array: list of integers :return: smallest positive integer not in array. """ # smallest answer so far i = 1 # visited values visited = [] for value in array: visited.append(value) # if i is equal to value, # we have to increment it before we visit the next item in array. if value == i: # we have to increment i to a number that we did not visit before. while True: value += 1 if value not in visited: break i = value return i
def parse_field(field_string): """ Get a tuple of the first entries found in an psimitab column (xref, value, desc) :param field_string: :return: A tuple (xref, value, desc) - desc is optional """ parts = field_string.split(":") xref = parts[0] rest = parts[1] if "(" in rest: subfields = rest.split("(") value = subfields[0] desc = subfields[1][:-1] else: value = rest desc = "NA" return xref, value, desc
def get_errno(exc): # pragma: no cover """ Get the error code out of socket.error objects. socket.error in <2.5 does not have errno attribute socket.error in 3.x does not allow indexing access e.args[0] works for all. There are cases when args[0] is not errno. i.e. http://bugs.python.org/issue6471 Maybe there are cases when errno is set, but it is not the first argument? """ try: if exc.errno is not None: return exc.errno except AttributeError: pass try: return exc.args[0] except IndexError: return None
def test_for_short_cell(raw_python_source: str) -> bool: """ Returns True if the text "# Long" is in the first line of `raw_python_source`. False otherwise. """ first_element = raw_python_source.split("\n")[0] if "#" in first_element and "short" in first_element.lower(): return True return False
def arg_parse(text, j): """Parsing arguments in op_par_loop to find the correct closing brace""" depth = 0 loc2 = j while 1: if text[loc2] == '(': depth = depth + 1 elif text[loc2] == ')': depth = depth - 1 if depth == 0: return loc2 loc2 = loc2 + 1
def mlist(x): """make sure x is a list""" if isinstance(x, list): return(x) else: return([x])
def subdict(d, keys): """Returns a new dictionary composed of the (key, value) pairs from d for the keys specified in keys""" return {k: d[k] for k in keys}
def isupper(char): """ Indicates if the char is upper """ if len(char) == 1: if ord(char) >= 0x41 and ord(char) <= 0x5A: return True return False
def manage_user_group_verification(config, tables, users, groups): """ Make sure the specified users and groups exist. """ if users: # if there is only one user, make it a list anyway if isinstance(users, str): user_list = users.split(',') else: user_list = users # Get the list of valid users. table = 'csv2_user' rc, msg, db_user_list = config.db_query(table) valid_users = {} for row in db_user_list: valid_users[row['username']] = False # Check the list of specified users. for user in user_list: if user not in valid_users: return 1, 'specified user "%s" does not exist' % user elif valid_users[user]: return 1, 'user "%s" was specified twice' % user else: valid_users[user] = True if groups: # if there is only one group, make it a list anyway if isinstance(groups, str): group_list = groups.split(',') else: group_list = groups # Get the list of valid groups. table = 'csv2_groups' rc, msg, db_group_list = config.db_query(table) valid_groups = {} for row in db_group_list: valid_groups[row['group_name']] = False # Check the list of specified groups. for group in group_list: if group not in valid_groups: return 1, 'specified group "%s" does not exist' % group elif valid_groups[group]: return 1, 'group "%s" was specified twice' % group else: valid_groups[group] = True return 0, None
def s2i(s): """ Convert a string to an integer even if it has + and , in it. """ # Turns out sometimes there can be text in the string, for example "pending", # and that made this function crash. if type(s)==type(0): # Input is already a number return s try: # Sometimes input has a number with commas in it, remove those. if s: return int(float(s.replace(',', ''))) except ValueError: pass return None
def get_default_bbox(kind): """ Get default rough estimate of face bounding box for `get_identity_descriptor()`. Args: kind: `str` Crop type that your model's pose encoder consumes. One of: 'ffhq', 'x2face', 'latentpose'. Returns: bbox: `tuple` of `int`, length == 4 The bounding box in pixels. Defines how much pixels to clip from top, left, bottom and right in a 256 x 256 image. """ if kind == 'ffhq': return (0, 30, 60, 30) elif kind == 'x2face': return (37, (37+45)//2, 45, (37+45)//2) elif kind == 'latentpose': return (42, (42+64)//2, 64, (42+64)//2) else: raise ValueError(f"Wrong crop type: {kind}")
def driver_function(prices,n): """The driver holds the lookup dictionary and makes the original function call to rodcut function. """ dict = {} def rodcut(prices,n): """ Note: this function was found in C++ on: https://www.techiedelight.com/rot-cutting/ Input: an array of prices with indexes that correlate to the size of the pieces of wood. an integer of the length of the wood to be cut. Output: a string of the inputs and the resulting max cost that can be made from the length of the wood and the prices. """ # each time the function gets called initialize maxValue to be negative infinity maxValue = float('-inf') # return 0 if the input length of the rod is 0 or if the input length is greater than the array as that will throw list index out of range errors below if n == 0 or len(prices) <= n: return 0 # generate numbers between 1 and the current rod_length + 1 (+1 because range() is non-inclusive at the upper bounds) for _ in range(1, n+1): # set 'entry' to a tuple of the current cut. a cut consists of two pieces. # cut == piece A and piece B: A is: _ and piece B is: the length of the rod - piece A. cut = (_, n-_) # memoization dictionary: if cut in dict: cost = dict[cut] else: # reference the price for piece A, taking into account the index of piece A will be: _-1 # need to determine the cost(s) of all pieces resulting from that cut. # so piece B is fed into "the wood chipper": the rodCut function, to determine its cost(s) cost = prices[_-1] + rodcut(prices, n - _) dict[cut] = cost # if the resuting cost is greater than the local maxValue set the local maxValue to the cost if (cost > maxValue): maxValue = cost # return the maxValue to the outside scope. return maxValue maxValue = rodcut(prices,n) printable_prices = [str(price) for price in prices] return "For this input:\n\n"+ "prices: " + ", ".join(printable_prices) + "\nwood length: " + str(n) + "\n\nThe solution is:\n\n" + str(maxValue)
def is_prime(num): """ Returns true is the number is prime. To check if a number is prime, we need to check all its divisors upto only sqrt(number). Reference: https://stackoverflow.com/a/5811176/7213370 """ # corner case. 1 is not a prime if num == 1: return False # check if for a divisor upto sqrt(number) i = 2 while i * i <= num: if num % i == 0: return False i += 1 return True
def string_enc(x): """ Fixing a string's coding""" try: return x.encode('latin').decode('utf-8') except: return x
def zero_hit_count_rules(hit_count_rules): """ Get list of zero hit count rules :param hit_count_rules: dictionary which contain json response with all hit count rules :return: list with all zero hit count rules (contain rule name, id, type and access policy name) """ rule = [] for i in hit_count_rules: if i["hitCount"] == 0: rule.append(i["rule"]) #rule.append({"Policy name": hit_count_rules[0]["metadata"]["policy"]["name"]}) return rule
def query_tw_author_id(author_id): """ES query by Twitter's author_id Args: author_id (str) Returns: ES query (JSON) Note: INCA """ return { "query": { "bool": { "filter": [ {"term": {"doctype": "tweets2"}}, {"match": {"author_id": author_id}}, ] } } }
def to_listdict(list_list): """Converts a list-of-lists to a list-of-dicts. Ex: [["a","b"],[1, 2],[3, 4]] ---> [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] Args: list_list (<list<list>>): A 2d list with a header row. Ex. [['a','b'], [1, 2], [3, 4]] Returns: <list<dict>>: list-of-dicts. Ex: [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] """ # Fastest way to this is cycle through every row but the first # and use zip with the first row and subsequent rows return [dict(zip(list_list[0], i)) for i in list_list[1:]]
def set_size(width, fraction=1, subplots=(1, 1)): """ Set figure dimensions to avoid scaling in LaTeX. Parameters ---------- width: float or string Document width in points, or string of predined document type fraction: float, optional Fraction of the width which you wish the figure to occupy subplots: array-like, optional The number of rows and columns of subplots. Returns ------- fig_dim: tuple Dimensions of figure in inches """ if width == 'thesis': width_pt = 426.79135 elif width == 'beamer': width_pt = 307.28987 elif width == 'pnas': width_pt = 246.09686 elif width == 'current': width_pt = 469.75499 else: width_pt = width # Width of figure (in pts) fig_width_pt = width_pt * fraction # Convert from pt to inches inches_per_pt = 1 / 72.27 # Golden ratio to set aesthetic figure height golden_ratio = (5**.5 - 1) / 2 # Figure width in inches fig_width_in = fig_width_pt * inches_per_pt # Figure height in inches fig_height_in = fig_width_in * golden_ratio * (subplots[0] / subplots[1]) return (fig_width_in, fig_height_in)
def newline(text, number=1): """adds number newlines to the end of text""" return text.strip() + ("\n" * number)
def hhmmss_to_seconds(hhmmss): """ Translates HHMMSS or HHMM formatted time into seconds. Args: hhmmss (str): String in HHMMSS or HHMM format Returns: seconds (int): Converted seconds """ hhmmss_split = hhmmss.split(":") try: seconds = (int(hhmmss_split[0]) * 60 * 60) + (int(hhmmss_split[1]) * 60) + int(hhmmss_split[2]) except IndexError: # If IndexError then it would be HHMM instead of HHMMSS so run below code \/ seconds = (int(hhmmss_split[0]) * 60 * 60) + (int(hhmmss_split[1]) * 60) return seconds
def calculations(pyramid, i): """ Calculate the value of the given path. """ res = 1 for x, row in enumerate(pyramid): res *= row[i[x]] return res
def is_video_json_valid(json_payload): """ Validates a video dictionary JSON from the client. Args: json_payload (dict): A JSON payload received from the client. Returns: bool: Whether or not the video JSON format was valid. """ if not json_payload["videoUri"] or not json_payload["title"]: return False return True
def get_canonical_prob_name(prob_name): """Transform string to match name of a probability function.""" prob_name = prob_name.lower() if not prob_name.endswith('_probability'): prob_name = prob_name + '_probability' return prob_name
def convert_codewords(codewords): """ Changes the codewords list of lists to a list of strings Parameters ---------- codewords : list allowed codewords for logical zero Returns ------- list_of_strings : list a list of strings Notes ----- No longer needed at present as codeword is a list of strings but retained in case needed in future. """ list_of_strings = [] for lists in codewords: new_string = '' for item in lists: new_string = new_string + str(item) list_of_strings.append(new_string) return(list_of_strings)
def format_float(val): """Set a floating point number into a specific format.""" return f'{val:.2f}'
def no_dups(recommend: list) -> list: """Remove the duplicates""" new = [] for x in recommend: if x not in new: new.append(x) return new
def pos_embed(x, position_num): """ get position embedding of x """ maxlen = int(position_num / 2) return max(0, min(x + maxlen, position_num))
def wordinset_wild(word, wordset, wild='*'): """Return True if word not in wordset, nor matched by wildcard. Note: accepts a wildcard (default '*') for '0 or more letters'. """ if word in wordset: return True else: if word[-1] != wild: word += wild while len(word) > 2: if word in wordset: return True else: word = word[:-2] + wild return False
def rgb2hex(r, g, b): """ Convert RGB to color hex Args: r (int): Red g (int): Green b (int): Blue Returns: **hex** (string) - Hex color code """ return '#%02x%02x%02x' % (r, g, b)
def product_of_2( numbers ): """ From the given list of numbers, find the pair of numbers that sum up to 2020. This function returns the prduct of those 2 numbers. """ numbers = [ int( item ) for item in numbers ] for i in range( len(numbers) ): for j in range( i+1, len(numbers) ): if numbers[i] + numbers[j] == 2020: return numbers[i] * numbers[j]
def validate_scalingpolicyupdatebehavior(scalingpolicyupdatebehavior): """ Validate ScalingPolicyUpdateBehavior for ScalingInstruction Property: ScalingInstruction.ScalingPolicyUpdateBehavior """ VALID_SCALINGPOLICYUPDATEBEHAVIOR = ( "KeepExternalPolicies", "ReplaceExternalPolicies", ) if scalingpolicyupdatebehavior not in VALID_SCALINGPOLICYUPDATEBEHAVIOR: raise ValueError( "ScalingInstruction ScalingPolicyUpdateBehavior must be one of: %s" % ", ".join(VALID_SCALINGPOLICYUPDATEBEHAVIOR) # noqa ) return scalingpolicyupdatebehavior
def invert_dict(old_dict): """ Helper function for assign_colors_to_clusters(). """ inv_dict = {} for k, v in old_dict.items(): inv_dict [v] = inv_dict.get(v, []) inv_dict [v].append(k) return inv_dict
def is_valid_hcl(value: str) -> bool: """ Return if value is a valid hcl (hair color). Parameter --------- value: str a hcl. Return ------ bool True if hcl is valid, False othewise. """ if value[0] != "#": return False return all((char.isdigit() or char in "abcdef" for char in value[1:]))
def format_dictionary_durations(dictionary): """ Takes a dict with values in seconds and rounds the values for legibility""" formatted_dict = {} for k, v in dictionary.items(): try: formatted_dict[k] = round(v) except TypeError: pass return formatted_dict
def open_table(table_name, append=False, default=None): """Open output file if file name specified.""" if not table_name: return default return open(table_name, "at" if append else "wt")
def RemoveSlash( dirName ): """Remove a slash from the end of dir name if present""" return dirName[:-1] if dirName.endswith('/') else dirName
def distx2(x1,x2): """ Calculate the square of the distance between two coordinates. Returns a float """ distx2 = (x1[0]-x2[0])**2 + (x1[1]-x2[1])**2 + (x1[2]-x2[2])**2 return distx2
def msg_from_harvester(timestamp_str: str, ip_address: str, node_id: str) -> str: """Get a fake log msg when a farmer receives data from a harvester""" line = ( f"{timestamp_str} farmer farmer_server : DEBUG" + f" <- farming_info from peer {node_id} {ip_address}" ) return line
def bytesto(bytes, to, bsize=1024): """convert bytes to megabytes, etc. sample code: print('mb= ' + str(bytesto(314575262000000, 'm'))) sample output: mb= 300002347.946 """ a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 } r = float(bytes) for i in range(a[to]): r = r / bsize return(r)
def jaccard_word_level_similarity(y_true: str, y_pred: str) -> float: """ Compute word level Jaccard similarity Parameters ---------- y_true : str True text y_pred : str Predicted text Returns ------- float Word level Jaccard similarity Examples -------- >>> from evaluations.text_extraction import jaccard_word_level_similarity >>> assert jaccard_word_level_similarity( ... "Be happy my friend", ... "be happy" ... ) 0.5 """ true_set = set(y_true.lower().split()) pred_set = set(y_pred.lower().split()) y_intersect = true_set.intersection(pred_set) return len(y_intersect) / (len(true_set) + len(pred_set) - len(y_intersect))
def should_check_integrity(f): """Returns True if f should be checked for integrity.""" return f not in ('README.md', 'TRAINING_LOG', 'checksum.md5', 'data') and not f.startswith('.')
def dont_exceed_max(Max,code_list): """I need to ensure that NetSurfP is not overwhelmed - so I split the queries to ensure that each is less than Max I will use Max = 100000""" C = len(code_list) temp_list=[] for_inclusion=[] limit = 0 for i in range(C): a,b = code_list[i] B = len(b) if limit+B<Max: for_inclusion.append(code_list[i]) limit+=B else: temp_list.append(for_inclusion) limit=B for_inclusion=[code_list[i]] temp_list.append(for_inclusion) return temp_list
def verify_structure(memlen, itemsize, ndim, shape, strides, offset): """Verify that the parameters represent a valid array within the bounds of the allocated memory: char *mem: start of the physical memory block memlen: length of the physical memory block offset: (char *)buf - mem """ if offset % itemsize: return False if offset < 0 or offset + itemsize > memlen: return False if any(v % itemsize for v in strides): return False if ndim <= 0: return ndim == 0 and not shape and not strides if 0 in shape: return True imin = sum(strides[j] * (shape[j] - 1) for j in range(ndim) if strides[ j] <= 0) imax = sum(strides[j] * (shape[j] - 1) for j in range(ndim) if strides[ j] > 0) return 0 <= offset + imin and offset + imax + itemsize <= memlen
def factorial(n): """ Return n! - the factorial of n. >>> factorial(1) 1 >>> factorial(0) 1 >>> factorial(3) 6 """ if n<=0: return 0 elif n==1: return 1 else: return n*factorial(n-1)
def _call_if_callable(s): """Call a variable if it's a callable, otherwise return it.""" if hasattr(s, '__call__'): return s() return s
def extract_package(path, output_directory): """Extract package at path.""" if path.lower().endswith('.tar.gz'): import tarfile try: tar = tarfile.open(path) tar.extractall(path=output_directory) tar.close() return True except (tarfile.ReadError, IOError): return False elif path.lower().endswith('.zip'): import zipfile try: archive = zipfile.ZipFile(path) archive.extractall(path=output_directory) archive.close() except (zipfile.BadZipfile, IOError): return False return True return False
def filter_float(value): """ Filter given float value. :param value: given value :type value: float :return: filtered version of value """ if isinstance(value, (float, int)): return value return None
def title_extractior(obj): """Extract title from content. Use NTLK to do stuff with text. - maybe later for know i will use first sentence in text @return: 'title', generated_content""" _, _, _, content = obj if not content: return 'title', '' cut = 40 if len(content) >= 40 else len(content) title = content[:cut].strip() + " ..." pos = content.find(".") if pos != -1: title = content[:pos].strip() return 'title', title
def multiples(x, n): """x is the number in question, n is a power of 2""" multiple = 2 if n >= x: return n else: while n * multiple < x: if n * multiple > x: print(n * multiple) return else: multiple += 1 print(n * multiple)
def sum_str(a, b): """Add two strings of ints and return string.""" if a == '' or a == ' ': a = 0 if b == '' or b == ' ': b = 0 return str(int(a) + int(b))
def format_response_not_found_error(command_text): """Format an ephemeral error when no Quip is found.""" response = { "response_type": "ephemeral", "text": f"No quip found for `{command_text}`.", } return response
def parts_to_decimal(major, minor): """ Convert an ICD9 code from major/minor parts to decimal format. """ if major[0] in ("V", "E"): major = major[0] + major[1:].lstrip("0") if len(major) == 1: major = major + "0" else: major = major.lstrip("0") if len(major) == 0: major = "0" return major + "." + minor
def merge_dict(base, to_merge, merge_extend=False) -> dict: """Deep merge two dictionaries""" if not isinstance(to_merge, dict): raise Exception(f"Cannot merge {type(to_merge)} into {type(base)}") for key, value in to_merge.items(): if key not in base: base[key] = value elif isinstance(value, dict): base[key] = merge_dict(base.get(key, {}), value, merge_extend) elif merge_extend and isinstance(value, (list, tuple, set)): if isinstance(base.get(key), tuple): base[key] += tuple(value) elif isinstance(base.get(key), list): base[key].extend(list(value)) elif isinstance(base.get(key), set): base[key].update(set(value)) else: base[key] = to_merge[key] return base
def get_prices_of_products_in_discounted_collections(order, discounted_collections): """Get prices of variants belonging to the discounted collections.""" line_prices = [] if discounted_collections: for line in order: if not line.variant: continue product_collections = line.variant.product.collections.all() if set(product_collections).intersection(discounted_collections): line_prices.extend([line.unit_price_gross] * line.quantity) return line_prices
def kdelta(i, j): """ Kronecker delta function """ assert i in (0,1) assert j in (0,1) return i*j
def get_highest_knowledge(knowledge): """ We assume that the N has the highest knowledge of N. """ k = {} for key in knowledge.keys(): k[key] = knowledge[key][key] return k
def _convert_from_degrees(value): """ Helper function to convert float format GPS to format used in EXIF. :param value: :return: """ degrees = int(value) temp = value - degrees temp = temp * 3600 minutes = int(temp / 60) seconds = temp - minutes * 60 return degrees, minutes, seconds
def is_fast_round(rnd: int, r_fast: int, r_slow: int) -> bool: """Determine if the round is fast or slow. :meta private: """ remainder = rnd % (r_fast + r_slow) return remainder - r_fast < 0
def parse_military_friendly(parts): """ Parse whether or not the ad indicates "military friendly". parts -> The backpage ad's posting_body, separated into substrings """ for part in parts: if 'military' in part: return 1 return 0
def print_nicely(counts): """ This function iterates through a count dictionary and prints the values in a user-friendly way :param counts: Dict, :return: None """ print("pdb id\tarticles\treviews") for entry_id in counts.keys(): print("%s\t%i\t%i" % (entry_id, counts[entry_id]["articles"], counts[entry_id]["reviews"])) return None
def starify_rating(rating): """Creates a number of full and half stars according to the given rating.""" rate = 0 try: rate = float(rating.split('/')[0]) except ValueError: print('Could not parse recipe rating: ', rating) full = ''.join('\uf005' * int(rate)) half = '\uf089' if rate != int(rate) else '' return '<font face="FontAwesome">{}{}</font>'.format(full, half)
def compute_image_shape(width: int, height: int, fmt: str) -> tuple: """Compute numpy array shape for a given image. The output image shape is 2-dim for grayscale, and 3-dim for color images: * ``shape = (height, width)`` for FITS images with one grayscale channel * ``shape = (height, width, 3)`` for JPG images with three RGB channels * ``shape = (height, width, 4)`` for PNG images with four RGBA channels Parameters ---------- width, height : int Width and height of the image fmt : {'fits', 'jpg', 'png'} Image format Returns ------- shape : tuple Numpy array shape """ if fmt == 'fits': return height, width elif fmt == 'jpg': return height, width, 3 elif fmt == 'png': return height, width, 4 else: raise ValueError(f'Invalid format: {fmt}')
def rounddown(num, multiple): """Rounds a number to the nearest lower multiple. Returns an int.""" return int(num / multiple) * multiple
def get_address(iface): """ Returns an IP address from an iface dict, preferring node_addr """ if iface["iface_addr"] is None: return iface["node_addr"] else: return iface["iface_addr"]
def title_case(sentence): """ Convert a string to title case. Parameters ---------- sentence: string String to be converted to title case Returns ---------- ret : string String converted to title case. Example ---------- >>> title_case('ThIS iS a StrInG to BE ConVerTed.') 'This Is A String To Be Converted.' """ # Check that input is string if not isinstance(sentence, str): raise TypeError('Invalid input %s - Input must be type string' %(sentence)) # Handle empty string if len(sentence) == 0: raise ValueError('Cannot apply title function to empty string.') ret = sentence[0].upper() for i in range(1, len(sentence)): if sentence[i - 1] == ' ': ret += sentence[i].upper() else: ret += sentence[i].lower() return ret