content
stringlengths
42
6.51k
def rect_from_sides(left, top, right, bottom): """Returns list of points of a rectangle defined by it's `left`, `top`, `right`, and `bottom` coordinates, ordered counter-clockwise.""" return [ (left, bottom), (right, bottom), (right, top ), (left, top ), ]
def merge_overpass_jsons(jsons): """Merge a list of overpass JSONs into a single JSON. Parameters ---------- jsons : :obj:`list` List of dictionaries representing Overpass JSONs. Returns ------- :obj:`dict` Dictionary containing all elements from input JSONS. """ el...
def xPathFirst(path): """Extends a XPath query to return the first result. >>> xPathFirst("//*[@class='test']") "(//*[@class='test'])[1]" @type path: string @param path: the initial XPath @rtype: string @return: the XPath with first result selection """ return "({0})[1]".format(path)
def _prepare_list(_list, list_expected): """Prepare a List and an expected List for validation. The preparation of the lists consists in accepting all lists that contain white spaces. In addition, lists that begin with "..." or parentheses are reversed for validation to work. parameters --...
def get_filename_pair(filename): """ Given the name of a VASF data file (*.rsd) or parameter file (*.rsp) return a tuple of (parameters_filename, data_filename). It doesn't matter if the filename is a fully qualified path or not. - assumes extensions are all caps or all lower """ param_file...
def strSim(txt1, txt2): """ String similarity returns a value between -1 and +1 """ if (not txt1) or (not txt2): return None #print 'strSim', txt1, ':', txt2 import difflib s = difflib.SequenceMatcher(None, txt1, txt2).ratio() return 2.0 * (s - 0.5)
def update_options(opts): """Helper function, returns dict for selectable options.""" return [{'label': i, 'value': i} for i in opts]
def apply_time_filter(dataset_row, time_interval): """Returns True if data is within the given time intervals.""" merge_time = dataset_row['grounded_normalized_time'] lower_time, upper_time = time_interval return merge_time > lower_time and merge_time < upper_time
def clean_link(link): """Removes leading and trailing whitespace and punctuation""" return link.strip("\t\r\n '\"\x0c")
def is_leapyear(year): """ Returns True if year is a leap year and false otherwise """ return year % 4 == 0 and not (year % 100 == 0 and year % 400 != 0)
def convert_to_float(svalues): """Takes a list of strings and converts them to floats.""" values = [] for value in svalues: values.append(float(value)) return values
def dict_contains_only(dct, allowed, allow_mpp=True): """Check whether a dictionary contains only allowed keys""" for key in dct.keys(): if allow_mpp and key.startswith("mpp-"): continue if key in allowed: continue return False return True
def clamp(n, minn, maxn): """ Parameters ---------- n : number Number to be clamped minn : number Lower bound of the clamp maxn : number Upper bound of the clamp """ return max(min(maxn, n), minn)
def compute_frequencies(words): """ Args: words: list of words (or n-grams), all are made of lowercase characters Returns: dictionary that maps string:int where each string is a word (or n-gram) in words and the corresponding int is the frequency of the word (or n-gram...
def confusionMatrix(labels_test, labels_predicted): """Calculates the complete confusion matrix from true/false positives/negatives""" if len(labels_test) != len(labels_predicted): return 0 TP = 0; FP = 0; TN = 0; FN = 0 for i in range(0, len(labels_test)): if labels_test[i] == 0 or labe...
def validateFilename(value): """ Validate filename. """ if 0 == len(value): raise ValueError("Filename for spatial database not specified.") return value
def traditional_constants_icr_equation_empty_fixed(fixed_params, X_col): """ Traditional ICR equation with constants from ACE consensus """ a = 450 tdd = X_col[0] return a / tdd
def _compute_win_probability_from_elo(rating_1, rating_2): """Computes the win probability of 1 vs 2 based on the provided Elo ratings. Args: rating_1: The Elo rating of player 1. rating_2: The Elo rating of player 2. Returns: The win probability of player 1, when playing against 2. """ m = max(...
def filter_ensureleadingslash(host): """ Adds a leading slash to URLs (or anything, really) if one isn't present Usage: {{ 'login.php' | ensureleadingslash }} Output: '/login.php' """ if not host.startswith("/"): host = "/" + host return host
def parse_rose_stream_name(stream_name): """ Convert the Rose stream name given to this ESGF dataset into more useful components..... :param str stream_name: The Rose stream name given to this ESGF data set. :returns: The dataset components from the stream name. :rtype: dict """ cmpts =...
def ensure_prefix(s, p): """Return a new string with prefix `p` if it does not.""" if s.startswith(p): return s return f"{p}{s}"
def test_user(user_num): """Pre-defined user variables for testing purposes""" users = { "1": (5, "", 3, True, True, True, True, True), "2": (0, "", 3, False, False, False, False, False), "3": (2, "", 4, True, True, False, False, True), "4": (1, "", 5, False, False, True, True, F...
def isPrice(price, high, low): """ Check whether the price is within the bound """ return (price >= low) and (price <= high)
def int8_to_byte(i): """ Utility function that converts an integer to its byte representation in little endian order. If `i` is not representable in a single byte it will raise OverflowError. Args: i (int): integer to convert Returns: bytes: the byte representation Raises: X...
def split_list(L, S): """Split list given a list of breaking elements""" output = list() for s in S: if s in L: idx = L.index(s) output.append(L[:idx]) L = L[idx+1:] return output
def _update_shape_dtype(shape, dtype, params): """Update shape dtype given params information""" if not params: return shape, dtype shape = shape.copy() shape.update({k : v.shape for k, v in params.items()}) if isinstance(dtype, str): for k, v in params.items(): if v.dtyp...
def seconds_to_hms(seconds): """ Converts seconds float to 'hh:mm:ss.ssssss' format. """ hours = int(seconds / 3600.0) minutes = int((seconds / 60.0) % 60.0) secs = float(seconds % 60.0) return "{0:02d}:{1:02d}:{2:02.6f}".format(hours, minutes, secs)
def strip_leading_characters(string, num): """Returns the input string after removing `num` leading characters""" return string[num:]
def image_rendering(keyword): """Validation for ``image-rendering``.""" return keyword in ('auto', 'crisp-edges', 'pixelated')
def manhattan_distance(a, b): """ Calculates the Manhattan distance between two points. """ return int(abs(a[0] - b[0]) + abs(a[1] - b[1]))
def sorted_shopping_list(shopping_list, mapping, departments_order): """ Getting shopping list, department-to-products mapping and departments order inside shop, returns products from shopping list, ordered by department location, effectively giving you optimal way to go through the market. ...
def _path_parts(path): """Takes a path and returns a list of its parts with all "." elements removed. The main use case of this function is if one of the inputs to relativize() is a relative path, such as "./foo". Args: path (str): A string representing a unix path Returns: list: A li...
def lstrip(val: str) -> str: """Remove leading whitespace.""" return val.lstrip()
def usktossk(usk, pathname): """Convert a USK to an SSK with the given pathname. >>> usktossk("USK@pAOgyTDft8bipMTWwoHk1hJ1lhWDvHP3SILOtD1e444,Wpx6ypjoFrsy6sC9k6BVqw-qVu8fgyXmxikGM4Fygzw,AQACAAE/", "folder") 'SSK@pAOgyTDft8bipMTWwoHk1hJ1lhWDvHP3SILOtD1e444,Wpx6ypjoFrsy6sC9k6BVqw-qVu8fgyXmxikGM4Fygzw,AQACAA...
def get_needed_fuel(masses, fuel_calculator): """Get needed fuel for masses using fuel_calculator function.""" return sum(fuel_calculator(mass) for mass in masses)
def filterByCloud(metalist, cmdargs): """ Filter the meta objects by cloud amount. If no cloud amount present, then all are acceptable (e.g. for Sentinel-1) """ metalistFiltered = [] for (urlStr, metaObj) in metalist: cloudPcnt = None if hasattr(metaObj, 'cloudCoverPcnt'): ...
def mean_sq(mean, var): """ Calculates <XX> of stochastic variable X """ return var + mean**2
def z_to_seq( z ): """Return a 4-element sequence (re, -im, im, re) Parameter --------- z : complex """ z = complex(z) re,im = z.real,z.imag return (re, -im, im, re)
def power_of_2(in_list): """ Return a list of powers of 2, corresponding to each value from in_list. """ return [2 ** n for n in in_list]
def convert_decimal(in_string, in_base, in_pos_list): """ Returns: Decimal Int Representation of Input. """ if in_base == 10: return str(in_string) return sum(map(lambda pos:(in_base**pos[0])*pos[1], enumerate(in_pos_list)))
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 metamodel_to_swagger_type_converter(input_type): """ Converts API Metamodel type to their equivalent Swagger type. A tuple is returned. first value of tuple is main type. second value of tuple has 'format' information, if available. """ input_type = input_type.lower() if input_type == 'd...
def commonsize(input_size): """Convert memory information to a common size (MiB).""" const_sizes = { 'B': 1, 'KB': 1e3, 'MB': 1e6, 'GB': 1e9, 'TB': 1e12, 'PB': 1e15, 'KiB': 1024, 'MiB': 1048576, 'GiB': 1073741824 } input_size = input_size.split(" ") # conv...
def check_for_missing_table(error, table_name): """ Determines if the error is caused by a missing table. Parses the exception message to determine this. Inputs ------ e (ProgrammingError): ProgrammingError exception caught during a query table_name (string): Name of the table to check. ...
def CommaSeparatedFloats(sFloatsCSV): """Read comma-separated floats from string. [sFloatsCSV]: string, contains comma-separated floats. <retval>: list, floats parsed from string. """ return [float(sFloat) for sFloat in sFloatsCSV.replace(" ","").split(",")]
def tidy_results(res): """ Function used to clean up read results before returning to the user """ for i in res: del i['_id'] del i['password'] return res
def encode(s): """Rot13-encode the given string.""" def encode_char(c): if 'A' <= c <= 'M' or 'a' <= c <= 'm': return chr(ord(c) + 13) elif 'N' <= c <= 'Z' or 'n' <= c <= 'z': return chr(ord(c) - 13) else: return c return ''.join(encode_char(c) f...
def BB_check(bb_1, bb_2): """ bb_1 and bb_2 are two bounding boxes. Each is a 4 element tuple of : (max_x,min_x,max_y,min_y) BB_check(bb_1, bb_2) returns 1 if the two boxes intersect returns 0 if the two boxes don't intersect """ if ( (bb_1[0] > bb_2[1]) and (bb_1[1] < bb_2[0]) and (bb_1[2] > bb_2...
def constrain(x: float, out_min: float, out_max: float) -> float: """Constrains ``x`` to be within the inclusive range [``out_min``, ``out_max``]. Sometimes called ``clip`` or ``clamp`` in other libraries. ``out_min`` should be less than or equal to ``out_max``. If ``x`` is less than ``out_min``, return...
def dijkstra_path(dijkstra_result, source, target): """Constructs a path from a distance map returned by Dijkstra's algorithm. Args: dijkstra_result: Distance map from Dijkstra's algorithm. source: Vertex to start path from. target: Vertex to end the path. Returns: List of ...
def is_simple_array(v): """ Return whether a value is considered to be an simple array """ return isinstance(v, (list, tuple))
def update_moments_w(x, w, m1, m2, w_sum): """Update statistical moments m1, m2 with a sample x with frequency-weight w E.g. on the first sample, m1 = w1*x1, m2 = 0 on the second sample, use m1,m2 = update_moments(w2, x2, m1, m2) m1 is the mean, m2 is the second moment sample variance = m2/(n-1), po...
def generatePairSum(search_array, expected_value): """ Returns all of the pairs whose elements sum up to expected_value """ if len(search_array) < 2: raise ValueError("Must enter a search_array with at least 2 elements to create ordered pairs") return [(x,y) for x in search_array for y in search...
def nativestr(x): """Return the decoded binary string, or a string, depending on type.""" r = x.decode("utf-8", "replace") if isinstance(x, bytes) else x if r == "null": return return r
def calculate_thermal_conductivity(thermal_diffusivity, density, specific_heat_capacity): """ Returns thermal conductivity from thermal diffusivity. k = alpha * c_p * rho :param thermal_diffusivity: :param density: :param specific_heat_capacity: :return: """ conductivity = thermal_di...
def twin_list(titanic_data): """Returns a list of tuples of pairs of passengers who are likely to be twin children, i.e., same last name, same age, same place of embarkment, and age is under 18; each tuple has the following format: (person1's "last name" + "first name", person2's "last name" + "first name") """...
def get_target(module, array): """Return Volume or None""" try: return array.get_volume(module.params['target']) except: return None
def slice_to_percent_mask(slice_value): """Convert a python slice [15:50] into a list[bool] mask of 100 elements.""" if slice_value is None: slice_value = slice(None) # Select only the elements of the slice selected = set(list(range(100))[slice_value]) # Create the binary mask return [i in selected for ...
def combine_dicts(dict1, dict2): """Combine two :class:`dict` objects into one, respecting common keys. If `dict1` and `dict2` both have key ``a``, then ``dict1[a]`` and ``dict2[a]`` must both be dictionaries to recursively merge. Parameters ---------- dict1 : :class:`dict` First dicti...
def find_length_from_labels(labels, label_to_ix): """ find length of unpadded features based on labels """ end_position = len(labels) - 1 for position, label in enumerate(labels): if label == label_to_ix['<pad>']: end_position = position break return end_position
def author_html(author, link): """ Create HTML anchor tag for author with correct link to ADSABS Inputs ------ author : str Name of the author(s) link : str Link to article Output ------ alink : str Author anchor tag to link """ if (',' in author) and (','...
def NO_VALUE(field): """ Helper function for determining the value to use when the field is an invalid value. """ if field in ('bm', 'bg', 'bs'): return 0 else: return None
def at_least_one_in_charset(must_chars, limit_chars, string): """Returns true if all string's chars are in limit_chars and at least one is in must_chars""" found_one = False for c in string: if c not in limit_chars: return False if c in must_chars: found_one = True ...
def groups_per_user(group_dictionary): """The groups_per_user function receives a dictionary, which contains group names with the list of users. Users can belong to multiple groups. It returns a dictionary with the users as keys and a list of their groups as values.""" user_groups = {} for group, users in group_di...
def if_let(expression, if_callable, else_callable=None): """ (if-let [tmp expression] (if-callable tmp) (else-callable tmp)) if_callable/else_callable can also be just a value. if it's not callable(), then we just return the value. """ if expression: if callable(if_callable): re...
def gcd(a: int, b: int) -> int: """Finds greatest common divisor between positive integers a and b Efficient, using Euclidean algorithm. Example: >>> greatest_common_divisor(15, 25) 5 """ assert a > 0 and b > 0, "Inputs should be positive integers" to_divide, remainder = max(a, b), min...
def location(C,s,k): """ Computes the location corresponding to the k-value along a segment of a polyline Parameters ---------- C : [(x,y),...] list of tuples The coordinates of the polyline. s : int The index of a segment on polyline C. Must be within [0,n-2] k :...
def multi_string(val): """Put a string together with delimiter if has more than one value""" if isinstance(val, (list, tuple)): return b"\\".join(val) # \ is escape chr, so "\\" gives single backslash else: return val
def update_cur_center(cur_center, matches, center): """Update current center""" matched = [] for match in matches: matched.append(match[0]) cur_center[match[1]] = (center[match[0]] + cur_center[match[1]]) / 2 for i in range(len(center)): if i not in matched: cur_cente...
def make_path2loc(lgrps): """ Set path2loc to map each path in lgrps (location groups) to the id of the location group associated with that path. Input is: lgrps = { 'loc1': [ 'path1', 'path2', ...]; 'loc2': ['path3', ...], ...} Return is a dictionary of form: { 'path1': 'loc1', 'path2': 'loc1', 'p...
def sensitivity_scale(x_in, sensitivity, original_min, original_max, desired_min, desired_max): """ Returns smoothed data point mapped to new range based on sensitivity """ linear_scale = ((desired_max - desired_min) * (x_in - original_min))/(original_max-original_min) + desired_min scale_to_1 = 2 / (original_max-...
def formatPath(path=''): """ This method format path and add trailing slashs. :params str path: :return str: """ if not path: return '/' else: path=path if path[0]=='/' else '/'+path path=path if path[-1]=='/' else path+'/' return path
def heuristic(point_1, point_2): """Calculates the manhattan distance between points and returns an integer""" x1, y1 = point_1 x2, y2 = point_2 man_dist = abs(x1 - x2) + abs(y1 - y2) return man_dist
def get_hashable_cycle(cycle): """ Cycle as a tuple in a deterministic order. Args ---- cycle: list List of node labels in cycle. """ # get index of minimum index in cycle. m = min(cycle) mi = cycle.index(m) mi_plus_1 = (mi + 1) if (mi < len(cycle) - 1) else 0 ...
def get_arg(arguments, index=0, convert_to_int=False): """ :param arguments: :param index: :param convert_to_int: :param do_parse: :return: """ try: arg = arguments[index].strip() if convert_to_int: return int(arg) return arg except Exception as ...
def keyOnUser(record): """ Args: record: ((user1, user2), (similarity, #movies both rated)) Returns: [(user1, (user2, similarity, #movies both rated)), (user2, (user1, similarity, #movies both rated))] """ return [(record[0][0], (record[0][1], record[1][0], record[1][1])), ...
def CallParams(method_name, proto): """Returns the parameters for calling a gRPC method Arguments: method_name: Name of the remote method to be called proto: The protobuf to be passed to the RPC method Returns: The parameters thast can be passed to grpc_cli call to execute the ...
def _resolve_subkeys(key, separator='.'): """Given a key which may actually be a nested key, return the top level key and any nested subkeys as separate values. Args: key (str): A string that may or may not contain the separator. separator (str): The namespace separator. Defaults to `.`. ...
def geom(k,p): """ Geometric probability mass function""" if(k<1): return None else: return ((1-p)**(k-1))*p
def remove_variables(variables, resnet_depth=50): """Removes low-level variables from the input. Removing low-level parameters (e.g., initial convolution layer) from training usually leads to higher training speed and slightly better testing accuracy. The intuition is that the low-level architecture (e.g., Res...
def formatTime(t): """Check if hour, minute, second variable has format hh, mm or ss if not change format. :param t: string time hh, mm or ss :return: string time in correct format eg. hh=02 instead of hh=2 """ if len(t) < 2: t = "0" + t return t
def add_lists(list1, list2): """ Add list1 and list2 and remove any duplicates. Example: list1=[1,2,3,4] list2=[3,4,5,6] add_lists(list1, list2) = [1, 2, 3, 4, 5, 6] :param list1: input list 1 :param list2: input list 2 :return: added lists with removed duplicates """ return...
def element_neg(a): """ Negate each element in a tuple """ return tuple(-x for x in a)
def dict_merge(dict1, dict2): """ Return a dict combining two underlying dict instances. """ combined = dict(dict1) combined.update(dict2) return combined
def upper(string): """UPPER CASE""" return string.upper()
def get_set_time(deadline: int): """Return time-step set: T = {1,2...tau}, tau = deadline""" T = list(range(1, deadline + 1)) return T
def _split_list(s, predicate): """Split sequence s via predicate, and return pair ([true], [false]). The return value is a 2-tuple of lists, ([x for x in s if predicate(x)], [x for x in s if not predicate(x)]) """ yes = [] no = [] for x in s: if predicate(x): ...
def factorial(n): """ Return factorial of n :param n: number :return: n! """ import math return math.factorial(n)
def mean(data): """ Calculate the average value in a numeric list """ _data = list(data) length = len(_data) if length > 0: return sum(_data)/length else: return 0
def get_classification(classification, return_codes): """Get expected classification for a host listed by a DNSBL service. :param classification: a dictionary with service return codes as its keys and classification terms pertaining to them as its values :param return_codes: a sequence of return codes ...
def keyed(v): """Convert the specified `v` into a dict keyed by the type, that will be accepted by DynamoDB""" if isinstance(v, bool): return {"BOOL": v} elif isinstance(v, int): return {"N": str(v)} elif isinstance(v, str): return {"S": v} elif isinstance(v, set): re...
def format_env_htcondor(env): """ Takes a dict of key : value pairs that are both strings, and returns a string that is formatted so that htcondor can turn it into environment variables """ return ( '"' + " ".join(["{0}='{1}'".format(key, value) for key, value in env.items()]) ...
def numbery_string_to_number(x): """ Take a string that has a number in it and returns only the numbers """ if type(x) is not str: return x a = [int(i) for i in x.split() if i.isdigit()] if len(a) == 1: return a[0] elif len(a) == 0: return None else: ...
def get_nested_value(dictionary, key): """This function reads the data from the FIO JSON file based on the supplied key (which is often a nested path within the JSON file). """ if not key: return None for item in key: dictionary = dictionary[item] return dictionary
def IsClose(a, b, rel_tol=1e-09, abs_tol=0.0): """Checks if two numerical values are same or almost the same. This function is only created to provides backwards compatability for python2 which does not support 'math.isclose(...)' function. The output of this function mimicks exactly the behavior of math.isclo...
def incremented_name(name: str) -> str: """Helper function. Returns name with the next number. Examples: test -> test_01 test_01 -> test_02 test_02 -> test_03 etc. """ digits: str = '' for c in reversed(name): if c.isdigit(): digits = c + digits...
def parse_enum_csv(key, value, enumeration, count = None): """ Parses a given value as being a comma separated listing of enumeration keys, returning the corresponding enumeration values. This is intended to be a helper for config handlers. The checks this does are case insensitive. The **count** attribute c...
def get_reply(replies, trigger): """ Get the reply dict assign to the trigger """ if replies: for reply in replies: if reply["trigger"] == trigger: return reply return None
def IDverificator(uuidList, sigh): """ This function checks for duplicate ids and creates the format to prettytable """ comparation = [] l_error = [] for uuid in uuidList: if uuid in comparation: l_error.append(["-", "Duplicate uuid", uuid, sigh]) else: comparation.append(uuid) return ...
def transform_pos(word_pos): """Map POS tag to first character lemmatize() accepts""" if word_pos == 'Noun': return 'n' elif word_pos == 'Verb': return 'v' elif word_pos == 'Adjective': return 'a' elif word_pos == '': return ''