content
stringlengths
42
6.51k
def convert_path(path): """ Convert jsonpath format so it's compatible with jsonpatch Parameters ---------- path : str jsonpath format Returns ------- Path in format compatible with jsonpatch Example: input = 'TraderPeriod.[0].TradeCollection.Trade.[0].@BandAvail1'...
def temp_coeff_hot(lower, upper): """ Calculates and returns the m and b coefficients for y = m*x + b for a line intersecting (lower, 255) and (upper, 0). """ m = -255/(upper-lower) b = 255 - m * lower return m, b
def _inv(a, prime): """ Compute multiplicative inverse modulo a prime. """ return pow(a, prime - 2, prime)
def get_added_asg_instances(old_instances, new_instances): """ diff two lists of asg instance dicts @param old_instances: list of asg instance dictionaries @param new_instances: list of asg instance dictionaries @return: list of new instances (ec2 ids) in the asg """ old_ids = [i['InstanceId...
def line_from_kwargs(view, kwargs): """Parse kwargs for line or point key and return line number.""" line = kwargs.get('line') if line is None: point = kwargs.get('point') if point is None: selection = view.sel() if not selection: return po...
def is_nonterminal(symbol): """nonterminals are formatted as this: [X]""" return symbol[0] == '[' and symbol[-1] == ']'
def ndependents(dependencies, dependents): """ Number of total data elements that depend on key For each key we return the number of data that can only be run after this key is run. The root nodes have value 1 while deep child nodes will have larger values. Examples -------- >>> dsk = {'a...
def is_iterable(obj): """Returns whether a Python object is iterable.""" typ = type(obj) if hasattr(typ, "__iter__"): return True return hasattr(typ, "__getitem__") and hasattr(typ, "__len__")
def format_role_order(roles): """Given roles, returns them in the format: role_arn,principal_arn. The format of the attribute value should be role_arn,principal_arn but lots of blogs list it as principal_arn,role_arn so let's reverse them if needed. Args: roles: List of roles. Returns...
def improve(update, close, guess=1, max_updates=100): """Iteratively improve guess with update until close(guess) is true or max_updates have been applied.""" k = 0 while not close(guess) and k < max_updates: guess = update(guess) k = k + 1 return guess
def rescale(in_min, in_max, out_min, out_max, value): """Rescales value from the specified range to the specified other range. Arguments: in_min: min bound of the range of value. in_max: max bound of the range of value. out_min: min bound of the range of the output. out_max: max...
def split_part_numbers(row): """Split part number string into main and alternates.""" part_no = '' part_no_alt = '' if row['manuf part'] != '': tmp = row['manuf part'].split(None, 1) part_no = tmp[0] if len(tmp) > 1: part_no_alt = tmp[1] row['manuf part'] = ...
def num(s): # Necessary to convert longitude and latitude from a string to a number. """ Convert string into a number (float or integer) :param s: string containing only digits :return: float or integer """ try: return int(s) except ValueError: return float(s)
def sum_naturals(n): """Sum the first N natural numbers. >>> sum_naturals(5) 15 """ total, k = 0, 1 while k <= n: total, k = total + k, k + 1 return total
def dict_scale(d, scl): """scales all values in dict and returns a new dict""" return dict([(k, v * scl) for k, v in d.items()])
def try_(func, default=None): """Try return the result of func, else return default.""" try: return func() except Exception: return default
def has_langname(words, langs): """ :type line: FrekiLine """ for word in words: if word in langs: return True return False
def strToBool(value): """ Convert a string representation of a boolean value to a :class:`bool`. Args: value (str): string to convert Returns: :class:`bool` """ true = ['true', 't', 'yes', '1', 'on'] false = ['false', 'f', 'no', '0', 'off'] value = value.lower() i...
def is_mapping_table(table_id): """ Return True if specified table is a mapping table :param table_id: identifies the table :return: True if specified table is an mapping table, False otherwise """ return table_id.startswith('_mapping_')
def find_nearest_index(vertices, x_from, y_from, vertice_count): """ Find the index of the vertex that is the closest to specified coordinate (x_from, y_from). """ min_distance_squared = 1000000 nearest_index = 0 x_from *= 1000 y_from *= 1000 for index, vertice in enumerate(vert...
def listMinus(x, y, delete=False): """If delete = True, removes all things in y that are in x. e.g. x = [1,2,3,4], y = [2,4] at the end x becomes [1,3], y remains the same. If delete = False, returns what x would have been while preserving x.""" if delete == True: to_be_diminished = x ...
def is_chinese_char(cp) -> bool: """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese an...
def count_slash_while(s): """ Returns the number of times '/' appears in string s Parameter s: the string to search Precondition: s is a (possibly empty) string """ # Accumulator count = 0 # Loop variable i = 0 while i < len(s): if s[i] == '/': count...
def check_sig_name(sig_name, sigs, errors): """ Check sig name :param sig_name: name of sig in sig-info.yaml :param sigs: content of all sigs :param errors: errors count :return: errors """ if sig_name not in [x['name'] for x in sigs]: print('ERROR! sig named {} does not exist in...
def _clear_none_params(function, *args, **kwargs): """ Decorator to clear any None value query and payload params from endpoint function results. """ result = function(*args, **kwargs) if 'params' in result: result['params'] = {k: v for k, v in result['params'...
def find_param_by_keyword(keyword, params): """ Searches for a specific param by keyword. This function will try to look for the keyword as-is first, and then tries to find the uppercase'd version of the keyword. """ if keyword in params: return params[keyword] keyword = keyword.upp...
def calculate_bending_moments_ring(force, r, theta): """ todo extend description ref http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.912.904&rep=rep1&type=pdf :param force: point load :param r: radius :param theta: angle :return: bending moment """ from math import cos, pi ...
def get_invalid_error(name: str): """ compose the error reason string :param name: name of the invalid parameter :return: """ return " Invalid " + name
def base36encode(number: int, alphabet: str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"): """Converts an integer to a base36 string. Taken from https://stackoverflow.com/questions/1181919/python-base-36-encoding """ base36 = "" sign = "" if number < 0: sign = "-" number = -number ...
def empty_to_format(value, target_format): """Convert empty value to specified format""" if target_format == float: ret = 0.0 elif target_format == int: ret = 0 else: ret = "" return ret
def convert_tag(tag): """Convert the tag given by nltk.pos_tag to the tag used by wordnet.synsets""" tag_dict = {'N': 'n', 'J': 'a', 'R': 'r', 'V': 'v'} try: return tag_dict[tag[0]] except KeyError: return None
def get_employee_data(line): """Get employee data in pattern""" line_values = line.split('=') employee_name = line_values[0] work_days = line_values[1] return employee_name, work_days
def bool_string_interpret(val_str, default_value = None): """ Interprets """ if val_str.upper() in ('T', 'TRUE', '1', 'Y', 'YES', 'AFFIRMATIVE'): return True elif val_str.upper() in ('F', 'FALSE', '0', 'N', 'NO', 'NEGATORY'): return False elif default_value is None: raise...
def _process_nested_list_element_recursive(element, level): """ @details Assume we know that element is already a nested list. """ assert isinstance(element, list) level_sum = 0 if len(element) == 0: return 0 for x in element: if not isinstance(x, list): leve...
def _trash_ratio(text): """ Return ratio of non-common symbols. """ trash_count = 0 for char in text: if char in list(u'.\'"+-!?()[]{}*+@#$%^&_=|/\\'): trash_count += 1 return trash_count / float(len(text))
def decode(bstr): """ Decodes an ASCII encoded binary MAC address tring into a number. """ bstr = bstr.replace(b':', b'') if len(bstr) != 12: raise ValueError('not a valid MAC address: {!r}'.format(bstr)) try: return int(bstr, 16) except ValueError: raise ValueError('not a valid MAC address:...
def _filter_kwargs(names, dict_): """Filter out kwargs from a dictionary. Parameters ---------- names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] The dictionary to select from. Returns ------- kwargs : dict[str, any] ``dict_`` where the...
def ethiopian_calc(Z1, Z2): """Diese Funktion multipliziert zwei Zahlen auf Aethiopische Art""" produkt = 0 if Z1 < Z2: zahl_klein = Z1 zahl_gross = Z2 else: zahl_klein = Z2 zahl_gross = Z1 while zahl_klein >= 1: if za...
def _make_lock_uri(s3_tmp_dir, cluster_id, step_num): """Generate the URI to lock the cluster ``cluster_id``""" return s3_tmp_dir + 'locks/' + cluster_id + '/' + str(step_num)
def _hamming_distance(x, bits=32): """ Calculate the bit-wise Hamming distance of x from 0: That is, the number 1s in the integer x. """ tot = 0 while x: tot += 1 x &= x - 1 return tot
def is_list(value): """ A custom Jinja filter function which determines if input is a list""" return isinstance(value, list)
def replace_backslashed(text): """!Turns \\t to tab, \\n to end of line, \\r to carriage return, \\b to backspace and \\(octal) to other characters. @param text the text to scan""" if '0123456789'.find(text[1])>=0: return chr(int(text[1:],8)) elif text=='\\n': return "\n" elif te...
def check_dates_in_range(activity_dates, start_date=None, end_date=None): """Check that an activity's dates fall into the allowed range. Prefers the planned date over the actual date when available. If the activity dates are missing, returns True @param activity_dates: the parsed activity dates. @pa...
def straight_line_from_points(a, b): """ Generate a geojson LineString object from two geojson points. Parameters ---------- a : geojson Point A b : geojson Point B Returns ------- line : geojson A geojson LineString object. """ line = { 'ty...
def ptilde(d, dstar): """Unnormalized probability density. ptilde(d) = d^2 / (2 d / (3 dstar) + 1)^5 Arguments: d {float} -- luminosity distance dstar {float} -- peak distance Returns: float -- unnormalized probability """ return d**2 / (2*d/(3*dstar) + 1)**5
def PostCategoryListToStringList(categories): """ Converts a collection of Category objects into a JSON-compatible list of strings. Return empty list on failure. """ if not categories: return [] try: category_list = [] for category in categories: category_list...
def make_ordinal(n): """Create an ordinal from a number.""" # https://stackoverflow.com/questions/9647202 suffix = ["th", "st", "nd", "rd", "th"][min(n % 10, 4)] if 11 <= (n % 100) <= 13: suffix = "th" return str(n) + suffix
def get_layer_indices(layer_lookup, tf_layers): """Giving a lookup of model layer attribute names and tensorflow variable names, find matching parameters. Arguments: layer_lookup {dict} -- Dictionary mapping pytorch attribute names to (partial) tensorflow variable names. Expects dict of...
def strikethrough(text: str) -> str: """Formats text for discord message as strikethrough""" return f"~~{text}~~"
def formatContexts(contexts, declaration=True): """Given a list of context type names, generate a list of declarations for them as formal parameters (if 'declaration' is true), or as arguments to a function (if 'declaration' is false). """ if declaration: s = "".join(", const {0}_t *{0...
def merge_compute_minrun(n): """Returns the minimum length of a run from 23 - 64 so that the len(array)/minrun is less than or equal to a power of 2.""" r = 0 while n >= 64: r |= n & 1 n >>= 1 return n + r
def count_episodes_by_director(episodes): """Constructs and returns a dictionary of key-value pairs that associate each director with a count of the episodes that they directed. The director's name comprises the key and the associated value a count of the number of episodes they directed. Duplicate keys are...
def dragon_step(a): """ For example, after a single step of this process, 1 becomes 100. 0 becomes 001. 11111 becomes 11111000000. 111100001010 becomes 1111000010100101011110000 """ b = [0 if x==1 else 1 for x in a] b.reverse() return a + [0] + b
def students_not_viewed(students, list_viewed): """ Determine which students need to be send a message. :param students: List of the enrolled students. :type students: list(str) :param list_viewed: List of the students who have viewed a course :type list_viewed: list(str) :return: A list of...
def parseArgs(args, aliases={}): """ takes all options (anything starting with a -- or a -) from `args` up until the first non-option. short options (those with only one dash) will be converted to their long version if there's a matching key in `shortOpts`. If there isn't, an KeyError is raised.""" ...
def extra_credit(grades,students,bonus): """ Returns a copy of grades with extra credit assigned The dictionary returned adds a bonus to the grade of every student whose netid is in the list students. Parameter grades: The dictionary of student grades Precondition: grades has netids as keys, i...
def _como_hasheable(matriz): """Retorna una copia hasheable (y por tanto inmutable) de `matriz`.""" return tuple(tuple(fila) for fila in matriz)
def str2list(string): """Returns list contained in a string. Args: string (str): A string containing a list. Returns: (list): inferred list from the string. """ # Removing brackets "[" "]" from the string string = string[1:-1] # Splitting at "," output = string...
def get_min_max(unsorted_list): """Find the min and max in an unsorted list. Args: unsorted_list: A list of unsorted ints to find the min and max of Returns: minimum, maximum: Two ints representing the min and max in the given list """ if len(unsorted_list) == 0: ...
def text_format(text: str, *args) -> str: """ format the str \n :param text: the origin str :param args: the args :return: the formatted str """ return text.format(*args)
def removeInstructions(to_delete, content): """ removes indices to_delete from content """ return [x for i, x in enumerate(content) if i not in to_delete]
def count_encoded_characters(string): """Count encoded number of characters. "" -> "\"\"" "abc" -> "\"abc\"" "aaa\"aaa" -> "\"aaa\\\"aaa\"" "\x27" -> "\"\\x27\"" """ return len(string.replace('\\', '\\\\').replace('"', r'\"')) + 2
def create_dict2(l): """ Group a seq of key-value pairs into dictionary of list. Using defaultdict is more efficient than setdefault -- But, it's not equiv to create_dict because it does not generate Error when key not in dict EXAMPLES: >>> create_dict2([('a',1),['b',2],('a',3),('c',4),('b'...
def extract_type_path(object_type): """Extract the full path of the given type. Agrs: object_type (type): an object type. Returns: str. type full path. """ return "%s.%s" % (object_type.__module__, object_type.__name__)
def _find_html_comment(text): """ We are NOT in a comment. Return a ref to any code found, a ref to the rest of the text, and the value of inComment. """ posn = text.find('<!--') # one-line comment if posn == -1: return text, '', False if posn + 4 < len(text): return...
def check_parentheses(s): """ Return True if the parentheses in string s match, otherwise False. """ j = 0 for c in s: if c == ')': j -= 1 if j < 0: return False elif c == '(': j += 1 return j == 0
def sort_by_name(list_to_sort): """ Sort list by Name attribute """ return sorted( list_to_sort, key=lambda k: k['Name'].lower() )
def double_every_other(lst): """ Takes in a list of numbers and returns a list where every other number is doubled. >>> double_every_other([5, 8, 9, 9, 8, 6, 8, 5, 7, 3, 7, 6, 5, 5, 4]) [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8] """ for i in range(0, len(lst), 2): lst[i] *...
def is_callback(func): """Check if function is callback.""" return "_pyhap_callback" in getattr(func, "__dict__", {})
def n5_order(a, b): """ The smallest non-modular lattice. """ if a == {0} or b == {1}: return True elif a == {'a'} and b == {'b'}: return True else: return False
def jaccard(seq1, seq2): """Compute the Jaccard distance between the two sequences `seq1` and `seq2`. They should contain hashable items. The return value is a float between 0 and 1, where 0 means equal, and 1 totally different. """ set1, set2 = set(seq1), set(seq2) return 1 - len(set1 & set2) / float(len(set1 ...
def Dic_Extract_By_Subkeylist(indic,keylist): """ Return a new dic by extracting the key/value paris present in keylist """ outdic={} for key in keylist: try: outdic[key]=indic[key] except KeyError: raise KeyError("input key {0} not present!".format(key)) ...
def _eval_feature_fn(fn, xs, classes): """_eval_feature_fn(fn, xs, classes) -> dict of values Evaluate a feature function on every instance of the training set and class. fn is a callback function that takes two parameters: a training instance and a class. Return a dictionary of (training set ind...
def truncate_pad(line, num_steps, padding_token): """Truncate or pad sequences.""" if len(line) > num_steps: return line[:num_steps] # Truncate return line + [padding_token] * (num_steps - len(line))
def is_s3(url: str) -> bool: """Predicate to determine if a url is an S3 endpoint.""" return url is not None and url.lower().startswith('s3')
def _extract_message_size(data: bytes): """Read out the full length of a CoAP messsage represented by data. Returns None if data is too short to read the (full) length. The number returned is the number of bytes that has to be read into data to start reading the next message; it consists of a constant...
def has_palindrome_permutation_2(string): """ Time Complexity: O(n) Space Complexity: O(n) n: number of characters in the string """ counter = {} for char in string: counter[char] = counter[char] + 1 if char in counter else 1 odd_counts = sum([1 for count in counter.values() i...
def to_degree(val, low=0, hi=127): """Convert hex value to degree.""" return 127 * val / 255
def shot_title(title): """ """ shot_outcome, player = title.split(" - ") return shot_outcome, player
def recognize_central_min(heightmap, l, m): """recognize central minimum""" neighbours = [ heightmap[l + 1][m], heightmap[l][m - 1], heightmap[l][m + 1], heightmap[l - 1][m], ] cntr = heightmap[l][m] if cntr == min(neighbours + [cntr]) and cntr < min(neighbours): ...
def get_interface_by_pci_id(pci_id, interfaces): """ Returns the list of network interfaces by pci id. Parameters ---------- pci_id : str The pci id. interfaces : dict The name of of the network interface if a match is found, None otherwise. Returns ------- ...
def find_largest_digit(n): """ :param n: int, eliminate the last number of the integer :return: the max number of the input integer """ if n < 0: n = -n return find_largest_digit(n) elif 0 < n < 10: return n else: # get the number number_1 = n - (n // 10) * 10 rest_num = (n - number_1) // 10 max_nu...
def environment_validator(env): """ Checks if the passed in environment is a valid one. like qa or eu """ if (env is None): print("environment is blank") return False # can't use app because when using the api, you should be using api.cloudcheckr.com if (env == "qa" or env == "api" o...
def quicksort(lst): """quicksort with filter and lambda""" if not lst: return lst else: pivot, *rest = lst return ( quicksort(list(filter(lambda x: x < pivot, rest))) + [pivot] + quicksort(list(filter(lambda x: x >= pivot, rest))) )
def get_lstm_out_dim(config): """ calculate output dimension of lstm """ lstm_last_ts_dim = config['lstm_nhid'] if config['lstm_pooling'] == 'all': lstm_out_dim = config['lstm_nhid'] * 24 else: lstm_out_dim = config['lstm_nhid'] return lstm_out_dim, lstm_last_ts_dim
def nps(total_promoters, total_detractors, total_respondents): """Return the Net Promoter Score (NPS) for a period. Args: total_promoters (int): Total number of promoters (9 or 10 out of 10) within the period. total_detractors (int): Total number of detractors responses (1 to 6 out of 10) withi...
def calcDiagonalIndex(position) : """ Given the position of the node, returns the index of the diagonal it belongs to. """ # Calculate the index diag_index = (position[1] - position[0]) // 2 # Return the index return diag_index
def _page_to_text(page): """Extract the text from a page. Args: page: a unicode string Returns: a unicode string """ # text start tag looks like "<text ..otherstuff>" start_pos = page.find(u"<text") assert start_pos != -1 end_tag_pos = page.find(u">", start_pos) assert end_tag_pos != -1 end...
def address_cleaner(string): """ This function cleans the address for Nominatim. Note: Regex would be faster here. I don't prefer it because of readability. """ return " ".join(str(string).split()[:2])
def match_type(one, another): """ Matcher which matches on type. :param one: dictionary A :param another: dictionary B :return: True or False. """ res = True # this will make sure network node is mapped to network node. if 'type' in one and 'type' in another: res ...
def checksum_length(entropy_bits: int) -> int: """ Calculates length of checksum based on entropy bits. :param entropy_bits: number of entropy bits :return: checksum length """ return int(entropy_bits / 32)
def bounding_box(points): """Compute the bounding box of a polygon * Sterblue image axis: (0,0): top left corner, x positive to the right, y positive upward * COCO image axis: (0,0): top left corner, x positive to the right, y positive downward Args: points: List of points [ [x0, y0], [x1, y1],...
def toggle_navbar_collapse(n, is_open): """ Controls the state of the navbar collapse :param n: number of clicks on collapse :param is_open: open state :return is_open: open/close state """ if n: return not is_open return is_open
def scale(val, src, dst): """ :param val: Given input value for scaling :param src: Initial input value's Min Max Range pass in as tuple of two (Min, Max) :param dst: Target output value's Min Max Range pass in as tuple of two (Min, Max) :return: Return mapped scaling from target's Min Max range ...
def winner(board): """ Returns the winner of the game, if there is one. """ def straight_lines(): ## checks if any player has completed the horizontal or verticle line ## takes len(board) iterations for row in range(0, len(board)**2, len(board)): first_in_row, row =...
def min2str(minutes): """ Convert hh:mm:ss to seconds since midnight """ h = int((int(minutes) / 60) % 24) m = int(minutes % 60) return "{:02d}:{:02d}".format(h, m)
def _port_enabled(port_data): """Return whether port is enabled. Args: port_data: Data related to the port Returns: active: True if active """ # Initialize key variables enabled = False # Assign state if 'ifAdminStatus' in port_data: value = port_data['ifAdmin...
def _ast_pretty( st ): """ AST string beautifying. """ WRAP = 100 INDENT = ' ' indent_l = len( INDENT ) parenth = {} p = {} depth = 0 for i, ch in enumerate( st ): if ch in ( ')', ']', '}' ): if depth: depth -= 1 # -- opening bra...
def _join_memory_tool_options(options): """Joins a dict holding memory tool options into a string that can be set in the environment.""" return ':'.join( '%s=%s' % (key, str(value)) for key, value in sorted(options.items()))
def get_all_indexes_of(value, iterable): """ Return all indexes for a value. """ # Convert the given object to a list. iterable = list(iterable) index_list = [] # Get each index and store them in the list of indexes. for index in range(len(iterable)): if value in iterable[inde...