content
stringlengths
42
6.51k
def reformat_urls(urls): """ Change urls format to store them in Elasticsearch (dot . issue) Args: urls (dict): output of urls_extractor Returns: list of all urls """ new_urls = [] for v in urls.values(): new_urls.extend(v) return new_urls
def ascii_to_hex(s: str) -> str: """A method that converts hex encoded strings to ascii encoded strings. :param s: An ascii encoded string :returns The parameter s encoded in hex format """ return s.encode().hex()
def truncate(s: str, amount: int) -> str: """Return a string that is no longer than the amount specified.""" if len(s) > amount: return s[:amount - 3] + "..." return s
def filter_max_loan_size(loan_amount, bank_list): """Filters the bank list by the maximum allowed loan amount. Args: loan_amount (int): The requested loan amount. bank_list (list of lists): The available bank loans. Returns: A list of qualifying bank loans. """ loan_size_a...
def foldl(function, xs, acc): """ To simulate reduce functionality. Start from left and take 2 elements at a time. For example: foldl(f, [a, b, c], z) == f(f(f(z, a), b), c) """ result = acc for elem in xs: result = function(result, elem) return result
def moneyformat(x, pos): """ Generic money formatter to help plot look nice """ if (x < 1000): return '$%1.0f' % x if (x < 10000): return '$%1.1fK' % (x/1000.0) if (x < 1000000): return '$%1.0fK' % (x/1000.0) if (x < 1e9): return '$%1.1fM' % (x/1.0e6) if (x < 1e12): return '$%1.1fB' % (...
def _partition_version(segments): """Partition a version list into public and local parts.""" needle = len(segments) for index, segment in enumerate(segments): try: int(segment) except ValueError: needle = index break return '.'.join(segments[:needle])...
def insert_after(sequence, offset, new_residues): """Mutate the given sequence by inserting the string `new_residues` after `offset`. Parameters ---------- sequence : sequence String of amino acids or DNA bases offset : int Base 0 offset from start of sequence, after which we s...
def rankSetList(s): """ Returns a string listing all the ranks in a set. Empty set: "none". Set containing -1: "all". """ if len(s) == 0: return 'none' elif -1 in s: return 'all' else: return ','.join([str(x) for x in s])
def all_eq(*items) -> bool: """ Tests whether all passed items are equal """ return items.count(items[0]) == len(items)
def inversion(noteset, inversion): """ increases or decreases the chord (noteset)'s inversion. """ noteset_copy = noteset.copy() noteset_copy.sort() if inversion > 0: for i in range(inversion): i=i%len(noteset_copy) noteset_copy[i]+=12 else: ...
def Bubble_Sort(arr): """ This functions loops through the array with an upper range of outer loop and it checks two elements at a time if the previous element is greater than the one next to it they swap their places. """ for i in range(0, len(arr)): for j in range(1, len(arr) - i): ...
def pretty_number(n): """Format number with comma as thousands separator""" return "{:,}".format(n)
def _NodeShape(data): """Helper callback to set default node shapes.""" node_type = data.get("type", "statement") if node_type == "statement": return "box" elif node_type == "identifier": return "ellipse" elif node_type == "magic": return "doubleoctagon" else: return ""
def get_dict_value(event_dict, *argv): """ This function takes as its first argument a dictionary, and afterwards any number of potenial keys (including none) to try to get a value for. The order of the potential keys matters, because as soon as any key yields a value it will return it (and quit). If none ...
def topolgical_sort(graph): """Given a graph in the form of a dictionary returns a sorted list Adapted from: http://blog.jupo.org/2012/04/06/topological-sorting-acyclic-directed-graphs/ :param graph: a dictionary with values containing lists of keys referencing back into the dictionary :returns: ...
def _parse_nodes_coords(osm_response): """ Parse node coordinates from OSM response. Some nodes are standalone points of interest, others are vertices in polygonal (areal) POIs. Parameters ---------- osm_response : string OSM response JSON string Returns ------- coords...
def levenshtein_distance(a, b): """Compute the Levenshtein edit distance between the sequences a and b.""" m = len(a) + 1 n = len(b) + 1 d = [[0]*n for _ in range(m)] for i in range(m): d[i][0] = i # deletion for j in range(n): d[0][j] = j # insertion for i in range(1, m): for j in...
def count(iterable): """ Consumes all items in an iterable and returns a count. """ n = 0 for item in iterable: n += 1 return n
def cli_db_params_from_dsn(dsn, user=None, database=None, port=None, host=None): """Convert DB-related command-line arguments from a DSN into a format appropriate for DIRBS CLI commands.""" db_args = [] db_args.append('--db-user={0}'.format(user if user is not None else dsn.get('user'))) db_args.append(...
def make_list(data): """Ensure data is a list :param data: data to check :returns: data as list """ if isinstance(data, list): return data if data is None: return [] return list(data) if not isinstance(data, str) else [data]
def size_of_cycle(number): """Crude function that counts cycles in long division of 1 by various numbers""" cycles = 1 def make_big_enough(n): while n < number: n *= 10 return n start = make_big_enough(10) remainder = start % number figures = [start, start - remain...
def good2Go(SC, L, CC, STR): """ Check, if all input is correct and runnable """ if SC == 1 and L == 1 and CC == 1 and STR == 1: return True else: print(SC, L, CC, STR) return False
def strip_and_split(s): """strip trailing \x00 and split on \x00 Useful for parsing output of git commands with -z flag. """ return s.strip("\x00").split("\x00")
def edit_distance(word1: str, word2: str) -> int: """Check the edit distance between 2 words""" memo = [[0 for _ in range(len(word2) + 1)] for _ in range(len(word1) + 1)] for i in range(len(word1) + 1): memo[i][0] = i for j in range(len(word2) + 1): memo[0][j] = j for i in range(1,...
def extract_shape(descriptor, key): """ Work around bug in https://github.com/bluesky/ophyd/pull/746 """ # Ideally this code would just be # descriptor['data_keys'][key]['shape'] # but we have to do some heuristics to make up for errors in the reporting. # Broken ophyd reports (x, y, 0). We...
def firstLetterCipher(ciphertext): """ Returns the first letters of each word in the ciphertext Example: Cipher Text: Horses evertime look positive Decoded text: Help """ return "".join([i[0] for i in ciphertext.split(" ")])
def square_digits(num): """"Return concatednated square of every digit of a given number""" num_list = [int(digit)**2 for digit in str(num)] return int(''.join(str(digit) for digit in num_list))
def remove_cols(df, cols): """Safely remove columns from dict.""" for key in cols: try: del df[key] except KeyError: pass return df
def create_Interfaces_Params(typeid, mainid, useip, ip, dns, port): """ typeid: 1-agent,2-SNMP,3-IPMI,4-JMX mainid: 0-not default,1-default useip: 0-usedns,1-useip """ interfaces = [{ "type": typeid, "main": mainid, "useip": useip, "ip": ip, "dns": dns, ...
def strip_non_alphabetical_characters(word, ignore=None): """Helper function for removing any non-alphabetical character with optional exclusion list. Wiktionary etymologies are a mess to parse. This function attempts to extra clean-up cases like *(-ness* or *"king+*. Optionally, it will return only strings th...
def build_constituents(sent_id: int, s: str) -> dict: """ """ s = s.rstrip().lstrip() open_bracket = s[0] # ( or [ close_bracket = s[-1] # ) or ] return { 'sent_id': sent_id, 'labeledBracketing': f'{open_bracket}ROOT {s}{close_bracket}' if s[1:5] != 'ROOT' else s }
def _check_biomart_response(response): """ Return True if the response doesn't look like an query ERROR or 404 page. >>> _check_biomart_response('') False >>> _check_biomart_response('<html>') False >>> _check_biomart_response('Query ERROR: caught BioMart::Exception') False >>> _che...
def join_path(parentpath, name): """Join a *canonical* `parentpath` with a *non-empty* `name`. .. versionchanged:: 3.0 The *parentPath* parameter has been renamed into *parentpath*. >>> join_path('/', 'foo') '/foo' >>> join_path('/foo', 'bar') '/foo/bar' >>> join_path('/foo', '/foo2...
def get_service_entry_info(service_entry): """Gets service name and instance of a service entry :service_entry: service entry name :return: tuple with service_name and instance name """ entry_split = service_entry.split("_") name = entry_split[0] instance = entry_split[1] return name, i...
def mixed_radix_to_base_10(x, b): """Convert the `mixed radix`_ integer with digits `x` and bases `b` to base 10. Args: x (list): a list of digits ordered by increasing place values b (list): a list of bases corresponding to the digits Examples: Generally, the base 10 representatio...
def _OtherVert(tri, a, b): """tri should be a tuple of 3 vertex indices, two of which are a and b. Return the third index, or None if all vertices are a or b""" for v in tri: if v != a and v != b: return v return None
def get_train_order(training_data, batch_size): """ :param data: List of tuples of source sentences and morph tags :return: start idxs of batches """ lengths = [len(sent) for sent in training_data] start_idxs = [] end_idxs = [] prev_length=-1 batch_counter = 0 for i, length in enumerate(lengths, s...
def textbetween(variable, firstnum=None, secondnum=None, locationoftext='regular'): """ Get The Text Between Two Parts """ if locationoftext == 'regular': return variable[firstnum:secondnum] elif locationoftext == 'toend': return variab...
def escape(s): """Helper for escaping semicolon by urlencoding.""" return s.replace(";", "%3B")
def getitem(dict, item): """ my_dict|getitem:'b' """ try: return dict.get(item) except KeyError: return ''
def identifier_has_block_data (identifier): """ Returns true if the identifier has block metadata, which affects both the display and the editability of the metadata in the UI. """ return (identifier["_profile"] == "erc" and "erc" in identifier) or\ (identifier["_profile"] == "datacite" and "datacite" in ...
def plural(items_or_count, singular: str, count_format='', these: bool = False, number: bool = True, are: bool = False) -> str: """Returns the singular or plural form of a word based on a count.""" try: count = len(items_or_count) except TypeEr...
def toCl(exp,terminate=False,wildcards=('*',' '),lower=True): """ Replaces * by .* and ? by . in the given expression. """ ## @PROTECTED: DO NOT MODIFY THIS METHOD, MANY, MANY APPS DEPEND ON IT exp = str(exp).strip() if lower: exp = exp.lower() if not any(s in exp for s in ('.*','\*',']*')): ...
def idx(i, j, n): """Let A[:, :] be a symmetric matrix (squareform) of size n by n with zeros on the diagonal Let L[:] be the longform of A. Then for i < j, we have A[i, j] = L[idx(i, j, n)]""" return n * (n - 1) // 2 - (n - i) * (n - i - 1) // 2 + j - i - 1
def version_to_string(version, parts=3): """ Convert an n-part version number encoded as a hexadecimal value to a string. version is the version number. Returns the string. """ part_list = [str((version >> 16) & 0xff)] if parts > 1: part_list.append(str((version >> 8) & 0xff)) i...
def get_date(fld): """input a date field, strip off the time and format :Useage - get_date(!FieldName!) :From - 2017-06-17 20:35:58.777353 ... 2017-06-17 :Returns -2017-06-17 """ if fld is not None: lst = [int(i) for i in (str(fld).split(" ")[0]).split("-")] return "{...
def sorted_alnum(list_): """ Returns a list sorted in-place alphanumerically. Useful for directories, like /proc, that contain pids and other files """ # Sort alphabetically list_.sort() # Sort numerically list_.sort(key=lambda x: int(x) if x.isdigit() else float('inf')) return list_
def mysplit2(s) -> str: """ Divide a string in their numerical content and their letters. Only works for strings like ('abcde144141'). """ head = s.rstrip('0123456789') tail = s[len(head):].zfill(3) both = head + tail return str(both)
def get_floating_ip(body_response_server_details, network_name): """ Retrieve the first floating IP from the given network attached to VM :param body_response_server_details: (dic) Parsed response. Server details data :param network_name (String): Name of the network where floating IP is allocated. ...
def _sorted_list(iterable, reverse=False): """ Transform an iterable to a sorted list. """ a = list(iterable) a.sort() if reverse: a.reverse() return a
def generate_numbers(partitions): """Return a list of numbers ranging from [1, partitions].""" return list(range(1, partitions + 1))
def iob1_to_iob2(annotated_sentence): """ Converts list of annotated sentences with entities encoded in the IOB1 scheme to a list with entities encoded in IOB2. Parameters ---------- annotated_sentence : list The list contains tuples (w1, t1, iob1), where w1 is the token and iob1 is...
def get_key(element, *keys): """ Check if *keys (nested) exists in `element` (dict). """ if not isinstance(element, dict): raise AttributeError('keys_exists() expects dict as first argument.') if len(keys) == 0: raise AttributeError('keys_exists() expects at least two arguments, one ...
def convert_dict_keys_to_strings(dictionary): """ Convert all the keys of the dictionary to strings, no matter which type they are. :param dictionary: dict() :return: dict() with converted keys """ res = dict() for p in dictionary: if isinstance(dictionary[p], dict): ...
def bytes_to_bool(byte_array): """ Encode boolean to a 1 byte array :param val: boolean value :return: a bytes object """ return bool(int(byte_array[0]))
def check_collision(targetX, targetY, targetWidth, targetHeight, x, y, width=0, height=0): """This is used to check to see if the target is colliding with the non-target.""" #Are we doing a box collision check? if width != 0: #print "Ax:%d, Aw:%d, Bx:%d, Bw:%d" % (x, width, targetX, target...
def calc_pmf(data, window): """Calculate probability mass function Args: data (list) window (int) Returns: dict """ lib = {} for i in range(window, len(data)): x = '_'.join([str(data_i) for data_i in data[i - window:i]]) if x not in lib:...
def make_entry( user_id=None, name=None, avatar_url=None, key=None, approved=False, valid=False ): """Template for the DB entry""" return { 'id': user_id, 'name': name, 'avatar_url': avatar_url, 'key': key, 'approved': appro...
def _rawopt(n): """ Reduce option name. """ return n.lstrip("--").lstrip("-")
def to_upper(string: str) -> str: """ Converts :string: to upper case. Intended to be used as argument converter. Returns ------- :class:`str` String to upper case """ return string.upper()
def getDomainOnly(url): """Return the domain out from a url url = the url """ # print ("getDomainOnly : ", url) tmp = url.split('.')[-2] + '.' + url.split('.')[-1] tmp = tmp.split('/')[0] return tmp
def is_info(file_name: str) -> bool: """Determines if a filename is a proper info name.""" return file_name == "info"
def _is_numeric(s) -> bool: """ Check if variable converted to float. :param s: any type variable :return: is variable convertable to float """ try: float(s) return True except ValueError: return False
def build_object_reference(body): """ Construct an object reference for the events. """ return dict( apiVersion=body['apiVersion'], kind=body['kind'], name=body['metadata']['name'], uid=body['metadata']['uid'], namespace=body['metadata']['namespace'], )
def equals(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when t...
def id_in_response(response:dict, has_site_id:bool=False): """Check if there is an \"id\" property with \"uuid\" and optionally \"site\" sub-properties in the response dict""" id_keys = {"uuid"} if has_site_id: id_keys.add("site") return ( "id" in response.keys() and i...
def _buildArgOptName(functionName, keywordName): """Builds the argument name to be in the argparser help.""" return '--' + functionName + '-' + keywordName
def calc_bin(value, bound_min, bound_max, bins): """Find bin in parameter range. Args: value (float): some value, the result of a simulation. bound_min (float): lower limit, defining the parameter-space. bound_max (float): upper limit, defining the parameter-space. bins (int): nu...
def create_diff_report(original_text_tokens: tuple, suspicious_text_tokens: tuple, accumulated_diff_stats: dict) -> str: """ Creates a diff report for two texts comparing them line by line :param original_text_tokens: a tuple of sentences with tokens :param suspicious_text_tokens: a tuple of sentences w...
def _chr(i: int) -> bytes: """Create a byte sequence of length 1. U{RFC 854<https://tools.ietf.org/html/rfc854>} specifies codes in decimal, but Python can only handle L{bytes} literals in octal or hexadecimal. This helper function bridges that gap. @param i: The value of the only byte in the sequ...
def update_points_crossing_antimeridian(listofpoints): """Return list of points which account for crossing of antimeridian""" if len(listofpoints) == 0: return(listofpoints) antimeridianlistofpoints = [] diff = 325.0 referencepointlon = listofpoints[0]['lon2'] crossingeasttowest = F...
def spectral_projection(u,eigenpairs): """ Returns the coefficients of each eigenvector in a projection of the vector u onto the normalized eigenvectors which are contained in eigenpairs. eigenpairs should be a list of two objects. The first is a list of eigenvalues and the second a lis...
def byte_pos(text, line, col): """ Return position index of (line, col) line is line index, col is column index The returning byte position __includes__ all '\n's. Text is unicode. """ if type(text) != list: lines = text.splitlines(True)[:line+1] else: lines = text[:line+1...
def contain_same_digit(a, b): """ This function tests whether or not numbers a and b contains the same digits. """ list_a = list(str(a)) list_b = list(str(b)) if len(list_a) == len(list_b): for elt in list_a: if elt not in list_b: return False return T...
def condense_atomic_map(atomic_map: dict) -> list: """Create condensed representation of the polar strength map. Polar strength map generated from `calculate_polar_strength_map()`. Args: atomic_map: polar strength map for all atoms in the system. """ condensed_map = list() for idx, props ...
def estimate(values, target): """ Given an array of parametrised values, estimates """ # next time # diff(values) return 1.
def truncate(f, n): """ Floors float to n-digits after comma. """ import math return math.floor(f * 10 ** n) / 10 ** n
def remove_last(list_of_data, index): """remove last time from data json or last_chronos array""" if len(list_of_data[index]) > 0: list_of_data[index].pop() return list_of_data
def possible_moves(node, game_map): """ Finds the possible neighbors of a node given the map """ y, x = node neighs = [] for i in [(y+1, x), (y-1, x), (y, x+1), (y, x-1)]: # Creates the list of tuples of possible neighbors if 0 <= i[0] < len(game_map) and 0 <= i[1] < len(game_map[0]): ...
def number_less_than(element, value, score): """Check if element is lower than config value. Args: element (float) : Usually vcf record value (float) : Config value score (integer) : config score Return: Float: Score """ if element < value: return s...
def complete_overlap(reg1, reg2): """ Return whether one of the two given regions contain the other. e.g. [10, 40], [20, 30] returns True. """ regions = sorted([sorted(reg1), sorted(reg2)]) try: return (((regions[0][0] == regions[1][0]) and (regions[0][1] <= regions[1][1...
def crop_center(width, height, target_width, target_height): """ Only crops if the image is bigger than targets. """ left = max(0, int(round((width - target_width) / 2.0))) top = max(0, int(round((height - target_height) / 2.0))) right = int(round((width + min(width, target_width)) / 2.0)) b...
def _get_default_headers( user_agent, content_type="application/json; charset=UTF-8", x_upload_content_type=None, ): """Get the headers for a request. Args: user_agent (str): The user-agent for requests. Returns: Dict: The headers to be used for the request. """ return {...
def get_temp_var(used_vars): """get a temp variable name """ for i in range(0, 1000): var_name = "t{}".format(i) if var_name not in used_vars: return var_name
def get_job_type_word_form(job_count): """ Get the singular / plural word form of a job type. While this function only returns "package" or "packages" it allows external code to replace the function with custom logic. :param job_count: The number of jobs :rtype: str """ return 'package...
def generate_uniform_prior(params, indent=4): """ Generates the JAGS prior declarations for a list of parameters. The strings are generated using a specifiable number of indentation whitespaces. """ prior_strings = [] for p in params: prior_strings.append( "{}{} ~ dunif(...
def groupBy(key, iterable): """ groupBy(key: function, iter: iterable) iterable elements grouped by key function args: key = L x: x%2, iter = [1,2,3] return: {0:[2], 1:[1,3]} """ res = {} for x in iterable: k = key(x) if k no...
def format_path(path_list): """ Formats path from raw APRS KISS frame. :param path_list: List of path elements. :type path_list: list :return: Formatted APRS path. :rtype: str """ return ','.join(path_list)
def mapping(target): """Map the value to true and false.""" if target > 6: return True return False
def iterable(obj): """ https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable """ try: iter(obj) except Exception: return False else: return True
def intersect_vectors_with_ground_plane(pose_ned, ground_m, v_list): """Intersect vectors with the ground plane.""" pt_list = [] for v in v_list: # solve projection p = pose_ned if v[2] > 0.0: d_proj = -(pose_ned[2] + ground_m) factor = d_proj / v[2] ...
def matrix_transpose(matrix): """matrix_transpose: returns the transpose of a 2D matrix. Args: matrix: matrix that is received to be transposed """ result = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))] return result
def plural_s(val): """ returns "s" if val > 1 or "" otherwise. Can be used in strings to have proper plural form. """ if val > 1: return "s" return ""
def parse_override_config(namespace): """Parse the command line for overriding the defaults""" overrides = dict() for config in namespace: kv = config.split("=") if len(kv) != 2: raise Exception("Invalid config property format (%s) expected key=value" % config) if kv[1] in ['true', 'True', 'TRUE...
def authorize_subscription(topic_name, connection): """ Says if a user can subscribe to a topic or not. Return: True or False and the error message ("" if no error occured). """ assert topic_name, "authorize_subscription requires topic_name" assert connection, "authorize_subscription requires co...
def _format_command_args(args): """Format command arguments and trim them as needed""" value_max_len = 100 value_too_long_mark = "..." cmd_max_len = 1000 length = 0 out = [] for arg in args: cmd = str(arg) if len(cmd) > value_max_len: cmd = cmd[:value_max_len] + ...
def get_gamma_distribution_params(mean, std): """Turn mean and std of Gamma distribution into parameters k and theta.""" # mean = k * theta # var = std**2 = k * theta**2 theta = std**2 / mean k = mean / theta return k, theta
def isPowerOfThree(n): """ :type n: int :rtype: bool """ return n > 0 and 1162261467 % n == 0
def memb_left_sh(x, shoulder): """ This function determines the membership value belonging to the user defined left shoulder INPUTS x - the value center - center of user defined left shoulder right - right value of user defined left shoulder left - left value of user defined left shoulder ""...