content
stringlengths
42
6.51k
def get_n_largest(n, lst, to_compare=lambda x: x): """ This returns largest n elements from list in descending order """ largests = [lst[0]]*n # this will be in descending order for x in lst[1:]: if to_compare(x) <= to_compare(largests[-1]): continue else: fo...
def dict2str(opt, indent_level=1): """dict to string for printing options. Args: opt (dict): Option dict. indent_level (int): Indent level. Default: 1. Return: (str): Option string for printing. """ msg = '' for k, v in opt.items(): if isinstance(v, dict): ...
def find_parens(s): """Get indices of matching parantheses in a string.""" # Source: https://stackoverflow.com/questions/29991917/indices-of-matching-parentheses-in-python toret = {} pstack = [] for i, c in enumerate(s): if c == '(': pstack.append(i) elif c == ')': ...
def get_members_and_supervisors(organization): """Return a tuple (members[], supervisors[]) for a given organization. Deals with the empty lists and null objects for you so you don't have to. The contents of the tuples are reporter objects. """ members = [] supervisors = [] ...
def _run_task_hook(hooks, method, task, queue_name): """Invokes hooks.method(task, queue_name). Args: hooks: A hooks.Hooks instance or None. method: The name of the method to invoke on the hooks class e.g. "enqueue_kickoff_task". task: The taskqueue.Task to pass to the hook method. queue_na...
def pp(x0,U,lam,L): """ pp means (p)robability to escape right with (p)ositive initial vel. """ return (U + x0*lam)/(U + L*lam)
def fmt_price(amt): """ Format price as string with 2 decimals """ return '{:,.2f}'.format(amt)
def tobytes(data): """convert str or int to bytes""" if type(data) is int: data = chr(data) if type(data) is str and str is not bytes: data = data.encode('utf8') return data
def group(items, n): """Group sequence into n-tuples.""" return list(zip(*[items[i::n] for i in range(n)]))
def recursive_search(event, lst, list_pointer, list_len): """Retrieve events from nested dict. Used to check if values in the template exists inside the event dictionary Parameters ---------- event : {dict} Dictionary of the JSON response from ESM lst : {string} Confi...
def key_in_slice(k, s): """Check if the key k is part of the slice s.""" if not isinstance(k, tuple): k = (k,) for i in range(len(s)): if (not isinstance(s[i], slice)) and k[i] != s[i]: return False if isinstance(s[i], slice): if s[i].start is not None and k[i...
def ChangeBackslashToSlashInPatch(diff_text): """Formats file paths in the given patch text to Unix-style paths.""" if not diff_text: return None diff_lines = diff_text.split('\n') for i in range(len(diff_lines)): line = diff_lines[i] if line.startswith('--- ') or line.startswith('+++ '): diff...
def namelist(names: list) -> str: """ Format a string of names like 'Bart, Lisa & Maggie' :param names: an array containing hashes of names :return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersa...
def has_segment_fraction_info(connections): """Check if connections include fraction information :param connections: list of connection objects :type connections: list :returns: True if connections include fragment information, otherwise False :rtype: Boolean """ if not connections: ...
def string_to_list(s): """ Convert argument string (of potentially a list of values) to a list of strings :param s: str :return: list[str] """ if s is not None: s = [c.strip() for c in s.split(',')] return s
def c_to_f(c): """Input: Temperature in celsius (or possibly None) Returns a human-friendly string in Fahrenheit. """ try: f = "%d degrees" % round(c * 9 / 5 + 32,0) except Exception as e: f = "temperature not available" pass return f
def find_odd_number(nums): """ Find one number in array which is not duplicated, or exsits odd times. """ s = 0 for n in nums: s ^= n return s
def get_carrier_index(option): """ Get an integer representing a pulse definition's carrier mode. """ if option == 'DRAG': return 3 if option == 'None': return 0 return int(option)
def retrieve_prop_from_edge(edge_info, prop): """Retrieve property info from the edge data.""" if prop == 'api': data = edge_info['info'].get('$api') if data: if not isinstance(data, list): data = [data] return ','.join(data) elif prop == 'source': ...
def value_in_range(number: int, low_bound: int, up_bound: int) -> bool: """The value is within the range given in your puzzle input.""" if low_bound <= number <= up_bound: return True return False
def statelist2dict(names,statestrings): """Converts a collection of statestrings to a dictionary. Parameters ---------- names : list of str An ordered list of variable names; (alphabetical order is pyboolnet's default, e.g. sorted(primes)). c : iterable of str Each element s...
def make_bold(text): """Wrap input string in HTML bold tag.""" return f'<b>{text}</b>'
def quote(amount_token1: int, reserve_token1: int, reserve_token2: int) -> int: """ Calculates the amount of token2 tokens that have the same value as the amount_token1. :param amount_token1: the amount of token1 :type amount_token1: int :param reserve_token1: how many token1 tokens are in the AMM ...
def get_rect_xmax(data): """Find maximum x value from four (x,y) vertices.""" return max(data[0][0], data[1][0], data[2][0], data[3][0])
def hex2rgb(hexcolor: str) -> tuple: """Convert a hexadecimal color to an RGB tuple. The returned values are always integers in ``range(256)``. >>> hex2rgb('#00ffff') (0, 255, 255) >>> hex2rgb('#0ff') (0, 255, 255) >>> hex2rgb('#000ffffff') (0, 255, 255) """ if hexcolor == '#' ...
def mapping_facebook_user_info_to_sso_user_info( cognito_id, cognito_email, facebook_user_info ): """ Map the Facebook ID token info to the user info. """ sso_user_info = dict() sso_user_info["cognito_id"] = cognito_id sso_user_info["cognito_email"] = cognito_email sso_user_info["federat...
def is_dict(object): """RETURN : True/False """ return isinstance(object, dict)
def walk(path, container): """ Recurse over the ActBlue JSON object, and get the values that we need, based on the settings file. Returns a single value for each path. """ if not container or isinstance(container, str): return None key = path[0] if len(path) == 1: if key...
def lucasLehmer(p): """ Teste de Lucas-Lehmer para detectar numeros de Mersenne primos """ if p == 2: return True # 2 ^ p - 1 mersenne = ( 1 << p ) - 1 print("M(%d) = %d" % (p, mersenne)) s = 4 print ("S0 = %d" % (s)) for i in range(1, p - 1): print("...
def check_flan_flavor(flavor): """Determine what kind of flavor we want for our Flan.""" if not flavor: flan_flavor = "plain old boring" else: flan_flavor = flavor return (flan_flavor + " flavored flan")
def to_seconds(days=None, hours=None): """ Convert given day/hours to seconds and return :param int days: days to be converted :param int hours: hours to be converted """ #only either days or hours should be speciefied, but atleast one should be specified if days and hours: raise Sys...
def thumbnail_url(img_uri, canvas_uri, width, height, compliance_lvl, canvas_dict): """ Create a URL for a thumbnail image. """ can_uri_parts = canvas_uri.split('#xywh=') fragment = 'full' if len(can_uri_parts) == 2: fragment = can_uri_parts[1] if compliance_lvl >= 2: ...
def combine_biases(*masks): """Combine attention biases. Args: *masks: set of attention bias arguments to combine, some can be None. Returns: Combined mask, reduced by summation, returns None if no masks given. """ masks = [m for m in masks if m is not None] if not masks: return None assert ...
def may_raise(f): """ Return the set of exceptions that a callable may raise. Returns {:class:`Exception`} if the callable has made no more precise declaration. """ try: return set(getattr(f, '_raises__xc_raises')) except: return set((Exception,))
def latest_of(upcoming_departures): """ for each departure in the list: if there isn't an equivalent departure already in the new list then add it otherwise (if there _is_ a equivalent departure in the new list) then if this one is newer replace that one than this one ...
def findall(element, path): """Safe helper method to find XML elements with guaranteed return type.""" if element is None: return [] return element.findall(path)
def digitsProduct(product): """ Given an integer product, find the smallest positive (i.e. greater than 0) integer the product of whose digits is equal to product. If there is no such integer, return -1 instead. Time Complexity: O(inf) Space Complexity: O(1) """ number = 1 ...
def heading_parse(index, lines_read_list): """heading tags""" count_heading = 0 list_heading = [] min_level = 1 max_level = 6 while (index < len(lines_read_list)): if lines_read_list[index][0] != '#': break data = lines_read_list[index].strip() headi...
def boolean2str(flag): """Returns string representation of boolean flag""" if flag: return "True" else: return "False"
def chop_at(s, sub, inclusive=False): """Truncate string ``s`` at the first occurrence of ``sub``. If ``inclusive`` is true, truncate just after ``sub`` rather than at it. >>> chop_at("plutocratic brats", "rat") 'plutoc' >>> chop_at("plutocratic brats", "rat", True) 'plutocrat' """ pos...
def get_parent_folder(path, sep="/"): """Returns the path corresponding to the parent folder of <path>.""" l = len(path) n = -1 for i in range(l-2, -1, -1): if path[i] == sep: n = i break if n > 0: return path[:n+1] else: return -1
def rel_error(*args): """ :param args: [actual, predicted] :return: Relative Error """ return args[1] - args[0]
def mask(x): """ Masking bits Used by xor_hex_search() and xor_text_search() """ if x >= 0: return 2 ** x - 1 else: return 0
def extract_config(configuration): """ This pulls the content from the configuration file at `configuration` location then parses it to populate the list_of_content variable that contains all contents that needs to be pulled and processed. :param configuration: Documentation build configuration file...
def _get_delta_list(integer_list): """For [0, 10, 11, 22, 25] return [10, 1, 11, 3].""" if (len(integer_list) > 0) and (integer_list[0] != 0): raise SystemExit('integer_list[0] = {} != 0'.format(integer_list[0])) if integer_list != sorted(integer_list): raise SystemExit('integer_list not sor...
def search(L, e): """Assumes L is a list, the elements of which are in ascending order. Returns True if e is in L and False otherwise""" def bin_search(L, e, low, high): #Decrements high - low if high == low: return L[low] == e mid = (low + high)//2 ...
def _parity_set(index): """ The bits whose parity stores the parity of the bits 0 .. `index`. Used in Bravyi-Kitaev transform. """ indices = set() # For bit manipulation we need to count from 1 rather than 0 index += 1 while index > 0: indices.add(index - 1) # Remove le...
def degF_to_degC(degF): """ Convert degF to degC Parameters ---------- degF : float Temperature in Fahrenheit. Returns ------- Temperature in Celsius """ return (degF - 32) * (5 / 9)
def _is_in_bounds(x: int, y: int, width: int, height: int) -> bool: """ Returns whether or not a certain index is within bounds. Args: x (int): x pos. y (int): y pos. width (int): max x. height (int): max y. """ if x < 0: return False if y < 0: re...
def arg_return_greeeting(name): """ this is greeting function with argument and return greeting message :param name: :return: """ message=F"hello {name}" return message
def session_ps_14bit(max_h, max_w): """Trim size to 14-bit limitation """ # why 16383 instead of 16384 for 14-bit? max_h = max(max_h, 24) max_w = max(max_w, 80) max_h = min(max_h, 204) # 16383 // 80 max_w = min(max_w, 682) # 16383 // 24 if max_h >= 127 and max_w >= 129: return...
def isfloat(str1): """ Check if a string is a float """ try: float(str1) except ValueError: return False return True
def clean_dict(d: dict, r=0, trash=[[], {}], verbose=0): """ rm all trash in a dict no deepcopy, thus potential side-effects trash :: list of values to remove return :: copy of d """ result = {} for k, v in d.items(): if not d[k] in [[], {}]: if r > 0: v ...
def CleanWords(WordList): """ Pass in a wordlist and this method will return the same list of words, with no whitespace either side of each word. """ return [word.strip() for word in WordList]
def _translate_backupjobrun_summary_view(context, backupjobrun): """Maps keys for backupjobruns summary view.""" d = {} d['id'] = backupjobrun['id'] d['created_at'] = backupjobrun['created_at'] d['status'] = backupjobrun['status'] return d
def add_begining_slash(string): """ Add begining slash """ if len(string)>0 and string[0] != '/': string = '/'+string return string
def _select_anno(annotation): """ Select annotation from multiple elements """ options = annotation.split(",") return options[0]
def to_iso_8601_format(dt): """ Convert the supplied datetime instance to the ISO 8601 format as per API specs. :param dt: The datetime instance to convert. :return: Supplied datetime as timestamp in ISO 8601 format. """ if not dt: return if isinstance(dt, str): return dt ...
def widthratio(value, max_value, max_width): """ Does the same like Django's `widthratio` template tag (scales max_width to factor value/max_value) """ ratio = float(value) / float(max_value) return int(round(ratio * max_width))
def strip_matching(from_str, char): """Strip a char from either side of the string if it occurs on both.""" if not char: return from_str clen = len(char) if from_str.startswith(char) and from_str.endswith(char): return from_str[clen:-clen] return from_str
def twos_difference(lst): """ Given an array of integers returns a list of tuples in ascending order with integers 2 numbers apart. :param lst: an array of integer values. :return: all pairs of integers from a given array of integers that have a difference of 2. """ return sorted((i, j) for i in...
def valid_post_data(data, required_keys): """ Return any missing required post key names. """ return [key for key in required_keys if not key in data]
def percentage(part, whole): """ Simple utility for calculating percentages """ return 100 * float(part) / float(whole)
def form_template(result, train_label, test_label, adversarial_validation_result, threshold) -> str: """ Validation template former This function put together all results of adversarial validation :param Result related values: train_label, test_label, adversarial_validation_result, threshold :return:...
def replace_tags(s, from_tag='i', to_tag='italic'): """ Replace tags such as <i> to <italic> <sup> and <sub> are allowed and do not need to be replaced This does not validate markup """ s = s.replace('<' + from_tag + '>', '<' + to_tag + '>') s = s.replace('</' + from_tag + '>', '</' + to_tag...
def check_socket(port): """Check whether the given port is open to bind""" import socket from contextlib import closing with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: try: sock.bind(('', port)) except: #Port is not open res =...
def strip_anything_before_h1_from_html(html): """ Strip everything before the first <h1> tag in the html Parameters: html - the html potentially containing a <h1> Returns: The same html, but without anything before the first <h1> tag (if there is one) """ stripped_html = html.strip() ...
def adds_args(*args): """Adds an arbitrary number of arguments Keyword argument: args (iterable of numbers) -- an iterable containing numbers Returns number -- Sum of all the numbers in args Ways to use the function: 1) With hand-written arguments: adds_args(10), adds_args(10, ...
def tokenize(s): """Convert a string into a list of tokens.""" return s.replace('(', ' ( ').replace(')', ' ) ').split()
def map_bits_to_bitvectors(vrs): """Return `dict` that maps each bit to an array expression.""" renaming = dict() for var, attr in vrs.items(): typ = attr['type'] if typ == 'bool': renaming[var] = var continue assert typ == 'int', typ bitnames = attr['...
def get_etc_shadow_algorithm(string: str): """Returns the salt found within the line retreived from the /etc/shadow file Examples: >>> line_from_etc_shadow = 'root:$1$umqC71l2$370xDLmeGD9m4aF/ciIlC.:14425:0:99999:7:::'\n >>> get_etc_shadow_algorithm(line_from_etc_shadow)\n 'MD5' ...
def dig(dictionary, *keys): """ Retrieves the value corresponding to each `keys` repeatedly from `dictionary`. Examples: ```python from flashback.accessing import dig # Without dig dictionary.get("key1", {}).get("key2", {}).get("key3") # With dig dig(dictio...
def _try_f2i(x): """If possible, convert float to int without rounding. Used for log base: if not used, base for log scale can be "10.0" (and then printed as such by pgfplots). """ return int(x) if int(x) == x else x
def restore_downloads(torrent_client, params): """ Restore partial torrent downloads, i.e. torrents in 'finished' state. params['info_hashes']: list of str - the list of info-hashes :return: 'OK' """ for info_hash in params['info_hashes']: torrent_client.set_piece_priorities(info_hash, ...
def check_type_of_nest_spec_keys_and_values(nest_spec): """ Ensures that the keys and values of `nest_spec` are strings and lists. Raises a helpful ValueError if they are. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nest...
def parse_longitude(x): """ Parses longitude-coordinate out of a latitude/longitude-combination (separated by ','). """ y = x.strip().split(',') return float(y[1])
def M(metric_name): """Make a full metric name from a short metric name. This is just intended to help keep the lines shorter in test cases. """ return 'django_migrations_%s' % metric_name
def get_priority(filter_item): """ Internal worker function to return the frame-filter's priority from a frame filter object. This is a fail free function as it is used in sorting and filtering. If a badly implemented frame filter does not implement the priority attribute, return zero (otherwise s...
def roll(state, dice): """Apply the roll action to a state (and a die roll d) to yield a new state. If d is 1, get 1 point (losing any accumulated 'pending' points), and it is the other player's turn. If d > 1, add d to 'pending' points. """ player, me, you, pending = state if dice == 1: ...
def yakovsky_change_unit(dadt): """ Change the drift of Yarkovsky effect from AU/Myr to AU/year. Essencial for some orbital integrators. """ for i in range(len(dadt)): dadt [i] =dadt[i]/(1.e6) return dadt
def namespace_result(dictionary, namespace): """Namespace the response This method takes the keys in the map and add a prefix to all the keys (the namespace):: resp = dict(key='value', index='storage') namespace_response(resp, 'namespace') # Returns: {'namespace.index': 'storage', ...
def silverS(home_score, away_score): """Calculate S for each team (Source: https://www.ergosum.co/nate-silvers-nba-elo-algorithm/). Args: home_score - score of home team. away_score - score of away team. Returns: 0: - S for the home team. 1: - S for the away team. ""...
def format_size(num_bytes): """Create a human readable string from a byte count.""" for x in ('bytes', 'KB', 'MB', 'GB', 'TB'): if num_bytes < 1024.0: return "%3.1f %s" % (num_bytes, x) num_bytes /= 1024.0
def rows(start, rows, max_rows=200): """Checks that the number of rows provided is valid.""" try: rows = int(rows) except: if rows != "all": raise TypeError("rows must be an integer-type or 'all'") if rows == "all" or rows > max_rows: # We may have to run multiple queries h...
def page_not_found(e): """Return a custom 404 error.""" return 'Sorry, nothing at this URL.', 404
def _construct_key(previous_key, separator, new_key): """ MIT License Copyright (c) 2016 Amir Ziai Returns the new_key if no previous key exists, otherwise concatenates previous key, separator, and new_key :param previous_key: :param separator: :param new_key: :return: a string if previ...
def aggregate_metrics(*value_update_tuples): """Aggregates the metric value tensors and update ops into two lists. Args: *value_update_tuples: a variable number of tuples, each of which contain the pair of (value_tensor, update_op) from a streaming metric. Returns: a list of value tensors and a li...
def do_wordcount(s): """ Count the words in that string. """ return len([x for x in s.split() if x])
def dereference_symbols(bv, il_instruction): """If the instruction contains anything that looks vaguely like a hex number, see if there's a function there, and if so, replace it with the function symbol.""" if il_instruction is not None: out = [] for item in il_instruction.tokens: ...
def _evaluate(comp): """ Evaluates the value of a given expression component. Parameters ---------- comp : dict Dictionary of references, coefficient and operator Returns ------- v : float Current value of the expression. """ ref = comp['ref'] val = comp['v...
def squared_loss(x1: float, x2: float): """Returns the squared difference between two numbers""" return (x1 - x2) ** 2
def v_d(val): """voltage divisor""" if val >= 0 and val <= 3: return 10 else: return None
def to_bin(value, edges): """Pass a list of numbers in `edges` and return which of them `value` falls between. If < the first item, return (0, <first>). If > last item, return (<last>, None). """ previous = 0 for v in edges: if previous <= value <= v: return (previous, v) ...
def expand_range(arg, value_delimiter=',', range_delimiter='-'): """ Expands a delimited string of ranged integers into a list of strings :param arg: The string range to expand :param value_delimiter: The delimiter that separates values :param range_delimiter: The delimiter that signifies a range o...
def add_auto_install(modules, to_install): """ Append automatically installed glue modules to to_install if their dependencies are already present. to_install is a set. """ found = True while found: found = False for module, module_data in modules.items(): if (module_data.get...
def extend_set(list_to_extend: list, new_elements: list) -> list: """ Helper function to extend a list while maintaining set property. They are stored as lists, so with this function set property is maintained. :return Returns: list of elements that were added to the set """ set_r...
def create_install_script(extensions_url: list, file_path: str, lib_path: str) -> str: """Create GeoServer plugin installation script. This function create a shell script to make GeoServer plugin install process more easy. Args: extensions_url (list): URL list of extensions to install file_...
def id_from_image_link(link: str) -> str: """Extracting ID as String from link to thumbnail. Arguments: link {str} -- Weblink to thumbnail. Returns: str -- ID of image. """ return link.split("/")[-2]
def remove_deleted_datasets_from_results(result): """ Remove datasets marked as removed from results. Arguments: result {object} -- Results with all datasets. Returns: [object] -- Results where removed datasets are removed. """ new_results = [dataset for dataset in result['res...
def _create_metadata_row(json_data, node_name, metadata_label): """ create row of metadata to write """ row = {} if node_name in json_data: row['Metadata_label'] = metadata_label row['Metadata_value'] = json_data[node_name] return row