content
stringlengths
42
6.51k
def clean_blocks(blocks): """remove *default* block if supplied - encompassing and irrelevant """ #return [b for b in blocks if b.name != "*default*"] # turns out we need for unix... typical :) return blocks
def translate_field(label, translator_map, **kwargs): """ Translate field with an old label into a list of tuples of form (new_label, new_value). :param translator_map - maps labels to appropriate tuple lists. Supplied by parsing script. For each label we get a list of tuples (new_label, mapping_functio...
def csv_to_json(csv_filename): """ converts string referencing csv file to a json file :param csv_filename: (string) name of data, as a csv file :return: string of json filename matching csv file """ csv_trimmed = csv_filename[:-3] json_added = csv_trimmed + 'json' return json_added
def dict_delete(a: dict, b: dict): """Elements that are in b but not in a""" return [k for k in a if k not in b]
def vec_leq(vec1, vec2): """ Check that vec1 is less than vec2 elemtwise """ assert isinstance(vec1, list), "Only work with lists" assert isinstance(vec2, list), "Only work with lists" assert len(vec1) == len(vec2), "Vector lengths should be the same" for x, y in zip(vec1, vec2): # if a coor...
def parse_csvs(s): """ parser for comma separated string fields, returning frozenset :s: the input string to parse, which should be of the format string 1, string 2, string 3 :returns: frozenset('string 1', ...) """ return frozenset(map(lambda ss: ss.strip(), s.spl...
def get_path_to_executable_package_location(platform, executable_name, base_destination_node): """ Gets the path to the executable location in a package based on the platform. :param platform: The platform to get the executable location for :param executable_name: Name of the executable that is being p...
def _mangle(cls, name): """ Given a class and a name, apply python name mangling to it :param cls: Class to mangle with :param name: Name to mangle :return: Mangled name """ return f"_{cls.__name__}__{name}"
def is_number(s): """ is_number(s) Try what you passed if is a number value. Parameters ---------- s : Object Value you want to try if is a number. Returns ------- Boolean Return if is a number. """ try: float(s) return True except ValueEr...
def clean(value) -> str: """Strips and converts bytes to str Args: value ([type]): [description] Returns: [type]: [description] """ if isinstance(value, bytes): value = value.decode() if isinstance(value, str): value = value.strip() return value
def unlinearize_term(index, n_orbitals): """Function to return integer index of term indices. Args: index(int): The index of the term. n_orbitals(int): The number of orbitals in the simulation. Returns: term(tuple): The term indices of a one- or two-body FermionOperator. """ ...
def diagonal(mat, diag_index): """Returns ith diagonal of matrix, where i is the diag_index. Returns the ith diagonal (A_0i, A_1(i+1), ..., A_N(i-1)) of a matrix A, where i is the diag_index. Args: mat (2-D list): Matrix. diag_index (int): Index of diagonal to return. Returns: ...
def determine_current_epsilon(time_step, fifty_percent_chance=100, start_epsilon=1.0, min_epsilon=0.1): """Determines the current epsilon value. :param time_step: The current time step from the training procedure. :pa...
def _increment_year_month(year, month): """Add one month to the received year/month.""" month += 1 if month == 13: year += 1 month = 1 return year, month
def compute_exact_score(predictions, target_lists): """Computes the Exact score (accuracy) of the predictions. Exact score is defined as the percentage of predictions that match at least one of the targets. Args: predictions: List of predictions. target_lists: List of targets (1 or mor...
def flaskify_endpoint(identifier): """ Converts the provided identifier in a valid flask endpoint name :type identifier: str :rtype: str """ return identifier.replace('.', '_')
def get_item(dictionary, key): """ Returns the object for that key from a dictionary. :param dictionary: A dictionary object :param key: Key to search for :return: Object that corresponds to the key in the dictionary """ return dictionary.get(key, None)
def get_parse_script_date( job ): """ The last time the job log file was parsed for the start/stop dates. """ if hasattr( job, 'parse_script_date' ): return job.parse_script_date return 0
def title_case(sentence): """ Convert a string to title case. Title case means that the first character of every word is capitalized and all the rest are lowercase. Parameters ---------- sentence: string String to be converted to title case Return ------ titled_sentenc...
def find_intermediate_color(lowcolor, highcolor, intermed): """ Returns the color at a given distance between two colors This function takes two color tuples, where each element is between 0 and 1, along with a value 0 < intermed < 1 and returns a color that is intermed-percent from lowcolor to hig...
def check_rent_history(rent_list, username): """ return farm ids that the given username has rented before """ farm_rent_before = [] for rent in rent_list: if rent.get('username') == username: farm_rent_before.append(str(rent.get('farm_id'))) return farm_rent_before
def variant_to_5p(hairpin, pos, variant): """ From a sequence and a start position get the nts +/- indicated by iso_5p. Pos option is 0-base-index Args: *hairpin(str)*: long sequence: >>> AAATTTT *position(int)*: >>> 3 *variant(int)*: number of nts involved in the ...
def get_iou(box1, box2): """ Computer Intersection Over Union """ xA = max(box1[0], box2[0]) yA = max(box1[1], box2[1]) xB = min(box1[2], box2[2]) yB = min(box1[3], box2[3]) inter_area = max(0, xB - xA + 1) * max(0, yB - yA + 1) box1_area = (box1[2] - box1[0] + 1) * (box1[3] - box1[...
def error(estimated, fitted): """ Calculates mean percentage error for fitted values to estimated values. :param estimated: estimated values :param fitted: fitted values :return: percent error """ return sum([abs(e / f - 1) for e, f in zip(estimated, fitted)]) / len(estimated)
def is_isogram(string: str) -> bool: """Return True if a given word or phrase is an isogram.""" letters = [letter for letter in string.casefold() if letter.isalpha()] return len(letters) == len(set(letters))
def is_positive_int(value: str) -> bool: """ refs: - https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python - isdigit vs isnumeric: https://stackoverflow.com/questions/44891070/whats-the-difference-between-str-isdigit-isnumeric-and-isdecimal-in-pytho...
def _all_dsym_infoplists(frameworks_groups): """Returns a list of Files of all imported dSYM Info.plists.""" return [ file for files in frameworks_groups.values() for file in files.to_list() if file.basename.lower() == "info.plist" ]
def bytes_to_big_int(data: bytearray) -> int: """Convert bytes to big int.""" return int.from_bytes(data, "big")
def fieldargs(field, width): """Ensure that the arguments of a function cannot go out of bounds.""" w = width or 1 assert field >= 0, 'Field cannot be negative.' assert w > 0, 'Width must be positive.' assert field + w <= 32, 'Bits accessed excede 32.' return field, w
def version_to_sip_tag(version): """ Convert a version number to a SIP tag. version is the version number. """ # Anything after Qt v5 is assumed to be Qt v6.0. if version > 0x060000: version = 0x060000 major = (version >> 16) & 0xff minor = (version >> 8) & 0xff patch = version & ...
def get_value(matrix: list, cell: tuple) -> str: """ Gets the value at the x,y coordinates in the matrix""" row, col = cell return str(matrix[row][col])
def main(textlines, messagefunc, config): """ KlipChop func to to convert lines into a CSV list """ result = list() count = 0 for line in textlines(): if line not in result: result.append(line) count += 1 if config['sort']: result = sorted(result)...
def _find_split_vs(out_vs, parallel): """Find variables created by splitting samples. """ # split parallel job if parallel in ["single-parallel", "batch-parallel"]: return [v["id"] for v in out_vs] else: return []
def parseopts(opts): """ parses the command-line flags and options passed to the script """ params = {} for opt, arg in opts: if opt in ["-K"]: params['K'] = int(arg) elif opt in ["--input"]: params['inputfile'] = arg elif opt in ["--output"]: ...
def get_additional_info_to_write_fc2_supercells( interface_mode, phonon_supercell_matrix, suffix: str = "fc2" ): """Return additional information to write fc2-supercells for calculators.""" additional_info = {} if interface_mode == "qe": additional_info["pre_filename"] = "supercell_%s" % suffix ...
def replace_spaces(lst): """ Replace all spaces with underscores for strings in the list. Requires that the list contains strings for each element. lst: list of strings """ return [s.replace(" ", "_") for s in lst]
def max_dict(dicts): """Merge dicts whose values are int. if key is present in multiple dict, choose the max. Args: dicts (list): list of dicts to merge Retrun: (dict) merged dict """ ret = {} for cur_dict in dicts: for key, value in cur_dict.items(): r...
def calc_vol(t, env): """Calculate volume at time t given envelope env envelope is a list of [time, volume] points time is measured in samples envelope should be sorted by time """ #Find location of last envelope point before t if len(env) == 0: return 1.0 if len(env) == 1: ret...
def length(database): """Computes the total number of tuning entries""" num_tuning_entries = 0 for section in database["sections"]: num_tuning_entries += len(section["results"]) return num_tuning_entries
def is_number(s: str): """ Args: s: (str) string to test if it can be converted into float Returns: True or False """ try: # Try the conversion, if it is not possible, error will be raised float(s) return True except ValueError: return False
def comma_separated_strings(value): """Parse comma-separated string into list.""" return [str(k).strip() for k in value.split(",")]
def empty_cells(keyword): """``empty-cells`` property validation.""" return keyword in ('show', 'hide')
def get_cardholder_from_notes(po_line_record): """Get cardholder note that begins with a CC- prefix from a PO line record.""" cardholder = "No cardholder note found" for note in [ n for n in po_line_record.get("note", [{}]) if n.get("note_text", "").startswith("CC-") ]: c...
def _to_str(value): """ Convert value to string if needed. """ return '' if value is None else str(value)
def find_pivot(array, high, low): """ Find the index of the pivot element """ if high < low: return -1 if high == low: return low mid = (high + low)/2 if mid < high and array[mid] > array[mid + 1]: return mid if mid > low and array[mid] < array[mid - 1]: return mid - 1 if array[low] >= array[mid]...
def measure_url(n: int) -> str: """Construct the url suitable for scraping a given measure.""" return f'https://www.ats.aq/devAS/Meetings/Measure/{n}'
def beautifulDays(i, j, k): """Problem solution.""" def reverse(n): return int(str(n)[::-1]) c = 0 for day in range(i, j + 1): if (day - reverse(day)) % k == 0: c += 1 return c
def isgzipped(f): """Check if file f is gzipped.""" with open(f, 'rb') as rpkm_file: magic = rpkm_file.read(2) return magic == '\037\213'
def safe_decode(txt): """Return decoded text if it's not already bytes.""" try: return txt.decode() except AttributeError: return txt
def degrees_to_miles_ish(dist:float): """ Convert degrees lat/lon to miles, approximately """ deg_lat = 69.1 # dist_lat_lon(42, 74, 43, 74) deg_lon = 51.3 # dist_lat_lon(42, 73, 42, 74) return dist * 60.2
def get_max(dic): """ Given a dictionary of keys with related values, return the entry with the highest value Example: A scoreboard of players and their scores. """ if len(dic.items()) == 0: return None max_item, max_value = list(dic.items())[0] for elem in dic: if dic[elem] ...
def determine_var(w, q2): """ :param w: omega as estimated :param q2: allele freq of SNP in p2 :return: sigma2, estimate of variation """ return w * (q2 * (1 - q2))
def _get_thumbnail_asset_key(asset, course_key): """returns thumbnail asset key""" # note, due to the schema change we may not have a 'thumbnail_location' in the result set thumbnail_location = asset.get('thumbnail_location', None) thumbnail_asset_key = None if thumbnail_location: thumbnail...
def _is_solution_mount(mount_tuple): """Return whether a mount is for a Solution archive. Any ISO9660 mounted in `/srv/scality` that isn't for MetalK8s is considered to be a Solution archive. """ mountpoint, mount_info = mount_tuple if not mountpoint.startswith('/srv/scality/'): return...
def group_by_types(units): """Return a dictionary of lists of units grouped by type.""" groups = {i.__class__: [] for i in units} for i in units: groups[i.__class__].append(i) return groups
def hello(friend_name): """ say hello to the world :param friend_name: a String. Ignore for now. :return: a String containing a message """ return f'Hello, {friend_name}!'
def _get_line_col(code: str, idx: int): """ Get line and column (1-based) from character index """ line = len(code[:idx + 1].splitlines()) col = (idx - (code[:idx + 1].rfind('\n') + 1)) return line, col
def is_in_references(references, doi): """ Search for a doi in a list of references. Args: references (Iterable): References to loop through. doi (str): DOI of work to search for. Returns: bool: True if doi is in any of the references, else False. """ url_doi = doi.replace(...
def build_current_state(sway_outputs): """Constructs an internal representation of the screens info.""" state = dict() for out_spec in sway_outputs: state[out_spec['name']] = { 'x': out_spec['rect']['x'], 'y': out_spec['rect']['y'], 'w': out_spec['modes'][-1]['width'], 'h': out...
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: O(n) Space Complexity: O(1) """ if nums == None: return 0 if len(nums) == 0: return 0 dp = [0 for i in range(len(...
def parse(string: str, delimiter: str = ' ', nest_open: str = '(', nest_close: str = ')') -> list: """ This function is for parsing a nested string structure into a nested list >>>parse("hello world") ["hello", "world"] >>>parse("a b (c d (e f)) g") ["a", "b", ["c", "d", ["e", "f"]], "g"] ...
def first_true(iterable, default=False, pred=None): """Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which pred(item) is true. """ # first_true([a,b,c], x) --> a or b or c or x # first_true([a,b...
def join(*args): """Create pipe separated string.""" return "|".join(str(a) for a in args)
def get_value(input_data, field_name, required=False): """ Return an unencoded value from an MMTF data structure. :param input_data: :param field_name: :param required: :return: """ if field_name in input_data: return input_data[field_name] elif required: raise Excep...
def is_leap_year(year: int) -> bool: """Check if a given year `year` is a leap year.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def shorten_file_name(name: str): """Description.""" max_length = 60 if len(name) > max_length: return name[0:max_length] + "..." return name
def dna_to_rna(dna): """ Transcribes dna to rna. Args: dna (str}: DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T'). Returns: str: rna where 'T' is replaced by 'U'. """ rna = dna.replace("T", "U") return rna
def stata_operator(leadlag, level): """Return the prefix applied to variable names in Stata e(b), e(V) matrices """ leadlag = int(leadlag) if leadlag == 0: ll='' elif leadlag == 1: ll='L' elif leadlag == -1: ll='F' elif leadlag > 1: ll='L'+str(leadlag) els...
def _label_check(label_string: str, search_label: str): """ Mask labels with Booleans that appear in row """ for label in label_string.split(' '): if search_label == label: return True return False
def parametrize(params): """Return list of params as params. >>> parametrize(['a']) 'a' >>> parametrize(['a', 'b']) 'a[b]' >>> parametrize(['a', 'b', 'c']) 'a[b][c]' """ returned = str(params[0]) returned += "".join("[" + str(p) + "]" for p in params[1:]) return returned
def sufpre(p, w): """ Return the maximal suffix of p which is also a prefix of w """ for i in range(0, len(p)): if w.startswith(p[i:]): return p[i:] return ''
def int_equals(a, b): """Small helper function, takes two objects and returns True if they are equal when cast to int. This is mainly intended to facilitate checking two strings that may or may not be ints. Most importantly, it will return False if either cannot be cast to int.""" try: return int(a) == int(b) ex...
def fill_gaps(indicies, elementss, size, gap): """Fill gaps of arrays with size with indicies and elems.""" full = [None] * size for ind, elem in zip(indicies, elementss): full[ind] = elem for ind in range(size): if full[ind] is None: full[ind] = gap() return full
def _is_chinese_char(cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korea...
def fold_dict(data, nb_level=10**5): """Fold dict `data`. Turns dictionary keys, e.g. 'level1/level2/level3', into sub-dicts, e.g. data['level1']['level2']['level3']. Parameters ---------- data: dict dict to be folded. nb_level: int Maximum recursion depth. Returns ...
def remove_prefix(state_dict, prefix): """ Old style model is stored with all names of parameters sharing common prefix 'module.' """ f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x return {f(key): value for key, value in state_dict.items()}
def fix_indentation(text): """Replace tabs by spaces""" return text.replace('\t', ' ' * 4)
def template2solution(code): """ Convert `code` marked up for exercise + solution to solution format. Parameters ---------- code : str String containing one or more lines of code. Returns ------- solution_code : str Code as it will appear in the solution version. """ ...
def inv(q, p): """ calculate q^-1 mod p """ for i in range(p): if q * i % p == 1: return i
def lerp(x, y): """ Linear interpolation between integers `x` and `y` with a factor of `.5`. """ # NOTE: integer division with floor return x + (y - x) // 2
def filter_dict(d, keys): """ Remove keys from dict "d". "keys" is a list of string, dotfield notation can be used to express nested keys. If key to remove doesn't exist, silently ignore it """ if isinstance(keys, str): keys = [keys] for key in keys: if "." in key: ...
def secant(f, a, b, n): """Approximate solution of f(x)=0 on interval [a,b] by the secant method. Parameters ---------- f : function The function for which we are trying to approximate a solution f(x)=0. a,b : numbers The interval in which to search for a solution. The function retu...
def varint_type_to_length(varint): """ Return the number of bytes used by a varint type """ if varint == 5: return (6, "") elif varint == 6 or varint == 7: return (8, "") elif varint == 8: return (0,0) elif varint == 9: return (0,1) else: return (varint, "...
def whitespace_tokenize(text): # from UDA [https://github.com/google-research/uda/tree/master/text/bert """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
def logg_to_vt_M08(logg): """ Marino et al. 2008 A&A 490, 625 (from Gratton et al. 1996) """ return 2.22 - 0.322 * logg
def make_odd(number): """ Return the input number if its odd, or return input number + 1 if its even or zero. """ if number == 0: number += 1 if number % 2 == 0: number += -1 return number
def get_start_date(participants, host_dict, repo_dates, repo): """ Finds start date based on participants. Checks if host participants have start dates associated with them. Args: participants: users in the pull request. host_dict: dictionary with host logins as keys and start dates as ...
def strip_trailing_fields_json(items): """ Strip trailing spaces for field name #456 """ data = [] for item in items: od = {} for field in item: stripped_field_name = field.strip() od[stripped_field_name] = item[field] data.append(od) return data
def remove_spaces(data): """ Create a return array and enumerate through the array and append it to the return array if the element is not a space( ) """ return_array = [] for index, el in enumerate(data): if el is not " ": return_array.append(el) retur...
def is_git(cmd): """Test if a git command.""" return cmd.endswith("git-bln")
def get_frequency_weighted_iou(n): """ Get frequency weighted intersection over union. Parameters ---------- n : dict Confusion matrix which has integer keys 0, ..., nb_classes - 1; an entry n[i][j] is the count how often class i was classified as class j. Returns -...
def _preprocess_sgm(line, is_sgm): """Preprocessing to strip tags in SGM files.""" if not is_sgm: return line # In SGM files, remove <srcset ...>, <p>, <doc ...> lines. if line.startswith("<srcset") or line.startswith("</srcset"): return "" if line.startswith("<refset") or line.start...
def hello(name: str) -> str: """ Just an greetings example. Parameters ---------- name : str Name to greet Returns ------- str Greeting message Examples -------- Examples should be written in doctest format, and should illustrate how to use the function...
def cohens_d_multiple(xbar1, xbar2, ms_with): """ Get the Cohen's-d value for a multiple comparison test. Parameters ---------- > `xbar1`: the mean of the one of the samples in the test. > `xbar2`: the mean of another of the samples in the test. > `ms_with`: the mean-squared variability of the samples ...
def unquote_and_split(arg, c): """Split a string at the first unquoted occurrence of a character. Split the string arg at the first unquoted occurrence of the character c. Here, in the first part of arg, the backslash is considered the quoting character indicating that the next character is to be added liter...
def tup_list_maker(tup_list): """ Takes a list of tuples with index 0 being the text_id and index 1 being a list of sentences and broadcasts the text_id to each sentence """ final_list = [] for item in tup_list: index = item[0] sentences = item[1] for sentence in sentenc...
def almostequal(first, second, places=7, printit=True): """ Test if two values are equal to a given number of places. This is based on python's unittest so may be covered by Python's license. """ if first == second: return True if round(abs(second - first), places) != 0: if...
def filter_list_dicts(list_dicts, key, values): """ filter out the dicts with values for key""" return [e for e in list_dicts if e[key] in values]
def find_omega(omega_r, omega_theta, omega_phi, em, kay, en, M=1): """ Uses Boyer frequencies to find omega_mkn Parameters: omega_r (float): radial boyer lindquist frequency omega_theta (float): theta boyer lindquist frequency omega_phi (float): phi boyer lindquist frequency ...
def func_args_realizer(args): """ Using an ast.FunctionDef node, create a items list node that will give us the passed in args by name. def whee(bob, frank=1): pass whee(1, 3) => [('bob', 1), ('frank', 3)] whee(1) => [('bob', 1), ('frank', 1)] """ items = map("('{0}', {0})".for...