content
stringlengths
42
6.51k
def _depth(obj): """Helper function to determine the depth of a nested list structure.""" return isinstance(obj, (list, tuple)) and max(map(_depth, obj)) + 1
def is_valid_tag(tag): """check if the tag is valid""" if int(tag) < 1 or int(tag) > 4294967295: return False return True
def floattostr(s, nb_digit=7): """ convertit un float en string 10,7""" s = "{0:0.{1}f}".format(s, nb_digit) return s.replace('.', ',').strip()
def _first_unvisited(graph, visited): """ Return first unvisited node. @type graph: graph @param graph: Graph. @type visited: list @param visited: List of nodes. @rtype: node @return: First unvisited node. """ for each in graph: if (each not in visited): ...
def find_interval_index(array, low, high, search_value): """ Finds the position index that the search_value should be inserted in the array. Parameters ---------- array : list The array for searching where to insert the search_value. <b>Must be sorted.</b> low : ...
def product(value1, value2, value3): """ Returns the product of the three input values. """ prod = value1 * value2 prod = prod * value3 return prod
def find_longest_match(body, current_index, window_size=4095): """ @param body The text in which to search @param current_index The index in the text from which N characters onwards will be matched to previous segments @returns (offset, length) How many characters back the match was found, and for how many characte...
def get_mr_command(app_dir,script,params): """ Script for creating line with call to mapper/reducer with parameters. """ command = app_dir + script + " " + params return(command)
def pixel_coordinate(origin_x, scale_x, theta_y, origin_y, theta_x, scale_y, i, j): """ Returns the Cartesian coordinate for a pixel http://www.gdal.org/gdal_datamodel.html Args: origin_x (float): the X dimension of the spatial coordinate for the top left pixel scale_x (flo...
def summation_i_squared(n): """ n: stopping condition return: total """ if type(n) != int or n < 1: return None return int(n / 6 + (n ** 2) / 2 + pow(n, 3) / 3)
def get_cons_or_prod_paired(function_list, xml_flow_list, xml_opposite_flow_list): """Get flow list if opposite flow is existing: e.g. if flow A is consumed and produced by function within function_list => Add it""" new_flow_list = [] for func in function_list: # Flow = [Data_name, Function] ...
def getMapParams(elem,attrmap,more=None): """ The supplied 'attrmap' is a list of (name,function) pairs. This function returns a list of parameters corresponding to named attributes from each of these pairs, converted using the associated functions, concatenated with the result of applying the sup...
def is_valid_directed_joint_degree(in_degrees, out_degrees, nkk): """ Checks whether the given directed joint degree input is realizable Parameters ---------- in_degrees : list of integers in degree sequence contains the in degrees of nodes. out_degrees : list of integers out degre...
def divisors(n: int) -> set: """ Returns all divisors of n """ divisors = set() for i in range(1, int(n ** 0.5) + 1): q, r = divmod(n, i) if r == 0: divisors |= {i, q} return divisors
def hamdist(str1, str2): # From http://code.activestate.com/recipes/499304-hamming-distance/ """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 addition(num1, num2=0): """ Adds two numbers Args: num1: The first number num2: The second number, default 0 Returns: The result of the addition process """ return (num1+num2)
def get_user_id(user): """Return id attribute of the object if it is relation, otherwise return given value.""" return user.id if type(user).__name__ == "User" else user
def ExternalArgNameFrom(arg_internal_name): """Converts an internal arg name into its corresponding user-visible name. This is used for creating exceptions using user-visible arg names. Args: arg_internal_name: the internal name of an argument. Returns: The user visible name for the argument. """ ...
def color2rgba(colorstring): """ convert #RRGGBB[AA] to an (R, G, B, [A]) tuple """ colorstring = colorstring.strip() if colorstring[0] == '#': colorstring = colorstring[1:] if len(colorstring) != 8: raise ValueError( "input #%s is not in #RRGGBBAA format" % colorstring) r, g, b, a = colorst...
def l1_distance(x, y): """ Computes the l_1 / Manhattan distance between two coordinates. """ return sum([abs(xx - yy) for xx, yy in zip(x, y)])
def format_name(name): """Remove non alphanumeric/whitespace characers from user input or restaurant data """ return ''.join(chr for chr in name if chr.isalnum() or chr.isspace())
def ipv6_mask_to_net_prefix(mask): """Convert an ipv6 netmask (very uncommon) or prefix (64) to prefix. If 'mask' is an integer or string representation of one then int(mask) will be returned. """ if isinstance(mask, int): return mask if isinstance(mask, str): try: ...
def extract_sentence_pairs(conversations): """ Extracts pairs of sentences from conversations """ qa_pairs = [] for conversation in conversations: # Iterate over all the lines of the conversation # We ignore the last line (no answer for it) for i in range(len(conversation["l...
def choose(n, k): """ This function is a fast way to calculate binomial coefficients, commonly known as nCk, i.e. the number of combinations of n things taken k at a time. (https://en.wikipedia.org/wiki/Binomial_coefficient). This is the *scipy.special.comb()* with long integer computation but this...
def factorial_recursive(num): """returns the factorial of num using a recursive method.""" if num == 1: return 1 return num * factorial_recursive(num -1)
def HtmlColorCode_to_strings(value): """ Convert a HTML color code like '#FFCC00' or 'FFCC00' to a list of strings ['FF', 'CC', '00'] """ x = 1 * value.startswith('#') return [value[x:x+2], value[x+2:x+4], value[x+4:x+6]]
def percentage(now, maximum): """ Given the present (now) value and the maximum value determine the percentage (now/maximum * 100) we have got to and return as a string Since now tends to be from 0 to maximum-1, we take 1 off of maximum :param now: The present value through a list :param maximum...
def update_Qi(Qval, reward, alpha): """ update q-value of selected action, given reward and alpha """ return Qval + alpha * (reward - Qval)
def get_sinks(G): """ A sink is a node with no children. This means that this is the end of the line, and it should be run last in topo sort. This returns a list of all sinks in a graph """ sinks = [] for node in G: if not len(list(G.successors(node))): sinks.append(n...
def divide(word): """Divide a word in half""" l = len(word) mid = 1 if l == 1 else round(l / 2) return [word[:mid], word[mid:]]
def from_perl_syntax(d): """ Essentially the inverse of to_perl_syntax() but we also nuke the '@' prefix on a list. """ return str(d).replace(' => ', ':').replace('(', '[').replace(')', ']').replace('@', '')
def zip2(L1, L2, L3): """ >>> zip2(range(2), range(5, 8), range(9, 13)) [(0, 5, 9), (1, 6, 10)] """ return list(zip(L1, L2, L3))
def newtonRaphson(function, derivative, initial_guess=1, error=1e-5): """ Perform the Newton-Raphson root-finding algorithm on a given function and its derivative. """ px = initial_guess nx = initial_guess - function(initial_guess)/derivative(initial_guess) while abs(nx - px)/abs(nx) > error: px = nx nx = nx...
def sort_freq(freqdict): """ sort_freq reads word:frequency key:val pairs from dict, and returns a list sorted from highest to lowest frequency word :param freqdict: :return: list named aux """ aux: list = [] for k, v in freqdict.items(): aux.append((v, k)) aux.sort(reverse=T...
def get_allafter_in_array(lst: list, obj: object, include_value=False): """Returns a list of all elements after the given value (if that value is in the list). Example: >>> mylst = ['exit', 'quit', 're', 'sys', 'teststring']\n >>> get_allafter_in_array(mylst, 're')\n ['sys', 'teststring'] >>> g...
def inverse(dist): """Inverse weight function""" return 1 / (dist + 1)
def total_distance(positons:list, loc:int) -> int: """Calculate the total distance to all line up at loc""" return sum([ abs(x) for x in [ i - loc for i in positons ] ])
def _join(*values): """ Join a series of values with semicolons. The values are either integers or strings, so stringify each for good measure. Worth breaking out as its own function because semicolon-joined lists are core to ANSI coding. """ return ';'.join(str(v) for v in values)
def EXP(number): """ Returns the exponential value of a number. See https://docs.mongodb.com/manual/reference/operator/aggregation/exp/ for more details :param number: The number or field of number :return: Aggregation operator """ return {'$exp': number}
def string_from_prompts_array(arr): """ Concatinates a list of prompts into a string. Used in development to separate prompts with a bar. Args arr: An array of prompts. Returns A concatinated string. """ prompts_string = '|'.join(arr) return prompts_string
def set_identity_providers_if_unset(facts): """ Set identity_providers fact if not already present in facts dict Args: facts (dict): existing facts Returns: dict: the facts dict updated with the generated identity providers facts if they were not already present ...
def compute_delta(num_levels): """Computes the delta value from number of levels Arguments --------- num_levels : int The number of levels Returns ------- float """ return num_levels / (2.0 * (num_levels - 1))
def getMenuItems (theDictionary): """Identify what items are on the menu. :param dict[str, float] theDictionary: Dict containing menu items as keys and respective prices as prices. :return: A sorted list of menu items. :rtype: list[str] """ items = sorted(list(theDiction...
def _get_wrapped(function): """Get the method at the bottom of a stack of decorators.""" if hasattr(function, '__wrapped__'): return getattr(function, '__wrapped__') if not hasattr(function, 'func_closure') or not function.func_closure: return function def _get_wrapped_function(functi...
def get_exitcode_stdout_stderr(cmd): """ Execute the external command and get its exitcode, stdout and stderr. """ from subprocess import Popen, PIPE import shlex args = shlex.split(cmd) proc = Popen(args, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() exitcode = proc.retur...
def gauss_sum(number): """ Computes the gaussian sum for an input number. """ return (number * (number + 1)) / 2
def q6(vector, n): """ Revertse the input vector in chunks of size n Args: vector (1xd): The array to be reversed n (int): chunk size Returns: Array: reversed array """ new_vector = [] while len(vector): new_vector+= vector[-n:] vector = vector[...
def _spaceship(a,b): """3-way comparison like the <=> operator in perl""" return (a > b) - (a < b)
def find_key(in_list, key): """In list of lists returns index[0] if index[1] == key This method is deployed in the get_medical_image() route It find the medical image string for an input file_name (key) :param in_list: :param key: str containing medical image in base 64 :return: """ f...
def fitness(problem, population, point, dom_func): """ Evaluate fitness of a point based on the definition in the previous block. For example point dominates 5 members of population, then fitness of point is 5. """ return len([1 for another in population if dom_func(problem, point, another)])
def gradient_step(local_gradients, local_centroids): """ Gradient descent update on local site Input: local_gradients - list of k many local gradients Output: updated local centroids, previous centroids from last iteration """ previous = local_centroids[:] local_centroids = [wk...
def merge_two_dicts(starting_dict: dict, updater_dict: dict) -> dict: """ Starts from base starting dict and then adds the remaining key values from updater replacing the values from the first starting dict with the second updater dict. Thus, the update_dict has precedence as it updates and replaces the...
def bisect_left(a, x, lo=0, hi=None): """ Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >=x. so if x already appears in the list, a.insert(x) will insert just before the leftmost x already t...
def linaddr(seg: int, off: int) -> int: """Convert a segmented address into a 20 bits linear address. Args: seg: segment value off: offset value Returns: effective linear address """ return (seg << 4) + off
def delete_subdir(config): """ Remove subdir from config """ if not config: return config if 'subdir' in config: del config['subdir'] return config
def f_bound(f, key, first, last, value, which, *args, **kwargs): """ :param f: the MONOTONIC function :param key: keyword arguments or position of argument to be searched :param first: [first, last) :param last: [first, last) :param value: value to be searched :param which: lower bo...
def get_surcharge(cart_value: int, limit: int = 1000) -> float: """ This function calculates surcharge if cart value is lower that the limit. --- Args: cart_value (int): Value of the cart limit (int): Surcharge threshold. Default value is 1000 cents. Returns: surcharge (f...
def _sympy(object): """is the object a sympy expression?""" import sys if "sympy" not in sys.modules: return False import sympy if isinstance(object, sympy.Expr): return True return False
def validate_analysis_result(result): """ Checks if a given result is a valid result by checking if all required fields are in the result dict :param dict result: the dict result to be checked :return: True if all fields are in the result or False if not """ REQUIRED_FIELDS = ["title", "det...
def isPalindrome(s): """ :type s: str :rtype: bool """ if len(s) == 0: return True import re pattern = re.compile('[\W_]+') s = pattern.sub('', s) s = s.lower() #Could just reverse string using s[::-1] s_len = len(s) for i in range(s_len): if s[i] is...
def _upper_confidence_bound(mu, sigma, kappa=2.): """ Calculates the upper confidence bound at the point 'x', for which: mu = mean(x) sigma = std(x) Parameters ---------- mu : array_like, shape (n,) Mean. sigma : array_like, shape (n,) Standard deviati...
def list_of_elem(elem, length): """return a list of given length of given elements""" return [elem for i in range(length)]
def aggregate_actions_and_lengths(actions_per_frame): """Identify the actions in a video and count how many frames they last for. Given a list of actions (e.g. ['a', 'a', 'a', 'b', 'b']) summarise the actions and count their lifespan. For the example input just given, the function returns (['a', 'b'], [3, ...
def reorder(colours): """ Reorder the colours to fit the Cube::Bit's weird space-filling curve. This is horribly hard-coded - if I ever get a cube that's not a 3x3x3, I'll do it properly """ indeces = [ 0, 3, 6, 7, 4, 1, 2, 5, ...
def buildJSON(dic): """ gets dictionary and converts it into json format """ import json json_object = json.dumps(dic, indent=4) return json_object
def luhnCheck(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(num_digits): digit = int(card_number[count]) if not ((count & 1) ^ oddeven): digit *= 2...
def fat(num=0): """ Calcula e retorna o fatorial de um numero como um numero inteiro.\n Returns r = int(num!) """ r = 1 for c in range(1, num+1): r *= c return r
def add_data_to_MSOA_data(consumer_data, population_data, variable): """ Take the WTP lookup table for all ages. Add to the population data based on age. """ d1 = {d[variable]:d for d in consumer_data} population_data = [dict(d, **d1.get(d[variable], {})) for d in population_data] return popu...
def json_validate(test_json, dict_schema): """A simplistic JSON validator for pre-clearing missing or incorrectly- typed arguments in a request body. Controlled by arguments and returns a tuple in (boolean, errors) format indicating whether or not the body passed and what, if any, errors are indicated. ...
def prod(arg): """ returns the product of elements in arg. arg can be list, tuple, set, and array with numerical values. """ ret = 1; for i in range(0,len(arg)): ret = ret * arg[i]; return ret;
def get_metafeatures_dim(metafeatures_spec): """Get dimensionality of metafeatures.""" return sum([len(m[2]) if m[1] is str else 1 for m in metafeatures_spec])
def isalphadigit_(s): """ Return ``True`` if ``s`` is a non-empty string of alphabetic characters or a non-empty string of digits or just a single ``_`` EXAMPLES:: sage: from sage.repl.preparse import isalphadigit_ sage: isalphadigit_('abc') True sage: isalphadigit_('12...
def next_index(state): """Parse state into index""" node = state for key in ("layers", "index"): node = node.get(key, {}) indices = [key for key in node.keys()] if len(indices) == 0: return 0 else: return max(indices) + 1
def As_Dollars_Pad(Number): """Format Dollars Amounts to strings & Pad Right""" Number_Display = f"${Number:,.2f}" Number_Display = f"{Number_Display:>15}" return Number_Display
def _parse_boolean(value): """ Returns a boolean value corresponding to the given value. :param value: Any value :return: Its boolean value """ if not value: return False try: # Lower string to check known "false" value value = value.lower() return value not...
def get_form(obj, index): """Get form index.""" try: return obj[index] except: return None
def macro_align(width: str, alignment: str, content: str) -> str: """Aligns given text using fstrings. Args: width: The width to align to. alignment: One of "left", "center", "right". content: The content to align; implicit argument. """ aligner = "<" if alignment == "left" els...
def ERR_BADMASK(sender, receipient, message): """ Error Code 415 """ return "ERROR from <" + sender + ">: " + message
def erase_seq(s): """ Erase the sequence from a string. """ if s is None: return None else: # Repeat "N" * len(s) times return 'N' * len(s)
def arithmetic(a, b, operator): """ Take two integers and perform a math operation on them depending on the operator input. :param a: positive integer. :param b: positive integer. :param operator: string of four operators: "add", "subtract", "divide", "multiply". :return: the result of the two n...
def ReleasePowerAssertion(io_lib, assertion_id): """Releases a power assertion. Assertions are released with IOPMAssertionRelease, however if they are not, assertions are automatically released when the process exits, dies or crashes, i.e. a crashed process will not prevent idle sleep indefinitely. Args: ...
def get_command_type(line): """ Returns the command type. str -> str """ line = line.split(' ', 1) return line[0]
def sum_mult_nums(x: int, y: int, z: int) -> str: """ 005 Ask the user to enter three numbers. Add together the first two numbers and then multiply this total by the third. Display the answer as 'The answer is <answer>. """ result = (x + y) * z return f"The answer is {result}."
def posreal(value, exception = ValueError): """Casts to positive real (well, float) if possible""" newvalue = float(value) #The exception may get raised here by the float function if needed if newvalue <= 0: raise exception return newvalue
def _(s, truncateAt=None): """Nicely print a string to sys.stdout, optionally truncating it a the given char.""" if truncateAt is not None: s = s[:truncateAt] return s
def transpose(matrix): """Transposes a 2D array """ transposed = [ [ matrix[j][i] for j in range(len(matrix)) ] for i in range(len(matrix[0])) ] return transposed
def eta_from_q(q): """ converts mass-ratio to symmetric mass-ratio input: q output: eta """ return q/(1.+q)**2
def get_pad_tuple1d(padding, kernel): """Common code to get the pad option Parameters ---------- padding : int or str Padding size, or ['VALID', 'SAME'] kernel : tuple of int Conv kernel size Returns ------- pad_left : int Padding size on left pad_right : int ...
def to_title(str): """returns a string formatted as a title""" return str.replace("_", " ").capitalize()
def get_min (matrix, support_minimal): """Retourne le plus petit nombre du tableau restant""" ligne_rayee = support_minimal['ligne'] colonne_rayee = support_minimal['colonne'] nb = list() for y, y_elt in enumerate(matrix): for x, x_elt in enumerate(y_elt): if x not in colonne_ray...
def date_parser(dates): """ The function that formats a date, removing the time(hh:mm:ss) and return the date as yyyy-mm-dd """ # use the split method to separate the date and time # use list comprehension to return formated date return [i.split(' ', 1)[0] for i in dates]
def pluralize(count: int) -> str: """ Returns string '' if count is equal to one otherwise 's'. Useful for making print/logging statements grammatically correct. :param count: The numerical count :return: A string if the noun needs to be plural or not """ return '' if count == 1 else 's'
def init_commands(peeling_deg, block_items): """ Initialize the commands in the body of the loop commands: list of list of tuples each list in the list corresponds to a 'peel' in a loop each tuple (node,i) contains the AST node and the corresponding ind """ commands = [] index = 0 ...
def _fits_section_header(section_name): """ Blank fits header cards for a section header. As in drizzle, one blank line, a line with the section name as a comment, then one more blank. """ return [('', '', ''), ('', '/ ' + section_name, ''), ('', '', '')]
def get_intersection(cx1, cy1, cos_t1, sin_t1, cx2, cy2, cos_t2, sin_t2): """ return a intersecting point between a line through (cx1, cy1) and having angle t1 and a line through (cx2, cy2) and angle t2. """ # line1 => sin_t1 * (x - cx1) - cos_t1 * (y - cy1) = 0. # line1 => sin...
def define(name: str, value: str = "") -> str: """ Return C++ macro-string #define name value Used for header defines. Parameters ---------- name : str Name of macro to be defined value : str, optional Value of defined macro (if any), Returns ------- str: ...
def remove_exclude_state(exclude_state_id, state_dict): """ To delete exclude image_id of each sceneray exclude_state_id: [image_id get from get_exclude_state] state_dict: {reading connectivity} return: [new state list without exclude image_id dict] """ new_state_dict = [] for each_state...
def tp_fp_fn(true_set, subm_set): """ Calculate tp, fp and fn when comparing the true set of tuples and the submitted set of tuples by the students. """ true_pos = true_set.intersection(subm_set) fals_pos = subm_set - true_set fals_neg = true_set - subm_set tp = len(true_pos) fp = ...
def _svg_convert_size(size): """ Convert svg size to the px version :param size: String with the size """ # https://www.w3.org/TR/SVG/coords.html#Units conversion_table = { "pt": 1.25, "pc": 15, "mm": 3.543307, "cm": 35.43307, "in": 90 } if len(si...
def inherit_doc(cls): """ A decorator that makes a class inherit documentation from its parents. """ for name, func in vars(cls).items(): # only inherit docstring for public functions if name.startswith("_"): continue if not func.__doc__: for parent in cls...