content
stringlengths
42
6.51k
def check_if_ssl(condition): """Check if a condition(policy) have SSL only enabled.""" if "Bool" in condition: if "aws:SecureTransport" in condition["Bool"]: if condition["Bool"]["aws:SecureTransport"] == "false": return(True) else: return(False) else: return(False) else: return(False)
def round_robin(teams, rounds=None): """ Based on recipe found at http://code.activestate.com/recipes/65200/ """ # ensure we have a list so we can perform appends and inserts if not isinstance(teams, list): teams = [t for t in teams] # ensure we have an even number of teams if len(teams) % 2: teams.append(0) count = len(teams) half = int(count / 2) # if the rounds is not set, we will produce one complete round if rounds is None: rounds = count - 1 schedule = [] for turn in range(rounds): pairings = [] for i in range(half): pairings.append((teams[i], teams[count - i - 1])) teams.insert(1, teams.pop()) schedule.append(pairings) return schedule
def getBlockBandwidth(m, nintj, nblok): """ Return block bandwidth JL, JU from CCCC interface files. It is common for CCCC files to block data in various records with a description along the lines of:: WITH M AS THE BLOCK INDEX, JL=(M-1)*((NINTJ-1)/NBLOK +1)+1 AND JU=MIN0(NINTJ,JUP) WHERE JUP=M*((NINTJ-1)/NBLOK +1) This function computes JL and JU for these purposes. It also converts JL and JU to zero based indices rather than 1 based ones, as is almost always wanted when dealing with python/numpy matrices. The term *bandwidth* refers to a kind of sparse matrix representation. Some rows only have columns JL to JH in them rather than 0 to JMAX. The non-zero band from JL to JH is what we're talking about here. """ x = (nintj - 1) // nblok + 1 jLow = (m - 1) * x + 1 jHigh = min(nintj, m * x) return jLow - 1, jHigh - 1
def timer(start, end): """ Computes and returns the elapsed time. :param start: time.time - Start time :param end: time.time - End time :return: str - Elapsed time as string with hours, minutes, seconds format """ hours, rem = divmod(end-start, 3600) minutes, seconds = divmod(rem, 60) return "{:02}:{:02}:{:05.2f}".format(int(hours), int(minutes), seconds)
def errors(usr_input): """functions check's user input for errors such as double operators(excluding + and -)""" for i, ch in enumerate(usr_input): if ch == "*" and usr_input[i + 1] == "*": return True elif ch == "/" and usr_input[i + 1] == "/": return True if "(" in usr_input and ")" in usr_input: if usr_input.index(")") < usr_input.index("("): return True if usr_input.count("(") != usr_input.count(")"): return True return False
def get_revisioned_template_name(template_name, revision): """Construct name of a template to include it's revision number.""" return f"{template_name}_rev{revision}"
def chop(s, n=1, d=None): """Chops initial words from a string and returns a list of them and the rest of the string. The returned list is guaranteed to be n+1 long. If too little words are found in the string, a ValueError exception is raised. :Parameters: s : str or unicode String to chop from. n : int Number of words to chop. d : str or unicode Optional delimiter. Any white-char by default. :return: A list of n first words from the string followed by the rest of the string (``[w1, w2, ..., wn, rest_of_string]``). :rtype: list of: str or unicode """ spl = s.split(d, n) if len(spl) == n: spl.append(s[:0]) if len(spl) != n + 1: raise ValueError('chop: Could not chop %d words from \'%s\'' % (n, s)) return spl
def arrayMultiplyByScalar(inputArray, scalar): """Multiplies each value in an input array by a scalar. inputArray -- a list-formatted array or matrix. For the purposes of recursion, inputArray is allowed to also be a scalar. scalar -- the value by which to multiply each value of the array. """ if isinstance(inputArray, list): return [arrayMultiplyByScalar(arrayItem, scalar) for arrayItem in inputArray] else: return inputArray*scalar
def closest_fraction(x, N): """Compute (a, b) such that a/b is closest to x from below, and with 0 <= a, b < N""" best_num = 0 best_den = 1 best_approx = 0.0 assert(x >= 0) for den in range(1, N): num = round(den * x) approx = num / den if x - approx >= 0 and x - approx < x - best_approx: best_num = num best_den = den best_approx = approx # If we are very close, no need to search for more. if x - approx < 1e-5: break return (best_num, best_den)
def _column_exists_in_prior_row( output_rows: list, row_index: int, col_index: int ) -> bool: """ Determine if a column exists in the prior row. Keyword arguments: row_index -- the index of the row col_index -- the index of the column output_rows -- the output rows Returns: True if the column exists, False otherwise """ return row_index > 0 and col_index < len(output_rows[row_index - 1])
def is_begin_layer_line(line: str) -> bool: """Check if current line is the start of a layer section. Args: line (str): Gcode line Returns: bool: True if the line is the start of a layer section """ return line.startswith(";LAYER:")
def generalizedCoordDir(iFace): """Not really sure how this works...""" if iFace in [0, 1]: return [0, 1, 2] elif iFace in [2, 3]: return [1, 2, 0] elif iFace in [4, 5]: return [0, 2, 1]
def check_max_one_training_agent(configuration): """ Checks if there is at most one agent set to be trained :param configuration: the object group to look at :return: if there is less than 2 defined agents with the "train_mode" argument """ training_agent_count = 0 for agent in configuration["agents"]: if "train_mode" in agent["arguments"] and agent["arguments"]["train_mode"] == "True": training_agent_count += 1 return training_agent_count < 2
def cpp_define(macro, params, val): """CPP macro definition, optionally with parameters.""" return "#define {macro}{params} {val}".format( macro = macro, params = "({})".format(",".join(params)) if params else "", val = val, )
def selection_sort(unsorted_list): """ Function sorting input list with selection sort algorithm :param unsorted_list: input list with unsorted elements :return: copy of input list with sorted elements """ sorted_list = unsorted_list.copy() for i in range(len(sorted_list)): min_elem = sorted_list[i] min_index = i for j in range(i, len(sorted_list), 1): if sorted_list[j] < min_elem: min_elem = sorted_list[j] min_index = j sorted_list[i], sorted_list[min_index] = sorted_list[min_index], sorted_list[i] return sorted_list
def KWW_modulus(x, logomega0, b, height): """1-d KWW: KWW(x, logomega0, b, height)""" return height / ((1 - b) + (b / (1 + b)) * (b * (10**logomega0 / x) + (x / 10**logomega0)**b))
def e_cm_mw(mx, vrel=1e-3): """Computes DM COM energy, assuming its velocity is much less than c. """ return 2 * mx * (1 + 0.5 * vrel ** 2)
def function_with_exception(val): """Return a `val` if it is non-negative""" if val < 0: raise ValueError("val cannot be negative.") return val
def gst_value_from_inclusive(amount, gst_rate): """Calculate GST component from a GST inclusive total. GST amount calculated as amount - (1 + gst_rate)). Args: amount (float): GST inclusive amount gst_rate (float): GST rate to apply. Returns: gst_component (float): Calculated GST component. """ return amount - (amount / (1 + gst_rate))
def call_if_attribute(obj, attr, *args, **kwargs): """ Call object method, if it exists. Arguments: obj (object): The object. attr (str): The name of the object method. *args (optional): Arguments for method. **kwargs (optional): Keyword arguments for method. Returns: Return value of calling method, or None if object does not have method. """ op = getattr(obj, attr, None) if callable(op): return op(*args, **kwargs)
def invert_dict(dct: dict) -> dict: """ Invert dictionary, i.e. reverse keys and values. Args: dct: Dictionary Returns: Dictionary with reversed keys and values. Raises: :class:`ValueError` if values are not unique. """ if not len(set(dct.values())) == len(dct.values()): print(dct) print(sorted(list(dct.values()))) raise ValueError("Dictionary does not seem to be invertible.") return {value: key for key, value in dct.items()}
def unpack_traces(traces): """Returns states, actions, rewards, end_states, and a mask for episode boundaries given traces.""" states = [t[0].state for t in traces] actions = [t[0].action for t in traces] rewards = [[e.reward for e in t] for t in traces] end_states = [t[-1].next_state for t in traces] not_done_mask = [[1 if n.next_state is not None else 0 for n in t] for t in traces] return states, actions, rewards, end_states, not_done_mask
def is_parent_of(page1, page2): """ Determines whether a given page is the parent of another page Example:: {% if page|is_parent_of:feincms_page %} ... {% endif %} """ try: return page1.is_ancestor_of(page2) except (AttributeError, ValueError): return False
def mapify_iterable(iter_of_dict, field_name): """Convert an iterable of dicts into a big dict indexed by chosen field I can't think of a better name. 'Tis catchy. """ acc = dict() for item in iter_of_dict: acc[item[field_name]] = item return acc
def prime_factors(n): """Returns a list of prime factors of n Args: n (int): The number whose prime factors will be returned Returns: prime_factors (list): List of prime factors of n """ i = 2 prime_factors = [] while i * i <= n: if n % i: i += 1 else: n //= i prime_factors.append(i) if n > 1: prime_factors.append(n) return prime_factors
def map_val(val, in_min, in_max, out_min, out_max): """ Function based on the map function for the arduino https://www.arduino.cc/reference/en/language/functions/math/map/ """ return (val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def rhombus_area(diagonal_1, diagonal_2): """Returns the area of a rhombus""" return (diagonal_1*diagonal_2)/2
def average(values): """ Get average of a list of values. """ return sum(values, 0.0) / len(values) if values else None
def calculateAverageNps(totalNpsCount, promoterCount, detractorCount): """ Return: {int .4} the actual NPS based on promoter and detractor counts. """ try: promoterPercent = (promoterCount / totalNpsCount) * 100 detractorPercent = (detractorCount / totalNpsCount) * 100 return round(promoterPercent - detractorPercent, 4) except: return None
def pop_optional_words(word_list, opt_words): """Pops off the given words in the order specified, skipping those that aren't present. Arg word_list is a list of words being parsed. Arg opt_words is a space-separated string of words to consider. """ popped = [] for word in opt_words.split(): if word_list and word_list[0] == word: popped.append(word_list.pop(0)) return " ".join(popped)
def rotate(l, n): """ Rotate (shift) the list, moving values n places to the left/right """ return l[n:] + l[:n]
def mergeTwoListsIntoOne(list1, list2): """ Function that takes two lists and assembles them into one list such that each entry of the final list is a list containing the two corresponding entries of the two input lists """ if len(list1) != len(list2): raise ValueError("Input lists not of same length") output_list = [[list1[i], list2[i]] for i in range(len(list1))] return output_list
def geom_converter(term): """A converter for normalizing the geometry type.""" if 'point' in term.lower(): return 'Point' elif 'string' in term.lower(): return 'Line' elif any(v_type in term.lower() for v_type in ['polygon', 'chain']): return 'Polygon' elif 'composite' in term.lower(): return 'Mixed' elif 'raster' in term.lower(): return 'Image' return term
def merge_styles(original, update): """\ Return style attributes as per ORIGINAL, in which attributes have been overridden by non-zero corresponding style attributes from UPDATE. """ style = [original / 100, original / 10 % 10, original % 10] merge = update / 100, update / 10 % 10, update % 10 for counter in range(3): if merge[counter]: style[counter] = merge[counter] return 100*style[0] + 10*style[1] + style[2]
def remove_suffix_ness(word): """ Remove a suffix from a word :param word: str of word to remove suffix from. :return: str of word with suffix removed & spelling adjusted. This function takes in a word and returns the base word with `ness` removed. """ result = word if word.endswith('ness'): if word[-5] in ['a', 'e', 'i', 'o', 'u']: result = word[0:-5] + 'y' else: result = word[0:-4] return result
def split_fieldname(s): """Split csv column name to name and unit""" if '[' not in s: return s, None name, unit = s.split('[') name = name.strip() unit = unit.split(']')[0] return name, unit
def is_overlapping(segment_time, previous_segments): """Check for time overlap Checks if the time of a segment overlaps with the times of existing segments. Args: segment_time (tuple): a tuple of (segment_start, segment_end) for the new segment previous_segments (tuple): a list of tuples of (segment_start, segment_end) for the existing segments Returns: overlap (bool): True if the time segment overlaps with any of the existing segments, False otherwise """ segment_start, segment_end = segment_time overlap = False for previous_start, previous_end in previous_segments: if segment_start <= previous_end and segment_end >= previous_start: overlap = True return overlap
def _sh_cmd(system, *args): """ Helper function to build a local shell command """ if len(args) == 0: return None return args
def ts_to_sec(ts): """ Splits a timestamp of the form HH:MM:SS.MIL :param ts: timestamp of the form HH:MM:SS.MIL :return: seconds """ rest, ms = ts.split('.') hh, mm, ss = rest.split(':') return int(hh) * 3600 + int(mm) * 60 + int(ss) + float('.{}'.format(ms))
def g(x): """ :param x: any number :return: function h """ x = x + 1 def h(y): """ :param y: Any number :return: Sum of two numbers """ return x + y return h(6)
def is_self_describe(line): """Check if number is self describing, return 1 if so, 0 if not.""" num_str = line.rstrip() if len(num_str) <= 10: numlist = list(num_str) for x in range(len(numlist)): # pylint: disable=invalid-name if int(numlist[x]) == numlist.count(str(x)): continue else: return 0 return 1 return 0
def is_iterable(obj): """ Are we being asked to look up a list of things, instead of a single thing? We check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays. Strings, however, should be considered as atomic values to look up, not iterables. We don't need to check for the Python 2 `unicode` type, because it doesn't have an `__iter__` attribute anyway. """ return hasattr(obj, "__iter__") and not isinstance(obj, str)
def _make_stat_length(shape): """converts the stat_length values.""" return tuple((shape[i], shape[i]) for i, _ in enumerate(shape))
def verify_rename_files(file_name_map): """ Each file name as key should have a non None value as its value otherwise the file did not get renamed to something new and the rename file process was not complete """ verified = True renamed_list = [] not_renamed_list = [] for k, v in file_name_map.items(): if v is None: verified = False not_renamed_list.append(k) else: renamed_list.append(k) return (verified, renamed_list, not_renamed_list)
def rotate(lines): """ Rotate the lines 90 degrees anticlockwise. Args: lines (list[str]) Returns: list[str]: The rotated lines. """ final_lines = [] for i in range(len(lines)): new_line = "".join(line[i] for line in lines) # Rotate the lines 90 degrees clockwise final_lines.append(new_line) return tuple(reversed(final_lines))
def _calculate_cut(lemmawords, stems): """Count understemmed and overstemmed pairs for (lemma, stem) pair with common words. :param lemmawords: Set or list of words corresponding to certain lemma. :param stems: A dictionary where keys are stems and values are sets or lists of words corresponding to that stem. :type lemmawords: set(str) or list(str) :type stems: dict(str): set(str) :return: Amount of understemmed and overstemmed pairs contributed by words existing in both lemmawords and stems. :rtype: tuple(float, float) """ umt, wmt = 0.0, 0.0 for stem in stems: cut = set(lemmawords) & set(stems[stem]) if cut: cutcount = len(cut) stemcount = len(stems[stem]) # Unachieved merge total umt += cutcount * (len(lemmawords) - cutcount) # Wrongly merged total wmt += cutcount * (stemcount - cutcount) return (umt, wmt)
def reverse(string, pos1, pos2): """ reverse positions X through Y means that the span of letters at indexes X through Y (including the letters at X and Y) should be reversed in order. """ a = list(string) b = a[pos1:pos2+1] b.reverse() return ''.join(a[:pos1] + b + a[pos2+1:])
def bold(s): """Return the string bold. Source: http://stackoverflow.com/a/16264094/2570866 :param s: :type s: str :return: :rtype: str """ return r'\textbf{' + s + '}'
def replace_punctuation(html_str: str): """ replace punctuation with html entities """ # special chars html_str = html_str.replace('.', '&#46;') html_str = html_str.replace(',', '&#44;') html_str = html_str.replace('!', '&#33;') html_str = html_str.replace('?', '&#63;') html_str = html_str.replace('(', '&#40;') html_str = html_str.replace(')', '&#41;') html_str = html_str.replace('[', '&#91;') html_str = html_str.replace(']', '&#93;') html_str = html_str.replace('{', '&#123;') html_str = html_str.replace('}', '&#125;') html_str = html_str.replace('<', '&lt;') html_str = html_str.replace('>', '&gt;') html_str = html_str.replace('"', '&quot;') html_str = html_str.replace("'", '&#39;') return html_str
def convert_training_shape(args_training_shape): """Convert training shape""" training_shape = [int(args_training_shape), int(args_training_shape)] return training_shape
def utf8(text): """return unicode text as a utf-8 encoded byte string.""" return text.encode("utf8")
def fn_Time_Duration(hrs_utc,mins_utc,secs_utc,duration_h,duration_m,duration_s): """ Find the time after a certain period. Date: 29 September 2016 originally in AstroFunctions.py """ s_UTC = secs_utc + duration_s; s_min = int(s_UTC/60.0); s_UTC = s_UTC - 60.0*s_min; m_UTC = mins_utc + duration_m + s_min; min_hrs = int(m_UTC/60.0); m_UTC = m_UTC - 60.0*min_hrs; h_UTC = hrs_utc + duration_h + min_hrs; return h_UTC,m_UTC,s_UTC
def shouldAvoidFileExtension(file, extensionsToAvoid): """ Given a file name and its path (file, of type string) and a set of file extensions types to avoid (extensionsToAvoid, of type set of strings), return a boolean value describing whether the file is of that extension. """ extension = file.split('.')[-1] if extension in extensionsToAvoid: return True return False
def any_true_p (seq, pred) : """Returns first element of `seq` for which `pred` returns True, otherwise returns False. """ for e in seq : if pred (e) : return e else : return False
def list_math_subtraction(a, b): """! @brief Calculates subtraction of two lists. @details Each element from list 'a' is subtracted by element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematical subtraction. @param[in] b (list): List of elements that supports mathematical subtraction. @return (list) Results of subtraction of two lists. """ return [a[i] - b[i] for i in range(len(a))]
def complement(base, material="DNA"): """returns the complement of a basepair""" if base in 'Aa': if material == "DNA": return "T" elif material =="RNA": return "U" else: raise RuntimeError("invaild materia") elif base in 'TtUu': return 'A' elif base in 'Gg': return 'C' else: return 'G'
def l7rule_to_humanrule(l7rules): """ reserial l7 rules to human rule :param l7rules: :return:[{"domain_name":"test.com","compare_type":"test"}, {"url":"test", "compare_type":"start_with"}] """ type_mapping = {"HOST_NAME": "domain_name", "PATH": "url", "COOKIE": "cookie"} rules = [] for l7rule in l7rules: rule = {} rule[type_mapping.get(l7rule.type, l7rule.type)] = l7rule.rule_value rule['compare_type'] = l7rule.compare_type rules.append(rule) return rules
def date_handler(obj): """Serialize dates.""" return obj.isoformat() if hasattr(obj, "isoformat") else object
def locate_element_scalar(x, elements, nodes): """Return number of element containing point x. Scalar version.""" for e, local_nodes in enumerate(elements): if nodes[local_nodes[0]] <= x <= nodes[local_nodes[-1]]: return e
def get_multiprocessing(parallel): """ If parallel indicates that we want to do multiprocessing, imports the multiprocessing module and sets the parallel value accordingly. """ if parallel != 1: import multiprocessing if parallel <= 0: parallel = multiprocessing.cpu_count() return parallel, multiprocessing return parallel, None
def sql_simple(index, key, prefix): """ return : string """ res = "" if key in index: if index[key] is not None: res = "%s %s" % (prefix, index[key]) return res
def should_we_end_early(logger): """Test if we should terminate early. If we see average Q-values exceeding some range, say outside (-10K, 10K), that means performance has collapsed, so we should exit training to avoid wasting compute. In healty online training of TD3, we should see average Q-values within (0, 1000). """ terminate = False # NOTE(daniel) On this branch (large-scale-runs), we're disabling this. #Q1Vals_avg, Q1Vals_std = logger.get_stats('Q1Vals') #terminate = (Q1Vals_avg < -5000) or (Q1Vals_avg > 10000) return terminate
def solution(s1, s2, s3): """Test case provided by Code Wars for the test_random_grades fcn.""" s = (s1 + s2 + s3) / 3 if s >= 90: return "A" if s >= 80: return "B" if s >= 70: return "C" if s >= 60: return "D" return "F"
def unbytify(b=bytearray([]), reverse=False): """ Returns unsigned integer equivalent of bytearray b b may be any iterable of ints including bytes or list of ints. Big endian is the default. If reverse is true then it reverses the order of the bytes in the byte array before conversion for little endian. """ b = bytearray(b) if not reverse: # process MSB first on the right b.reverse() n = 0 while b: n <<= 8 n += b.pop() return n
def plugin_filter(_dir): """Filter plugins.""" return _dir in ['scounter', 'stdout']
def remove_by_min_overlapping_users(keen_keen_graph, min_overlapping_user): """It only keeps the edges whose weight >= min_overlapping_user""" filtered = {} for ka, ints in keen_keen_graph.items(): new_ints = {kb: n_users for kb, n_users in ints.items() if n_users >= min_overlapping_user} if new_ints: filtered[ka] = new_ints return filtered
def short(text, count_stripped=False): """ >>> short('Something wrong with compatibility regressions.'.split()) u'Som-ng wrong with com-ty reg-s.' >>> short('Something wrong with compatibility regressions.'.split(), True) u'Som4ng wrong with com8ty reg7s.' """ def sh(word): l = len(word) if l > 7: if count_stripped: return "{}{}{}".format(word[:3], l - 5, word[-2:]) else: return "{}-{}".format(word[:3], word[-2:]) else: return word return " ".join(map(sh, text))
def fibonacci(n): """fibonacci function Args: n - The final amount of fibonacci numbers calculated. Returns: returns a array called "result" which holds the fibonacci sequence to the nth term. Raises: Custom exception "Exception" Is thrown when the user inputs an integer < 1. Instructs user to enter another integer greater than 0. typer error: If user does not input an integer, this error is thrown. """ if n < 1: raise Exception("Error. Enter a proper int greater than 0") result = [] a = 0 b = 1 c = 1 for i in range(n): c = a+b result.append(c) b = a a = c return result
def word_flipper(our_string): """ Flip the individual words in a sentence Args: our_string(string): Strings to have individual words flip Returns: string: String with words flipped """ word_list = our_string.split(" ") for idx in range(len(word_list)): word_list[idx] = word_list[idx][::-1] # [index1:index2:step] return " ".join(word_list)
def first_order_diff(X): """ Compute the first order difference of a time series. For a time series X = [x(1), x(2), ... , x(N)], its first order difference is: Y = [x(2) - x(1) , x(3) - x(2), ..., x(N) - x(N-1)] """ D=[] for i in range(1,len(X)): D.append(X[i]-X[i-1]) return D
def map_to_layers(edges, layers): """Map graph to respective layers removing excess edges""" result = set() for (u, v) in edges: e = (layers[u], layers[v]) result |= {e} return result
def uri_to_id(uri): """ Utility function to convert entity URIs into numeric identifiers. """ _, _, identity = uri.rpartition("/") return int(identity)
def wavelength2index(wl, step, min_wl): """Return the index of the given wavelength.""" return int((wl - min_wl) / step)
def is_string_list(lst): """Return true if 'lst' is a list of strings, and false otherwise.""" return isinstance(lst, list) and all(isinstance(x, str) for x in lst)
def checksum(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'): """Calculate the checksum. A valid number should have a checksum of 1.""" modulus = len(alphabet) check = modulus // 2 for n in number: check = (((check or modulus) * 2) % (modulus + 1) + alphabet.index(n)) % modulus return check
def lists_are_same(list1, list2): """return 1 if the lists have identical values, else 0""" if not list1 and not list2: return 1 if not list1: return 0 if not list2: return 0 if len(list1) != len(list2): return 0 for ind in range(len(list1)): if list1[ind] != list2[ind]: return 0 return 1
def parseEPSGCode(string, parsers): """ parse EPSG code using provided sequence of EPSG parsers """ for parser in parsers: epsg = parser(string) if epsg is not None: return epsg return None
def count_possible_words(current_characters, current_count): """ Given a set of characters and a count of terminating words find the number of terminating words """ if not current_characters: return current_count non_terminating_nodes = set() for charnode in current_characters: if charnode.letter == '$': current_count += 1 else: for child in charnode.children: non_terminating_nodes.add(child) return count_possible_words(non_terminating_nodes, current_count)
def indented (text, level, indent=2): """Take a multiline text and indent it as a block""" return "\n".join ("%s%s" % (level * indent * " ", s) for s in text.splitlines ())
def beta(alpha, beta): """Return the determinant of the jacobian for the beta function. """ return -1.0*alpha*beta/((beta+alpha)**3*(beta+alpha+1)**2)
def ntToPosixSlashes(filepath): """ Replaces all occurrences of NT slashes (\) in provided filepath with Posix ones (/) >>> ntToPosixSlashes('C:\\Windows') 'C:/Windows' """ return filepath.replace('\\', '/') if filepath else filepath
def autocorrect(user_word, valid_words, diff_function, limit): """Returns the element of VALID_WORDS that has the smallest difference from USER_WORD. Instead returns USER_WORD if that difference is greater than LIMIT. """ # BEGIN PROBLEM 5 "*** YOUR CODE HERE ***" if user_word in valid_words: return user_word else: diff = [diff_function(user_word,valid_word,limit) for valid_word in valid_words] if min(diff) > limit: return user_word else: return valid_words[diff.index(min(diff))] # END PROBLEM 5
def get_output_config_by_name(model_config, name): """Get output properties corresponding to the output with given `name` Parameters ---------- model_config : dict dictionary object containing the model configuration name : str name of the output object Returns ------- dict A dictionary containing all the properties for a given output name, or None if no output with this name exists """ if 'output' in model_config: outputs = model_config['output'] for output_properties in outputs: if output_properties['name'] == name: return output_properties return None
def get_unique_value(value, existing_values): """Create new value if the current value exist.""" index = 1 new_value = value while new_value in existing_values: new_value = '{}-{}'.format(value, index) index += 1 return new_value
def get_rs_id_by_name(name, response_sets): """ Return the response_set that matches the passed name :param name: Name of response_set to return :param response_sets: List of response_sets to check :return: Response_set with the passed name """ for rs in response_sets: if rs['name'] == name: return rs
def calc_check_digit(number): """Calculate the check digits for the number.""" # we use the full alphabet for the check digit calculation alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' # convert to numeric first, then double some, then sum individual digits number = ''.join( str(alphabet.index(n) * (1, 2)[i % 2]) for i, n in enumerate(number[:11])) return str((10 - sum(int(n) for n in number)) % 10)
def _corput(index, base): """Generate the nth Van der Corput number.""" x = 0 norm = 1.0/base while index > 0: x += (index % base)*norm index //= base norm /= base return x
def existing_gene(store, panel_obj, hgnc_id): """Check if gene is already added to a panel.""" existing_genes = {gene['hgnc_id']: gene for gene in panel_obj['genes']} return existing_genes.get(hgnc_id)
def pkgconfig_script(ext_build_dirs): """Create a script fragment to configure pkg-config Args: ext_build_dirs (list): A list of directories (str) Returns: list: Lines of bash that perform the update of `pkg-config` """ script = [] if ext_build_dirs: for ext_dir in ext_build_dirs: script.append("##increment_pkg_config_path## $$EXT_BUILD_DEPS$$/" + ext_dir.basename) script.append("echo \"PKG_CONFIG_PATH=$${PKG_CONFIG_PATH:-}$$\"") script.extend([ "##define_absolute_paths## $$EXT_BUILD_DEPS$$ $$EXT_BUILD_DEPS$$", "##define_sandbox_paths## $$EXT_BUILD_DEPS$$ $$EXT_BUILD_ROOT$$", ]) return script
def camera_private(as_dict: bool = False): """Returns a list or dict of private camera datasets.""" data = [] return {} if as_dict else data
def append_to_csv(csv, new): """Add a new value to a string formatted, comma separted value list.""" if csv == '': return new arr = csv.split(',') arr.append(new) return ','.join(arr)
def _Contains(i, j, areas, lens, cls): """Return True if path i contains majority of vertices of path j. Args: i: index of supposed containing path j: index of supposed contained path areas: list of floats - areas of all the paths lens: list of ints - lenths of each of the paths cls: dict - maps pairs to result of _ClassifyPathPairs Returns: bool - True if path i contains at least 55% of j's vertices """ if i == j: return False (jinsidei, joni) = cls[(i, j)] if jinsidei == 0 or joni == lens[j] or \ float(jinsidei) / float(lens[j]) < 0.55: return False else: (insidej, _) = cls[(j, i)] if float(insidej) / float(lens[i]) > 0.55: return areas[i] > areas[j] # tie breaker else: return True
def clamp(value: int, min_value: int, max_value: int): """ :param value: value to clap between min_value and max_value :param min_value: lower limit used to clamp value :param max_value: upper limit used to clamp value :return: """ return max(min(value, max_value), min_value)
def human_to_real(iops): """Given a human-readable IOPs string (e.g. 2K, 30M), return the real number. Will return 0 if the argument has unexpected form. """ digit = iops[:-1] unit = iops[-1] if digit.isdigit(): digit = int(digit) if unit == 'M': digit *= 1000000 elif unit == 'K': digit *= 1000 else: digit = 0 else: digit = 0 return digit
def toPow2Ceil(x: int): """ Get the smallest 2**N where 2**N >= x """ i = 0 while 2 ** i < x: i += 1 return 2 ** i
def has_field(val, name): """Check whether @p val (gdb.Value) has a field named @p name""" try: val[name] return True except Exception: return False
def check_flower_label(value, spec, **_): """ Checks if incoming label value is the one assigned to flower service and deployment """ return value == f"{spec['common']['appName']}-flower"
def address_from_host_and_port( host: str, port: int, bound: bool = False ) -> str: """Return a TCP address for a given host and port. If the address is meant to be bound, it will be bound to all available TCP interfaces (*).""" if bound: address = "tcp://*:{}".format(port) else: address = "tcp://{}:{}".format(host, port) return address
def xor(block_a: "str | bytes", block_b: "str | bytes"): """ Computes the XOR of two bytes objects. Args: block_a (str | bytes): The first block of bytes block_b (str | bytes): The second block of bytes Returns: bytes: The result of block_a ^ block_b """ if isinstance(block_a, str): block_a = block_a.encode() if isinstance(block_b, str): block_b = block_b.encode() result = bytearray(block_a) for index, byte in enumerate(block_b): result[index] ^= byte return bytes(result)
def factI(n): """ Assumes that n is an int > 0 Returns n!""" result = 1 while n > 1: result = result * n n -= 1 return result