content
stringlengths
42
6.51k
def verify_splits(splits, keyfunc): """ Verifies that the splits of each transaction sum to 0 Args: splits (dict): return value of group_transactions() keyfunc (func): function that returns the transaction amount Returns: (bool): true on success Examples: >>> from operat...
def is_overlapping(segment_time, previous_segments): """ Checks if the time of a segment overlaps with the times of existing segments. Arguments: segment_time -- a tuple of (segment_start, segment_end) for the new segment previous_segments -- a list of tuples of (segment_start, segment_end) for the...
def getRadixArray(n, max_radix): """ For any n, this function decomposes n into factors for loacal memory tranpose based fft. Factors (radices) are sorted such that the first one (radix_array[0]) is the largest. This base radix determines the number of registers used by each work item and product of...
def argument(*args, **kwargs): """Convenience function to properly format arguments to pass to the command decorator. """ return (list(args), kwargs)
def is_user_signed_request(request): """ This function returns True if the request is a signed valid link """ try: return request.user_from_signed_request except AttributeError: return False
def hasNumbers(inputString): """ Return true if inputString contains numbers. """ return any(char.isdigit() for char in inputString)
def if_(test, result, alternative): """Like C++ and Java's (test ? result : alternative), except both result and alternative are always evaluated. However, if either evaluates to a function, it is applied to the empty arglist, so you can delay execution by putting it in a lambda. >>> if_(2 + 2 == 4,...
def nickparse(nick): """ strip @ and + from a nickname. Assume a nick is never empty """ if nick[0] in ('@','+'): return nick[1:], nick[0] return nick, None
def detected(numbers, mode): """ Returns a Boolean result indicating whether the last member in a numeric array is the max or min, depending on the setting. Arguments - numbers: an array of numbers - mode: 'max' or 'min' """ call_dict = {'min': min, 'max': max} if mode not in ca...
def _collapse_leading_ws(header, txt): """ ``Description`` header must preserve newlines; all others need not """ if header.lower() == 'description': # preserve newlines return '\n'.join([x[8:] if x.startswith(' ' * 8) else x for x in txt.strip().splitlines()]) els...
def validate_mode(value, _): """ Validate mode input port. """ if value: allowedmodes = ["constant-height", "constant-current"] if value.value not in allowedmodes: return f"The allowed options for the port 'mode' are {allowedmodes}."
def solucion_a(fuente: str, analizador: dict) -> str: """Reemplaza pares de caracteres si son encontrados en el analizador. :param fuente: Texto fuente :fuente type: str :param analizador: Mapeo de caracteres a reemplazar :analizador type: dict :returns: Texto modificado :rtype: str ...
def matvecMul(mat, vec): """Return matrix * vector.""" dim = len(mat) return tuple( sum( mat[i][j] * vec[j] for j in range(dim) ) for i in range(dim) )
def compare(candidate, pattern): """Compares a candidate TML tree against a given pattern. If the pattern contains no wildcards, this simply compares the two trees and returns true if identical. Alternately, the pattern may contain the "\?" wildcard to match any node (any list or string), or the "\...
def prob_drunk_given_positive(prob_drunk_prior=0.001, prob_positive=0.08,prob_positive_drunk=1.0): """ Returns the Bayesian probability that a person is drunk, given a positive result in a breathalyzer test Arguments: prob_drunk_prior (float, optional, default: 0.001): Probability that a person in the prior popu...
def straight(ranks): """Return True if the ordered ranks form a 5-card straight.""" return (max(ranks) - min(ranks) == 4) and len(set(ranks)) == 5
def get_name(properties, lang): """ Return the Place name from the properties field of the elastic response. Here 'name' corresponds to the POI name in the language of the user request (i.e. 'name:{lang}' field). If lang is None or if name:lang is not in the properties then name receives the local name...
def view_inv(inventory_list): """list -> None empty string that adds Rental attributes """ inventory_string = '' for item in inventory_list: inventory_string += ('\nRental: ' + str(item[0])+ '\nQuantity: '+ str(item[1])+ '\nDeposit: '+"$"+ str(item[2])+"\nPr...
def non_repeat(line: str) -> str: """ the longest substring without repeating chars """ results = [] result = [] for i in range(len(line)): for c in line[i:]: if c not in result: result.append(c) else: results.append(''.join(res...
def flatten(value, sep=","): """ >>> flatten([1,2,3,4]) '1,2,3,4' >>> flatten((5,6)) '5,6' >>> flatten(0.987654321) '0.987654' >>> flatten(7) '7' >>> flatten("flatten") 'flatten' """ flat = None # tuple or list if isinstance(value, tuple) or isinstance(value, ...
def gen_group_names(n_groups): """ Generate `n_groups` random names. """ if n_groups == 0: return return [str(i) for i in range(n_groups)]
def node_type(node) -> str: """ Get the type of the node. This is the Python equivalent of the [`nodeType`](https://github.com/stencila/schema/blob/bd90c808d14136c8489ce8bb945b2bb6085b9356/ts/util/nodeType.ts) function. """ # pylint: disable=R0911 if node is None: return "Null"...
def to_lower_case(str): """ Convert string to lower case """ return str.lower()
def unlistify(x): """Unpacks single-object lists into their internal object If list is longer than one, returns original list Parameters ---------- x: :obj:`list` Input list Returns ---------- :obj:`list` or other non-list object If ``len(x) == 1``, returns the sin...
def BulletedList(str_list): """Converts a list of string to a bulleted list. The returned list looks like ['- string1','- string2']. Args: str_list: [str], list to be converted. Returns: list of the transformed strings. """ for i in range(len(str_list)): str_list[i] = '- ' + str_list[i] re...
def xor(n1, n2): """XORs two numbers""" return (int(n1) + int(n2)) % 2
def interp(xval, xmin, xmax, ymin, ymax): """Linear interpolation.""" xval = xmin if (xval<xmin) else xval xval = xmax if (xval>xmax) else xval xv = float(xval) xn = float(xmin) xx = float(xmax) yn = float(ymin) yx = float(ymax) xi = yn + (xv-xn) * ((yx-yn)/(xx-xn)) return int(xi...
def strtobool(value): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ value = value.lower() if value in (...
def _set_default_max_rated_temperature(subcategory_id: int) -> float: """Set the default maximum rated temperature. :param subcategory_id: the subcategory ID of the inductive device with missing defaults. :return: _rated_temperature_max :rtype: float """ return 130.0 if subcategory_id =...
def cell_edge(subidx, subncol, cellsize): """Returns True if highres cell <subidx> is on edge of lowres cell""" ri = (subidx // subncol) % cellsize ci = (subidx % subncol) % cellsize return ri == 0 or ci == 0 or ri + 1 == cellsize or ci + 1 == cellsize
def imputed_indices(invalid, length, method='bfill'): """Imputation indices assuming the last element is valid. Args: invalid: List of negative indices of invalid entries. length: Length of the list to impute. method: Imputation methods. Default 'bfill' implements backward-fill ...
def search_bt_loop(t, d, is_find_only=True): """ similar to search_bt, but use a while loop instead of recursive """ while True: if t is None: return if t.data == d: if is_find_only: return t else: return if d < ...
def last1bit(b): """ Return index of highest order bit that is on """ return 0 if b==0 else 1+last1bit(b>>1)
def create_cell(first, second): """ creates set of string from concatenation of each character in first to each character in second :param first: first set of characters :param second: second set of characters :return: set of desired values """ res = set() if first == set() or second...
def validate_size(value): """Raise exception if size fails to match constraints.""" if value.lower() not in ["small", "large"]: return "satisfy enum value set: [Small, Large]" return ""
def is_valid_xml_char_ordinal(i): """ Defines whether char is valid to use in xml document XML standard defines a valid char as:: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] """ return ( # conditions ordered by presumed frequency 0x20 <= i <=...
def data_mean(data_vec): """ Returns the mean of an data structure itterable by sum() """ return sum(data_vec) / len(data_vec)
def pathsplit(str): """ takes a path with filters which may include literals, and ignores filter contents when splitting """ result = [] tok_start = 0 infilt= False for i,c in enumerate(str) : if c == '.' and not infilt : result.append( str[tok_start:i]) tok_start = i...
def extend_xmax_range(xmax_bins, templates): """ Copy templates in empty xmax bins, helps to prevent problems from reaching the edge of the interpolation space. :param templates: dict Image templates :return: dict Extended image templates """ # Create dictionary for our new...
def subgroup(iterable, width, itype=None): """Split an iterable into nested sub-itypes of width members.""" # Return the same type as iterable if itype is None: if isinstance(iterable, list): itype = list else: itype = tuple # Will leave short groups if not enough...
def required_build_info(settings): """ Checks if all settings required for producing build urls are set """ try: return all([ settings.get('jenkins', setting) != '' for setting in ['url', 'job_name', 'build_num'] ]) except KeyError: return False
def factorize_naive(n): """ A naive factorization method. Take integer 'n', return list of factors. """ if n < 2: return [] factors = [] p = 2 while True: if n == 1: return factors r = n % p if r == 0: factors.append(p) ...
def sort_string(s): """A simple little toy to sort a string.""" return ''.join(sorted(list(s))) if s else s
def get_full_tags_helper(data): """ Accepts raw REST Response for tags key and returns list of longest heirarchical tags. """ tags = [] temp_tags = [t for t in data.keys()] if temp_tags: tags.append(temp_tags.pop(0)) else: return tags for i in range(0, len(temp_tags)): ...
def assemble_api_cmd(url, cmd): """ Adapt Address to Different Url Format """ if url.endswith('/'): return url + cmd else: return url + "/" + cmd
def solution(S): # O(N) """ Given that a valid password requires an upper case character and must not contain a digit. Write a function to compute the longest valid password from a given string. eg. "a0B0cdAg1", longest valid password is "cdAg". >>...
def extname(path, **kwargs): """Return the extension from *path*""" import os.path name, ext = os.path.splitext(path, **kwargs) return ext
def dotted_name(names): """Returns a dotted name of a list of strings, integers, lists, and tuples.""" # It will just return the value instead of "b.a.d" if input was "bad"! if isinstance(names, str): return names resolved = [] for name in names: if isinstance(name, str): resolved.append(name)...
def _DeprecatedDateTimeToCell(zone_or_region): """Returns the turndown timestamp of a deprecated machine or ''.""" deprecated = zone_or_region.get('deprecated', '') if deprecated: return deprecated.get('deleted') else: return ''
def get_field_index(multi_hot_flags): """infer field index of each column using `multi_hot_flags` Example: get_field_index([False,False,True,True,True,False]) # [0,1,2,2,2,3] """ field_indices = [] cur_field_index = 0 for i, flag in enumerate(multi_hot_flags): field_indices.append(c...
def xor(key, pad): """Make the XOR between key and pad Args: key (bytes|bytearray|str): The secret key pad (bytes): Is equal to OPAD or IPAD Returns: (bytes|bytearray|str): XOR between key and pad """ return key.translate(pad)
def kmh_to_ms(speed_in_kmh): """ Convert kilometers/hour to meters/second. Args: speed_in_kmh (float): speed in kilometers/hour Returns: float: the speed in meters/second """ meters_per_second = speed_in_kmh * 1000 / 3600 return meters_per_second
def decode_wanted(parts): """ Parse missing_check line parts to determine which parts of local diskfile were wanted by the receiver. The encoder for parts is :py:func:`~swift.obj.ssync_receiver.encode_wanted` """ wanted = {} key_map = {'d': 'data', 'm': 'meta'} if parts: # r...
def is_requirement(line): """ Return True if the requirement line is a package requirement. Returns: bool: True if the line is not blank, a comment, a URL, or an included file """ return line and not line.startswith(("-r", "#", "-e", "git+", "-c"))
def utility(wealth, alpha): """If wealth is negative, return it straight so that utility is linearly bad when wealth is negative.""" if wealth < 0: return wealth else: return wealth**alpha
def ShouldRunTest(tests, name): """Returns True if |name| is an entry in |tests|.""" if not tests: return False if name in tests: return True return False
def is_user_message(message): """Check if the message is a message from the user""" return (message.get('message') and message['message'].get('text') and not message['message'].get("is_echo"))
def _get_item_at_index(list, index): """Returns the item if it exists, otherwise returns None""" if len(list) == 0: return None if index >= 0 and index < len(list): return list[index] return None
def popCallBack(resp): """ :param resp: a dict which has some callback choices in it :return: dict of all callback choices """ return {cb:c for cb,c in resp.items() if cb.startswith("xcallback__")}
def _getRightmost(categories): """ Get rightmost toplevel category. categories -- list of Category, all category from database. """ rightmost = None for cat in categories: if not rightmost or cat.getRight() > rightmost.getRight(): rightmost = cat return rightmost
def average_gate_error_to_rb_decay(gate_error: float, dimension: int): """ Inversion of eq. 5 of [RB]_ arxiv paper. :param gate_error: The average gate error. :param dimension: Dimension of the Hilbert space, 2^num_qubits :return: The RB decay corresponding to the gate_error """ return (gat...
def _word_wrap(string, max_length=0): """wrap long strings to be no longer then max_length""" if max_length <= 0: return string return '\n'.join([string[i:i + max_length] for i in range(0, len(string), max_length)])
def maketid(sfs,pt,syst='nom'): """Interpolate for second to last bin.""" # f = TFormula('f',sf) # for x in [10,20,29,30,31,35,45,100,200,499,500,501,750,999,1000,1001,1500,2000]: x, f.Eval(x) # "x<20?0: x<25?1.00: x<30?1.01: x<35?1.02: x<40?1.03: 1.04" # "x<20?0: x<25?1.10: x<30?1.11: x<35?1.12: x<40?1.13: x...
def all_subclasses(klass): """ :return: All the subclasses of the class passed, scanning the inheritance tree recursively to find ALL the subclasses. """ return klass.__subclasses__() + [child for subclass in klass.__subclasses__() for child in all_subcl...
def raw(string): """ Escapes a string into a form which won't be colorized by the ansi parser. """ return string.replace('{', '{{').replace('%', '%%')
def freq_for_shape(freq, shape): """ Given a base frequency as int, generate noise frequencies for each spatial dimension. :param int freq: Base frequency :param list[int] shape: List of spatial dimensions, e.g. [height, width] """ height = shape[0] width = shape[1] if height == width...
def engineering_notation(value, n_dec=6): """ Represent a numeric value in engineering notation. 2400,000,000 Hz = 2.4 GHz 31,300,000 Hz = 31,3 MHz """ form = "%" + ("1.%df "%n_dec) if value >= 1e12: # Terra (1e12) return (form + "T")%(float(value) / 1e12) elif value >...
def search_parse(search_results): """ Return a simplified version of the json object returned from the USDA API. This deletes extraneous pieces of information that are not important for providing context on the search results. """ if 'errors' in search_results.keys(): return None # Store...
def find_title(roles_set, title_list): """returns the index of the title that a client matches with""" title_indx = [] for i in range(len(title_list)): inters = roles_set.intersection(set(title_list[i])) if not (list(inters) == []): title_indx.append(i) return title_indx
def combine_lists_recursive(list_of_lists): """Recursive combination function. This makes no attempt to avoid temporary copies""" if(len(list_of_lists) < 2): #Nothing to combine return list_of_lists elif(len(list_of_lists) == 2): list1 = list_of_lists[0] else: list1 = combine_lists_recursive(li...
def inferRegion_(peak): """Infer start and end for a (non-intermediate) region This helper function computes the applicability region for variation tuples whose INTERMEDIATE_REGION flag is not set in the TupleVariationHeader structure. Variation tuples apply only to certain regions of the variation space; outsid...
def bool_on_off(process, longname, flag, value): """ Phrase Boolean values as 'on' or 'off' """ if value in [True, 'on', 'On']: return "on" if value in [False, 'off', 'Off']: return "off" # Anything else wasn't a bool! raise ValueError("Flag value '%s' wasn't boolean." % repr(value))
def get_sanitised_kubernetes_name(name: str, replace_dots: bool = False) -> str: """ Helper to ensure that any names given to Kubernetes objects follow our conventions replace_dots is an optional parameter for objects such as Containers that cannot contain `.`s in their names (in contrast to objects su...
def evaluate_predictions(test_y, predictions): """ Evaluate on the test set. """ assert len(test_y) == len(predictions) right_cycle = 0 right_menstr = 0 for idx, y in enumerate(test_y): if y[0] == predictions[idx][0]: right_cycle += 1 if y[1] == predictions[idx][1]: ...
def index_closest_left(words, start, what): """Returns index of the closest specified element to the left of the starting position or -1 if no such element was present.""" i = start - 1 while i >= 0: if words[i] == what: return i i -= 1 return -1
def back_order_rate(total_back_orders, total_orders): """Return the back order rate for a period. Back orders are those that could not be shipped due to lack of stock. Args: total_back_orders (int): Total number of back orders. total_orders (int): Total number of orders. Returns: B...
def specific_heat(T): """ Shchomate equation to calculate specific heat of water vapor for a given temperature T. :param T: Temperature (K) """ t = T / 1000 if 500 <= T < 1700: a, b, c, d, e = [30.092, 6.832514, 6.793425, -2.53448, 0.082139] elif T == 1700: return 2.7175 elif 1700 < T <= 6000: a, b, c, d,...
def test_vcs(req): """Checks if requirement line is for VCS. """ return '+' in req and req.index('+') == 3
def sizeof_fmt(num, suffix='B'): """ Human readable file size. Source: https://stackoverflow.com/a/1094933 """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num...
def fieldsConversion(fields): """ Convert fields to list of fields to filter """ if isinstance(fields, str): return [fields] elif isinstance(fields, list): for field in fields: assert isinstance(field, str) return fields else: raise TypeError("fields...
def colourfulness_correlate(F_L, C_94): """ Returns the *colourfulness* correlate :math:`M_94`. Parameters ---------- F_L : numeric Luminance adaptation factor :math:`F_L`. numeric *Chroma* correlate :math:`C_94`. Returns ------- numeric *Colourfulness* corr...
def middle(min_value, max_value): """ Compute the middle values. .. math:: {middle_values_formula} Parameters ---------- {min_value} {max_value} Returns ------- {middle_value} """ return (min_value + max_value) / 2
def remove_white_space(query: str) -> str: """Remove unnecessary white space from scrapped schema, if exists. Args: query: The SQL Schema for the leetcode problem as one string. Returns: The SQL Schema with unnecessary space removed. """ query_lines = query.split("\n") query_lin...
def console_sep(char='- ', length=40): """Return a separator line to the console output.""" return ''.join([char * length])
def int_to_binary_string(number, bit_width): """ Convert a number to a binary string. @type number: int @param number: (Optional, def=self._value) Number to convert @type bit_width: int @param bit_width: (Optional, def=self.width) Width of bit string @rtype: str @return: Bit s...
def shortest_sequence(predecessors, start_symbol): """ CAVEAT! Will enter an infinite loop if topology contains loops. Can not deal with equal length sequences. Just good enough for the #79 case. Might not give satisfying results with sequences that contain repeated symbols. """ sequence = [start_s...
def filter_instances(timings, name): """ Filters a single cell instance from the given timing data """ cells = {} for cell_type, cell_data in timings.items(): # Don't have that instance if name not in cell_data: continue # Leave only the one that we are looking...
def _split_chunks(l): """ Generates a list of lists of neighbouring ints. `l` must not be empty. >>> _split_chunks([1,2,3,5,6,7,9]) [[1,2,3],[5,6,7],[9]] :type l: list[int] :rtype list[list[int]] """ ret = [[l[0]]] for c in l[1:]: if ret[-1][-1] == c - 1: ret[-1...
def _make_feature_descriptions(features): """ Prepare a formatted list of features. """ return [' {:24}{}\n'.format(cls.__name__, cls.get_description()) for cls in features]
def a_or_an(word: str, lowercase: bool = True): """ Returns "an" if `word` starts with a, e, i, o, or u. Otherwise returns "a". May not be compatible with British English. :param word: str :param lowercase: bool :return: str """ if lowercase: a = "a" an = "an" else: ...
def _decode_membership_type(row): """ Decode membership type: 'r' Regular _ Reduced? """ if row[5] == "r": return "regular" return "reduced"
def selection_to_string(selection): """Convert dictionary of coordinates to a string for labels. Parameters ---------- selection : dict[Any] -> Any Returns ------- str key1: value1, key2: value2, ... """ return ", ".join(["{}".format(v) for _, v in selection.items()])
def _small_body(close, low, open, high): """ do we have a small body in relation to the wicks :param close: :param low: :param open: :param high: :return: 0 if no 1 if yes (wicks are longer than body) """ size = abs(close - open) if close > open: top_wick = ...
def mndwi(b3, b11): """ Modified Normalized Difference Water Index (Xu, 2006). .. math:: MNDWI = (b3 - b11) / (b3 + b11) :param b3: Green. :type b3: numpy.ndarray or float :param b11: SWIR 1. :type b11: numpy.ndarray or float :returns MNDWI: Index value .. Tip:: Xu, H. (...
def cyPalette(name='set1'): """Supply a set of colors from Brewer palettes (without requiring rColorBrewer). Args: name (str): name of a set of colors (e.g., 'set1', 'burd') Returns: list: list of color values in the cy_palette Raises: KeyError: if cy_palette name is invalid ...
def parse_range(s): """Parse a string "a-b" describing a range of integers a <= x <= b, returning the bounds a, b.""" return tuple(map(int, s.split("-")))
def get_connection_port(os_type: str) -> int: """Get default connection port per the OS type""" if os_type.lower() == "windows": return 3389 else: return 22
def wms100format(format): """ >>> wms100format('image/png') 'PNG' >>> wms100format('image/GeoTIFF') """ _mime_class, sub_type = format.split('/') sub_type = sub_type.upper() if sub_type in ['PNG', 'TIFF', 'GIF', 'JPEG']: return sub_type else: return None
def cleanly_separate_key_values(line): """Find the delimiter that separates key from value. Splitting with .split() often yields inaccurate results as some values have the same delimiter value ':', splitting the string too inaccurately. """ index = line.find(':') key = line[:index] value = line[index + 1:] r...
def _cal_pvalue(ref_match_pct, hap_match_pct): """ Description: Helper function to calculate a p-value for a given match percent. Arguments: ref_match_pct list: Match percents from reference populations as the null distribution. hap_match_pct float: Match percent of a haplotype in a...