content
stringlengths
42
6.51k
def time_to_ssmmm(time_value): """ Format the given time value into a ``SS.mmm`` string. Examples: :: 12 => 12.000 12.345 => 12.345 12.345432 => 12.345 12.345678 => 12.346 :param float time_value: a time value, in seconds :rtype: string """ if tim...
def _replace_semicolons(s): """Replaces matlab semicolons with nothing in string s.""" s = s.replace(';', '') return s
def sanitizex(board, way): """ Function used to de-zero a list and append zeros in a horizontal axis in right or left """ cache=[] result=[ [], [], [], [] ] for i in range(len(board)): for j in range(len(board)): if(board[i][j] != 0): ...
def get_answer_texts( questions,): """Get all answer texts.""" answers = set() def get_answers(question, answer): if not answer.answer_texts: raise ValueError(f"Question without answer: {question}") answer_texts = tuple(sorted(answer.answer_texts)) answers.add(answer_texts) for question ...
def default_if_none( object_argument, default_type, function ): """ Returns a defualt for an expected type, else runs a function with the given object as an argument """ if object_argument is None: if default_type == str: return "" return function(object_argument)
def is_consonant(letter): """Return True if the letter is a consonant, False otherwise >>> is_consonant("a") False >>> is_consonant("b") True """ return letter in "bcdfghjklmnpqrstvwxyz"
def timy_checksum(msg): """Return the character sum for the Timy message string.""" ret = 0 for ch in msg: ret = ret + ord(ch) return ret & 0xff
def _tensor_name(node_name): """Appends the :0 in the op name to get the canonical tensor name.""" if ':' in node_name: return node_name return node_name + ':0'
def collect_uppercase_chars(text): """Given string, collect only uppercase characters""" return [1 for c in text if c.isupper()]
def set_verbose_level(level, quiet=False): """ Set the different verbosity level. Args: level (int): Level number to be set-. Kwargs: quiet (bool): If it should be quiet. Returns: str. The return values:: ERROR -- 0 WARNING -- 1 INFO ...
def invert_tree_recursive(root): """ Invert binary tree :param root: root node :type root: TreeNode :return: root node of inverted tree :rtype: TreeNode """ # basic case if root is None: return None root.left, root.right = invert_tree_recursive(root.right), invert_tree_...
def get_mediafiles(obs_id, mediafile, keys): """Create list for each of the comment in the observation. Parameters: obs_id: int observation unique identifier number mediafile: dic contains all the observation for a category keys: list key which repres...
def rfind_nth(s, sub, n, start=0, end=float('inf')): """ Get the index of the nth-last occurrence of a substring within a string Args: s (:obj:`str`): string to search sub (:obj:`str`): substring to search for n (:obj:`int`): number of occurence to find the position of start (:o...
def map_numbers(input_num, old_min, old_max, new_min, new_max): """ Linear Conversion between ranges used for normalization http://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio """ old_value = float(input_num) old_min = float(old_min) old_max =...
def getValuesInRange(x, dx, minx, maxx): """Find x1, x2, obeying certain conditions The conditions are * 0 <= x0 <= x <= x1 <= maxx * x0 + dx == x1 """ d2 = int(dx / 2.) x0 = max(x - d2, minx) x1 = min(x + dx, maxx) x0 = x1 - dx return x0, x1
def _GetComponentName(path): """Return the component name of a path.""" host_dirs = [ 'src/chrome/browser/resources/', 'src/chrome/test/data/layout_tests/', 'src/media/', 'src/sdch/', 'src/testing/', 'src/third_party/WebKit/', 'src/third_party/', 'src/tools/', '...
def _grompp_str(root, op_name, gro_name, sys_name): """Helper function, returns grompp command string for operation """ cmd = ( "gmx grompp -f {root}/src/util/mdp_files/{op}.mdp -c {gro}.gro " "-p {sys}.top -o {op}.tpr" ) return cmd.format(root=root, op=op_name, gro=gro_name, sys=sys_nam...
def has_number(input_str): """Returns true if input_str contains any numbers.""" return any(char.isdigit() for char in input_str)
def _xor(a,b): """Return true iff exactly one of and b are true. Used to check some conditions.""" return bool(a) ^ bool(b)
def changed_files(old_status, new_status): """ Returns a list of files that are either new or have been modified. """ new_files = set(new_status.keys()).difference(set(old_status.keys())) common_files = set(new_status.keys()).intersection(set(old_status.keys())) changed = list(new_files) for f in c...
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 arg list, so you can delay execution by putting it in a lambda. Ex: if_(2 + 2...
def reverse_string(s): """ Write a function that takes a string as input and returns the string reversed. :param s: string :return: string """ r = list(s) i, j = 0, len(r) - 1 while i < j: r[i], r[j] = r[j], r[i] i += 1 j -= 1 return "".join(r)
def geologic_color_map(aquifers): """Map the aquifer codes to colors. This mapping of colors is based on the recommendations of numerous geologists and academics. Parameters ---------- aquifers : list List of four-character aquifer abbreviation strings, as defined in Minnesota ...
def invert_permutation(perm): """Implement `invert_permutation`.""" return tuple(perm.index(i) for i in range(len(perm)))
def compromised(targets): """ Filter list of targets to return only those marked as compromised. **Parameters** ``targets`` List of dictionary objects (JSON) for targets """ filtered_targets = [] for target in targets: if target["compromised"]: filtered_targets....
def convert_sec_to_time(duration_in_sec: float): """converts time in seconds to HH:MM:SS Args: duration_in_sec (float): duration in seconds Returns: (str): the time in the format: HH:MM:SS """ hours = int(duration_in_sec/3600) remainder = duration_in_sec%3600 minutes = int(...
def tamper(payload, **kwargs): """ Appends encoded NULL byte character at the end of payload Requirement: * Microsoft Access Notes: * Useful to bypass weak web application firewalls when the back-end database management system is Microsoft Access - further uses are ...
def secs2time(secs): """Converts integer number of seconds to a time string of format hh:mm:ss.""" h = secs//(60*60) m = (secs-h*60*60)//60 s = secs-(h*60*60)-(m*60) x = [ h, m, s ] for i in range(len(x)): if x[i] < 10: x[i] = '0' + str(x[i]) x[i] = str(x[i]) retu...
def given_variables(context): """Return a list of variables using in given steps.""" return {key for values in context.get("_given", {}).values() for key in values}
def __Calc_HSL_to_RGB_Components(var_q, var_p, C): """ This is used in HSL_to_RGB conversions on R, G, and B. """ if C < 0: C += 1.0 if C > 1: C -= 1.0 # Computing C of vector (Color R, Color G, Color B) if C < (1.0 / 6.0): return var_p + ((var_q - var_p) * 6.0 * C) ...
def splitdrive(p): """Split a pathname into drive and path. On Posix, drive is always empty.""" return p[:0], p
def skip_space(pos, line): """Skip a (possibly empty) sequence of space characters (the ASCII character '\x20' exactly). Returns a pair (pos, num_skipped).""" begin = pos while pos < len(line) and line[pos] == "\x20": pos += 1 return pos, pos - begin
def is_p2pk(script: bytes) -> bool: """ Determine whether a script is a P2PK output script. :param script: The script :returns: Whether the script is a P2PK output script """ return (len(script) == 35 or len(script) == 67) and (script[0] == 0x21 or script[0] == 0x41) and script[-1] == 0xac
def pretty_fw_version( fw_version_as_string ): """ :return: a version with leading zeros removed, so as to be a little easier to read """ return '.'.join( [str(int(c)) for c in fw_version_as_string.split( '.' )] )
def table2coords(seg_table): """Return x, y arrays for plotting.""" x = [] y = [] for start, size, val in seg_table: x.append(start) x.append(start + size) y.append(val) y.append(val) return x, y
def flipHit(hit): """Returns a new hit where query and subject are flipped""" return [hit[1], # 0. Query id, hit[0], # 1. Subject id, hit[2], # 2. % identity, hit[3], # 3. alignment length, hit[4], # 4. mismatches, hit[5], # 5. gap op...
def nCk(n, k): """Simple binomial function, so we don't have to import anything""" from operator import mul # or mul=lambda x,y:x*y from fractions import Fraction from functools import reduce return int(reduce(mul, (Fraction(n - i, i + 1) for i in range(k)), 1))
def get_weekday_word(number): """ Using weekday index return its word representation :param number: number of weekday [0..6] :return: word representation """ weekdays = ( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', '...
def _update_output_error(error=None): """Return error mapping for output *context*.""" if error is not None: config, exception = error message = "Output Template configuration contains an error [{}]".format(config.id) return { "message": message, "details": ( ...
def extends_dict(target, source): """ Will copy every key and value of source in target if key is not present in target """ for key, value in source.items(): if key not in target: target[key] = value elif type(target[key]) is dict: extends_dict(target[key], value) ...
def calculate_score(cards): """Take a list of cards and return score calculated from the cards""" if sum(cards)==21 and len(cards)==2: return 0 if 11 in cards and sum(cards)>21: cards.remove(11) cards.append(1) return sum(cards)
def assert_fraction_is_big_enough(fraction: float, size: int, verbose: bool) -> bool: """tests that the fraction is bigger than the smallest fraction possible with that size to get at least one example in splitting""" calculation_inaccuracy = 10e-5 min_frac = 1 / size y = min(fraction, 1 - fraction) if y + ca...
def is_relative(fname): """ Returns True for leading '/', False else """ if str(fname) and (str(fname)[0] != "/"): return True return False
def mapDataTypesCP(valueFormatUrl): """ Convert meta data descriptor to numerical descriptor :param valueFormatUrl = full url to the description example: https://meta.icos-cp.eu/ontologies/cpmeta/float32 return: numerical descriptor to build schema to send a post request for...
def forward_chain(rules, data, apply_only_one=False, verbose=False): """ Apply a list of IF-expressions (rules) through a set of data in order. Return the modified data set that results from the rules. Set apply_only_one=True to get the behavior we describe in class. When it's False, a...
def multiplier(t_diff): """ Args: a scalar, difference in time (unit in second) Return: a scalar, a multiplication coefficient """ if t_diff<=30*60: return 1 elif t_diff<=180*60: return 5 elif t_diff<=1080*60: return 10 else: return 50
def sequence_accuracy(hypotheses, references): """ Compute the accuracy of hypothesis tokens: correct tokens / all tokens Tokens are correct if they appear in the same position in the reference. :param hypotheses: list of hypotheses (strings) :param references: list of references (strings) :ret...
def validar_cpf(cpf): """ Valida CPFs """ def calcula_dv1(_cpf): start = 10 cpf_list = [int(i) for i in _cpf] soma = 0 for i in cpf_list[:-2]: val = i * start soma += val start -= 1 resto = soma % 11 _dv1 = 11 - resto ...
def get_shortest(location, coins_list, remaining_coins): """ Return the nearest remaining_coins from location""" dists_list = coins_list[location] min_dist = float('inf') min_loc = (0, 0) for loc in remaining_coins: if dists_list[loc] < min_dist: min_dist = dists_list[loc] ...
def int_to_hex_string(integer): """Converts an integer to an hex string with at least a length of 4, e.g. 255 to '00FF'. """ return hex(integer)[2:].upper().zfill(4)
def camel_case(text, sep=None): """Convert to camel case. Convert *text* to camel case. Use the *sep* keyword to specify the word separator. The default is to split on whitespace. >>> from landlab.framework.decorators import camel_case >>> camel_case("eric idle") 'EricIdle' >>> camel_case(...
def grvi(b3, b4): """ Green-Red Vegetation Index (Tucker, 1979). .. math:: GRVI = (b3 - b4)/(b3 + b4) :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :returns GRVI: Index value .. Tip:: Tucker, C.J. 1979. Red and photog...
def get_ocw_department_list(course_json): """ Get list of OCW department numbers Args: course_json (dict): The raw json for the course Returns: List of string department identifiers """ departments = [course_json.get("department_number")] for extra_course_number_json in cou...
def validate_usid_id(usid_id): """ Validate a uSID identifier. A valid uSID id should be an integer in the range (0, 0xffff). :param usid_id: uSID idenfier to validate. :type usid_id: str :return: True if the uSID identifier is valid. :rtype: bool """ try: # A valid uSID id ...
def isNestedInstance(obj, cl): """ test is an object is an instance of a deep subclass """ tree = [] for k in cl.__subclasses__(): tree+=k.__subclasses__() tree += cl.__subclasses__() + [ cl ] print(tree) return issubclass(obj.__class__, tuple(tree))
def is_in_structure(key_to_search, value_to_search, structure): """Recursive function checking structures made of nested dictionaries and lists if they contain specific key having a specific value""" if isinstance(structure, dict): if key_to_search in structure: value = structure.get(key_to_...
def drop_at(nth, xs): """ Drop nth element in a list. Returns the init and tail of the xs without the nth element. """ if nth <= 0: return [], xs elif len(xs) < nth: return xs, [] return xs[: nth - 1], xs[nth:]
def get_mask(size: int) -> int: """ Get bit mask based on byte size. :param size: number of bytes to obtain mask for :return: mask of width size """ return (1 << (8 * size)) - 1
def closestValue(aList: list, givenV: int): """ Return the nearest value to a given one in a list. """ abs_diff = lambda list_value: abs(list_value - givenV) return min(aList, key=abs_diff)
def rotate (angles, obj): """ Function rotate return openscad rotate command @param angles: [x, y, z] angles matrix @param obj: text object to translate """ return "rotate({}){{{}}}".format(angles, obj)
def get_list_parameter(val, n_elements, n_repeater=None): """ create a list of parameters with n_elements form a list or a scalar In case val is a scalar or has len 1 the value is duplicated n_elements times In case val is of len n_elements//n_repeater each of its elements will be repeated n_repeater t...
def uncertainty(x): """ Return the standard uncertainty If ``x`` is an uncertain complex number, return a 2-element sequence containing the standard uncertainties of the real and imaginary components. If ``x`` is an uncertain real number, return the standard uncertainty. Othe...
def getArtists(tracks): """ Returns distinct artists names from the specified tracks. The names are sorted alphabetically. Tracks is expected to be an [] of Track Result example: [artistName1, artistName2, ...] """ artists = [] if tracks: for track in tracks: artis...
def fission_processes_to_rates(process_list): """ Define linear fission processes between compartments. Parameters ========== process_list : :obj:`list` of :obj:`tuple` A list of tuples that contains fission rates in the following format: .. code:: python [ ...
def build_tokens_types_paddings_from_ids(text_a_ids, text_b_ids, max_seq_length, cls_id, sep_id, pad_id): """Build token types and paddings, trim if needed, and pad if needed.""" ids = [] types = [] paddings = [] # [CLS]. ids.append(cls_id) types.ap...
def _find_reserved_periods(events, quantity, capacity): """Find the reserved periods.""" reserved_periods = [] used = 0 reserved_start = None for event_date in sorted(events): used += events[event_date]['quantity'] if not reserved_start and used + quantity > capacity: res...
def get_scene(videoname_): """Get the scene camera from the ActEV videoname.""" s = videoname_.split("_S_")[-1] s = s.split("_")[0] return s[:4]
def capitalized(s): """Return a string with its first character capitalized.""" if not s: return s return s[0].upper() + s[1:]
def istype(type, *obj): """ Returns whether or not all the inputs are of the specified type Parameters ---------- type : type the type to check against to *obj : object... a sequence of objects Returns ------- bool True if the inputs are of the specified typ...
def fofx (x): """ fofx (): return value of a piecewise discontinuous function """ x0=953.155e3 x1=956.0e3 x2=957.0e3 x3=957.2e3 (x3cad,y3cad) = (957738.41,1844520.82) (x4cad,y4cad)= (957987.1, 1844566.5) x4=958.15e3 x5=959.640e3 y1=1844.5e3 y2=1843.6e3 y3...
def lsr(value, count, width=32): """Logical Shift Right""" count %= width value &= (1 << width) - 1 # First shift 1 to the left to leave room for the carry. value <<= 1 value >>= count carry = value & 1 value >>= 1 return carry, value
def _decodeASCII(string): """Returns an ASCII decoded version of the null terminated string. Non ASCII characters are ignored.""" return str(string.decode("ascii", "ignore").split("\0", 1)[0])
def _end_of_set_index(string, start_index): """ Returns the position of the appropriate closing bracket for a glob set in string. :param string: Glob string with wildcards :param start_index: Index at which the set starts, meaning the position right behind the opening b...
def flat_config(config): """Flat config loaded from a yaml file to a flat dict. Args: config (dict): Configuration loaded from a yaml file. Returns: dict: Configuration dictionary. """ f_config = {} category = config.keys() for cate in category: for key, val in conf...
def get_product_from_prokka_fasta_header(fasta_header: str) -> str: """ Grabs the gene portion of a .ffn or .faa fasta header """ contig, delim, product = fasta_header.partition(" ") return product
def _parse_volumes_param(volumes): """Parse volumes details for Docker containers from blueprint Takes in a list of dicts that contains Docker volume info and transforms them into docker-py compliant (unflattened) data structures. Look for the `volumes` parameters under the `run` method on [this pa...
def pairs_to_annotations(annotation_pairs): """ Convert an array of annotations pairs to annotation array. :param annotation_pairs: list(AnnotationPair) - annotations :return: list(Annotation) """ annotations = [] for ap in annotation_pairs: if ap.ann1 is not None: annota...
def parse_progress_identifier(identifier): """ >>> parse_progress_identifier('') None >>> parse_progress_identifier('0-1') [(0, 1)] >>> parse_progress_identifier('0-1|2-4') [(0, 1), (2, 4)] """ if not identifier: return None levels = [] for level in identifier.split('...
def re(inputStr): """ Reverse the string. (e.g. re('hello') -> olleh) """ inputList = list(str(inputStr)) inputList.reverse() return "".join(inputList)
def asymnet(netext, asym=None): """Whether the network is asymmetric (directed, specified by arcs rather than edges) Note: file extension based value overwrites asym parameter for the known extensions netext - network extension (starts with '.'): .nse or .nsa asym - whether the network is asymmetric (directed), ...
def _format_bool(b: bool) -> str: """ bool to string compatible with C#. :param b: bool to format. :return: stringified b. """ return "true" if b else "false"
def truthy(val): """Turn a one or zero value into a boolean. """ return bool(int(val))
def edgelist_for_workflow_steps( steps ): """ Create a list of tuples representing edges between ``WorkflowSteps`` based on associated ``WorkflowStepConnection``s """ edges = [] steps_to_index = dict( ( step, i ) for i, step in enumerate( steps ) ) for step in steps: edges.append( ( ...
def reduce_scenes(scenes): """Windows terminal can't handle more than ~500 scenes in length.""" count = len(scenes) interval = int(count / 500 + (count % 500 > 0)) scenes = scenes[::interval] return scenes
def _rhex(byte): """converts bytecode to hex, while reading from right to left""" rhex = byte[::-1].hex() return (rhex)
def get_ids(cls, inherit=None): """Function that returns all the IDs to use as primary key For a given class, this function will check for the _ids parameter and call itself recursively on the given class' base classes to append all other required IDs, thus generating the list of parameters to use as ...
def abbreviate(string): """Abbreviates dot-delimited string to the final (RHS) term""" return string.split(".")[-1]
def build_ctg_header(module_name, module_number): """Creates the first line of a module given the name and module number""" result = "|".join( [ f"{module_name}:[module_num:{module_number}", "svn_version:\\'Unknown\\'", "variable_revision_number:4", ...
def hamdist(str1, str2): """Count the # of differences between equal-length strings str1 and str2""" diffs = 0 for ch1, ch2 in zip(str1, str2): if ch1 != ch2: diffs += 1 return diffs
def factorial(n): """ This function returns the factorial of n (denoted n!) Input: n (number to compute the factorial of) Returns: value of n factorial Doctests: >>> factorial(3) 6 >>> factorial(1) 1 >>> factorial(0) 1 """ result = 1 for i in range(1...
def group_coding(dementia_status): """ Determines the level of agreement between the OASIS data set's classification of dementia versus the current study's (see function 'new_mmse_group'). """ if dementia_status == 'Nondemented': return 0 elif dementia_status == 'Intact': return ...
def _evaluate_usecols(usecols, names): """ Check whether or not the 'usecols' parameter is a callable. If so, enumerates the 'names' parameter and returns a set of indices for each entry in 'names' that evaluates to True. If not a callable, returns 'usecols'. """ if callable(usecols): ...
def extract_labels(trainingData): """product an array of truth labels for the genres""" return [y["truth"]["polarity"] for y in trainingData]
def hex2rgb(hex): """ method will convert given hex color (#00AAFF) to a rgb tuple (R, G, B) """ h = hex.strip('#') return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
def _compute_lcs_elements(trace, x, y): """ Compute the elements of a LCS given a pre-computed trace table. In this table, the key is (i, j) coordinate drawn from x and y, and the value is: - 'd': goes diagonal. - 'u': goes up. - 'l': goes left. :param trace: dict. A trace table. :para...
def step_schedule_with_warmup(epoch, step_size, warmup_epochs=0, hold_max_epochs=0, lr_start=1e-4, lr_max=1e-3, step_decay=.5): """ Create a schedule with a step decrease preceded by a warmup period during which the learning rate increases linearly between {lr_start} and {lr_max}. """ if epoch < wa...
def mean(numbers, as_decimal=False): """ compute mean """ if sum([float(x) for x in numbers]) > 0: m = (sum(numbers)) / max(len(numbers), 1) return m else: return 0
def _findfirststart(starts, names): """ Find first elements in names that begin with elements of starts Example ------- >>> hout = _findfirststart(['TA', 'LE'], ['TIMESTAMP', 'TAU_1_1_1', 'H_1_1_1', 'LE_1_1_1', ...
def _filter_country_region(postcode_data): """Filter down to just country and region data""" return { "postcode": postcode_data.get('postcode', ''), "country": postcode_data.get('country', 'Unknown'), "region": postcode_data.get('region', 'Unknown'), }
def average(entry): """providing average time for an individidual test.""" return entry['total time (s)'] / float(entry['correct answers'] + entry['wrong answers'])