content
stringlengths
42
6.51k
def compara_edades(edad1, edad2): """ (int, int) -> str Genera un mensaje segun la diferencia de edad: la primera o la segunda mas joven o iguales >>> compara_edades(10, 20) 'El primero es mas joven' >>> compara_edades(89, 56) 'El segundo es mas joven' >>> compara_edades(56, 56) ...
def check_if_point_in_extents(point,extents): """check if a 2D point lies within the bounding box extents = (xmin,ymin,xmax,ymax) returns: boolean""" if (point[0]>=extents[0]) & (point[0]<=extents[2]) & \ (point[1]>=extents[1]) & (point[1]<=extents[3]): return True else: return False return
def add_service(logger, method_name, event_dict): # pylint: disable=unused-argument """ Add the service name to the event dict. """ event_dict["service"] = "eq-questionnaire-runner" return event_dict
def dict_builder(data: dict) -> dict: """function for building dict of parsed data Args: data (dict): parse data Returns: dict: builded dict """ try: pageviews = data['stats']['pageviews'] except KeyError: pageviews = None return {'title': data['title'], 'a...
def kinematic_viscosity(mu, rho): """ Calculates kinematic viscosity of a fluid. Input variables: T : Thermal conductivity rho : Fluid density C_p : Specific heat capacity """ nu = mu / rho return nu
def valid_template_page(title): """ Only edit certain template pages. An "opt-in" for the template namespace. """ return title.startswith("Template:Did you know nominations/")
def bytes_to_str(s, encoding='latin-1'): """Extract null-terminated string from bytes.""" if b'\0' in s: s, _ = s.split(b'\0', 1) return s.decode(encoding, errors='replace')
def int_(value): """int with handle of none values """ if value is None: return None else: return int(value)
def convert_to_types(decoded_object, template): """Decode list of bytes to list of python objects. Use a template""" if isinstance(decoded_object, bytes): if template: return template().convert(decoded_object) else: return decoded_object elif isinstance(decoded_objec...
def reverse(A, b, e): """Completely flip the given array/subarray. Args: A (array): the array to flip. b (int): the index of the beginning of the array/subarray to flip e (int): the index of the end of the array/subarray to flip Returns: array: the refersed...
def get_word_spacer(word_limit): """ Return a word spacer as long as the word limit exists and the user doesn't want to quit. """ while word_limit: spacer = input('Enter a symbol to separate the words in your passphrase' '\n(Hit space bar and enter for no symbols): ') ...
def song_decoder(song): """De-WUB song.""" return ' '.join(' '.join(song.split('WUB')).split())
def helper_for_hijacking_services_via_dns(service): """ Helper for hijacking a service via dns """ args = [] args.append("-iptables-hijack-dns-to") args.append("127.0.0.1:53") args.append("-dns-proxy-hijack") args.append(service) return args
def numeric_to_record(n_field): """ Check if the field has a value other then zero. :param str_field_to_check: :return: """ if n_field == 0: return None else: return n_field
def value_is_multiple(value, multiple): """Test if given value is a multiple of second value.""" is_multiple = False try: if value % multiple == 0: is_multiple = True else: pass except ZeroDivisionError: is_multiple = False return is_multiple
def is_silent(data, THRESHOLD): """Returns 'True' if below the threshold""" return max(data) < THRESHOLD
def interleave_keys(a, b): """Interleave bits from two sort keys to form a joint sort key. Examples that are similar in both of the provided keys will have similar values for the key defined by this function. Useful for tasks with two text fields like machine translation or natural language inference. ...
def get_anno_desc(fin_anno, anno_type): """Indicate annotation format: gaf, gpad, NCBI gene2go, or id2gos.""" if anno_type is not None: return anno_type if fin_anno[-7:] == 'gene2go': return 'gene2go' if fin_anno[-3:] == 'gaf': return 'gaf' if fin_anno[-3:] == 'gpa': ...
def create_graph_list(sorted_list, days=0): """Creates a list of weights that have been sorted by date in descending order.""" graph_xlist = [] graph_ylist = [] for i, entry in enumerate(sorted_list[days:]): graph_x, graph_y = entry[2], i graph_ylist.append(graph_x) graph_xlist.a...
def double(list_to_double): """Double each element in a list >>> l = [1, 2, 3, 4, 5] >>> double(l) [2, 4, 6, 8, 10] >>> l = [] >>> for value in range(10): ... l.append(value) >>> double(l) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] """ return [n*2 for n in list_to_double]
def recursive_longest_common_subsequence(text_1, text_2): """ Parameters ---------- text_1 : str first string text_2 : str second string Returns ------- int length of the longest common subsequence >>> recursive_longest_common_subsequence("abcde", "ace") ...
def calc_min_rm_and_dlet(list_rm, list_dlet): """ calculates the robustness margins/delta let values for all tasks based on the analyses of all cause-effect chains defined for a given system :param list_rm: list of dicts :param list_dlet: list of dicts :rtype: dict, dict """ rm = dict() ...
def file_contains_doctests(path): """Scan a python source file to determine if it contains any doctest examples. Parameters ---------- path : str Path to the module source file. Returns ------- flag : bool True if the module source code contains doctest examples. """ ...
def isList(x): """ returns True if argument is of type list, otherwise False >>> isList(3) False >>> isList([5,10,15,20]) True """ return ( type(x) == list ) # True if the type of x is a list
def get_key_values_in_list(dic): """Create two lists with keys and values of dictionaries. Parameters ---------- dic : Dictionary. Returns ------- key_list : List of keys. value_list : List of values. """ key_list = [] value_list = [] for keys in dic.keys(): ke...
def compare(user_score, computer_score): """Compares the scores and returns the result.""" if user_score == computer_score: return "Draw." elif computer_score == 0: return "You lose, opponent has a blackjack." elif user_score == 0: return "You win with a blackjack." elif user...
def prepare_expand_argument(expand: str, default_fields: str) -> str: """ The 'expand' command argument specifies which properties should be expanded. In this integration, several of the most significant characteristics are extended by default. Other attributes that users want to expand can still be pro...
def _obtainAction(actionNumber, numberProjects): """"Function to obtain action in qTable""" studentNumber = actionNumber / numberProjects projectNumber = actionNumber % numberProjects return [studentNumber, projectNumber]
def calculateHeatCapacity(averageEnergySquared, averageEnergy, temperature): """function to calculate heat capacity (<EE> - <E><E> ) / (kTT) """ k = 1 return (averageEnergySquared - (averageEnergy ** 2)) / (k * (temperature ** 2))
def codepoint2usv(codepoint): """Convert a character to a string of the USV.""" return "%04X" % codepoint
def _place_caravanserai(new_map, size): """ Find a 3x3 region of desert near but not on the east or south edges. """ # find a space to fit it along the eastern edge, # starting from the north found_y = -1 rows = 0 for y in range(2, 19): cols = 0 for x in range(19 - size, ...
def constReplacements(tex): """ Replace the Latex command "\CONST{<argument>}" with just argument. """ while (tex.find("\\CONST") != -1): index = tex.find("\\CONST") startBrace = tex.find("{", index) endBrace = tex.find("}", startBrace) tex = tex[:index] + tex[star...
def escape_ass_tag(text: str) -> str: """Escape text so that it doesn't get treated as ASS tags. :param text: text to escape :return: escaped text """ return text.replace("\\", r"\\").replace("{", r"\[").replace("}", r"\]")
def _copy(a:bytes) -> bytes: """Ugly copy that works everywhere incl micropython""" if len(a) == 0: return b"" return a[:1] + a[1:]
def check_instanceid(iid): """ Validate the instance id to make sure it is not empty. Args: iid: The instance id to check Returns: The instance id. Raises: ValueError if the instance id is the empty string or None. """ if iid == "" or iid is None: raise ValueError('No instance specified f...
def sub(a, b): """This program subtracts two numbers and return the result""" result = a - b return result
def str2foam(value: str) -> str: """Translate Python strings to OpenFOAM style.""" return f"{value}"
def _GetAllocatorDumps(trace: dict) -> list: """Takes in a trace (as returned from |LoadTrace|), and returns the parts of it related to the allocators. Args: trace: Trace content as returned by LoadTrace. Returns: The parts of the trace related to allocator metrics. Note that these entries are tak...
def get_inventory_hosts_to_ips(inventory, roles, fqdn=False): """Return a map of hostnames to IP addresses, e.g. {'oc0-ceph-0': '192.168.24.13', 'oc0-compute-0': '192.168.24.21', 'oc0-controller-0': '192.168.24.23', 'oc0-controller-1': '192.168.24.15', 'oc0-controlle...
def safe_addr(ip_addr): """Strip off the trailing two octets of the IP address.""" return '.'.join(ip_addr.split('.')[:2] + ['xxx', 'xxx'])
def parse_int(word): """ Parse into int, on failure return 0 """ try: return int(word) except ValueError: return 0
def extract_path(prec, v): """extracts a path in form of vertex list from source to vertex v given a precedence table prec leading to the source :param prec: precedence table of a tree :param v: vertex on the tree :returns: path from root to v, in form of a list :complexity: linear """ ...
def decimal_string(value, precision=6, padding=False): """ Convert float to string with limited precision Parameters ---------- value : float A floating point value. precision : Maximum number of decimal places to print Returns ------- value : string The specif...
def version_tuple(v): """Convert a version string to a tuple containing ints. Returns ------- ver_tuple : tuple Length 3 tuple representing the major, minor, and patch version. """ split_v = v.split(".") while len(split_v) < 3: split_v.append('0') if len(split_v...
def reverse_int_bits(n: int, n_bits: int = 10) -> int: """Reverses the bits of *n*, considering it is padded by *n_bits* first""" return int(format(n, '0' + str(n_bits) + 'b')[::-1], 2)
def find_aliases(fields, aliases): """ Scans through columns and finds the proper name """ col_map = dict() for k in fields: if k in aliases: col_map[k] = aliases[k] if k.lower() in aliases: col_map[k] = aliases[k.lower()] return col_map
def replace_if_match(xs, y): """ Find the first pattern match in list. Return the corresponding value of patterns if matches, return the same value of x if there has no match. Parameters ---------- xs : [(pattern, value)] y : object Returns ------- result : object """ ...
def tickers_to_rockets(entity_pairs): """ Converts tickers to rocket replacements >>> tickers_to_rockets([['Test','TST']]) ['t s t -> TST'] """ tickers = [e[1].strip() for e in entity_pairs] entities = [" ".join(list(e.lower())) for e in tickers] return ["{0} -> {1}".format(x, y) for x...
def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: """ " Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 >>> sum_of_geometric_progression(1, 10, 5) 11111.0 >>> sum_of_geometr...
def ansible_stdout_to_str(ansible_stdout): """ The stdout of Ansible host is essentially a list of unicode characters. This function converts it to a string. Args: ansible_stdout: stdout of Ansible Returns: Return a string """ result = "" for x in ansible_stdout: ...
def dfs(graph, start): """ Browse the graph using a DFS (depth) tranversal algorithm. A DFS is using a stack. """ visited, stack = set(), [start] while stack: vertex = stack.pop() if vertex not in visited: visited.add(vertex) if vertex not in graph: ...
def _replace_class_names(class_names): """Replaces class names based on a synonym dictionary. Args: class_names: Original class names. Returns: A list of new class names. """ synonyms = { 'traffic light': 'stoplight', 'fire hydrant': 'hydrant', 'stop sign': 'sig...
def sol(s): """ Count the no. of 1s. Start and end can be any 1. So soln is combination of nC2 which is n*(n-1)//2*1 """ c = 0 for x in s: if x == '1': c+=1 return (c*(c-1))//2
def take_docstring_of(chars): """ Take the lines between the first triple-quote and the next, such as from \"\"\" to \"\"\", or from \'\'\' to \'\'\' but ignore empty lines and ignore leading lines begun with a hash # """ qqq = None lines = list() for line in chars.splitlines(): ...
def sample_random_rewards(n_states, step_size, r_max, ptrial, allrew): """ sample random rewards form gridpoint(R^{n_states}/step_size). :param n_states: :param step_size: :param r_max: :return: sampled rewards """ rewards = allrew[ptrial] # rewards = np.random.uniform(low=(-2,-10), ...
def CreateItem(title="", subtitle="", label="", icon="", action="", actionParam=""): """ This function is to create item :title<string> :subtitle<string> :lable<string> :icon<string> :action<string> :actionParam<string> :return item<dict> """ item = {} item['title'] = tit...
def plotstyle(i, c=['b', 'g', 'r', 'c', 'm', 'y', 'k'], \ s=['.', 'x', 's', '^', '*', 'o', '+', 'v', 'p', 'D'], \ l=['-', '--', '-.', ':']): """Return plot properties to help distinguish many types of plot symbols. :INPUT: i -- int. :OPTIONAL INPUT: c --...
def public_byte_prefix(is_test): """Address prefix. Returns b'\0' for main network and b'\x6f' for testnet""" return b'\x6f' if is_test else b'\0'
def matrix_augment(A,b): """ return an augmented matrix for a linear system Ax=b where A is an NxN matrix and x,b are both column vectors of length N an augmented matrix is an Nx(N+1) matrix where each value in b is appended to the end of the corresponding row in A. ...
def _get_source_files(commands): """Return a list of all source files in the compilation.""" return list(commands.keys())
def same_list_of_list_of_bboxes(l_1, l_2): """test same list of list of bboxes.""" assert len(l_1) == len(l_2) for i in range(len(l_1)): assert len(l_1[i]) == len(l_2[i]) for j in range(len(l_1[i])): assert l_1[i][j] == l_2[i][j] return True
def http_verb(dirty: str) -> str: """ Given a 'dirty' HTTP verb (uppercased, with trailing whitespaces), strips it and returns it lowercased. """ return dirty.strip().lower()
def utxo_to_txin(utxo): """Return a dict of transaction input build from an utxo. Args: utxo: an utxo dict. { txid: '' value: 0, vout: 0, scriptPubKey: '' } """ return { 'tx_id': utxo['txid'], 'index': utxo['vout'], 'script': utxo['scriptPubK...
def BuildCommandList(command, ParamList): """ command is a list of prepared commands ParamList is a dictionary of key:value pairs to be put into the command list as such ("-k value" or "--key=value") """ for key in ParamList.keys(): # Single character command-line parameters preceded by ...
def selection(sortlist): """ checks for the largest and then replaces - ascending order only""" for i in range(0,len(sortlist)-1): small = sortlist[i] pos = i for j in range(i+1,len(sortlist)): if sortlist[j] < small: small = sortlist[j] pos = j sortlist[pos] = sortlist[i] sortlist[i] = smal...
def approve_for_packaging(doi_id): """ After downloading the zip file but before starting to package it, do all the pre-packaging steps and checks, including to have a DOI """ if doi_id is None: return False return True
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 v2_group_by(iterable, key_func): """Group iterable by key_func. The setdefault method was invented for dictionaries to solve just this situation. The setdefault method does two things: it returns the value for the given key from the dictionary and sets the value to the given key (an empty list...
def isSubStringOf(term1, term2): """ check if term1 is a substring of term2 on token-level :param term1: :param term2: :return: """ if len(term1.strip()) == 0 or len(term2.strip()) == 0: return False term1_token_set = set(term1.split(' ')) term2_token_set = set(term2.split('...
def set_feature_file(data_type, network = 'Resnet50'): """ Construct file name for the bottleneck file """ return network + '_features_' + data_type + '.npz'
def map_to_int_range(values, target_min=1, target_max=10): """Maps a list into the integer range from target_min to target_max Pass a list of floats, returns the list as ints The 2 lists are zippable""" integer_values = [] values_ordered = sorted(values) min_value = float(values_ordered[0]) max_valu...
def colorizer(x, y): """ Map x-y coordinates to a rgb color """ r = min(1, 1-y/3) g = min(1, 1+y/3) b = 1/4 + x/16 return (r, g, b)
def zzis(arr, n): """las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its ...
def is_gu_wobble(b1, b2): """Check if 2 nts are a GU wobble if the first sequence was reverse complemented""" if (b1 == 'C' and b2 == 'U') or (b1 == 'A' and b2 == 'G'): return True else: return False
def d_timeToString(dateString): """ input: string output: string description: format dateString to yyyymmddHHMM example: 2018-08-26 14:18:40 ->> 201808261418 """ return dateString.replace("-", "").replace(" ", "").replace(":", "...
def getRegressorName(runNum): """"Return station classification filename""" # this is the actual run number, 1-based filename = "regressor_run-{0:02d}.mat".format(runNum) return filename
def _is_boolean(arg): """Check if argument is a boolean value (True or False).""" return isinstance(arg, bool)
def split_word(sequences, space="_"): """Split word sequences into character sequences. Arguments --------- sequences : list Each item contains a list, and this list contains a words sequence. space : string The token represents space. Default: _ Returns ------- The lis...
def npv_converter(sensitivity, specificity, prevalence): """Generates the Negative Predictive Value from designated Sensitivity, Specificity, and Prevalence. Returns negative predictive value sensitivity: -sensitivity of the criteria specificity: -specificity of the criteria preval...
def getLastRow(array): """Returns the last row of the entered array.""" row = array[len(array)-1::] return row
def unscale_action(scaled_action, low: float, high: float): """ Rescale the action from [-1, 1] to [low, high] (no need for symmetric action space) :param scaled_action: Action to un-scale """ return low + (0.5 * (scaled_action + 1.0) * (high - low))
def pers_name(data): """ extract text from TEI element <persName> """ try: return data.find(".//persName", namespaces=data.nsmap).text except AttributeError: pass return None
def has_decorator(source_lines: list) -> bool: """ Checks if the source code for a function has a decorator or not :param source_lines: Source code lines of a function :return: True if there is a decorator else False """ return '@' in source_lines[0]
def horizon_float(k0: int, plus_or_minus: str) -> float: """Returns a floating point representation of k direction face index; eg. 3.5 for face between layers 3 and 4. """ result = float(k0) if plus_or_minus == '+': result += 0.5 elif plus_or_minus == '-': result -= 0.5 else...
def _unencapsulate_facts(facts, check_version=False): """Extract node facts and version from final fact format.""" assert 'nodes' in facts, 'No nodes present in parsed facts file(s)' return facts['nodes'], facts.get('version')
def hard_most_common_letter(a): """Takes in a string of lowercase letters and returns the most common letter (if multiple, just pick one).""" # too tricky? d = {} for c in a: d[c] = d.get(c, 0) + 1 l = list(d.items()) l.sort(key=lambda x: -x[1]) return l[0][0]
def merge_dicts(*dict_args): """ This function is not meant to be used but rather to serve as a reminder to use the syntax {**x, **y, **z}. This function works but is not as fast as that syntax by as much as twice. Given any number of dictionaries, shallow copy and merge into a new dict, prece...
def get_param_i(param, i): """Gets correct parameter for iteration i. Parameters ---------- param : list List of model hyperparameters to be iterated over. i : integer Hyperparameter iteration. Returns ------- Correct hyperparameter for iteration i. """ if len(p...
def int_from_bit_str(s: str) -> int: """Convert binary representation to integer ### Positional arguments - s (str) - A binary representation string ### Returns An integer of the binary pattern ### Raises - TypeError - Raised when the parametres are of incorrect type ...
def check_sorted(a): """Determines if list is sorted.""" for i, val in enumerate(a): if i > 0 and val < a[i-1]: return False return True
def complexAdd(complex1, complex2): """This method is used to add 2 complex numbers Arguments: complex1 {tuple} -- tuple of 2 representing the real and imaginary part complex2 {tuple} -- tuple of 2 representing the real and imaginary part Returns: tuple -- tuple...
def usage_help(program_name): """Returns usage help string""" return ('Usage: {0} [--opts] +src_opts[=arg,] ' '+to +tgt_opts[=[~]arg,] filename'.format(program_name))
def _flatten(object): """Given a hierarchical object of classes, lists, tuples, dicts, or primitive values, flattens all of the values in object into a single list. """ if isinstance(object,(list,tuple)): return sum([_flatten(v) for v in object],[]) elif isinstance(object,dict): retu...
def legendre_polynomial(x: float, n: int) -> float: """Evaluate n-order Legendre polynomial. Args: x: Abscissa to evaluate. n: Polynomial order. Returns: Value of polynomial. """ if n == 0: return 1 elif n == 1: return x else: polynomials = [...
def set_metrics(metrics): """ Set properly metrics that we want to load @metrics: list """ result = [] for i in metrics: d = { 'expression': i } result.append(d) return result
def compute_in_degrees(digraph): """Takes a directed graph digraph (represented as a dictionary) and computes the in-degrees for the nodes in the graph.""" degrees = {} for looked_node in digraph: degree = 0 for node in digraph: if node != looked_node: if lo...
def _bytearray_to_str(value: bytearray) -> str: """Convert ``bytearray`` to ``str``""" return bytes(value).decode("utf-8")
def checkSubstring(str1, str2): """ Checks if STR1 is a substring of STR2. """ len1 = len(str1) len2 = len(str2) for i in range(len2-len1+1): if str1 == str2[i:len1 + i]: return True return False
def enable_rewind_data_button(n): """ Enable the rewind button when data has been loaded """ if n and n[0] < 1: return True return False
def contains_failure(lines): """Check if any line starts with 'FAILED'.""" for line in lines: if line.startswith('FAILED'): return True return False