content
stringlengths
42
6.51k
def create_individual_tests(test_set): """ Creates test definitions from a test set as dictionaries. Assumes 'expected_outputs' is a list of tuples defining expected outputs key value pairs [('schema', [SCHEMA-DICT]), ...] """ test_inputs = {k: v for k, v in test_set.items() if k != "expected...
def get_corr_hex(num): """ Gets correspondence between a number and an hexadecimal string Parameters ------------- num Number Returns ------------- hex_string Hexadecimal string """ if num < 10: return str(int(num)) elif num < 11: return ...
def addContent(old_html, raw_html): """Add html content together""" old_html += raw_html return old_html
def left_beats_right(left: str, right: str) -> bool: """Determines if left choice beats right choice in RPS.""" beats_map = { "rock": "scissors", "paper": "rock", "scissors": "paper" } if beats_map[left] == right: return True return False
def parse_field(es_article, hit, es_key, api_key): """ update the record with the value in the hit, if the key not found, then the record does not change :param es_article: the record data which will be inserted into ElasticSearch :param hit: the input data :param es_key: the key in the elastic sear...
def ctof(at :float) ->float: """ Simple Celsius to Fahrenheit conversion """ return float(at * (9/5) + 32)
def is_abbreviation(sentence): """ Evaluate a word to be an abbreviation if the immediate word before the period contains a capital letter and not a single word sentence. """ sentence_split = sentence.split(" ") if len(sentence_split) == 1: return False elif len(sentence_split[-1]) <...
def is_power(a, b): """ This functions check if the number a is a power of b. That is, if the following is true for a certain number n: a == b**n. """ if (a == 1): return True elif (a == b): return True elif (a == 0) and (b != 0): return False elif (a != 1) and (b ==...
def unicode_path(utf8path): """Turn an utf8 path into a unicode path.""" if isinstance(utf8path, bytes): return utf8path.decode("utf-8") return utf8path
def clean_whitespace(text): """Standardizes whitespaces so there is only one space separating tokens Parameters ---------- text : str The fixed text Returns ------- str fixed text """ return ' '.join(str(text).split())
def get_last_pair(dictionary, key): """Throws exception if key not in dictionary""" if isinstance(dictionary[key], list): return dictionary[key][-1] return dictionary[key]
def create_id(fname: str, lname: str) -> str: """Create a player ID from a first name and last name. String format: <first 5 characters of last name><first 2 characters of first name><01> The last two integer digits allow for the prevention of ID conflicts. To increment by an integer n, use add_n(player...
def recursive_s(l, x, low=None, high=None, mid=None): """Searches for x in sorted list l, returning the index of x or None. Assumes that l only contains distinct values. If l contains duplicate x values then an arbitrary matching index will be returned. Recursive implementation. """ if not l: return ...
def transposed(table): """Returns the transposition of the table.""" if table == None: return None t_table = [] for i in table: while len(i) > len(t_table): t_table.append([]) for collumn in table: for i in range(len(collumn)): t_table[i].append(coll...
def add_array_type(property_schema): """Convert the parameter schema to be of type list. :param dict property_schema: schema to add array type to :returns: a new dict schema """ new_schema = property_schema.copy() new_schema['type'] = [property_schema['type'], 'array'] return new_schema
def is_even(val): """ Predicate testing if a value is even """ return val % 2 == 0
def points_intermediates(p1, p2, nb_points): """ "Return a list of nb_points equally spaced points between p1 and p2, includes p1 and p2""" if not nb_points: nb = 3 x_spacing = (p2[0] - p1[0]) / (nb_points + 1) y_spacing = (p2[1] - p1[1]) / (nb_points + 1) points = [ [p1[0] + i...
def _tree_to_paths(tree): """Build a list of paths made by walking from the root of the tree to each leaf.""" if len(tree) == 0: return [""] return [ c + path for c, subtree in sorted(tree.items()) for path in _tree_to_paths(subtree) ]
def find_loop_size( public_key, subject=7 ): """ To transform a subject number, start with the value 1. Then, a number of times called the loop size, perform the following steps: - Set the value to itself multiplied by the subject number. - Set the value to the remainder after dividing...
def thresh_hold_binarization(feature_vector, thresh_hold): """ Turn each value above or equal to the thresh hold 1 and values below the thresh hold 0. :param feature_vector: List of integer/float/double.. :param thresh_hold: Thresh hold value for binarization :return: Process and binarized list ...
def _encapsulate_admin(cmd): """Encapsulate a command with an Administrator flag""" # To get admin access, we start a new powershell instance with admin # rights, which will execute the command return "Start-Process PowerShell -windowstyle hidden -Wait -Verb RunAs -ArgumentList '-command &{%s}'" % cmd
def is_superincreasing(seq): """Return whether a given sequence is superincreasing.""" ct = 0 # Total so far for n in seq: if n <= ct: return False ct += n return True
def format_run_status(run, default='-'): """common formatting success boolean field""" if not run: return default return run.success
def title_case(string: str) -> str: """ Capitalizes the first character and all characters immediately after spaces in the given string (the string.title() method additionally capitalizes characters after punctuation) :param s: the string to be title-cased :return: s in title case """ return...
def combine(d1, d2): """Combine dictionaries into one.""" return {**d1, **d2}
def is_iterable(x): """Return True if an object is iterable.""" try: iter(x) except TypeError: return False return True
def tuple2str(tuple_in): """Converts a tuple into a string. :param tuple_in: tuple to convert :type tuple_in: tuple :returns: concatenated string version of the tuple :rtype: str """ string = '' for i in tuple_in: string += str(i) return string
def koma_sepp(n): """ Take input integer n and return comma-separated string, separating 1000s. >>> koma_sepp(131032047) '131,032,047' >>> koma_sepp(18781) '18,781' >>> koma_sepp(666) '666' """ return '{:,}'.format(n)
def generate_hashtag(s): """ Generates a hashtag which ever word is capitalized and we start with a hashtag. Also, string can't be longer than 140 chars or empty. :param s: a string value. :return: the string in hashtag form otherwise, False. """ if len(s) > 140 or len(s) < 1: return False ...
def add_backticks(s): """ Adds double-backticks to the beginning and end of s for mono-spaced rst output. e.g.: add_backticks("zone_helper") -> "``zone_helper``" """ return "``{s}``".format(s=s)
def alfa_(w): """This function returns True if the given string 'w' contains only alphabetic or underscore characters Note: It is implemented in a hacky way to increase speed """ return (w + "a").replace('_', '').isalpha()
def recurrence_abc(n, alpha, beta): """See A&S online - https://dlmf.nist.gov/18.9 . Pn = (an-1 x + bn-1) Pn-1 - cn-1 * Pn-2 This function makes a, b, c for the given n, i.e. to get a(n-1), do recurrence_abc(n-1) """ aplusb = alpha+beta if n == 0 and (aplusb == 0 or aplusb == -1): ...
def add_marker(x, y, z): """ Create a plotly marker dict. """ return { "x": [x], "y": [y], "z": [z], "mode": "markers", "marker": {"size": 25, "line": {"width": 3}}, "name": "Marker", "type": "scatter3d", "text": ["Click point to remove annotation...
def TestResourceName(name): """Return a resource name for a resource under the test data directory.""" prefix = __name__ + ':data/' return prefix + name
def monet_escape(data): """ returns an escaped string """ data = str(data).replace("\\", "\\\\") data = data.replace("\'", "\\\'") return "'%s'" % str(data)
def running_sum(x): """ Returns a list representing the running sum of a list """ sum_val = 0 running_sum = [0] * len(x) for n in range(len(x)): sum_val += x[n] running_sum[n] = sum_val return running_sum
def transpose_loggraph(loggraph_dict): """Transpose the information in the CCP4-parsed-loggraph dictionary into a more useful structure.""" columns = loggraph_dict["columns"] data = loggraph_dict["data"] results = {} # FIXME column labels are not always unique - so prepend the column # nu...
def fn_Z_L_1(omega,L_1): """Readout inductor impedance as a function of angular frequency omega and inductance L_1.""" return 1j * omega * L_1
def is_fmt(obj): """ Returns true iff `obj` is a formatter instance. """ return callable(obj) and hasattr(obj, "width")
def get_hashable_value_tuple_from_dict(d): """ Hashable tuple of values with sorted keys. >>> get_hashable_value_tuple_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, }) (45, 5.0) >>> get_hashable_value_tuple_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, "resolutions": [(740, 480), (1920,...
def _rectangles_overlap(bottomleft_1, topright_1, bottomleft_2, topright_2): """Compare two rectangles and return True if they are overlapping. Parameters ---------- bottomleft_1 : listlike, float x, y coordinate of bottom left corner of rectangle 1. topright_1 : listlike, float x, ...
def min_equals_max(min, max): """ Return True if minimium value equals maximum value Return False if not, or if maximum or minimum value is not defined """ return min is not None and max is not None and min == max
def ms2knots(ms: float) -> float: """ Convert meters per second to knots. :param float ms: m/s :return: speed in knots :rtype: float """ if not isinstance(ms, (float, int)): return 0 return ms * 1.94384395
def residual_imag(im, fit_re, fit_im): """ Relative Residuals as based on Boukamp's definition Ref.: - Boukamp, B.A. J. Electrochem. SoC., 142, 6, 1885-1894 Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ modulus_fit = (fit_re ** 2 + fit_im ** 2) ** (1 / 2) ...
def cadence(a, b, required_gap, start): """ For the pair of numbers determine when they first repeat with the required gap and the period that it will repeat, starting at the given value >>> cadence(67, 7, 1, 0) (335, 469) >>> cadence(67, 7, 2, 0) (201, 469) >>> cadence(1789, 37, 1, 0) ...
def check_datasets_compatible(dataset1, dataset2): """ Used for cross-corpus datasets that are combined from two datasets. Checks if two datasets have the same class names and original shape. The first entry of the original shape is ignored, since the number of samples does not matter. ...
def _pelt_tau(half_life, window): """ Compute the time constant of an equivalent continuous-time system as defined by: ``tau = period * (alpha / (1-alpha))`` https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter """ # Alpha as defined in https://en.wikipedia.org/...
def find_already_present_insp_keys(replacements, bib_dbs): """Filter replacements to those whose INSPIRE key appear in bibs. Parameters ---------- replacements: array of dict Each dict has keys "ads_key", "insp_key", and "bib_str". bib_dbs: array of `bibtexparser.bibdatabase.BibDatabase` ...
def log_new_fit(new_fit, log_gplus, mode='residual'): """Log the successful refits of a spectrum. Parameters ---------- new_fit : bool If 'True', the spectrum was successfully refit. log_gplus : list Log of all previous successful refits of the spectrum. mode : str ('positive_re...
def simple_1arg_default(hello: str = "default"): """This will print hello. Args: hello: Your name. """ return f"Hello {hello}"
def getchapter(chapter): """To change chapter number into desired format for saving""" chapter = str(chapter) if int(chapter) < 10: chapter = '00' + chapter elif int(chapter) < 100: chapter = '0' + chapter return chapter
def strip_trailing_nl(s): """If s ends with a newline, drop it; else return s intact""" return s[:-1] if s.endswith('\n') else s
def extract_data(dat): """ Function to extract data from api in particular separate players data from the match data perform basic filtering of removing invalid_matches invalid matches are those where all players ids are known and the result is known (i.e. not missing) also adds match_id to ...
def transObj(object, disp): """ Translate an object """ return (object[0]+disp,object[1])
def summarize_node_support(snp_clade_info): """ Conversts SNP data into a clade indexed datastructure :param snp_clade_info: [dict] Dictionary of clades and SNPs supporting them :return: [dict] Summary of clade SNP support """ clades = {} for chrom in snp_clade_info: for position in ...
def IoU(bbox0, bbox1): """ Runs the intersection over union of two bbox :param bbox0: bbox1 list :param bbox1: bbox2 list :return: IoU """ dim = int(len(bbox0)/2) overlap = [max(0, min(bbox0[i+dim], bbox1[i+dim]) - max(bbox0[i], bbox1[i])) for i in range(dim)] intersection = 1 ...
def _default_combiner(tokens): """Default token combiner which assumes each token is a line.""" return '\n'.join(tokens)
def set_param(param, default, row, issues, pre, overrides={}, verbose=False): """ Set a parameter value Given a parameter name, that parameter's default value, a data table row, and a JSON dictionary which may have an entry for the current row that will override the parameter, return the parame...
def normalize_knot_vector(knot_vector): """Returns a normalized knot vector within the [0, 1] domain. Parameters ---------- list of float A knot vector Returns ------- list of float The normalized knot vector. """ knot_vector = [v - knot_vector[0] for v in knot_vect...
def get_short_from_little_endian_bytearray(array, offset): """ Get a short from a byte array, using little-endian representation, starting at the given offset :param array: The byte array to get the short from :type array: bytearray :param offset: The offset at which to start looking :type ...
def cfs_to_mmday(cfs, SA_sq_ft): """ cfs: (float) flow rate in cubic feet per second SA_sq_ft: (float) surface area in square feet """ return(cfs/SA_sq_ft * 24 * 60 * 60 * 304.8)
def _get_embedded(inspected_interfaces): """Gets embedded interfaces from inspected interfaces.""" embedded_interfaces = [] for interface in inspected_interfaces: _biosdevname = interface['predictable_names'].get('biosdevname', '') if _biosdevname: if 'em' in _biosdevname: ...
def intersectionRect(r1, r2, shift1 = (0,0), shift2 = (0,0), extraSize = 3 ): """ gets two 4-tuples of integers representing a rectangle in min,max coord-s optional params. @shifts can be used to move boxes on a larger canvas (2d plane) @extraSize, forces the rectangles to stay a...
def decode_http_header(raw): """ Decode a raw HTTP header into a unicode string. RFC 2616 specifies that they should be latin1-encoded (a.k.a. iso-8859-1). If the passed-in value is None, return an empty unicode string. :param raw: Raw HTTP header string. :type raw: string (non-...
def resultCombine(type, old, new): """Experimental-ish result-combiner thing If the result isn't something from action=query, this will just explode, but that shouldn't happen hopefully? """ ret = old if type in new['query']: # Basic list, easy ret['query'][type].extend(new['query'][type]) else: # Else its...
def get_str_arg(param: dict, key: str, required: bool = False, default: str = "") -> str: """Get a key from a command arg and convert it into an str.""" value = param.get(key, default) if not isinstance(value, str): raise ValueError(f"Please provide a valid string value for the parameter {key!r}") ...
def _splitnport(host, defport=-1): """Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number.""" host, delim, port = host.rpartition(':') ...
def v(t): """ modell for farten v ved konstant tyngdeakselerasjon g og utgangsfart v_0=10 """ g = -9.81 v_0 = 10 return v_0 + g*t
def merge_items(base, new_items): """ Merges two lists and eliminates duplicates :type base: list :type new_items: list :rtype: list """ for item in new_items: if not item in base: base = base + [item] return base
def safe_key_extractor(dico, key, default_val): """ Get the value from a dictionary based on a key, If the key is not present, return the default value :param dico: dict :param key: key present or not in the dictionary :param default_val: default value to return :return: value or default_v...
def parse_fragment(fragment_string): """Takes a fragment string nd returns a dict of the components""" fragment_string = fragment_string.lstrip('#') try: return dict( key_value_string.split('=') for key_value_string in fragment_string.split('&') ) except ValueErr...
def get_credentials_from_event(event): """Get passed credentials from the event.""" username = event.get('username') password = event.get('password') refresh_token = event.get('refresh_token') return username, password, refresh_token
def byte_align(size, alignment): """Returns the int larger than ``size`` aligned to ``alginment`` bytes.""" mask = alignment - 1 if size & mask == 0: return size else: return (size | mask) + 1
def _setup_smoothing_sigmas(scale: int=1): """Setup the smoothing sigmas array for registration""" smoothing_sigmas = [0] if scale > 1: for idx in range(1, scale, 1): smoothing_sigmas.insert(0, 2**(idx - 1)) print('No smoothing sigmas given...
def standard_deviation(list1): """Calculate a standard deviation :param list1: list of values :return: standard deviation value""" # moyenne moy = sum(list1, 0.0) / len(list1) # variance variance = [(x - moy) ** 2 for x in list1] variance = sum(variance, 0.0) / len(variance) # e...
def split_magics( buffer ): """ Split the cell by lines and decide if it contains magic or bot input @return (tuple): a pair \c stripped_lines,is_magic """ # Split by lines, strip whitespace & remove comments. Keep empty lines buffer_lines = [ ls for ls in ( l.strip() for l in buffer.split('\n...
def status_request(token): """Create ACME "statusRequest" message. :param unicode token: Token provided in ACME "defer" message. :returns: ACME "statusRequest" message. :rtype: dict """ return { "type": "statusRequest", "token": token, }
def find_called_name_offset(source, orig_offset): """Return the offset of a calling function. This only approximates movement. """ offset = min(orig_offset, len(source) - 1) paren_count = 0 while True: if offset <= 1: return orig_offset elif source[offset] == '(': ...
def getChunkPartition(chunk_id): """ return partition (if any) for the given chunk id. Parition is encoded in digits after the initial 'c' character. E.g. for: c56-12345678-1234-1234-1234-1234567890ab_6_4, the partition would be 56. For c-12345678-1234-1234-1234-1234567890ab_6_4, the partition ...
def util_key_index ( keys, key ): """Returns index for key in list""" result = -1 n = 0 for i in keys: if (i == key): result = n n += 1 return result
def contains(list, item): """Return 1 if item is in list, 0 otherwise.""" try: i = list.index(item) except: return 0 else: return 1
def dequote(s): """ If a string has single or double quotes around it, remove them. Make sure the pair of quotes match. If a matching pair of quotes is not found, return the string unchanged. """ if len(s) >= 2 and (s[0] == s[-1]) and s.startswith(("'", '"')): return s[1:-1] return s
def _get_edge_length_in_direction(curr_i: int, curr_j: int, dir_i: int, dir_j: int, i_rows: int, i_cols: int, edge_pixels: set) -> int: """ find the maximum length of a move in the given direction along the perimeter of the image :param curr_i: current row index :param ...
def dp_key(relations): """ generates a unique key for the dptable dictionary :param relations: set of relations :return: str """ return '-'.join(sorted([r.name for r in relations]))
def first_part(txt): """First logical part for password.""" return txt[0].upper()
def neat_data(data): """ returns list of neat strings data should not include blob !!!ESPECIALLY DONE FOR GET RECENT FUNCTION!!! """ neat_data = [] dockets = [] for i in data: neat_str = "Docket# : {} \n Customer : {} \n Date Shipment {} \n Delivery Address : \n {}".format( ...
def escape(text): """Escape slack control characters""" return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
def get_filename_from_url(url, accession): """ Return the filename extracted from the given URL. If it is not a pdf file, return the original url :param url: url to parse :param accession: accession number :return: file name """ if (not url) or (url and len(url) == 0): # print(f"{acc...
def hello(who): """Say hello.""" return "Hello %s!" % who
def query(*args): """ Execute a database query """ # Table query actions (dict, string, func, args*) if (isinstance(args[0], dict) and isinstance(args[1], str) and callable(args[2])): query_args = args[3:] def table_loop(i, db): if i > 0: i = i - 1 ...
def toggleBit(int_type: int, offset: int) -> int: """ toggleBit() returns an integer with the bit at 'offset' inverted, 0 -> 1 and 1 -> 0. """ mask = 1 << offset return int_type ^ mask
def _get_module_name(function): """Extracts module signature of a function.""" full_name = function.__module__ return full_name.split(".")[0]
def get_len_single_middle_vertex(len_leading, len_middle, len_trailing): """Get the length of the resulting sequence if only one middle vertex is used. Args: len_leading: The length of the leading input n-grams. len_middle: The length of the middle input n-grams. len_trailing: The length of the trailin...
def to_none_int_or_checkpoint(value): """Coerce-ish a value that is None, int, or "checkpoint" """ if value is None or value == "checkpoint": return value else: return int(value)
def _preferential_attachment(set_one: list, set_two: list) -> int: """ Calculate Preferential attachment score for input lists :param set_one: A list of graph nodes -> part one :param set_two: A list of graph nodes -> part two :return: Preferential attachment score """ return len(set(set_on...
def extract_var_id(fpath): """ Extract the main variable of the file given by the file path. The variable is extracted according to its expected position in the file path. :param fpath: The file path of the file to extract the var_id from :return: The variable id of the main variable in the given f...
def kappa_analysis_altman(kappa): """ Analysis kappa number with Altman benchmark. :param kappa: kappa number :type kappa : float :return: strength of agreement as str """ try: if kappa < 0.2: return "Poor" if kappa >= 0.20 and kappa < 0.4: return "Fa...
def pad_extra_whitespace(string, pad): """ Given a multiline string, add extra whitespaces to the front of every line. """ return '\n'.join(' ' * pad + line for line in string.split('\n'))
def recipe_has_step_processor(recipe, processor): """Does the recipe object contain at least one step with the named Processor?""" if "Process" in recipe: processors = [step.get("Processor") for step in recipe["Process"]] if processor in processors: return True return False
def _check_option(parameter, value, allowed_values, extra=''): """Check the value of a parameter against a list of valid options. Return the value if it is valid, otherwise raise a ValueError with a readable error message. Parameters ---------- parameter : str The name of the parameter t...