content
stringlengths
42
6.51k
def _AccumulatorResultToDict(partition, feature, grads, hessians): """Converts the inputs to a dictionary since the ordering changes.""" return {(partition[i], feature[i, 0], feature[i, 1]): (grads[i], hessians[i]) for i in range(len(partition))}
def bbox_vert_aligned_right(box1, box2): """ Returns true if the right boundary of both boxes is within 2 pts """ if not (box1 and box2): return False return abs(box1.right - box2.right) <= 2
def collatz(n): """returns length of sequence""" acc = 0 m = n while True: acc = acc + 1 if m == 1: return acc else: if m % 2 == 0: m = m // 2 else: m = 3*m + 1
def get_players(string): """ Parses a string representing the number of other players (i.e. excluding the player) in the round. Currently supports only 1-9 other players. Returns a string in the correct form for the lookup table. Returns None if the input could not be parsed. """ if "nine" i...
def get_abis(arch): """Return the ABIs supported for the given architecture.""" return { 'arm': ['armeabi', 'armeabi-v7a'], 'arm64': ['arm64-v8a'], 'mips': ['mips'], 'mips64': ['mips64'], 'x86': ['x86'], 'x86_64': ['x86_64'], }[arch]
def title_format(name): """" This customized title function transform names in title format while keeping prepositions like "de" and "das" in lowercase """ person_names = [k.title() if len(k)>3 else k for k in name.split(' ')] return ' '.join(person_names)
def field_match(value, query): """ Determines whether a given field of an edge (or, in particular, an assertion) matches the given query. If the query is a URI, it will match prefixes of longer URIs, unless `/.` is added to the end of the query. For example, `/c/en/dog` will match assertions a...
def auth_headers(auth_token): """Return HTTP authentication headers for API requests. Kwargs: auth_token: valid API token. Returns a dict that can be passed into requests.post as the 'headers' dict. """ assert auth_token is not None, ( u"No valid HipChat authentication tok...
def remove_directories(list_of_keys): """ Removes directories from a list of S3 keys. """ return [path for path in filter(lambda x: x[-1] != '/', list_of_keys)]
def minutes_to_runtime(minutes): """Turns an amount of minutes into a runtime as if for a movie or TV show :param minutes: The amount of minutes to turn into a runtime """ # Turn the minutes into hours hours = minutes // 60 # Return the result return "{}h {}m".format(hours, minute...
def matmul(a00, a10, a01, a11, b00, b10, b01, b11): """ Compute 2x2 matrix mutiplication in vector way C = A*B C = [a00 a01] * [b00 b01] = [c00 c01] [a10 a11] [b10 b11] [c10 c11] """ c00 = a00 * b00 + a01 * b10 c10 = a10 * b00 + a11 * b10 c01 = a00 * ...
def GetTypeDataName(name, type_name='object'): """Returns the data name for name of type type_name. Args: name: The data name. type_name: The data type name. Returns: The data name for name of type type_name. """ return '{name}::{type_name}'.format(name=name, type_name=type_name)
def merge_sort(array): """ the merge sort algorithm sorts an array of elements out of place, is stable, and takes O(n log n) time Divide: split the array into left and right halves Conquer: sort the half Combine: merge the two sorted array """ def merge(left, right): """Merge t...
def is_number(text): """ This function checks if a string is a number, positive or negative value. :type text: string :param text: string to be tested :rtype: boolean :return: True if is a number, else False """ try: float(text) return True except ValueError:...
def remove_elements_from_list(lst: list, elements: list): """ remove elements from lst. """ return [e for e in lst if e not in elements]
def right_part_of(txt, sub_txt, n=-1): """ Return the right part after the nth of sub_txt appeared in txt. :param txt: text :param sub_txt: separate text :param n: the nth of sub_txt(default:-1) """ parts = txt.split(sub_txt) return sub_txt.join(parts[n:])
def merge_dicts_value(primary_dict: dict, *dictionaries: dict): """ Merges the values of various dictionarys to the common key of the primary dictionary :param primary_dict: dict :param dictionaries: dict :return: dict """ merged_dict = {} for dictionary in dictionaries: for key, val...
def levelOrder(root): """ :type root: TreeNode :rtype: List[List[int]] """ to_return = [] if not root: return to_return level = [root] while level: next_level, current_level_val = [], [] for node in level: if node is not None: ...
def linear_interpolate(x, y, x0, y0, x1, y1): """Format a call to linear_interpolate for the given arguments and expected result. """ fmt = """ select linear_interpolate({x}, {x0}, {y0}, {x1}, {y1}), {y} as answer, {y} = linear_interpolate({x}, {x0}, {y0}, {x1}, {y1}) as match ;""" ...
def wheel(pos): """b->g->r color wheel from 0 to 1020, neopixels use grb format""" if pos < 255: return [pos , 0 , 255] elif pos < 510: pos -= 255 return [255 , 0, 255 - pos ] elif pos < 765: pos -= 510 return [255 , pos, 0] elif pos<=1020: pos -=...
def get_knockout_sequence(n, depth=0, indices=[1, 2], complements=[]): """ Return a list of indices disposing n competitors in a knockout/eliminatory turn (recursive implementation). Based on http://stackoverflow.com/questions/13792213/""" if len(complements) <= depth: complements.append...
def _dirac(a, b): """Calculate the dirac function for labels.""" return int(a == b)
def _key_transform(values, keys_from, keys_to): """ Transform keys in ``values`` by replacing keys in ``keys_from`` by the key in ``keys_to`` with the same index. """ tr = {a: b for a, b in zip(keys_from, keys_to)} return {tr[key]: val for key, val in values.items()}
def check_api_subifs_for_parent(interface_id, interfaces_cache): """ Check for existing subinterfaces on an interface ID :param interface_id: Interface ID to check :param interfaces_cache: Interfaces API Response cache :return: Bool, True if active Subinterfaces. """ active_subifs = False ...
def linear_interpolation(listx, listy, argument): """calculates the linear interpolation of [listx,listy] at argument :param listx: x choordinates (should be ordered in ascending order) :param listy: y choordinates :param argument: where to evaluate the linear interpolation :returns: value of the linear interpol...
def sub_field(k, v): """Return a nested dictionary with field keys k and value v.""" res = {} field_d = res fields = k.split('.') for f in fields[:-1]: field_d[f] = {} field_d = field_d[f] field_d[fields[-1]] = v return res
def preprocess_sparql(query): """Do various preprocessing on the SPARQL query.""" # Tokenize braces. query = query.replace('count(*)', 'count ( * )') tokens = [] for token in query.split(): # Replace 'ns:' prefixes. if token.startswith('ns:'): token = token[3:] # Replace mid prefixes. i...
def calculate_relative(modifier: str, start: float, end: float) -> float: """ Helper method for settings. Lets you specify numbers relative to a range. For example: calculate_relative("-10.0", 0, 100) == 90 calculate_relative("10", 0, 100) == 10 calculate_relative("-0", 0, 100) == 1...
def create_datafile_url(base_url, identifier, is_filepid): """Creates URL of Datafile. Example - File ID: https://data.aussda.at/file.xhtml?persistentId=doi:10.11587/CCESLK/5RH5GK Parameters ---------- base_url : str Base URL of Dataverse instance identifier : str Identifie...
def detrc2krc(rdet, cdet, rstart, cstart, r0, c0, fr, fc, rstep, cstep): """ Conversion from detector coordinates (rdet, cdet) to momentum coordinates (kr, kc). """ rdet0 = rstart + rstep * r0 cdet0 = cstart + cstep * c0 kr = fr * ((rdet - rdet0) / rstep) kc = fc * ((cdet - cdet0) / cstep) ...
def sub_and_super_both_in(sub_string, super_string, main_string): """ Check if a substring and a super (contains the substring) string are both in another string in non overlapping areas. :param sub_string: The string contained in the super-string. :param super_string: The string containing the sub-str...
def _CalcLutOffsets(lods, isalpha): """ Compute the offset into the lookup tables by LOD level. Return an array of offsets indexed by LOD. Also return (appended to the end of the result) the lookuop table size. The result differs depending on whether this is the alpha or brick LUT. The highe...
def get_posterior(X, prior, likelihood): """ Compute posterior of testing samples, based on prior and likelihood @param X: testing samples @param prior: dictionary, with class label as key, corresponding prior as the value @param likelihood: dictionary, with class label as key, corresponding conditi...
def _get_object_for_given_param(same_arr_size_list, param): """ This function, for a given list of ArraysSameSize objects, returns the object has a certain param in its parameters list """ for elem in same_arr_size_list: if param in elem.parameters_list: return elem return No...
def make_destination_paths_map(source_paths, destination_dir_path, strip_prefix=None): """Create a mapping of source paths to destination paths. Args: source_paths: An iterable of absolute paths. destination_dir_path: A destination directory path. strip_prefix: A path pre...
def path_sequence(list_of_links, source, target): """ Convert set of tuples representing path in random order to a path :param list_of_links: set of tuples representing path :param source: source node :param target: destination node :return: pretty path as sequence of nodes """ pretty_p...
def merge_sort_td(ls): """ Top down merge sort algorithm (divide and conquer sorter) Time: O(nlog(n)); Auxiliary space: O(n) Notes: This implementation works, because in python lists are mutable and are thus passed by reference and not copied to a new local object within the function implicitly...
def int_to_ordinal(num: int) -> str: """ Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc. """ n = int(num) if 4 <= n <= 20: return f"{n}th" elif n == 1 or (n % 10) == 1: return f"{n}st" elif n == 2 or (n % 10) == 2: return f"{n}nd" ...
def binary_search(arr, l, r, x): """ Function to search number in a list in logn time""" while l <= r: mid = (l + r) // 2 # Check if x is present at mid if arr[mid] == x: return mid # If x is greater, ignore left half elif arr[mid] < x: l = mid + 1 # If x is smaller, ignore right half else: ...
def _get_value(scikit_value, mode = 'regressor', scaling = 1.0, n_classes = 2, tree_index = 0): """ Get the right value from the scikit-tree """ # Regression if mode == 'regressor': return scikit_value[0] * scaling # Binary classification if n_classes == 2: # Decision tree ...
def subset(part, whole): """Test whether `part` is a subset of `whole`. Both must be iterable. Note consumable iterables will be consumed by the test! This is a convenience function. Examples:: assert subset([1, 2, 3], [1, 2, 3, 4, 5]) assert subset({"cat"}, {"cat", "lynx"}) ...
def pairwise(iterable): """This function returns all contiguous pairs of elements in an iterator """ return list(zip(iterable, iterable[1:]))
def compute_precision(true_positive, false_positive): """ Function to compute Precision""" if true_positive == 0: return 0 return float(true_positive) / float(true_positive + false_positive)
def compound_fwd_query(query, rel): """ Create a compound forwards query that selects the destination nodes, which have source nodes within the subquery. :param query: The subquery. :param rel: The relation. """ smt = 'SELECT dst FROM %s WHERE src IN (%s)' return smt % (rel, query),...
def unquote(value): """Remove surrounding single or double quotes.""" if value.startswith('"') and value.endswith('"'): return value[1:-1].replace('\\"', '') return value
def x_pixel_to_coords(x_pixel_loc, axis_info_dict): """ Converts the pixel location on the x axis to coordinates :param x_pixel_loc: int, distance in pixels of a single pixel from the left side of the image :param axis_info_dict: dict, result of the get_axis_info function :return coord_x: tuple with...
def format_public_key(unformated_pk): """ Raised when the paramter -u is given :param unformated_pk: unformated public key value with ':'character :return: the unformated public key value without ':' character """ return unformated_pk.replace(':', '')
def dep_parenreduce(mysplit, mypos=0): """Accepts a list of strings, and converts '(' and ')' surrounded items to sub-lists: >>> dep_parenreduce(['']) [''] >>> dep_parenreduce(['1', '2', '3']) ['1', '2', '3'] >>> dep_parenreduce(['1', '(', '2', '3', ')', '4']) ['1', ['2', '3'], '4'] """...
def blend1(d = 0.0, u = 1.0, s = 1.0): """ blending function pisig d = delta x = xabs - xdr u = uncertainty radius of xabs estimate error s = tuning scale factor returns blend """ v = float(abs(u * s)) #scale uncertainty radius make sure positive a = float(abs(d)) #sy...
def fmt_numeric(value: float, precision=10) -> str: """Format any numeric value. Args: value: The numeric value to format. precision: The numeric precision Returns: The numeric value with the given precision. """ return "{{:.{precision}g}}".format(precision=precision).forma...
def nice_time(sec_in): """ Pretty formatting for time stamps """ seconds = int(sec_in) % 60 minutes = int((sec_in / 60)) % 60 hours = int(sec_in / 3600) return "{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds)
def allow_degree_specification(value): """Dash callback for enabling/disabling the degree input widget for support vector classification. Given a kernel from the dropdown menu, allow the user to specify a degree if the selected kernel is polynomial, "poly." Otherwise, do not the allow th user to sp...
def equal_string_modulo_digits(s1, s2): """Returns whether two strings without their digits are the same """ s1 = (c for c in s1 if not c.isdigit()) s2 = (c for c in s2 if not c.isdigit()) return all(c1 == c2 for c1, c2 in zip(s1, s2))
def pixel_to_terrain_height(pixel): """ Convert a RGBA pixel to a terrain height. The R channel composes the lower 8 bits, the G channel composes the upper 8 bits. """ return pixel[0] & 0xff |( (pixel[1] & 0xff) << 8)
def append_write(filename="", text=""): """string at the end of a text file""" with open(filename, 'a') as f: c = f.write(text) return c
def get_number(items: dict) -> int: """ return maximum consecutive number of items """ _number = [item.number for item in items.values()] try: return max(_number) except ValueError: return 0
def linkTotal(currentIndex, linkNumber, lowerBound, upperBound): """Calculates the total possible links for link entropies. This function is a specialty function for calculating the total number of possible links when considering the different link entropies of all links, forelinks, and backlinks. ...
def commented_line(l): """ """ if l[:1] == '#': return True else: return False
def _convertResultsToArray(result, varNameList): """Extracts for each SPARQL result binding in 'result' the 'value' of variables specified in 'varNameList' and creates an Array of these result values.""" resultArray = list() for r in result['results']['bindings']: resultList = list() for...
def convert_upper_case_to_snake_case(string): """Converts a string from UpperCase to snake_case. Primarily used to translate module names when retrieving them from version modules' __init__.py files. Args: string: an arbitrary string to convert. Returns: A new snake_case represent...
def createRoundKey(expandedKey, roundKeyPointer): """Create a round key. Creates a round key from the given expanded key and the position within the expanded key. """ roundKey = [0] * 16 for i in range(4): for j in range(4): roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4...
def R(pcset): """Returns retrograde of pcset.""" return [pcset[x] for x in range(len(pcset)-1, -1, -1)]
def bintodec(x): """Convert Binary to Decimal. Input is a string and output is a positive integer.""" num = 0 n = len(x) for i in range(n): num = num + 2 ** i * int(x[n - i - 1]) return num
def get_page_text(soup): """Return all paragraph text of a webpage in a single string. """ if soup is None: return '' paragraphs = [para.text for para in soup.select('p')] text = '\n'.join(paragraphs) return text
def is_2x2_matrix(mat): """ A quick check to ensure a value is a 2x2 matrix :param mat: :return: """ return len(mat) == 2 and len(mat[0]) == 2 and len(mat[1]) == 2
def list_to_empty_dict(data): """Recieve list of and return dict with empty keys""" return {i : "" for i in data}
def is_leap(year): """ return true for leap years, False for non leap years """ return year % 4 == 0 and ( year % 100 != 0 or year % 400 == 0)
def array_info(arr): """ returns ndims, *lengths """ if not isinstance(arr, (list, tuple, set)): return 0, subs = set([array_info(elem) for elem in arr]) if len(subs) > 1: raise ValueError('subarray dimensions must match') if len(subs) == 0: return 1, 0 s = subs.p...
def nonEmptyValuesCount(map): """Returns the number of non-empty values in a map.""" return len([x for x in map.values() if x])
def _celsius_to_fahrenheit(degrees) -> int: """ >>> _celsius_to_fahrenheit(0) 32 >>> _celsius_to_fahrenheit('23.4') 74 >>> _celsius_to_fahrenheit(34.5) 94 """ return int(round((float(degrees) * 9/5) + 32))
def S_find_square_floors_values(_data_list): """ Returns locations of values which do not change """ s_data = [] ds = len(_data_list) pd = _data_list[0] start = end = -1 for i in range(1, ds): if pd == _data_list[i]: if start == -1: start = i - 1...
def escape_characteristic_name(char_name): """Escape any dash or dots in a characteristics name.""" return char_name.replace("-", "_").replace(".", "_")
def humanize(number, suffix=''): """Transforms given input into human readable format.""" if number > 1e9: return '%dG%s' % (round(number/1e9, 1), suffix) if number > 1e6: return '%dM%s' % (round(number/1e6, 1), suffix) if number > 1e3: return '%dK%s' % (round(number/1e3, 1), suffix) return '%d%s'...
def simpleVoigt(vsh,vsv): """ seis_model.simpleVoigt(vsh,vsv) voigt average of horizontal and vertical shear wave velocities v = 0.5 * (vsh + vsv) Parameters ----------- vsh horizontal shear wave velocity, array or scalar vsv vertical shear wave velocity, array or scalar ...
def elem_C_fit(params, w): """ Fit Function: -C- """ C = params["C"] return 1 / (C * (w * 1j))
def get_affix_table_type(file_prefix): """ Retrieve the minimal prefix for an affix file name. The result of these is used to i18n the equipment types an affix can occur on in the frontend. """ for prefix in [ # Both arm and arms are used: 'armmage', 'armsmage', ...
def mergeTwoTimeCut(cut1, cut2): """Merge two cuts.""" s1, e1 = cut1 s2, e2 = cut2 if s1 > s2: s1, e1 = cut2 s2, e2 = cut1 return s1, max(e1, e2)
def _NumberOfTestsToString(tests): """Returns an English sentence describing the number of tests.""" return "%d test%s" % (tests, 's' if tests != 1 else '')
def pie_pct_format(value): """ Determine the appropriate format string for the pie chart percentage label Args: value: value of the pie slice Returns: str: formated string label; if the slice is too small to fit, returns an empty string for label """ return '' if value < 7 else '%.0f...
def get_hosts_ram_total(nova, hosts): """Get total RAM (free+used) of hosts. :param nova: A Nova client :type nova: * :param hosts: A set of hosts :type hosts: list(str) :return: A dictionary of (host, total_ram) :rtype: dict(str: *) """ hosts_ram_total = dict() #dict of (host...
def first_negative(l): """ Returns the first negative element in a given list of numbers. """ for x in l: if x < 0: return x return None
def num_mul_permutations(n_l: list): """ :param n_l: [1,2,3,4,5] """ # from itertools import permutations # result = set() # if not op_l: # for c in permutations(n_l, 2): # num = c[0] * c[1] # result.add(num) # else: # for c in permutations(n_l, sum(op...
def get_dist_from_koji_build_name(koji_build_name): """ Split the dist from the end of the koji build name :param koji_build_name: The full build name including the dist :type koji_build_name: str :return: The short name of the dist from the build :rtype: str """ return koji_build_name[k...
def _validate_argument(arg, argname, valid_args): """ Validate interpolation method for quantile function. """ if arg not in valid_args: msg = 'Invalid value for {} ({}). Must be on of {}.' raise ValueError(msg.format(argname, arg, valid_args)) return arg
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. If the optional allow_dotted_names argument is false, dots are ...
def improve_humidity_measurement(raw_humidity, dig_h, t_fine): """Refine the humidity measurement. Adapts the humidity measurement by using the available temperature information, along with the humidity readout details. Args: raw_humidity (int): raw humidity dig_h (list): raw data bloc...
def translate_contents_without_string(input): """ translate string contents of list into contents without string e.g. function_list = ['function1', 'function2'] -> translated_function_list = [function1, function2] input = 'hoge' -> translated_input = hoge :param input...
def fibonacci(num): """ Examples ------------ >>> fibonacci(5) Calculating fibonacci(5) Calculating fibonacci(4) Calculating fibonacci(3) Calculating fibonacci(2) Calculating fibonacci(1) Calculating fibonacci(0) 5 >>> fibonacci(4) 3 >>> fibonacci(3) 2 >>>...
def num_pad(num, length): """ Returns given number with zero's at prefix to match given length :param num: int :param length: int :return: str """ num_str = str(num) length_str = str(length) num_chars = len(num_str) length_chars = len(length_str) if num_chars < length_chars:...
def sum_iter(iterable, start=0, inplace=True): """Compute the product of a series of elements. This function works with any type that implements __add__ (or __iadd__ if inplace is True). In particular, it works with tf.Tensor objects. Parameters ---------- iterable : series of elements ...
def s_v_m(c, v): """Performs scalar vector multiplication. c = number, v = vector""" return [c * vi for vi in v]
def _suffix_rules(token, **kwargs): """ Default morphological tagging rules for English, based on word suffixes. """ word, pos = token if word.endswith("ing"): pos = "VBG" if word.endswith("ly"): pos = "RB" if word.endswith("s") and not word.endswith(("is", "ous", "ss")): ...
def _is_tempo_or_prob(line: dict) -> bool: """ Returns True if report type is TEMPO or non-null probability """ return line.get("type") == "TEMPO" or line.get("probability") is not None
def is_subset(subsampling, reference): """Return whether indices specified by ``subsampling`` are subset of the reference. Args: subsampling ([int] or None): Sample indices reference ([int] or None): Reference set. Returns: bool: Whether all indices are contained in the reference s...
def all_valid(formsets): """Returns true if every formset in formsets is valid.""" valid = True for formset in formsets: if not formset.is_valid(): valid = False return valid
def filter_controls(rows): """Remove crRNA controls from rows. This leaves in target controls. Returns: rows with only experiments """ rows_filtered = [] for row in rows: if row['guide_type'] == 'exp': # Check this row assert 'control' not in row['crRNA'...
def set_header_field(headers, name, value): """ Return new headers based on `headers` but with `value` set for the header field `name`. :param headers: the existing headers :type headers: list of tuples (name, value) :param name: the header field name :type name: string :param value: the ...
def is_bond_member(yaml, ifname): """Returns True if this interface is a member of a BondEthernet.""" if not "bondethernets" in yaml: return False for _bond, iface in yaml["bondethernets"].items(): if not "interfaces" in iface: continue if ifname in iface["interfaces"]: ...
def standard_deviation(x): """ calculates the standard deviation. Does not correct for bias inputs ------ x: list of all floats/integers returns: float - standard deviation """ for elem in x: if isinstance(elem, int) != True and isinstance(elem, float) != True: ...
def sanitize_pairs(pairs, pairs_all): """Clean up a single-element mapping configuration attribute as returned by Confuse's `Pairs` template: keep only two-element tuples present in pairs_all, remove duplicate elements, expand ('str', '*') and ('*', '*') wildcards while keeping the original order. Note ...