content
stringlengths
42
6.51k
def rms(x): """Return the root mean square of x, instead of doing matplotlib.mlab.rms_flat. """ import numpy as np return np.sqrt(np.mean(x*x))
def matrix_to_edge_list(matrix, n): """Keep only the upper triangle of the adjacency matrix without its diagonal. Probably, should only be used in the case of an undirected graph. Parameters ---------- matrix : list of a list Square adjacency matrix of an undirected graph. n : int ...
def get_stage_suffix(stage): """ Which suffix to use (i.e. are we packaging a checkpoint?) - maps a stage to a suffix. :param stage: :return: """ if stage == 'final': return '' else: return ".%s" % stage
def chebyshev(dx, dy): """ Chebyshev distance. """ return max(dx, dy)
def posFromPVT(pvt): """Return the position of a PVT, or None if pvt is None or has no valid position. Inputs: - PVT: an opscore.RO.PVT.PVT position, velocity, time object. This is a convenience function to handle the case that the input is None """ if pvt is None: return None retu...
def avg_for_the_day(data): """Retuns average values for each day in a list. Accepts a list of lists, each containing a datatime in position 0 and a numerical (int or float) value in position 1. Returns a list of lists with a datetime in position 0 and a float in position 1. """ new_list =...
def make_range(probability, factor, current_value): """Return a tuple to be the new value in the histogram dictionary. Param: probability (float): num in the sample space currently factor (float): the fraction of the source text for a token current_value(int): appearances of a typ...
def _parse_text(text, dtype): """Parse the text of an element or an attribute.""" if dtype == str: return text elif dtype == float: ret = [float(word) for word in text.split(' ')] if len(ret) == 1: ret = ret[0] return ret elif dtype == bool: return boo...
def encode_output_str(value): """Takes value and converts to an string byte string""" return bytes(value, 'utf-8')
def filterdict(origdict, keyset): """returns the subset of origdict containing only the keys in keyset and their corresponding values """ newdict = {} # this cunningly works with cidict (case-insensitive dictionary class) # since we just check if key in origdict, not the reverse... # the keys are th...
def last_index_not_in_set(seq, items): """Returns index of last occurrence of any of items in seq, or None. NOTE: We could do this slightly more efficiently by iterating over s in reverse order, but then it wouldn't work on generators that can't be reversed. """ found = None for i, s in...
def load_words_file(filename): """Load an ignore or only file as a list of words""" if not filename: return [] with open(filename, "r") as file: return file.read()
def _use_constant_crc_init(sym): """ Return True if the inintial value is constant. """ return sym['crc_init_value'] is not None
def pack_str(string: str) -> bytes: """Packs a string into a byte object. Arguments: string: The string to pack. Returns: The bytes object representing the string in network order (big endian). """ return bytes(map(ord, string))
def sum_str_to_list_izq(s, lst): """ Suma un string a una lista u otro string por la izquierda :param s: String :param lst: Lista o strng :return: Lista o string sumado """ assert isinstance(s, str) if isinstance(lst, str): return s + lst elif isinstance(lst, list): ...
def s2b(s): """ String to binary. """ ret = [] for c in s: ret.append(bin(ord(c))[2:].zfill(8)) return "".join(ret)
def _is_breakline(statement): """Returns True if statement is a breakline, False otherwise.""" return len(statement) == 1 and statement[0].strip() == ''
def get_lines(blocks): """Convert list of text blocks into a nested list of lines, each of which contains a list of words. :param list[TextBlock] blocks: List of text blocks. :return: List of sentences :rtype: list[list[TextWord]] """ lines = [] for block in blocks: for para in bloc...
def bbox_to_geojson(bounds): """Convert coordinates of a bounding box to a geojson. Args: bounds (list): A list of coordinates representing [left, bottom, right, top]. Returns: dict: A geojson feature. """ return { "geometry": { "type": "Polygon", "c...
def above_threshold(student_scores, threshold): """ :param student_scores: list of integer scores :param threshold : integer :return: list of integer scores that are at or above the "best" threshold. """ above_threshold = [] for score in student_scores: if score >= threshold...
def get_latest_snapshot_identifier(snapshot_list, engine): """Return snapshot to use based off latest available snapshot from a list of snapshots""" latest_date = None latest_snapshot = '' for snapshot in snapshot_list: if not snapshot['Status'] == 'available': continue if la...
def get_valid_coastal_variant(split, possible_orders): """Find a variation on the `split` order that is in `possible_orders` Args: - split: a list of order string components, e.g. ["F", "AEG", "S", "F", "BUL", "-", "GRE"] - possible_orders: a list of order strings, ...
def make_hashable_params(params): """ Checks to make sure that the parameters submitted is hashable. Args: params(dict): Returns: """ tuple_params = [] for key, value in params.items(): if isinstance(value, dict): dict_tuple = tuple([(key2, value2) for key2, ...
def generate(random, pid, autogen_tools, n): """ Generate an instance of the problem Needs to return a list of files to copy to particular instance. """ return { "resource_files": { "public": [ ], }, "static_files": { }, "problem_updat...
def pairwise(iterable): """ s -> (s0,s1), (s2,s3), (s4, s5), ... >>> liste = ['C1', 'C2', 'C2', 'C3', 'C4', 'C5', 'C5', 'C6'] >>> pairwise(liste) [('C1', 'C2'), ('C2', 'C3'), ('C4', 'C5'), ('C5', 'C6')] """ a = iter(iterable) return list(zip(a, a))
def in_decl_set(decls, c): """ True if the cursor is in an sequence of cursor """ for d in decls: if c == d: return True return False
def spring1s(ep,ed): """ Compute element force in spring element (spring1e). Parameters: ep = k spring stiffness or analog quantity ed = [u1 u2] element displacements u1, u2: nodal displacements Returns: ...
def parse_molecule_gcmc(dlstr): """Grand Canonical MC includes chemical potential/partial pressure""" try: tok = dlstr.split() molecule = {"id": tok[0], "molpot": float(tok[1])} except (IndexError, TypeError): raise ValueError("Unrecognised GCMC Molecule: {!r}".format(dlstr)) ...
def idf(term, corpus): """ computes inverse document frequency. IDF is defined as the logarithm of the total number of documents in the corpus over the number of documents containing the search term: log(all documents/documents containing the search term) Note that if *no* document contains the...
def getpath(data, path): """`getpath()` returns the value at a dot-separated getitem path. `data` can be a nested combination of dicts and arrays. Each part of the path is interpreted as an integer if it looks like an integer. """ for p in path.split('.'): try: p = int(p) ...
def calculate_cigar_operations_lady(current_readlength, insertions, deletions, substitutions): """ Given a read length, and three lists of positions with insertions, deletions, substitutions, respectively, calculate the cigar string for one read. Return list of pairs of (cigar operation codes, count...
def get_previous_blank_line_no(lines, idx): """Find a blank line before the object definition""" while True: if not lines[idx].strip(): # found a blank line break else: idx -= 1 return idx
def overrides(method): """Decorator to indicate that the decorated method overrides a method in superclass. The decorator code is executed while loading class. Using this method should have minimal runtime performance implications. This is based on my idea about how to do this and fwc:s highly improved ...
def _clean_metrics(metrics, output_format="float"): """ Reformat metrics dictionary """ new_dict = {} for k, v in metrics.items(): if isinstance(v, dict): v = v["string"] if isinstance(v, str): if v.endswith("%"): v = v[:-1] if output_f...
def get_local_type(xmltype): """ Simplifies types names, e.g. XMLInteger is presented as int. This is used for nice printing only. """ if xmltype == "XMLBoolean": return 'bool' elif xmltype == "XMLDecimal": return 'decimal' elif xmltype == "XMLInteger": ...
def raw_string(txt): """ Python automatically converts escape characters (i.e. \\n), which causes problems when inputing latex strings since they are full of backslashes. This function returns a raw string representation of text Parameters ---------- txt : string string that p...
def distance(a, b): """Calculate the distance between two points a and b.""" return ((a[0] - b[0])**2 + (a[1] - b[1])**2)**0.5
def calculate_temperature_rise_input_power_weight( power_input: float, weight: float, ) -> float: """Calculate the temperature rise based on input power and xfmr weight. .. attention:: input power must be calculated by the calling function from voltage and current as it is not an attribute of an in...
def write_new_frag_file(barcode_cluster,list_parts_quality, new_fragment_file): """ writing a file input: a dictionary of splited output: a dictionary, key: barcode values: """ alleles_parts = list_parts_quality[0] quality = list_parts_quality[1] if len(quality)>1: # it can be impr...
def generate_negative_proposition(proposition): """ Get negative proposition: 1:red -> ~(1:red) """ negative = "~(" + proposition + ")" return negative
def simple_solution_sum(solutions, *args, **kwargs): """ Returns a simple sum of scores of the given solutions, neglecting the given user. """ return sum([s.score or 0 for s in solutions if s is not None])
def copy_grid(grid): """Copy grid.""" return [row[:] for row in grid]
def filter_geom(geom, _type): """Find all elements of type _type in geom iterable""" return list(filter(lambda x: isinstance(x, _type), geom))
def from_pt(value, units, dpi=96): """ convert length from pt to given units Arguments --------- value : float length in measurement units units : str unit type (e.g. "pt", "px", "in", "cm", "mm") dpi : float / int dots per inch (conversion between inches and px) ...
def compactRange(values): """Build the range string that lists all values in the given list in a compacted form. *values* is a list of integers (may contain duplicate values and does not have to be sorted). The return value is a string that lists all values (sorted) in a compacted form. The ret...
def factors(number): """Returns a mapping of factors for the given int""" if not isinstance(number, int): raise TypeError('number must be an int') factors = {} for num in range(1, number + 1): if number % num == 0: # if no remainder factors[num] = int(number / num) return...
def copy_letter(letter: str, source: str, target: str) -> str: """ Copy letters from source string to same positions to target. Arguments: letter - copied letter source - source string target - target string Returns: Target string with letter copied from source """ ...
def dedup(seq): """ Remove duplicates from a sequence, but: 1. don't change element order 2. keep the last occurence of each element instead of the first Example: a = [1, 2, 1, 3, 4, 1, 2, 6, 2] b = dedup(a) b is now: [3 4 1 6 2] """ out = [] for e in reversed(seq): ...
def findSmallestInt(arr): """First sort the list : return first item.""" result = sorted(arr) return result[0]
def _is_audio_link(link): """Checks if a given link is an audio file""" if "type" in link and link["type"][:5] == "audio": return True if link["href"].endswith(".mp3"): return True return False
def num_to_varint(a): """ Based on project: https://github.com/chaeplin/dashmnb """ x = int(a) if x < 253: return x.to_bytes(1, byteorder='big') elif x < 65536: return int(253).to_bytes(1, byteorder='big') + \ x.to_bytes(2, byteorder='little') elif x < 4294967296:...
def dict_to_sequence(d): """ Returns an internal sequence dictionary update. """ if hasattr(d, "items"): d = d.items() return d
def safe_string(value): """ consistently converts a value to a string :param value: :return: str """ if isinstance(value, bytes): return value.decode() return str(value)
def domain_to_aol_attr_convert(quad_attr): """Convert an attribute from the domain-level syntax (which should be a valid Python name) to the AOL-level syntax. """ if not quad_attr.startswith('is_'): quad_attr = f'has_{quad_attr}' return quad_attr.replace('_', '-')
def six_digit(password): """Check if password has 6 digits Parameters ---------- password : int password number Returns ------- is_six_dig: bool True if password has six digits, False if not """ # Test if password is a 6 digit number if password > 99999 and pas...
def csv(arg): """Returns a list from a `csv` input argument. """ return [x.strip() for x in arg.split(',')]
def format_value(value): """ This function contains heuristics to improve results, e.g. by transforming an empty string value ('') to the word empty. The goal is to input known values into the (transformer)-encoder, so he can learn the attention to the question. The heuristic in this method should stay ...
def parse_player_id(data: dict) -> int: """Parse the player ID from the data payload.""" return int(data["pid"])
def transform_pagerduty_results(results): """Filters the PagerDuty API results to a subset of fields we care about.""" transform = [] for entry in results['oncalls']: transform.append({ 'name' : entry['user']['name'], 'email' : entry['user']['email'], 'level' : ...
def format_number_latex(number: float, sig_figures: int = 3) -> str: """ Formats the number in latex format and round it to defined significant figures. If the result is in the exponential format, it will be formatted as ``[number] \\times 10^{[exponent]}``. Parameters ---------- number : ...
def _calc_c(H, r_eq): """ Calculates the b coefficient used to calculate the distance from the satellite to a point P Parameters ---------- H : int GOES-16 projection perspective point height, in meters r_eq : int GOES-16 semi-major axis of projection, in meters Returns...
def format_repo_info(vcs_name, vcs_path, vcs_type, integration_status): """Helper function for creating dict containing repository information :param str vcs_name: name of the repository :param str vcs_path: absolute path to the repository :param str vcs_type: type of the underlying vcs :param str i...
def _read_dict(instream, until=None): """Read key-value pairs.""" result = {} for line in instream: if not line: continue if ' ' not in line: break keyword, values = line[:-1].split(' ', 1) result[keyword] = values.strip() if keyword == until: ...
def median(values): """Calculates the median of the values. :param values: The values. :return: The median. """ values = sorted(values) if len(values) % 2: return values[len(values) // 2] else: return (values[len(values) // 2 - 1] + values[len(values) // 2]) / 2
def return_network_layers(connectivity): """ return_network_layers takes a string, that describes the connectivity of the network i.e. "BLT", and returns the number of layers the network has. """ if "D" in connectivity: return (7-1)*2+1 else: return 7
def maximum_mutation_frequency(H, F, D): """ # ======================================================================== MAXIMUM MUTATION FREQUENCY PURPOSE ------- Calculates the maximum mutation frequency. INPUT ----- [INT] [H] The number of haplotypes. [FLOAT LIS...
def fahrenheit_to_celsius(temp): """ Convert degrees Fahrenheit to degrees Celsius :param float temp: The temperature in Fahrenheit :return: The temperature in Celsius :rtype: float """ return (temp - 32.0) / 1.8
def pid_filename(component: str) -> str: """Obtain the canonical pid filename for the specified component name.""" return f".lta-{component}-pid"
def summary_data(name_list, weight_list): """ Reads the names and weights of fruits in two list and puts them in a string format to be written into a pdf file. name: Fruit names weight: Fruit Weight lbs Args: name_list(list): list of fruit names. weight_list(list): list...
def is_section(line: str, pattern: str) -> bool: """Returns a boolean Checks if line matches the pattern and returns True or False """ return line.find(pattern) > -1
def lorenz(t, x, sigma=10, beta=2.66667, rho=28): """ parameters: :sigma : 10 :beta : 2.7 :rho : 28 """ return [ sigma * (x[1] - x[0]), x[0] * (rho - x[2]) - x[1], x[0] * x[1] - beta * x[2], ]
def urljoin(*args: str) -> str: """ Join an array of strings using a forward-slash representing an url. :param args: list of strings to join :return: joined strings """ return "/".join(map(lambda x: str(x).rstrip('/'), args))
def _handle_special_yaml_cases(v): """Handle values that pass integer, boolean or list values. """ if ";" in v: v = v.split(";") else: try: v = int(v) except ValueError: if v.lower() == "true": v = True elif v.lower() == "false"...
def InterferenceDict(data_list): """Creates an interferenceReturns a double dict from a list of lat,lng, interferences.""" if not isinstance(data_list, list): data_list = [data_list] result = {} for lat, lon, data in data_list: if lat not in result: result[lat] = {} result[lat][lon] = data return...
def generate_challenge(user: str, passwd: str, device_token: str, sendviasms: bool) -> str: """ Generate a 2FA challenge ID. Can be rolled into other packages later. For now, generates a mock ID. """ if sendviasms: challenge_type = "sms" else: challenge_type = "email" #P...
def _concat_fasls(ctx, inputs, output): """Concatenates several FASLs into a combined FASL. Args: ctx: Rule context inputs: List of files to concatenate. output: File output for the concatenated contents. """ if not inputs: return None elif len(inputs) == 1: return...
def zone_current_temperature(zone): """ Get current temperature for this zone """ return zone["currenttemperature"]
def convertfrom_hex_notation(bytes_string: bytes): """Takes a given bytes object containing hex notation (e.g. b'\\x00\\x01\\x02\\x03') and returns a bytes object with the hexadecimal notation '\\x' glyphs removed from the output (or, transforming the output to the "Hexadecimal representation of binary data", as th...
def undo_replace_underscores(ranger_outputs): """ opens all the ranger output files, replaces the XX0XX in each tipname with an underscore like it was originally args: list of file names output: modifies the contents of those files to have correct underscore placement. """ for file in ranger_outputs: ...
def make_segment(segment, discontinuity=False): """Create a playlist response for a segment.""" response = [] if discontinuity: response.append("#EXT-X-DISCONTINUITY") response.extend(["#EXTINF:10.0000,", f"./segment/{segment}.m4s"]), return "\n".join(response)
def build_folder_names(result, folder_name=None): """Build list of folder names from a hierarchical dictionary.""" folders = [] folder_name = "/".join((folder_name or "", result.get("name", ""))).replace("//", "/") folders.append(folder_name) if not result.get("children", []): return fold...
def search_greater_ten(a, b): """ Operator function that searches for greater-than-10 values within its inputs. Inputs a, b: integers or booleans Outputs True if either input is equal to True or > 10, and False otherwise """ if type(a) == type(b): #in case both a and b a...
def removeBadBands(spectrum, wavelengths, bbl): """ Remove bands that are marked as bad in bbl list. Parameters ---------- spectrum : list of int Spectrum as a list. wavelengths : list of int List of measured wavelength bands bbl : list of str/int/bool List of bbl va...
def len_after_key(field, operation): """.""" if operation['key'] in field: result = field[operation['key']] return len(result) return 0
def human_readable(bytes, units=[' bytes','kB','MB','GB','TB', 'PB', 'EB']): """ Returns a human readable string reprentation of bytes""" return str(bytes) + units[0] if bytes < 1024 else human_readable(bytes>>10, units[1:])
def concentrations_std(concentrations, standards): """ Returns only species with known concentrations, i.e. standards. This is a subset of the data generated from concentrations. It provides a simple way get the standards from the dataset. Args ---- concentrations : pandas....
def is_intable(an_object): """Return True if the object can be converted to an int, False otherwise.""" intable = False try: int(an_object) intable = True except Exception: # Sorry for the naked except, but I don't care why the above failed. pass return intable
def is_iterable(value): # noinspection PyUnresolvedReferences """ Returns ``True`` if *value* is an iterable container (e.g. ``list`` or ``tuple`` but not a **generator**). Note that :func:`is_iterable` will return ``False`` for string-like objects as well, even though they are iterable. The same a...
def get_list_from_ranges_str(ranges_str): """Convert the range in string format to ranges list And yield the merged ranges in order. The argument must be a string having comma separated vlan and vlan-ranges. get_list_from_ranges_str("4,6,10-13,25-27,100-103") [4, 6, 10, 11, 12, 13, 25, 26, 27, 100...
def pth(path): """Prepends root icon path to path.""" return 'img/icons/ratings/' + path
def by_length(arr): """ Given an array of integers, if the number is an integer between 1 and 9 inclusive, replace it by its corresponding name from "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", otherwise remove it, then sort the array and return a reverse of sorted array. ...
def _is_user_context(context): """Indicates if the request context is a normal user.""" if not context: return False if context.is_admin: return False if not context.user_id or not context.project_id: return False return True
def _cleanUpAllPullRequests(results, all_pull_requests): """ Helper function for _getAllPullRequests(). Clean up pull requests and strip out cursor info. GIVEN: results (dict) -- initial query response with metadata all_pull_requests (list) -- nested list of pull_requests with comments and meta...
def default(value, default): """ Return `default` is `value` is :data:`None`, otherwise return `value`. """ if value is None: return default return value
def text_to_bits(text: str, encoding="utf-8", errors="surrogatepass") -> str: """ Thanks jfs - convert-binary-to-ascii-and-vice-versa >>> text_to_bits('Jive Turkey') '010010100110100101110110011001010010000001010100011101010111\ 0010011010110110010101111001' >>> text_to_bits('j1>3_t|_|rK3Y') '0...
def istag(arg, symbol='-'): """Return true if the argument starts with a dash ('-') and is not a number Parameters ---------- arg : str Returns ------- bool """ return arg.startswith(symbol) and len(arg) > 1 and arg[1] not in '0123456789'
def validate_country_codes(parser, arg): """Check that the supplied 2 country code is correct.""" country_codes = ["us", "de"] if arg.strip().lower() not in country_codes: parser.error("Invalid country code. Available codes are: %s" % ", ".join(country_codes)) else: return ar...
def post_report_users_update(reporter_check, reported_check): """ Prepares message to send to guild owner in event of save failure. Helper method for generating user/guild member profiles upon a report """ msg = "" if not reporter_check[0]: msg += "reporting user info failed to save!\n" if n...
def list_sra_accessions(reads): """ Return a list SRA accessions. """ accessions = [] if reads is not None: accessions = reads.keys() return accessions
def educations(education_block): """ :param bs4.Tag education_block: education block :return: list """ page_educations = [] if education_block is not None: education_block = education_block.find("div", {"class": "resume-block-item-gap"}) \ .find("...