content
stringlengths
42
6.51k
def _name_as_key(name): """Uppercase, stripped, no repeated interior whitespace.""" name = name.upper().strip() while ' ' in name: name = name.replace(' ', ' ') return name
def parse_literal(x): """ return the smallest possible data type for a string or list of strings x: str or list a string to be parsed Returns int, float or str the parsing result Examples -------- >>> isinstance(parse_literal('1.5'), float) >>> isinstance(parse_lite...
def str2data(str): """ Convert a string to some data bytes. An empty or None value is returned unchanged (helpful for testing), e.g.: 'WunderbarIR' -> '57 75 6e 64 65 72 62 61 72 49 52' '' -> '' """ if not str: return str data = ' '.join([hex(ord(c))[2:] for c in str]) return data
def print_array(arr): """ Prints the content of a list :param arr: a list that needed to be printed :return: the string needed to print """ string = '' for a in arr: string += str(a) + ' ' return string.strip(' ')
def multi_inputs(dicts): """ Deal with components that have multiple values and multiple IDs from id-value dicts (can be found inside def process_inputs; dicts pre-processed inside the function) """ dict_list = {} for k, v in dicts.items(): if k[-1:].isnumeric() is False: ...
def transpose_matrix(matrix): """Transposes a matrix. Returns the transposed matrix. Args: matrix (2-D list): Matrix. Returns: Transposed matrix. """ transpose = [[0] * len(matrix) for _ in range(len(matrix[0]))] for i, row in enumerate(matrix): for j in range(len(...
def check_opposite_directions(encoding_directions): """ Check if we have an opposite direction in the list """ for dir in encoding_directions: if dir + "-" in encoding_directions: return True return False
def column_one(text): """ For a given in-memory sequence of texts, return the first column of the embedded csv formatted as a string. """ #creates an empty list_of_words list_of_words = [] #split string into lines lines = text.splitlines() # create in for-loop: takes t...
def mod_namelist_val(val): """Remove unnecessary dots and commas from namelist value and use only one type of quotation marks.""" val = val.replace('"', "'") if val[-1] == ",": val = val[:-1] if val[-1] == ".": val = val[:-1] try: val = float(val) if val == int(val):...
def getpoint(line): """Gets data entries from html lines """ spline = line.split('<tr><td class="xl28b">&nbsp;&nbsp;') if len(spline) > 1: data = spline[1].split('</td></tr>')[0] else: data = None return data
def join_cmd(strings): """Joins a sequence of objects as strings, with select statements that return strings handled correctly. This has O(N^2) performance, so don't use it for building up large results. This is mostly equivalent to " ".join(strings), except for handling select stateme...
def parse_regex(rfile): """Read file and return regex""" if rfile: with open(rfile) as fp: lines = fp.readlines() lines = map(lambda x: x.strip(), lines) return lines return None
def closed_form_solution(max_number: int) -> int: """Closed form solution.""" square_of_sum = (max_number * (max_number + 1) // 2)**2 sum_of_squares = (max_number * (max_number + 1) * (2 * max_number + 1)) // 6 return square_of_sum - sum_of_squares
def is_prime(n): """ Naive implementation of a primality test. Adapted from: https://en.wikipedia.org/wiki/Primality_test#Pseudocode """ if n <= 1: return False elif n <= 3: return True elif n % 2 == 0 or n % 3 == 0: return False i = 5 while i*i <= n: if n % i == 0 or n % (i + 2) == 0...
def get_insert_components(options): """ Takes a list of 2-tuple in the form (option, value) and returns a triplet (colnames, placeholders, values) that permits making a database query as follows: c.execute('INSERT INTO Table ({colnames}) VALUES {placeholders}', values). """ col_names = ','.join(opt[0] for opt in o...
def obj_to_jsonable_dict(obj, attrs): """converts a object into a json-serializable dict, geting the specified attributes. """ as_dict = {} for attr in attrs: if hasattr(obj, attr): as_dict[attr] = getattr(obj, attr) return as_dict
def _clean_dict(row): """ Transform empty strings values of dict `row` to None. """ row_cleaned = {} for key, val in row.items(): if val is None or val == "": row_cleaned[key] = None else: row_cleaned[key] = val return row_cleaned
def from_u16(n: int) -> int: """Reinterpret the unsigned 16-bit integer `n` as a signed integer.""" if n >= 2 ** 15: return -(2 ** 16 - n) else: return n
def listIn(container, maybe_contained, *, strict=True): """ strictly sublists no equality here """ lc = len(container) lmc = len(maybe_contained) if lc > lmc or not strict and lc == lmc: z = maybe_contained[0] if z in container: substart = container.index(z) subco...
def mix_wave(src, dst): """Mix two wave body into one.""" if len(src) > len(dst): # output should be longer dst, src = src, dst for i, sv in enumerate(src): dv = dst[i] if sv < 128 and dv < 128: dst[i] = int(sv * dv / 128) else: dst[i] = int(2...
def _parallel_decision_function(estimators, estimators_features, X): """Private function used to compute decisions within a job.""" return sum(estimator.decision_function(X[:, features]) for estimator, features in zip(estimators, estimators_features))
def lowest_common_ancestor(root, i, j): """ We traverse to the bottom, and once we reach a node which matches one of the two nodes, we pass it up to its parent. The parent would then test its left and right subtree if each contain one of the two nodes. If yes, then the parent must be the LCA and we ...
def listOfTuplesToList(listOfTuples): """Convert a list of tuples into a simple list of tuple[0] items.""" res = [] for item in listOfTuples: res.append(item[0]) return res
def check_if(value): """check if value exists""" if value: return value else: return "no-record"
def is_correct_answer(user_answer, correct_answer, limit, answer_handler=None): """Check if answer correct (more than :limit: of words is ok). :param user_answer: text of user answer :param correct_answer: text of correct answer :param limit: number between 0 and 1, this is percentage of correct answer...
def Protein_translation_RNA(t, y, L, U, D, mRNA): """ Defines ODE function Conversion of Amb_mRNA to protein p1,p2,p3....: Protein concentrations for all ODEs It will have list of all parameter values for all my ODEs, so 36 values : L, U, D for each mRNA to protein conversion equation """ # ...
def epoch_to_num(epoch): """ Taken from spacepy https://pythonhosted.org/SpacePy/_modules/spacepy/pycdf.html#Library.epoch_to_num Convert CDF EPOCH to matplotlib number. Same output as :func:`~matplotlib.dates.date2num` and useful for plotting large data sets without converting the times through da...
def cls_get_by_name(cls, name): """ Return a class attribute by searching the attributes `name` attribute. """ try: val = getattr(cls, name) except AttributeError: for attr in (a for a in dir(cls) if not a.startswith('_')): try: val = getattr(cls, attr) ...
def _flatten_ingredients_tree(ingredients_tree: list) -> list: """Returns a list of dicts""" ingredients = {} ingredients_without_subs = [] sub_ingredients = [] for item_id, item_amount, item_ingredients in ingredients_tree: if item_id in ingredients.keys(): ingredients[item_id]...
def value(val, transform=None): """ Convenience function to explicitly return a "value" specification for a Bokeh :class:`~bokeh.core.properties.DataSpec` property. Args: val (any) : a fixed value to specify for a ``DataSpec`` property. transform (Transform, optional) : a transform to appl...
def divide_by_100(value): """Converts lateral position and color value from Covering array to their correct values as float.""" return float(value / 100.0)
def consistentCase(name): """Converts snake_case strings to CameCase""" splitted = name.split('_') out = ''.join([word[0].upper() + word[1:] for word in splitted]) return out
def infer_combined_lens_separation(f1, f2, f): """Infer the separation of a combined lens from the individual focal lengths and the effective focal length. Args: f1: focal length of first lens f2: focal length of second lens f: effective focal length Returns: separation bet...
def _convert_single_instance_to_multi(instance_shap_values): """Convert a single shap values instance to multi-instance form. :param instance_shap_values: The shap values calculated for a new instance. :type instance_shap_values: np.array or list :return: The instance converted to multi-instance form. ...
def preprocess(images): """Transform images before feeding them to the network.""" return (2.0*images) - 1.0
def file_text(txt_or_fname: str) -> str: """ Determine whether text_or_fname is a file name or a string and, if a file name, read it :param txt_or_fname: :return: """ if len(txt_or_fname) > 4 and '\n' not in txt_or_fname: with open(txt_or_fname) as ef: return ef.read() re...
def search_for_vowels(phrase: str) -> set: """Search for vowels in entered word""" v = set('aeiou') found = v.intersection(set(phrase)) return found
def count_words(text): """Count the words of text passed as argument.""" total_words = 0 for word in text.split("\n"): if word.strip(): total_words += 1 return total_words
def get_embedding_size(n: int, max_size: int = 100) -> int: """ Determine empirically good embedding sizes (formula taken from fastai). Args: n (int): number of classes max_size (int, optional): maximum embedding size. Defaults to 100. Returns: int: embedding size """ i...
def to_perl_syntax(d): """ Convert a list of dictionaries to Perl-style syntax. Uses string-replace so rather brittle. """ return str(d).replace(':', ' => ').replace('[', '(').replace(']', ')')
def squared_root_normalization_output_shape(input_shape): """ Return the output shape for squared root normalization layer for any given input size of the convolution filter :param input_shape: shape of the input :return: output shape """ return (input_shape[0], input_shape[-1])
def is_tar(name): """Check if name is a Tarball.""" return ( name.endswith(".tar") or name.endswith(".gz") or name.endswith(".bz2") )
def collect_sentences_coco(data): """Collect all sentences from COCO captions""" sentences = [] for ann in data['annotations']: sentences.append(ann['caption']) return sentences
def get_seconds(value, scale): """Convert time scale dict to seconds Given a dictionary with keys for scale and value, convert value into seconds based on scale. """ scales = { 'seconds': lambda x: x, 'minutes': lambda x: x * 60, 'hours': lambda x: x * 60 * 60, 'days': lambda x: x * 60 * 60 *...
def get_season(x): """Extract summer from month values.""" summer, fall, winter, spring = 0, 0, 0, 0 if (x in [5, 6, 7]): summer = 1 if (x in [8, 9, 10]): fall = 1 if (x in [11, 0, 1]): winter = 1 if (x in [2, 3, 4]): spring = 1 return summer, fall, winter, s...
def _inv_dict(d): """Reverse a dictionary mapping. Returns multimap where the keys are the former values, and values are sets of the former keys. Args: d (dict[a->b]): mapping to reverse Returns: dict[b->set[a]]: reversed mapping """ ret = {} for k, v in d.items(): ...
def split_cli(line): """ Split the command line into individual tokens. we'd like to use shlex.split() but that doesn't work well for windows types of things. for now we'll take the easy approach and just split on space. We'll then cycle through and look for leading quotes and join those lines...
def feed_url(itunes_lookup_response): """ Returns feed URL from the itunes lookup response :param itunes_lookup_response: :return: str """ if len(itunes_lookup_response.get('results')) == 0: raise LookupError("iTunes response has no results") url = itunes_lookup_response.get('results...
def get_ckpt_name(scope): """Auxillary funtion. Argus: scope: String or `None`. """ if scope is None: return 'all_scopes.ckpt' return '{}_scope.ckpt'.format(scope)
def is_path_like(obj, attr=('name', 'is_file', 'is_dir', 'iterdir')): """test if object is pathlib.Path like""" for a in attr: if not hasattr(obj, a): return False return True
def bytes_endswith(x: bytes, suffix: bytes) -> bool: """Does given bytes object end with the subsequence suffix? Compiling bytes.endswith, with no range arguments, compiles this function. This function is only intended to be executed in this compiled form. Args: x: The bytes object to examine....
def string_distance(s1, s2): """ Calculate the number of characters that differ between two strings of identical length. Returns 1 if lengths do not match. """ if len(s1) != len(s2): return 1 diff_count = 0 for c1, c2, in zip(s1, s2): if c1 != c2: diff_count ...
def default_k_rdm(n_rdm): """ the default number of rdm groupsfor crossvalidation minimum number of subjects is k_rdm. We switch to more groups whenever the groups all contain more rdms, e.g. we make 3 groups of 2 instead of 2 groups of 3. We follow this scheme until we reach 5 groups of 4. From the...
def splitAndStrip(myString, sep=',', n=-1, fixed=0): """ This methods splits a string in a list of n+1 items, striping white spaces. @param myString @param sep: separation character @param n: how many split operations must be done on myString @param fixed: use fixed if the resulting list must be...
def flatten(a): """ Recursively flatten tuple, list and set in a list. """ if isinstance(a, (tuple, list, set)): l = [] for item in a: l.extend(flatten(item)) return l else: return [a]
def from_digits(digits): """ Make a number from its digit array (inverse of get_digits) """ n = 0 multiplier = 1 for d in reversed(digits): n += multiplier * d multiplier *= 10 return n
def isAnagram(string1, string2): """assumes string1 and string2 are string of alphabetical chars of any case returns a boolean, True is string1 and string2 are casse insensite anagrams else False """ return sorted(string1.lower()) == sorted(string2.lower())
def phase(flags): """ Returns the layer thermodynamical phase, as identified from the feature classification flag 0 = unknown / not determined 1 = randomly oriented ice 2 = water 3 = horizontally oriented ice """ # 96 = 0b1100000, bits 6 to 7 return (flags & 96) >> 5
def fix_name(name): """ Fixes album/artist name. """ name = str(name).strip() if name.endswith(")"): name = name.rsplit("(", 1)[0].rstrip() name = name.replace(".", " ") return name
def provider_names(providers): """ Returns the names of the :providers:, separated by commas. """ return ", ".join([p.provider_name for p in providers])
def sweep_activation_toggle( _, sourced_val, meas_triggered, swp_on, swp_stop, swp_step, mode_choice ): """decide whether to turn on or off the sweep when single mode is selected, it is off by default when sweep mode is selected, it enables the sweep if is wasn't on otherwise it stops the sweep once...
def unwrap(func): """ Finds the innermost function that has been wrapped using `functools.wrap`. Note: This function relies on the existence of the `__wrapped__` attribute, which was not automatically added until Python 3.2. If you are using an older version of Python, you'll have t...
def clean_name(name): """Make the name nice looking for plots""" if name.startswith('SUBSET'): name = 'Subset' + name[-1] else: name = name.capitalize() return name
def get_pkg_ver(pv, add_quotes=True): """Return package name and version""" #XXX Fix package names with spaces bug. n = len(pv.split()) if n == 2: #Normal package_name 1.0 pkg_name, ver = pv.split() else: parts = pv.split() ver = parts[-1:] if add_quotes: ...
def split_on_space(text): """ split text on spaces. :param text: the text that needs to be tokenized :type text: string """ return text.split(' ')
def filter_slice(s,start=None,stop=None,step=None): """slice(s,start=0,stop=-1,step=1) -> str Extract a slice of the given string, from start to stop, taking every step characters.""" xstart = None xstop = None xstep = None if start: try: xstart = int(start) except ValueError as e: xstart...
def search_for_vowels(phrase: str) -> set: """Returns set of vowels found in 'phrase'.""" return set('aeiou').intersection(set(phrase))
def remove_userfcn(ppc, stage, fcn): """Removes a userfcn from the list to be called for a case. A userfcn is a callback function that can be called automatically by PYPOWER at one of various stages in a simulation. This function removes the last instance of the userfcn for the given C{stage} with the ...
def hPa_to_inHg(p_hPa): """Convert hectopascals to inches of mercury.""" if p_hPa is None: return None return p_hPa / 33.86389
def _reversemap_vhosts(names, vhosts): """Helper function for select_vhost_multiple for mapping string representations back to actual vhost objects""" return_vhosts = list() for selection in names: for vhost in vhosts: if vhost.display_repr().strip() == selection.strip(): ...
def value_default(func, value, default=None): """Return `func(value)`, or `default` on `exception`.""" try: return func(value) except (ValueError, TypeError): return default
def ansi_red(string): """Colorizes the given string with `ANSI escape codes <https://en.wikipedia.org/wiki/ANSI_escape_code>`_ :param string: a py:class:`str` .. note:: This function is here for demo purposes, feel free to delete it. :returns: a string """ return '\033[1;31m{}\033[0m'.format...
def _convert_to_new_device_coordinate(device_coordinate, tensor_map): """ Convert device_coordinate according to the tensor map. Args: device_coordinate (list): The coordinate for local device in the device matrix. tensor_map (list): The map relation between tensor and devices. Returns...
def _twos_complement(val, bits): """compute the 2's complement of int value val""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) return val
def splitLine(pt1, pt2, where, isHorizontal): """Split the line between pt1 and pt2 at position 'where', which is an x coordinate if isHorizontal is False, a y coordinate if isHorizontal is True. Return a list of two line segments if the line was successfully split, or a list containing the original ...
def elem_Q(w,Q,n): """ Simulation Function: -Q- Inputs ---------- w = Angular frequency [1/s] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] """ return 1/(Q*(w*1j)**n)
def get_full_function_name(f): """ Constructs full module path for a given function. Args: f (function): Function to construct the path for Returns: str """ return f"{f.__module__}.{f.__qualname__}"
def count_rollback_success(success_count, rollback_success_count, rollback_count, oscillating_success_count, oscillating_count, traj, error_margin=3.0): """ check if the viewpoint was visited in the previous 2 steps, if YES, we define this was a rollback action We count the total ...
def dedupe_list(seq): """ Utility function to remove duplicates from a list :param seq: The sequence (list) to deduplicate :return: A list with original duplicates removed """ seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
def _value_sorter(feature_value): """Custom sorting function taking into account the structure of values. Given a feature value extracts its numeric portion, e.g. "18 ObligDoubleNeg" -> "18". Args: feature_value: (string) WALS feature value. Returns: An integer corresponding to the first portion ...
def to_camel_case(snake_str): """ Converts snake_case to camelCase. :param snake_str: a string in snake case :return: equivalent string in camel case >>> to_camel_case('a_b') 'aB' >>> to_camel_case('some_important_string') 'someImportantString' """ components = snake_str.split(...
def get_string(value): """ Returns string representation of the value or empty string if None """ if value: return str(value) else: return ""
def recursive_factorial(num): """Recursive solution""" if num >= 2: return num * recursive_factorial(num - 1) return 1
def split(list, index): """ Split the given list into two sublists at the given index and return both sublists. The first sublist should contain items at index 0 through `index - 1`, and the second sublist should contain the items at index `index` through the end. If the given index is too high, ...
def check_all_equal(lst): """Check that all items in a list are equal and return True or False """ return not lst or lst.count(lst[0]) == len(lst)
def create_hr_context_output(result: list) -> list: """ For creating context and human readable :param result: list of raw data :return: list """ hr_context_output_list = [] for result_row in result: hr_context_output_list.append({ 'Id': result_row.get('Id', ''), ...
def chromosomesInCluster(cluster): """ Determine the chromosomes in a cluster of hotspot regions :param cluster: list List of hotspot regions :return: dict Chromosomes and first last positions within the chromosomes in the cluster """ chromosomes = dict(); for point in clu...
def url_remove_fragment(url): """ http://one/two#three => http://one/two """ index = url.find("#") if index > 0: return url[0:index] else: return url
def check_winner(board_state): """ Iterates over the board spaces, Recording the indices of 1's (1) and 0's (0) in two sets. Iterates through the winning combinations in WINNERS to see if there is a winner. Returns 1, 0, or -1 if True wins, False wins, or if there i...
def partition(list, start, end): """Partition helper function for quicksort.""" sorted = False pivot = list[start] left = start + 1 right = end while not sorted: while left <= right and list[left] <= pivot: left = left + 1 while list[right] >= pivot and right >= lef...
def warning(flag=True): """Presence condition mutator/wrapper: When flag is True, a warning should be issued if the related keyword/element is not defined. Returns "W" or False. >>> warning(True) 'W' >>> warning(False) False """ return "W" if flag else False
def find(n): """ Finds the sum of all multiples of 3 and 5 of an integer. :param n: an integer value. :return: the sum of all multiples of 3 and 5. """ return sum(x for x in range(n+1) if x % 5 == 0 or x % 3 == 0)
def _sort_tuple(t): """copies the given sequence into a new tuple in sorted order""" l = list(t) l.sort() return tuple(l)
def strike_text(text): """Add a strikethtough effect to text.""" striked = '' for char in text: striked = striked + char + '\u0336' return striked
def merge_params(params): """ Build a complete parameter set by merging all parameters in the provided list from left to right. """ assert isinstance(params, list), f"params needs to be a list of dicts, got {type(params)}={params}" for p in params: assert isinstance(p, dict), f"params n...
def get_guess_doc_provenance(sources, icsd=None): """ Returns a guess at the provenance of a structure from its source list. Return possiblities are 'ICSD', 'SWAP', 'OQMD' or 'AIRSS', 'MP' or 'PF'. """ prov = 'AIRSS' if isinstance(sources, dict): sources = sources['source'] elif...
def bool_converter(value: str) -> bool: """ :param value: a string to convert to bool. :return: False if lower case value in "0", "n", "no" and "false", otherwise, returns the value returned by the bool builtin function. """ if value.lower() in ['n', '0', 'no', 'false']: return False ...
def check_shape(mat): """Check if the two matrices has the same shape if not return None""" shape = [] while isinstance(mat, list): shape.append(len(mat)) mat = mat[0] # print("shapes are {}".format(shape)) return shape
def query_encode(query): # type: (str) -> str """Replaces ' ' for '+'""" return query.replace(" ", "+")
def videoQualityToInteger(test_video_quality): """def videoQualityToInteger(test_video_quality): -> test_video_quality convert str video quality to integer.""" try: test_video_quality = str(test_video_quality[:-1]) test_video_quality = int(test_video_quality) return test_video_quali...