content
stringlengths
42
6.51k
def match_locations(locations): """ A method to match locations that appear multiple times in the same list and return year-ordered lists that can then be plotted sequentially """ ident = 'Climate Identifier' yr = 'Year' mon = 'Month' matches = [] order_months = [[]] processed_...
def int_input(input_str): """ Parse passed text string input to integer Return None if input contains characters apart from digits """ try: input_val = int(input_str) except ValueError: input_val = None return input_val
def bson2bool(bval: bytes) -> bool: """Decode BSON Boolean as bool.""" return bool(ord(bval))
def tfilter(*args, **kwargs): """Like filter, but returns a tuple.""" return tuple(filter(*args, **kwargs))
def cull_candidates(candidates, text, sep=' '): """Cull candidates that do not start with ``text``. Returned candidates also have a space appended. Arguments: :candidates: Sequence of match candidates. :text: Text to match. :sep: Separator to append to match. >>> cull_candidat...
def chunkFx(mylist, n): """Break list into fixed, n-sized chunks. The final element of the new list will be n-sized or less""" # Modified from http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python chunks = [] for i in range(0, len(mylist), n): chunk...
def is_nan(n): """Return True if n is NaN""" try: return map(lambda x: not (x==x), n) except TypeError: # probably just integer return not (n == n)
def version_components(version): """Split version string into major1.major2.minor components.""" components = version.split(".") num = len(components) if num < 1: raise ValueError("version should have at least one component.") major1 = components[0] if num >= 2: major2 = compo...
def form_frequency_dict(data): """ Profile Forms sorted dictionary with probabilities values for every character """ laters = {} for char in data: if char in laters: laters[char] += 1 else: laters.update({char: 1}) for later in laters:...
def pytest_gherkin_apply_tag(tag, scenario): """Hook for pytest-gherkin tag handling. All tests and trace identifier numbers are given as Gherkin tags as well as the normal tags. Here, in this example we convert id tags to user properties instead, and leaving the rest to the default hook implementat...
def stripSurrogatePairs(ustring): """Removes surrogate pairs from a Unicode string""" # This works for Python 3.x, but not for 2.x! # Source: http://stackoverflow.com/q/19649463/1209004 try: ustring.encode('utf-8') except UnicodeEncodeError: # Strip away surrogate pairs tm...
def str2bool(v) -> bool: """Converts a string to a boolean. Raises: ValueError: If it cannot be converted. """ if isinstance(v, bool): return v elif isinstance(v, str): v_low = v.lower() if v_low in ("yes", "true", "t", "y", "1", "1.0"): return True ...
def compliment_bools(v1, v2): """Returns true if v1 and v2 are both bools and not equal""" return isinstance(v1, bool) and isinstance(v2, bool) and v1 != v2
def find_tail(tags, num): """ Get the position of the end of the aspect/opinion span in a tagging sequence. Args: tags (list): List of tags in a sentence. num (int): Number to look out for that signals the end of an aspect/opinion. Returns: """ last = False for i, ...
def exp4(i): """returns \eps**i in GF(4), coded as 2,3,1 for i=0,1,2""" return 1 + i%3
def _get_split_size(split_size): """Convert human-readable bytes to machine-readable bytes.""" if isinstance(split_size, str): exp = dict(MB=20, GB=30).get(split_size[-2:], None) if exp is None: raise ValueError('split_size has to end with either' '"MB" o...
def gaussian(epsilon, obs_data, sim_data): """Gaussian kernel.""" return -0.5 * ((obs_data - sim_data) / epsilon) ** 2
def get_player_details(curr_player): """Function to get player identifier and marker""" if curr_player == 'A': return ['B','O'] else: return ['A','X']
def above_range(test_value: float, metric: float, center: float, interval_range: float) -> bool: """ Check whether test_value is larger (>) than a certain value that is computed as: center + metric * interval_range :param float test_value: value to be compared :param float metric: value of metric u...
def calculate_gc(x): """Calculates the GC content of DNA sequence x. x: a string composed only of A's, T's, G's, and C's.""" x = x.upper() return float(x.count('G') + x.count('C')) / (x.count('G') + x.count('C') + x.count('A') + x.count('T'))
def sequalsci(val, compareto) -> bool: """Takes two strings, lowercases them, and returns True if they are equal, False otherwise.""" if isinstance(val, str) and isinstance(compareto, str): return val.lower() == compareto.lower() else: return False
def edge_clustering_coefficient_4(u, v, degree, neighbors): """ Computes a modified form of the edge clustering coefficient using squares instead of triangles. """ udeg = degree[u] vdeg = degree[v] mdeg = (udeg-1)*(vdeg-1) if mdeg == 0: return float('inf') else: uneighbor...
def create_filter_for_endpoint_command(hostnames, ips, ids): """ Creates a filter query for getting the machines according to the given args. The query build is: "or" operator separetes the key and the value between each arg. For example, for fields_to_values: {'computerDnsName': ['b.com', 'a.com']...
def strip_dev_suffix(dev): """Removes corporation suffix from developer names, if present. Args: dev (str): Name of app developer. Returns: str: Name of app developer with suffixes stripped. """ corp_suffixes = ( "incorporated", "corporation", "limited", ...
def isChineseChar(uchar): """ :param uchar: input char in unicode :return: whether the input char is a Chinese character. """ if uchar >= u'\u3400' and uchar <= u'\u4db5': # CJK Unified Ideographs Extension A, release 3.0 return True elif uchar >= u'\u4e00' and uchar <= u'\u9fa5': ...
def flatten_lists_of_lists(lists_of_lists): """ Flatten list of lists into a list ex: [[1, 2], [3]] => [1, 2, 3] :param lists_of_lists: list(list(elems)) :return: list(elems) """ return [elem for sublist in lists_of_lists for elem in sublist]
def run_length_encode(in_array): """A function to run length decode an int array. :param in_array: the inptut array of integers :return the encoded integer array""" if(len(in_array)==0): return [] curr_ans = in_array[0] out_array = [curr_ans] counter = 1 for in_int in in_array[1...
def get_pip_package_name(provider_package_id: str) -> str: """ Returns PIP package name for the package id. :param provider_package_id: id of the package :return: the name of pip package """ return "apache-airflow-providers-" + provider_package_id.replace(".", "-")
def pack(batch): """ Requries the data to be in the format >>> (*elem, target, [*keys]) The output will be a tuple of {keys: elem} and target """ inp = batch[:-2] target = batch[-2] keys = batch[-1] inp = {k : v for k, v in zip(keys, inp)} return inp, target
def fix_variables( instance, dynamic_components, scenario_directory, subproblem, stage, loaded_modules ): """ :param instance: the compiled problem instance :param dynamic_components: the dynamic component class :param scenario_directory: str :param subproblem: str :param stage: str :par...
def format_node(node): """Returns a formatted node Parameters: node: the the math node (string) Returns: : a formatted node """ node = str(node).lower() node = node.replace("*", "\*") for letter in "zxcvbnmasdfghjklqwertyuiop": node = node.replace("?" + letter, "*") ...
def is_diagonal_interaction(int_tuple): """True if the tuple represents a diagonal interaction. A one-qubit interaction is automatically "diagonal". Examples -------- >>> is_diagonal_interaction((2, 2)) True >>> is_diagonal_interaction((2, 0)) True >>> is_diagonal_interaction((1, 1...
def limit_lines(lines, N=32): """ When number of lines > 2*N, reduce to N. """ if len(lines) > 2*N: lines = [b'... showing only last few lines ...'] + lines[-N:] return lines
def add_ngram(sequences, token_indice, ngram_range=2): """ Augment the input list by appending n-grams values :param sequences: :param token_indice: :param ngram_range: :return: Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, ...
def bezout(a, b): """ Compute Bezout's coefficients. """ r2, r1 = a, b s2, s1 = 1, 0 t2, t1 = 0, 1 while r1 != 0: q = r2 // r1 r2, r1 = r1, r2 - q * r1 s2, s1 = s1, s2 - q * s1 t2, t1 = t1, t2 - q * t1 return s2, t2
def format_report(count, new_inst, del_inst, svc_info): """ Given a service's new, deleted inst, return a string representation for email """ needed = False body = '' if new_inst is not None and len(new_inst) > 0: needed = True body += '\n\n New Instances: ' for inst in ...
def format_fields(field_data, include_empty=True): """Format field labels and values. Parameters ---------- field_data : |list| of |tuple| 2-tuples of field labels and values. include_empty : |bool|, optional Whether fields whose values are |None| or an empty |str| should be...
def aliased(aliased_class): """ Decorator function that *must* be used in combination with @alias decorator. This class will make the magic happen! @aliased classes will have their aliased method (via @alias) actually aliased. This method simply iterates over the member attributes of 'aliased_class'...
def is_runway_visibility(item: str) -> bool: """Returns True if the item is a runway visibility range string""" return ( len(item) > 4 and item[0] == "R" and (item[3] == "/" or item[4] == "/") and item[1:3].isdigit() )
def channel_from_scope(scope): """Helper method to extract channel ID from a Backplane scope.""" idx = scope.find('channel') return scope[idx + 8:]
def compile_question_data(surveys): """ creates a double nested dict of question ids containing dict with question text, and an empty list. """ #Note: we want to keep the question text around so it can be displayed on the page. if not surveys: return {} all_questions = {} for ques...
def _entity_string_for_errors(entity): """Derive a string describing `entity` for use in error messages.""" try: character = entity.character return 'a Sprite or Drape handling character {}'.format(repr(character)) except AttributeError: return 'the Backdrop'
def calc_check_digit(number): """Calculate the check digit. The number passed should not have the check digit included.""" check = (11 - sum((8 - i) * int(n) for i, n in enumerate(number)) % 11) # this results in a two-digit check digit for 11 which should be wrong return '0' if check == 10 else str...
def perfect_score(student_info): """ :param student_info: list of [<student name>, <score>] lists :return: first `[<student name>, 100]` or `[]` if no student score of 100 is found. """ # first = [] student_names = [] score = [] print (student_info) for name in student...
def search(bs, arr): """ Binary search recursive function. :param bs: int What to search :param arr: array Array of ints where to search. Array must be sorted. :return: string Position of required element or "cannot found" string """ length = len(arr) check_item ...
def transform_string_mac_address_to_mac_address(string_mac_address): """ It transforms a MAC address from human readable string("00:11:22:33:44:55") to a raw string format("\x00\x11\x22\x33\x44\x55"). """ result = str() for i in string_mac_address.split(':'): result += chr(int(i, 16)...
def fibonacci(n): """ Return the nth fibonacci number, that is n if n < 2, or fibonacci(n-2) + fibonacci(n-1) otherwise. @param int n: a non-negative integer @rtype: int >>> fibonacci(0) 0 >>> fibonacci(1) 1 >>> fibonacci(3) 2 """ if n < 2: return n else...
def move_to_tile(location, tile): """ Return the action that moves in the direction of the tile. """ # actions = ['', 'u', 'd', 'l', 'r', 'p'] print(f"my tile: {tile}") # see where the tile is relative to our current location diff = tuple(x - y for x, y in zip(location, tile)) if diff == (0, ...
def any_alt_args_in_list(args, l): """Report whether any arguments in the args list appear in the list l.""" for a in args.get('alt_args', {}): if a in l: return True return False
def densityGlycerol(temperature): """ Calculates the density of glycerol from an interpolation by Cheng (see viscosity docstring for reference). Args: temperature (float): in Celsius in the range [0, 100] Returns: :class:`float` Density of Glycerol in kg/m^3 """ rho = 1277 - 0....
def normalizer(value, max_value): """ """ if value is None: return 0.0 if value >= max_value: return 1.0 else: return float(value)/float(max_value)
def arabic_to_roman(number: int) -> str: """Return roman version of the specified arabic number.""" if number > 3999: raise ValueError(f"Number can not be represented with roman numerals: " f"{number}") roman_number = "" for index, digit in enumerate(reversed(str(number...
def _reform_inputs(param_dict, out_species): """Copies param_dict so as not to modify user's dictionary. Then reformats out_species from pythonic list to a string of space separated names for Fortran. """ if param_dict is None: param_dict = {} else: # lower case (and conveniently cop...
def _FirewallRulesToCell(firewall): """Returns a compact string describing the firewall rules.""" rules = [] for allowed in firewall.get('allowed', []): protocol = allowed.get('IPProtocol') if not protocol: continue port_ranges = allowed.get('ports') if port_ranges: for port_range in ...
def split_timecode(time_code): """ Takes a timecode string and returns the hours, minutes and seconds. Does not simplify timecode. :param time_code: String of format "HH:MM:SS.S" ex. "01:23:45.6" :return: HH (float), MM (float), SS (float) """ hh, mm, ss = time_code.split(':') hh = float(hh) ...
def col_letter(col): """Return column letter given number.""" return chr(ord("A") + col - 1)
def GroupNamedtuplesByKey(input_iter, key): """Split an iterable of namedtuples, based on value of a key. Args: input_iter: An iterable of namedtuples. key: A string specifying the key name to split by. Returns: A dictionary, mapping from each unique value for |key| that was encountered in |inpu...
def single_multiple(status: int): """ >>> single_multiple(0b1000) 'multiple sensors have errors' >>> single_multiple(0b0000) 'only a single sensor has error (or no error)' """ if status & 0b1000: return 'multiple sensors have errors' else: return 'only a single sensor ha...
def _xtract_bsx(rec_type): """Parse rec_type to bsx_type""" bsx_type = None if not rec_type or rec_type == 'None': # rec_type None means running a beam with no recording bsx_type = None elif rec_type == 'bst' or rec_type == 'sst' or rec_type == 'xst': bsx_type = rec_type elif...
def f_numeric(A, B): """Operation on numeric arrays """ return 3.1 * A + B + 1
def from_string(s): """Converts a time series to a list of (int, int) tuples. The string should be a sequence of zero or more <time>:<amount> pairs. Whitespace delimits each pair; leading and trailing whitespace is ignored. ValueError is raised on any malformed input. """ pairs = s.strip().spl...
def other(e): """Reverse the edge""" if e == e.lower(): return e.upper() else: return e.lower()
def get_release_date(data): """gets device release date""" try: launch = data['launch'] splt = launch.split(' ') return int(float(splt[0])) except (KeyError, TypeError): return None
def isascii(s): """Return True if there are no non-ASCII characters in s, False otherwise. Note that this function differs from the str.is* methods in that it returns True for the empty string, rather than False. >>> from bridgedb.util import isascii >>> isascii('\x80') False >>> isascii('...
def _assoc_list_to_map(lst): """ Convert an association list to a dictionary. """ d = {} for run_id, metric in lst: d[run_id] = d[run_id] + [metric] if run_id in d else [metric] return d
def _language_name_for_scraping(language): """Handle cases where X is under a "macrolanguage" on Wiktionary. So far, only the Chinese languages necessitate this helper function. We'll keep this function as simple as possible, until it becomes too complicated and requires refactoring. """ return...
def _update_addition_info(addition_info): """ Update default addition_info with inputs """ add_info = {"epoch": 0, "batch": 0, "batch_size": 0} if not addition_info: return add_info elif not isinstance(addition_info, dict): raise TypeError("The type of 'addition_info' should be 'dict', "...
def flatten_dict(d, separator='.', prefix=''): """Flatten nested dictionary. Transforms {'a': {'b': {'c': 5}, 'd': 6}} into {'a.b.c': 5, 'a.d': 6} Args: d (dist): nested dictionary to flatten. separator (str): the separator to use between keys. prefix (str): key prefix Returns...
def is_num(var): """ Test if variable var is number (int or float) :return: True if var is number, False otherwise. :rtype: bol """ return isinstance(var, int) or isinstance(var, float)
def odd_pair(nums): """Solution to exercise C-1.14. Write a short Python function that takes a sequence of integer values and determines if there is a distinct pair of numbers in the sequence whose product is odd. -------------------------------------------------------------------------- Solut...
def remove_null_values(dictionary: dict) -> dict: """Create a new dictionary without keys mapped to null values. Args: dictionary: The dictionary potentially containing keys mapped to values of None. Returns: A dict with no keys mapped to None. """ if isinstance(dictionary, dict): ...
def flatten(d, key_as_tuple=True, sep='.'): """ get nested dict as {key:val,...}, where key is tuple/string of all nested keys Parameters ---------- d : dict key_as_tuple : bool whether keys are list of nested keys or delimited string of nested keys sep : str if key_as_tuple...
def generate_dhm_response(public_key: int) -> str: """Generate DHM key exchange response :param public_key: public portion of the DHMKE :return: string according to the specification """ return 'DHMKE:{}'.format(public_key)
def index(_, __): """ Index Enpoint, returns 'Hello World' """ return {"content": "Hello World!"}
def block_aligned(location, block_size): """Determine if a location is block-aligned""" return (location & (block_size - 1)) == 0
def f_pitch(p, pitch_ref=69, freq_ref=440.0): """Computes the center frequency/ies of a MIDI pitch Notebook: C3/C3S1_SpecLogFreq-Chromagram.ipynb Args: p (float): MIDI pitch value(s) pitch_ref (float): Reference pitch (default: 69) freq_ref (float): Frequency of reference pitch (de...
def position_case_ligne_motif(pos_ligne_motif, sens, colonne, ligne): """ renvoie la position de la case en fontion du sens des lignes """ x_debut, y_debut = pos_ligne_motif if sens=="gauche": x_case = x_debut-colonne*25 else: x_case = x_debut+colonne*25 return x_cas...
def isNEIC(filename): """ Checks whether a file is ASCII NEIC format. """ try: temp = open(filename, 'rt').readline() except: return False try: if not temp.startswith('time,latitude,longitude,depth,mag,magType,nst,'): return False except: return Fa...
def replace_matrix(base, x, y, data): """ base = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] x = 1 y = 0 data = [[x], [y], [z]] return [[1, x, 3], [4, y, 6], [7, z, 9]] """ data_height = len(data) data_width = len(data[0...
def stream_has_colours(stream): """ True if stream supports colours. Python cookbook, #475186 """ if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return c...
def surface_color_format_to_texture_format(fmt, swizzled): """Convert nv2a draw format to the equivalent Texture format.""" if fmt == 0x3: # ARGB1555 return 0x3 if swizzled else 0x1C if fmt == 0x5: # RGB565 return 0x5 if swizzled else 0x11 if fmt in [0x7, 0x08]: # XRGB8888 r...
def bit_read(data, position): """Returns the value of a single bit in a number. :param: data The number (bytearray) that contains the desired bit. :param: position The position of the bit in the number. :return: The bit value (True or False). """ byte_pos = int(position // 8) # byte posi...
def Beta22_1(X): """ Coefficient for the 1PN tidal correction to h_22 mode Defined in arXiv:1203.4352, eqn A15 Input X -- mass fraction of object being tidally deformed Output double, coeff for 1PN tidal correction to h_22 mode """ return (-202.+560.*X-340.*X*X+45.*X*X*X)/42./(3.-2.*X)
def problem_48_self_powers(series_limit, digits): """ Problem 48: Find the last digits of series n^n (n = 1 to series limit). Args: series_limit (int): The maximum base and power in the series. digits (int): The number of last digits to take from sum. """ result = 0 for number in ra...
def accuracy(labels, preds): """Calculate the accuracy between predictions.""" correct = 0 for idx, label in enumerate(labels): pred = preds[idx] if isinstance(label, int): if label == pred: correct += 1 else: if pred in label: ...
def space_to_kebab(s): """Replace spaces with dashes. Parameters ---------- s : str String that may contain " " characters. """ return "-".join(s.split(" "))
def isTool(name): """ Check if a tool is on PATh and marked as executable. Parameters --- name: str Returns --- True or False """ from distutils.spawn import find_executable if find_executable(name) is not None: return True else: return False
def convertNumbers(s,l,toks): """ Convert tokens to int or float """ n = toks[0] try: return int(n) except ValueError: return float(n)
def _list_to_index_dict(lst): """Create dictionary mapping list items to their indices in the list.""" return {item: n for n, item in enumerate(lst)}
def __parseAuthHeader(string): """ Returns the token given an input of 'Bearer <token>' """ components = string.split(' ') if len(components) != 2: raise ValueError('Invalid authorization header.') return components[1]
def dashed_line(length: int, symbol: str="=") -> str: """Print out a dashed line To be used as visual boundaries for tests. Args: length (int): number of charters symbol (str): symbol to be used in the dashed line default: "=" Returns: a...
def left_to_right_check(input_line: str, pivot: int): """ Check row-wise visibility from left to right. Return True if number of building from the left-most hint is visible looking to the right, False otherwise. input_line - representing board row. pivot - number on the left-most hint of the in...
def make_list_unique(elem_list): """ Removes all duplicated values from the supplied list. :param elem_list: list to remove duplicate elements from :return: new list with all unique elements of the original list """ return list(dict.fromkeys(elem_list))
def lenght(value, min, max, message_error=None, message_valid=None): """ min : integer max: integer value : value element DOM. Example : document['id].value message_error : str message message_valid: str message function return tuple """ if min is not None and len(value) < min: ...
def is_pangram(sentence: str) -> bool: """Return True if given string is a panagram.""" # a pangram is a sentence using every letter of the alphabet at least once sentence = sentence.lower() alphabet = 'abcdefghijklmnopqrstuvwxyz' return set(sentence).issuperset(alphabet)
def has_perm(permissions, context): """ Validates if the user in the context has the permission required. """ if context is None: return False if type(context) is dict: user = context.get('user', None) if user is None: return False else: user = context...
def excel_title_to_column(column_title: str) -> int: """ Given a string column_title that represents the column title in an Excel sheet, return its corresponding column number. >>> excel_title_to_column("A") 1 >>> excel_title_to_column("B") 2 >>> excel_title_to_column("AB") 28 ...
def gcd( a , b ): """ Calculate the greatest common divisor. """ while b: a , b = b , a%b return a
def fisbHexBlocksToHexString(hexBlocks): """ Given a list of 6 items, each containing a hex-string of an error corrected block, return a string with all 6 hex strings concatinated. Used only for FIS-B. This only returns the bare hex-string with '+' prepended and no time, signal strength, or error count att...
def running_mean_estimate(estimate, batch_estimate, num_samples, batch_size): """Update a running mean estimate with a mini-batch estimate.""" tot_num_samples = float(num_samples + batch_size) estimate_fraction = float(num_samples) / to...