content
stringlengths
42
6.51k
def queryMaker(readList, outLoc="queryTemp.txt"): """ Takes a counts object (nested list in the form [[read, total, unique],...]) and creates a file formatted for input into BLAST. :param readList: nested list in the form [[read, total, unique],...] :param outLoc: file location. temporary place to s...
def traverse_fields(entry, ignore_fields=None): """ Returns a list of sets of nested fields (one set per level of nesting) of a JSON data entry produced by a benchmark analysis script. Ignores the dashboard-appended 'timestamp' and 'tvm_hash' fields at the top level by default. Also ignores the 'det...
def get_memory_in_GB(memory_str): """Returns the memory value in GB from a given string in kB""" try: return '{0} GB'.format(int(memory_str[:-2]) / 1000000) except (ValueError, TypeError): return ''
def getWordsUnder(wordList, targetLength): """ return list of words of a specified length in the list """ return [word for word in wordList if len(word) < targetLength]
def deposit_money(amount, card_balance): """Deposit given amount of money to the account.""" card_balance += amount # save new balance to the database return card_balance
def _filter_subs_packages(initial, subs): """Rename and filter package list with subsitutions; for similar systems. """ final = [] for p in initial: try: new_p = subs[p] except KeyError: new_p = p if new_p: final.append(new_p) return sorted...
def linear(iteration: int, frequency: int = 10) -> bool: """Optimize hyperparameters at equally spaced intervals Args: iteration (int): current iteration frequency (int, optional): Spacing between the True outputs. Defaults to 10. Returns: bool: True if iteration can be divided by ...
def bai_path(bamfilepath): """Return the path to BAI file in the same directory as BAM file.""" return f"{bamfilepath}.bai"
def scale(num, base): """ If num is a float, multiplies it by base and returns that. Otherwise, returns num unchanged. """ if isinstance(num, float): return num * base else: return num
def RPL_WHOISOPERATOR(sender, receipient, message): """ Reply Code 313 """ return "<" + sender + ">: " + message
def model(fr, p): """ Using this model because it satisfies some things that should be true in asymptotic limits: As the fineness ratio goes to infinity, the drag-divergent Mach should go to 1. As the fineness ratio goes to 0, the drag-divergent Mach should go to some reasonable value in the range of ...
def golden_section_search(function, a, b, tol=1e-3): """Golden section search algorithm for finding the minimum or maximum of a strictly unimodal function by successively narrowing the range of values inside which the extremum is known to exist. Parameters ---------- function : Function Eva...
def get_tag_text(tag): """Gets the text from a valid tag (just the text without the leading #)""" return tag[1:]
def get_latest_sudo_policies(sudo_policies_list): """ Example of sudo_policies_list: [ ['qpm-rhel6-64a', '/etc/opt/quest/qpm4u/policy/sudoers', '7.1.99.7-55-g787b0a37a', '1634124307'], ['qpm-rhel6-64b', '/etc/opt/quest/qpm4u/policy/sudoers', '7.1.99.7-55-g787b0a37b', '1634124308'], [...
def validate_nb_custom_field(custom_field): """ Validate NetBox custom field environment variable """ # Ensure NetBox custom_field is present if custom_field == "" or custom_field is None: print("Missing custom_field to update") return False return True
def get_data_list_name(name): """ get plural form city -> cities unit -> units :param str name: name of unit :return: """ last = name[-1] if last in 'y': if last in 'a,e,i,o,u,y': name = name[0:-1] + 'ies' else: name += 's' elif last in 'ou': ...
def _le_from_ge(self, other): """Return a <= b. Computed by @total_ordering from (not a >= b) or (a == b).""" op_result = self.__ge__(other) if op_result is NotImplemented: return NotImplemented return not op_result or self == other
def parse_int(text: str) -> bool: """ Normally we would use str.isnumeric and int. The problem is, that isnumeric doesn't account for negative values. That is the job of this helper function. In earlier versions this function returned the integer value, but now it returns a boolean. This is because we m...
def _get_yield_and_servings(value): """Returns a tuple consisting of the yield value and servings value. Only one of these has a meaningful value while the other is set to a default value. If there is an integer followed optionally by the word 'serving' or 'servings' then return this integer value as t...
def unsnake(field): """ Return a string that converts underscore to spaces and capitalizes first letter. """ return str(field).replace('_', ' ').capitalize()
def get_group_gn(dim, dim_per_gp, num_groups): """get number of groups used by GroupNorm, based on number of channels.""" assert dim_per_gp == -1 or num_groups == -1, \ "GroupNorm: can only specify G or C/G." if dim_per_gp > 0: assert dim % dim_per_gp == 0, \ "dim: {}, dim_per_g...
def get_size_string(size): """Return string representation for size.""" if size < 1 << 10: return '%d B' % size elif size < 1 << 20: return '%d KB' % (size >> 10) elif size < 1 << 30: return '%d MB' % (size >> 20) return '%d GB' % (size >> 30)
def _GetChannelIndicesInChannelDataIdList(id_list): """Returns a list of all the unique channel indices requested.""" channel_indices = [] for ch in id_list: if ch.HasField('bipolar_channel'): request_indices = [ ch.bipolar_channel.index, ch.bipolar_channel.referential_index ] else: ...
def success_responses_filter(responses): """ :param responses: :return: """ return [each for each in filter(lambda r: r.status_code == 200, responses)]
def join_url(url, *paths): """ Joins individual URL strings together, and returns a single string. Usage:: >>> util.join_url("example.com", "index.html") 'example.com/index.html' """ to_rstrip = [url] + list(paths[:-1]) parts = [path.rstrip('/') for path in to_rstrip] + [paths[...
def merge_two_dicts(x, y): """ Helper function to merge dictionaries into one """ z = x.copy() z.update(y) return z
def recursive_dict_update(d, u): """Update d with values from u, recursing into sub-dictionaries.""" for k, v in u.items(): if isinstance(v, dict): try: # copy because we don't want to modify the sub-dictionary # just use its values to create an updated sub-di...
def dfttk_config_to_espei(config): """Convert a DFTTK configuration, e.g. [['Fe', 'Ni'], ['Fe']] to ESPEI's configuration [['FE', 'NI'], 'FE']""" espei_config = [] for subl in config: if len(subl) == 1: # this sublattice is an endmember espei_config.append(subl[0].upper()) ...
def error_413(error): """Payload Too Large""" return "Uploaded file is too large", 413
def format_date(match_date): """ Formats a data string for printing and display purposes. Param: my_price (str) like "2019-08-11T13:00:00Z" Example: format_date(2019-08-11T13:00:00Z) Returns: 2019-08-11 """ return match_date[0:10]
def is_substring(subseq, seq): """Check if `subseq` is a substring of `seq`.""" n = len(seq) m = len(subseq) if m > n: return False j = 0 i = 0 while i < n: if seq[i] == subseq[j]: j += 1 if j == m: return True elif j > 0: ...
def generate_section(inputfiles, align_sizes): """ generates the all section """ cmd = ["tmp.all"] for index, file in enumerate(inputfiles): cmd += [file] if align_sizes != [None]: # the first input is None cmd += ["--sectionalign", align_sizes[index + 1]] retur...
def traverse(dictionary, keys, default=None): """Find a deep value in a dictionary Args: dictionary (dict): The event port. keys (tuple|str): The hiearchical list of keys. default: The default value if not found. Returns: The value, or `default` if not found. """ i...
def check_mandatory_keys(config, section, keys): """Check that mandatory keys are present in config :param dict config: the dictionary containing the configuration :param string section: the section in which to check for the keys :param list keys: the keys to check for existence :return: True :...
def CRRAutilityPP(c, gam): """ Evaluates constant relative risk aversion (CRRA) marginal marginal utility of consumption c given risk aversion parameter gam. Parameters ---------- c : float Consumption value gam : float Risk aversion Returns ------- (unnamed) : ...
def zfp_expert_opts(minbits, maxbits, maxprec, minexp): """Create compression options for ZFP in "expert" mode See the ZFP docs for the meaning of the parameters. """ zfp_mode_expert = 4 return zfp_mode_expert, 0, minbits, maxbits, maxprec, minexp
def extract_type_for_type_or_null_property(property_): """ Serpyco use "anyOf" (null, or defined type) key to define optional properties. Example: ``` json [...] "properties":{ "id":{ "type":"integer" }, "nam...
def generate_file_name(file_name="playlist", resolution="SD", extention="m3u8"): """ return file name with resulotion ex: generate_file_name('output', 'HD') >> 'output_HD.m3u8 """ if file_name is None: file_name="playlist" if extention is None: extention="m3u8" return f"{file_name}_...
def pickfirst(files): """Return first file from a list of files Parameters ---------- files : list of filenames Returns ------- file : returns the filename corresponding to the middle run """ if isinstance(files, list): return files[0] else: return files
def safe_cast(value, __class, default=None): """Try, cast, handle""" try: return __class(value) except (ValueError, TypeError) as err: print(f'Error casting {value} as {__class}: {err}') return default
def _format_csv(record: dict) -> str: """formats the values of the record as comma separated values """ return ','.join([str(val) for val in record.values()])
def application_error(e): """Return a custom 500 error.""" return 'Sorry, unexpected error: {}'.format(e), 500
def remove_block_head(block, head): """.""" new_block = [] for line in block: if line.startswith(head): index = len(head) line = line[index:] if line.startswith('.'): line = line[1:] new_block.append(line) return new_block
def profbfiles(date): """Observation file locator stub .. note:: User-specified stub :param date: The verification date in string format ``'%Y%m%d'`` :returns: List of files """ files = ['profb.nc'] return files
def next_page(page_list, page): """Returns next page of a list. Its needed for pagination. :param page_list: A list of available page numbers. :param page: Page to get next page from. :type page_list: list :type page: int :return: Page number of next page. :rtype: int """ if pa...
def timeBlock(block, dur): """Adjusts the block for the proper timing interval""" nBlock = [] for i, b in enumerate(block): # i is the index, b is the isi element within block if i == 0: nBlock.append(b) else: j = i - 1 prev = block[j] # prev is the ...
def map_ids(elems): """ Turn a list of objects into a list of spotify ids. """ return [elem.spotify_id() for elem in elems]
def full_kwargs(state, kwargs): """ Merge command state with keyword arguments. Command state takes precedence over any keyword argument. :param state: The current command state. Can be ``None``. :param kwargs: The base keyword arguments. :returns: A dictionary containing all of ``kwargs``, wi...
def gettags(comment): """ Parse documentation strings into JavaDoc-like tokens """ tags = [] tag = None datatype = None name = None tag_lineno = lineno = 0 tag_text = [] for line in comment.split('\n'): line = line.strip() if line.startswith("@"): tags.appe...
def convert_lines_to_object(lines: list) -> dict: """ Convert an array of lines into an object indexed by the line number Indexing from 0 Parameters ---------- lines : list The list of lines to convert Returns ------- dictionary A dictionary of the lines, indexed by...
def humanized_class_name(obj, *args, **kwargs): """ Adds spaces to camel-case class names. """ humanized = '' class_name = obj.__class__.__name__ for i in range(len(class_name)): humanized += class_name[i] # Insert space between every camel hump. if (i + 1 < len(class_n...
def _convert_to_string(input_value): """Converts input value to string. :param input_value: Input value. :return: output_value: Float value. """ try: return str(input_value).strip().upper() except: return ''
def nested_contains(list_: list, value: object) -> bool: """ Return whether list_, or any nested sub-list of list_ contains value. >>> list_ = ["how", "now", "brown", 1] >>> nested_contains(list_, "now") True >>> nested_contains(list_, 1) True >>> nested_contains(list_, 3) False ...
def bubble_sort(array): """ Sorts a list using bubble sort algorithm Input: A list of integers Output: A list containing the same integers as the input, but sorted in ascending order Sorts by iterating through a list swapping values that are in the wrong order. Stops when it is imp...
def gen_workspace_tfvars_files(environment, region): """Generate possible Terraform workspace tfvars filenames.""" return [ # Give preference to explicit environment-region files "%s-%s.tfvars" % (environment, region), # Fallback to environment name only "%s.tfvars" % environment...
def _tail_avg(timeseries, tidx=0, vidx=1): """ This is a utility function used to calculate the average of the last three datapoints in the series as a measure, instead of just the last datapoint. It reduces noise, but it also reduces sensitivity and increases the delay to detection. """ try...
def it(item): """Utility to convert rounded floats to int.""" try: is_equal = int(item) == float(item) except ValueError: # Item may not be numerical return item return int(item) if is_equal else float(item)
def replace_sanalinkki(text, words): """ Korjaa sanalinkit. """ for key in words.keys(): text = text.replace("#sanalinkki_{}".format(key), "#" + words[key]) return text
def getObjectName(objects): """Create a string representing the objects name. objects - list of one or more DejaVu geom. objects""" name = "" for object in objects: try: objectName = object.fullName if objectName.split("|")[-1] != 'root': if objectName.fin...
def punct(w_list): """ :param w_list: word list to be processed :return: w_list with punct and number filter out """ return [word for word in w_list if word.isalpha()]
def dictmerge(*dicts): """ """ result = {} for d in dicts: result.update(d) return result
def get_hashtags(hashtag_entity): """ - gets all the hashtags if available in the tweet """ hashtags = [] if hashtag_entity is not None: for hashtag in hashtag_entity: hashtags.append(hashtag['text']) return hashtags
def _class_is_reference(cls): """ Checks if the current model entity is in fact a (data) reference class, for external elements reference. The data reference classes are used to refer external components of the model, for a loose connection. :rtype: bool :return: If the current cl...
def partition(pred, iterable): """Returns [[trues], [falses]], where [trues] is the items in 'iterable' that satisfy 'pred' and [falses] is all the rest.""" trues = [] falses = [] for item in iterable: if pred(item): trues.append(item) else: falses.append(item...
def equation(x: float) -> float: """ hasil dari pengurangan dan perkalian dari x parameter dan tipe: x: float return: hasil dari 10 - x * x tipe: float >>> equation(5) -15 >>> equation(0.1) 9.99 """ return 10 - x * x
def det3(u, v, w): """Determinant of 3x3 matrix formed by input 3-vectors ``u``, ``v`` and ``w``.""" return u[0] * (v[1] * w[2] - v[2] * w[1]) + u[1] * (v[2] * w[0] - v[0] * w[2]) + u[2] * (v[0] * w[1] - v[1] * w[0])
def get_source_id(sl): """sl is list of sources in form: ns:id. Return the ns and id of the last entry""" source = sl[len(sl) - 1] # get last source item ns, id = source.split(':') return (ns, id)
def vars_are_encrypted(vars): """Returns True if any of the values in the dictionary vars contains content which is encrypted by the AWX encryption algorithm """ for value in vars.values(): if isinstance(value, str): if value.startswith('$encrypted$'): return True ...
def qb_account(item_title): """ Given an item title, returns the appropriate QuickBooks class and account Parameter: item_title Returns: item_class, item_account Note that this is only guaranteed to work for Ticketleap sales, not PayPal invoices. """ if 'Northern' in item...
def encodeHTML(string): """ Encodes some things as HTML Entities, making them safe to print anywhere. Currently changes [&<>'"] "'# work around Emacs bug... """ return string.replace('&', '&amp;') \ .replace('<', '&lt;') \ .replace('>', '&gt;') \ .repl...
def get_type(value): """ Build current config file structure. """ if isinstance(value, dict): return {key: get_type(value[key]) for key in value} else: return str(type(value))
def blank_if_zero(n): """Return str(n) unless n is zero, in which case return "".""" if n == 0: return "" return str(n)
def make_breakable(keyword): """Inserts zero-width-space HTML entities after each underscore IF the keyword is long. This is useful to allow long keywords to be split into different lines. """ return '_&ZeroWidthSpace;'.join(keyword.split('_')) if len(keyword) > 30 else keyword
def find_endurance_tier_iops_per_gb(volume): """Find the tier for the given endurance volume (IOPS per GB) :param volume: The volume for which the tier level is desired :return: Returns a float value indicating the IOPS per GB for the volume """ tier_description_split = volume['storageTierLevel']['...
def extract_ratings(txt): """Extract the rating histogram from embedded Javascript code The embedded code looks like this: |----------------------------------------------------------| | renderRatingGraph([6, 3, 2, 2, 1]); | | if ($('rating_details')) { ...
def only_digit(s: str) -> str: """Filter out the digits in the string.""" return ''.join([c for c in s if c.isdigit()])
def ProfitArrayToHierarchy(oneway,prune=None): # add old hierarchy as second parameter to add to it # hierarchy follows this simple structure: """ fromId toId commodId=traderow toId commodId=traderow fromId toId commodId=traderow toId commodId=traderow """ if prune is...
def get_dict_list(data_array): """Returns a list of dictionaries based on the column headers (the 0th line in the column headers) """ key_list = data_array[0] dict_list = [] for index, line in enumerate(data_array[1:]): params = {} for i in range(len(key_list)): # t...
def get_lr_run_identifier(lrs): """Computes the run identifier for the given learning rates. Search identifier will not contain w_eval. Args: lrs (dict): That that contains the learning rate for every searched learning rate. Returns: str: String that uniquely represents a run with the give...
def Yagi13_fitcoefs(ell): """ Coefficients of Yagi 2013 fits for multipolar $\bar{\lambda}_\ell = 2 k_\ell/(C^{2\ell+1} (2\ell-1)!!)$ Tab.I (NS) http://arxiv.org/abs/1311.0872 """ if ell==3: c = [-1.15,1.18,2.51e-2,-1.31e-3,2.52e-5]; elif ell==4: c = [-2.45,1.43,3.95e-2,-1.81...
def list_diff_want_only(want_list, have_list): """ This function generated the list containing values that are only in want list. :param want_list: :param have_list: :return: new list with values which are only in want list """ if have_list and not want_list: diff = None elif...
def has_progressed_validly(status_old, status_new): """ If there happened to be progress between the two statuses we check if it was valid. Thus, we return False if there was invalid progress, and True otherwise. (even if there was no progress) stage change counts as progress, but has to be done in the ...
def changeFrom12To24(aString): """ Changes the format from am/pm to 24h system. :param aString: String representing an hour value. :return: """ if aString == "1": aString = "13" if aString == "2": aString = "14" if aString == "3": aString = "15" if aString == ...
def gene_to_filename(gene): """ Convert a formal gene name to be suitable for file names """ return gene.lower().replace(' ', '')
def win_percent(num_games, game_wins): """returns the percentage of wins""" total_games = num_games win_percents = game_wins[:] for i in range(0, len(win_percents)): win_percents[i] = round((1.0 * (game_wins[i])) / (total_games * 1.0), 2) return win_percents
def _flatten_dict(original_dict): """Flatten dict of dicts into a single dict with appropriate prefixes. Handles only 2 levels of nesting in the original dict. Args: original_dict: Dict which may contain one or more dicts. Returns: flat_dict: Dict without any nesting. Any dicts in the original dict ha...
def _validate_positive_int(value): """Validate value is a natural number.""" try: value = int(value) except ValueError as err: raise ValueError("Could not convert to int") from err if value > 0: return value else: raise ValueError("Only positive values are valid")
def magtoflux(marr, fzero): """Convert from magnitude to flux. marr--input array in mags fzero--zero point for the conversion """ return fzero * 10 ** (-0.4 * marr)
def find_primes(n): """ Finds all the primes below number n using the sieve of Eratosthenes """ candidates = [i + 2 for i in range(n-1)] for p in candidates: for i in candidates: if i % p == 0 and p != i: candidates.remove(i) return candidates
def normalize(name: str) -> str: """Normalize a value name to a valid Python (PEP8 compliant) identifier. Args: name: The name of a value returned by MPD. Returns: The normalized name, in all lowercase with - replaced by _. """ return name.lower().replace('-', '_')
def child_support_payor_c(responses, derived): """ Return who the payor is depends on the monthly amount from Factsheet C """ try: amount_1 = float(responses.get('your_child_support_paid_c', 0)) except ValueError: amount_1 = 0 try: amount_2 = float(responses.get('your_spouse_chi...
def table_append(row, category='default'): """ Take any number of string args and put them together as a HTML table row. """ html_row = '</td><td>'.join(row) html_row = f'<tr><td>{html_row}</td></tr>' if category == 'header': html_row = html_row.replace('td>', 'th>') return html_row
def all_lowercase(title_words): """ if the words are all in lowercase >>> all_lowercase(["a", "b", "c"]) True >>> all_lowercase(["a", "12b", "c12"]) True >>> all_lowercase(["a", "12b", "C12"]) False """ concat_str = ''.join(title_words) return concat_str.lower() == concat_st...
def boundaries_intersection(boundaries): """ compute the intersections inside a boundary :param boundaries: list of list of vertex indices corresponding to the path :return: list of common vertices between each tuple """ bound_conn = [] for bound_ind1 in range(len(boundaries) - 1): f...
def merge(base, overrider): """ Override base dict with an overrider dict, recursively. """ for key, value in overrider.items(): if isinstance(value, dict): subitem = base.setdefault(key, {}) merge(subitem, value) else: base[key] = value return base
def escape_dn_chars(s): """ Escape all DN special characters found in s with a back-slash (see RFC 4514, section 2.4) """ if s: s = s.replace('\\','\\\\') s = s.replace(',' ,'\\,') s = s.replace('+' ,'\\+') s = s.replace('"' ,'\\"') s = s.replace('<' ,'\\<') s = s.replace('>' ,'\\>') ...
def divergence_index(constant, iterations): """ :param constant: A complex number (the position) :param iterations: The number of iterations to run at the given constant :return: n = the number of stable iterations """ n = 0 z = 0 for i in range(iterations): if abs(z) > 4: ...
def ensure_scripts(linux_scripts): """ Creates the proper script names required for each platform (taken from 4Suite) """ from distutils import util if util.get_platform()[:3] == 'win': scripts_ = linux_scripts + [script + '.bat' for script in linux_scripts] else: ...
def reducer_cumsum(event, data): """ Parse int from the input then add to 'cumsum data' """ text = event[1] val = 0 try: val=int(text) except Exception as e: action =('ERROR', 'not an int') return action, {} data.setdefault('cumsum',0) data['cumsum'] += val retu...
def write_select_dimensions(dims_dict): """Create a string for a SELECT part of an SQL query for dimension tables Given a dictionary key-value pairs, this function outputs a string to be used as part of an SQL SELECT section. This is meant to be used when flatenning a table, and the given dict should c...