content
stringlengths
42
6.51k
def capitalise_string(string): """ Capitalise the first letter of each word in a string. The original string may contain (). """ capitalised_string = '' string_list = string.lower().split(' ') for i in range(len(string_list)): if not string_list[i]: continue elif stri...
def test_format(fmt): """ Test the format string with a floating point number :param fmt: string, the format string i.e. "7.4f" :type fmt: str :returns: bool, if valid returns True else returns False :rtype: bool """ try: if fmt.startswith('{') and fmt.endswith('}'): ...
def table_formatter(rows): """Format the rows (a list of col/cell lists) as an HTML table string.""" row_cells = [''.join([f'<td style="font-size: 14px; padding: 20px;">{cell}</td>'for cell in row]) for row in rows] trs = [f'<tr>{cells}</tr>' for cells in row_cells] return f'<table class="lemma-table">{...
def samples_number(session, Type='Int32', RepCap='', AttrID=1150021, buffsize=0, action=['Get', '']): """[Get Number of Samples] Returns the integer number of complex samples that will be available to Get Data or Get Data Block when the measurement completes. """ return session, Type, RepCap, AttrID, bu...
def round_closest(x, base=10): """ Args: x: base: Returns: """ return int(base * round(float(x)/base))
def calc_crc(message_array): """ CRC7 Algorithm, given an array of "bytes" (8-bit numbers) calculate a CRC7. Polynomial: 0x89 @param message_array, array of bytes to calculate a CRC7. """ message_length = len(message_array) * 8 remainder = message_array[0] polynomial = 0x89 # origi...
def hook_makeOutline(VO, blines): """Return (tlines, bnodes, levels) for list of Body lines. blines can also be Vim buffer object. """ tlines, bnodes, levels = [], [], [] tlines_add, bnodes_add, levels_add = tlines.append, bnodes.append, levels.append seen = {} # seen previousely on the command...
def make_readable(val): """ a function that converts bytes to human readable form. returns a string like: 42.31 TB example: your_variable_name = make_readable(value_in_bytes) """ data = float(val) tib = 1024 ** 4 gib = 1024 ** 3 mib = 1024 ** 2 kib = 1024 if data >= tib: ...
def _get_all_techs(postgame, de_data): """Get all techs flag.""" if de_data is not None: return de_data.all_techs if postgame is not None: return postgame.all_techs return None
def is_backend_supported(name: str) -> bool: """Returns if the backend is supported. Args: name: The backend name. Returns: bool """ return name == 's3'
def make_cmd_invocation(invocation, args, kwargs): """ >>> make_cmd_invocation('path/program', ['arg1', 'arg2'], {'darg': 4}) ['./giotto-cmd', '/path/program/arg1/arg2/', '--darg=4'] """ if not invocation.endswith('/'): invocation += '/' if not invocation.startswith('/'): invocat...
def is_6_digits(number: int) -> bool: """It is a six-digit number.""" if len(str(number)) == 6: return True return False
def correct_sentence(text: str) -> str: """ returns a corrected sentence which starts with a capital letter and ends with a dot. """ # your code here if ord(text[0]) >= 97 and ord(text[0]) < 123: text = chr(ord(text[0]) - 32) + text[1:] if text[-1] != ".": text += "."...
def lcs_len(s1, s2): """ return lenght of the lcs of s1 and s2 s1 : sequence , (len = n) s2 : sequence , (len = m) Try to be memory efficient O(n) CPU time O(m.n) Usually faster than computing the full lcs matrix. And generally best algorithm to use if you are only interested in ...
def direct(corpus): """la fonction qui renvoie la liste des phrases issues de la traduction directe""" return [elt for elt in corpus if elt["src_lang"] == elt["orig_lang"]]
def luhn_check(card_number): """ checks to make sure that the card passes a luhn mod-10 checksum """ sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for count in range(0, num_digits): digit = int(card_number[count]) if not ((count & 1) ^ oddeven): digit *...
def roll(s, first, last): """ Determine the variability of a variant by looking at cyclic permutations. Not all cyclic permutations are tested at each time, it is sufficient to check ``aW'' if ``Wa'' matches (with ``a'' a letter, ``W'' a word) when rolling to the left for example. >>> roll(...
def binc(n, k): """binc(n, k): Computes n choose k.""" if (k > n): return 0 if (k < 0): return 0 if (k > int(n/2)): k = n - k rv = 1 for j in range(0, k): rv *= n - j rv /= j + 1 return int(rv)
def _get_id_given_url(original_url: str) -> str: """ Parse id from original URL """ return original_url.replace('https://', 'http://').replace('http://vocab.getty.edu/page/ia/', '')
def RPL_ENDOFWHO(sender, receipient, message): """ Reply Code 315 """ return "<" + sender + ">: " + message
def determine_format(supported): """ Determine the proper format to render :param supported: list of formats that the builder supports :return: Preferred format """ order = ['image/svg+xml', 'application/pdf', 'image/png'] for format in order: if format in supported: retu...
def base_loss_name_normalizer(name: str) -> str: """Normalize the class name of a base BaseLoss.""" return name.lower().replace('loss', '')
def find_all_highest(l, f): """Find all elements x in l where f(x) is maximal""" if len(l) == 1: return l maxvalue = max([f(x) for x in l]) return [x for x in l if f(x) == maxvalue]
def get_safe_name(progname, max_chars = 10): """Get a safe program name""" # Remove special characters for c in r'-[]/\;,><&*:%=+@!#^()|?^': progname = progname.replace(c,'') # Set a program name by default: if len(progname) <= 0: progname = 'Program' # Force the program ...
def prepare_author(obj): """ Make key {author.identifier.id}_{author.identifier.scheme} or {author.identifier.id}_{author.identifier.scheme}_{lot.id} if obj has relatedItem and questionOf != tender or obj has relatedLot than """ base_key = u"{id}_{scheme}".format( sch...
def frequency(tokens: list, seq_len: int = 5) -> dict: """ Counts the frequency of unique sequences in a list of tokens. Returns a dictionary where keys are unique sequences of length 1 to `seq_len` and values are the count of occurences of those sequences in the `tokens` list. Parameters: ...
def is_palindrome(num): """ Returns true if num is a palindrome. """ return str(num) == str(num)[::-1]
def flatten(fields): """Returns a list which is a single level of flattening of the original list.""" flat = [] for field in fields: if isinstance(field, (list, tuple)): flat.extend(field) else: flat.append(field) return flat
def _should_keep_module(name): """Returns True if the module should be retained after sandboxing.""" return (name in ('__builtin__', 'sys', 'codecs', 'encodings', 'site', 'google') or name.startswith('google.') or name.startswith('encodings.') or # Making mysql available is a...
def dictFromPool(fields, pool): """ pool is assumed to be a list of lists, of various lengths, but the same order, where fields are present fields is the fields to check against """ result = {} found = [i for i in pool if i[:len(fields)] == fields] for i in found: if fields == i: continue newField = i[ len(f...
def make_test_config(contexts, clusters, users, current_context): """ Return a KubeConfig dict constructed with the given info All parameters are required. """ return { 'apiVersion': 'v1', 'kind': 'Config', 'clusters': [{'name': key, 'cluster': value} for key, value in clusters....
def convert_km_to_length(length): """Convert length like '1' to 1000 or '30M' to 30""" try: if length[-1:] == "M": t_length = int(length[:-1]) # Trim off the 'M' else: t_length = int(float(length) * 1000) # Convert to meters length_str = str(t_length) exc...
def is_bidirectional_conversion(letter_id, letter_case, reverse_letter_case): """ Check that two unicode value are also a mapping value of each other. :param letter_id: An integer, representing the unicode code point of the character. :param other_case_mapping: Comparable case mapping table which ...
def python2js(d): """Return a string representation of a python dictionary in ecmascript object syntax.""" objs = [] for key, value in d.items(): objs.append( key + ':' + str(value) ) return '{' + ', '.join(objs) + '}'
def get_fewest_steps(pts1, pts2, intersections): """Returns the minimum number of steps required to get to an intersection point between the two paths. Args: pts1: the list of points along the first path pts2: the list of points along the second path intersections: the list of point...
def validate_alignments(item, base_chars='()-'): """Simple validator for alignments Note ---- Make sure an alignment is not longer than its segments. """ for alm in ['Alignment']: derived_alignment = [x for x in item[alm] if x not in '()-'] if len(derived_alignment) != len(item[...
def normalize_matrix1D(lst): """ Normalizes a given 1 dimensional list. :param lst: list of items :return: normalized list """ max_val = max(lst) if max_val == 0: return lst else: norm_list = list() for val in lst: norm_list.append(val / max_val) ...
def collapse(values): """Collapse multiple values to a colon-separated list of values""" if isinstance(values, str): return values if values is None: return "all" if isinstance(values, list): return ";".join([collapse(v) for v in values]) return str(values)
def filterRssData(bssid_data, rss_data, keys, minimum_rss_value=-95): """ Filter the rss data by using pre-selected bssids. Args: bssid_data: list of strings with each representing bssid of different access point rss_data: list of integers with each representing signal strength from dif...
def hex_to_rgb(hex_color): """ Fungsi ini menerima inputan berupa string hexadecimal dan mengembalikan hasilnya dalam bentuk tuple (r, g, b). Alur proses: * Deklarasi variabel `hex_string` dengan nilai `hex_color` yang telah di bersihkan dari tanda #. * Mengecek apakah panjang string `h...
def binary_search(values, target): """ :param values: :param target: :return: """ left, right = 0, len(values) - 1 while left <= right: mid = int((left + right) / 2) if target < values[mid]: right = mid - 1 elif target > values[mid]: left =...
def remove_duplicates(items): """Recieve list and return list without duplicated elements""" return list(set(items))
def emitlist(argslist): """Return blocks of code as a string.""" return "\n".join([str(x) for x in argslist if len(str(x)) > 0])
def fn_range(fn): """In : fn (function : dict) Out: range of function (list of values of dict) """ return [v for v in fn.values()]
def scol(string, i): """Get column number of ``string[i]`` in `string`. :Returns: column, starting at 1 (but may be <1 if i<0) :Note: This works for text-strings with ``\\n`` or ``\\r\\n``. """ return i - string.rfind('\n', 0, max(0, i))
def cvsecs(*args): """ converts a time to second. Either cvsecs(min, secs) or cvsecs(hours, mins, secs). """ if len(args) == 1: return float(args[0]) elif len(args) == 2: return 60 * float(args[0]) + float(args[1]) elif len(args) == 3: return 3600 * float(args[0]) + 60 * ...
def likes(names): """ You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item. Implement a function likes :: [String] -> String, which must take in input array, cont...
def extract_doi(doi): """Ensure that 'doi' is a single string Occasionally, INSPIRE returns a list of identical DOIs. This just extracts the first element if it is such a list, or returns the input otherwise. """ if isinstance(doi, list) and len(doi)>0: return doi[0] return doi
def numericise(value, empty_value=''): """Returns a value that depends on the input string: - Float if input can be converted to Float - Integer if input can be converted to integer - Zero if the input string is empty and empty2zero flag is set - The same input string, empty or not, ...
def B_supp(n, s=1, dx=0, intsupp=False): """ Returns a min and max value of the domain on which the 1D cardinal B-spline of order n is non-zero. INPUT: - degree n, an integer INPUT (optional): - scale s, a real scalar number. Specifies the support of scaled B-splines...
def consistent_typical_range_stations(stations): """ returns the stations that have consistent typical range data Inputs ------ stations: list of MonitoringStation objects Returns ------ a list of stations that have consistent typical range data """ consistent_station_list = [...
def snake2camel( s ): """ Switch string s from snake_form_naming to CamelCase """ return ''.join( word.title() for word in s.split( '_' ) )
def runge_step(f, xk, yk, h, *args): """ completes a single step of the runge cutter method (K4) ---------- Parameters ---------- f: callable differential equation to solve xk: float x ordinate for step start tk: float y ordinate for step start h: float step size ---------- ...
def parseUpdatedEntity(entityLine): """ parse entity line """ result = entityLine.split() #entity_ID = result[0]+'_'+result[1] entity_name = result[1] #particle = '-' #particle = 'GenericParticle' if len(result) == 3: attributes = result[2] #attributes = attributes.lower() ...
def resolve_variables(template_configuration: dict) -> dict: """ The first step of the lifecycle is to collect the variables provided in the configuration. This will add the name and value of each variable to the run-configuration. :param template_configuration: :return: """ run_configurat...
def byte_to_str_index(string, byte_index): """Converts a byte index in the UTF-8 string into a codepoint index. If the index falls inside of a codepoint unit, it will be rounded down. """ for idx, char in enumerate(string): char_size = len(char.encode('utf-8')) if char_size > byte_index...
def is_same_dictionary(a, b): """Shallow dictionary comparison""" keysA = set(a.keys()) keysB = set(b.keys()) sharedKeys = keysA & keysB if len(keysA) != len(keysB) or len(sharedKeys) != len(keysB): return False for k, v in a.items(): if b[k] != v: return False re...
def twos_comp(val, bits=32): """compute the 2's complement of int value val from https://stackoverflow.com/questions/1604464/twos-complement-in-python""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val
def huffman_decoding(data, tree): """ Decode Huffman code Parameters: data (str): string of bits Returns: decoded (str): decoded data in original form """ current = tree decoded = "" for bit in data: if bit == '0': current = current.left_child ...
def _image_type(typestr): """Return the translation of CRDS fuzzy type name `typestr` into numpy dtype str() prefixes. If CRDS has no definition for `typestr`, return it unchanged. """ return { 'COMPLEX':'complex', 'INT' : 'int', 'INTEGER' : 'int', 'FLOAT' : 'float', ...
def is_valid(var, var_type, list_type=None): """ Check that the var is of a certain type. If type is list and list_type is specified, checks that the list contains list_type. Parameters ---------- var: any type Variable to be checked. var_type: type Type the variable is...
def is_multiline(s): """Returns True if the string contains more than one line. This tends to perform much better than len(s.splitlines()) or s.count('\n') :param s: string to check :return: Bool """ start = 0 lines = 1 while True: idx = s.find('\n', start) if idx == -1...
def set_defaults(data: dict) -> dict: """Set default values for data if missing.""" # Set tuning as default if "tuning" not in data: data.update({"tuning": True}) # Set int8 as default requested precision if "precision" not in data: data.update({"precision": "int8"}) if not dat...
def clamp(value, minimum, maximum): """Clamp value within a range - range doesn't need to be ordered""" if minimum > maximum: minimum, maximum = maximum, minimum if value < minimum: return minimum if value > maximum: return maximum return value
def exposure_time(vmag, counts, iodine=False, t1=110., v1=8., exp1=250., iodine_factor=0.7): """ Expected exposure time based on the scaling from a canonical exposure time of 110s to get to 250k on 8th mag star with the iodine cell in the light path Parameters ---------- expcounts : flo...
def async_wm2_to_lx(value: float) -> int: """Calculate illuminance (in lux).""" return round(value / 0.0079)
def get_year(born_txt): """ input: a list of string output: 'yyyy' or '' """ for i in range(len(born_txt)): words = born_txt[i].split() for word in words: if len(word) == 4 and word.isnumeric(): return word if len(word) == 9 and word[4] == '/' ...
def calculate_crc16(buffer): """ Calculate the CRC16 value of a buffer. Should match the firmware version :param buffer: byte array or list of 8 bit integers :return: a 16 bit unsigned integer crc result """ result = 0 for b in buffer: data = int(b) ^ (result & 0xFF) data = ...
def unique(lst): """Unique with keeping sort/order ["a", "c", "b", "c", "c", ["d", "e"]] Results in ["a", "c", "b", "d", "e"] """ nl = [] [(nl.append(e) if type(e) is not list else nl.extend(e)) \ for e in lst if e not in nl] return nl
def powers(n, k): """Computes and returns a list of n to the powers 0 through k.""" n_pows = [] for i in range(k+1): n_pows.append(n**i) return n_pows
def setdiff(list1, list2): """ returns list1 elements that are not in list2. preserves order of list1 Args: list1 (list): list2 (list): Returns: list: new_list Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool ...
def fib(n: int): """fibonacci""" if n < 2: return n return fib(n - 1) + fib(n - 2)
def kps_to_BB(kps,imgW,imgH): """ Determine imgaug bounding box from imgaug keypoints """ extend=1 # To make the bounding box a little bit bigger kpsx=[kp[0] for kp in kps] xmin=max(0,int(min(kpsx)-extend)) xmax=min(imgW,int(max(kpsx)+extend)) kpsy=[kp[1] for kp in kps] ...
def bytesToNumber(b): """ Restoring the stripped bytes of an int or long into Python's built-in data types int or long. """ result = 0 round = 0 for byte in b: round += 1 if round > 1: result <<= 8 result |= byte return result
def dh(d, theta, a, alpha): """ Calcular la matriz de transformacion homogenea asociada con los parametros de Denavit-Hartenberg. Los valores d, theta, a, alpha son escalares. """ T = 0 return T
def nested_to_dotted(data): """ Change a nested dictionary to one with dot-separated keys This is for working with the weird YAML1.0 format expected by ORBSLAM config files :param data: :return: """ result = {} for key, value in data.items(): if isinstance(value, dict): ...
def html(html_data): """ Builds a raw HTML element. Provides a way to directly display some HTML. Args: html_data: The HTML to display Returns: A dictionary with the metadata specifying that it is to be rendered directly as HTML """ html_el = { 'Type': ...
def killwhitespace(string): """ Merge consecutive spaces into one space. """ return " ".join(s.strip() for s in string.split())
def get_thousands_string(f): """ Get a nice string representation of a field of 1000's of NIS, which is int or None. """ if f is None: return "N/A" elif f == 0: return "0 NIS" else: return "%d000 NIS" % f
def percent_to_zwave_position(value: int) -> int: """Convert position in 0-100 scale to 0-99 scale. `value` -- (int) Position byte value from 0-100. """ if value > 0: return max(1, round((value / 100) * 99)) return 0
def safenum(v): """Return v as an int if possible, then as a float, otherwise return it as is""" try: return int(v) except (ValueError, TypeError): pass try: return float(v) except (ValueError, TypeError): pass return v
def dx_to_wes_state(dx_state): """Convert the state returned by DNAnexus to something from the list of states defined by WES. """ if dx_state in ("running", "waiting_on_input", "waiting_on_output"): return "RUNNING" elif dx_state == "runnable": return "QUEUED" elif dx_state in (...
def other_heuristic(text, param_vals): """ Post-processing heuristic to handle the word "other" """ if ' other ' not in text and ' another ' not in text: return text target_keys = { '<Z>', '<C>', '<M>', '<S>', '<Z2>', '<C2>', '<M2>', '<S2>', } if param_vals.keys() != target_keys: return...
def get_loss_gradients(model, loss_blobs): """Generate a gradient of 1 for each loss specified in 'loss_blobs'""" loss_gradients = {} for b in loss_blobs: loss_grad = model.net.ConstantFill(b, [b + '_grad'], value=1.0) loss_gradients[str(b)] = str(loss_grad) return loss_gradients
def render_dusk(data, query, local_time_of): """dusk (d) Local time of dusk""" return local_time_of("dusk")
def reversemap(obj): """ Invert mapping object preserving type and ordering. """ return obj.__class__(reversed(item) for item in obj.items())
def str_confirmacao(value): # Only one argument. """Converts a string into all lowercase""" if(value == 0): return "Nao Confirmada" else: return "Reservado"
def blender_id_endpoint(endpoint_path=None): """Gets the endpoint for the authentication API. If the BLENDER_ID_ENDPOINT env variable is defined, it's possible to override the (default) production address. """ import os import urllib.parse base_url = os.environ.get('BLENDER_ID_ENDPOINT', 'https...
def sum_cubes(n): """Sum the first N cubes of natural numbers. """ total, k = 0\ , 1 while k <= n: total, k = total + pow(k, 3), k + 1 return total
def mechanism_thermo(mech1_thermo_dct, mech2_thermo_dct): """ Combine together the thermo dictionaries for two mechanisms. :param mech1_thermo_dct: thermo dct for mechanism 1 :type mech1_thermo_dct: dict[spc: [[H(t)], [Cp(T)], [S(T)], [G(T)]] :param mech2_thermo_dct: thermo dct for mechanis...
def which_one_in(l, f): """ returns which one element of list l is in f, otherwise None """ included = [i for i in l if str(i) in f] if len(included) == 1: return included[0] elif len(included) > 1: return False else: return None
def sizeof_fmt(mem_usage: float, suffix: str = 'B') -> str: """ Returns the memory usage calculation of the last function. Parameters ---------- mem_usage : float memory usage in bytes suffix: string, optional suffix of the unit, by default 'B' Returns ------- str ...
def get_float_value(obj): """ Returns float from LLDB value. :param lldb.SBValue obj: LLDB value object. :return: float from LLDB value. :rtype: float | None """ if obj: value = obj.GetValue() return None if value is None else float(value) return None
def make_iscorr(row, prediction_col_name='predictions', answer_col_name='answer'): """Calculates accuracy @3.""" if bool(set(row[answer_col_name]) & set(row[prediction_col_name])): return 1 else: return 0
def execute_code_if(condition, code, glob=None, loc=None): """ Execute code if condition is true Args: condition (bool): if true the code is executed code_if_obj_not_found (str): the code to be evaluated if the object has not been found. globals (dict): the global varia...
def create_account(caller): """Create a new account. This node simply prompts the user to enter a username. The input is redirected to 'create_username'. """ text = "Enter your new account's name." options = ( { "key": "_default", "desc": "Enter your new usernam...
def custom_division(numerator: int, denominator: int) -> int: """ Works only if both integers are +ve """ while numerator > denominator: numerator -= denominator return numerator
def MergeStyles(styles1, styles2): """Merges the styles from styles2 into styles1 overwriting any duplicate values already set in styles1 with the new data from styles2. @param styles1: dictionary of StyleItems to receive merge @param styles2: dictionary of StyleItems to merge from @return: styl...
def format_errors(errors, config): """Format errors for output to console.""" if config['debug']: return str(errors) else: formatted = {} for key, error in errors.items(): formatted[key] = error['message'] return str(formatted)
def factorize(distri, binlength): """ Helper function for createHisto. """ INTarea = 0 for ns in distri: INTarea += ns * float(binlength) return INTarea