content
stringlengths
42
6.51k
def backupise_name(file_name, counter): """ Return the backupised name. We ignore `.*.bak` in `.gitignore`. The leading dot makes it hidden on Linux. Bad luck if you use Windows. """ return f'.{file_name}-{counter}.bak'
def ia(ta, r, a, b, c): """Chicago design storm equation - intensity after peak. Helper for i function. Args: ta: time after peak in minutes (measured from peak towards end) r: time to peak ratio (peak time divided by total duration) a: IDF A parameter - can be calculated from getABC ...
def flatten(lst): """Shallow flatten *lst*""" return [a for b in lst for a in b]
def trait_label(trait, sep=' '): """Generate a label for the trait.""" label = [trait['part']] if 'subpart' in trait: label.append(trait['subpart']) label.append(trait['trait']) label = sep.join(label) label = label.replace('-', '') label = label.replace('indumentum' + sep + 'surface...
def dropZeros(dictionary): """Drops zero valued items from dictionary""" sansZeros = {key:value for key,value in dictionary.items() if value != 0} if len(sansZeros) != 0: dictionary = sansZeros return dictionary
def is_valid_test_file(test_file): """ Checks if file is a .pyc or from __pycache__ :param test_file: str :return: str """ return '.pyc' not in test_file and '__pycache__' not in test_file
def _make_lock_uri(cloud_tmp_dir, cluster_id, step_num): """Generate the URI to lock the cluster ``cluster_id``""" return cloud_tmp_dir + 'locks/' + cluster_id + '/' + str(step_num)
def int_set(subset): """ This function transforms subset into corresponding integer representation. Parameters ---------- subset : set The subset you want to transform. Returns ------- representation : int The integer representation of a given subset. """ repres...
def convertRegionDisplayNameToRegionName(regionDisplayName): """Converts given region display name to region name. For ex; 'HDInsight.EastUS' to 'eastus'""" return str(regionDisplayName.split(".")[1]).lower()
def cc(key): """ Changes python key into Camel case equivalent. For example, 'compute_environment_name' becomes 'computeEnvironmentName'. :param key: :return: """ components = key.split('_') return components[0] + "".join([token.capitalize() for token in components[1:]])
def normalize_data_format(value): """Normalize the keras data format.""" if value is None: value = 'channels_last' data_format = value.lower() if data_format not in {'channels_first', 'channels_last'}: raise ValueError( 'Excepted <data_format> as one of ' '"channe...
def rivers_with_station(stations): """This function creates a set containing all the river names which have a station on it. It is set up so each river only occurs onece """ rivers = set() for station in stations: rivers.add(station.river) rivers = sorted(rivers) return rivers
def readBits(value, bitmasks): """ Extract bits from the integer value using a list of bit masks. bitmasks is a list of tuple (mask, text). >>> bitmask = ( ... (1, "exec"), ... (2, "write"), ... (4, "read")) ... >>> readBits(5, bitmask) ['exec', 'read'] >>> readBits...
def call_fn_with_state_keys(jit_fn, state, other_inputs, keys): """Executes `jit_fn`, filtering out all keys except some subset.""" state = state.copy() extra_state = {} for k in list(state.keys()): if k not in keys: extra_state[k] = state.pop(k) return jit_fn(state, *other_inputs), extra_state
def drone_res(constants): """Dummy drone response for tests""" drone_res = { "@context": f"/{constants['api_name']}/contexts/Drone.jsonld", "@id": f"/{constants['api_name']}/Drone/1", "@type": "Drone", "DroneState": { "@id": f"/{constants['api_name']}/State/1", ...
def to_upper(text): """Convert word to uppercase.""" return text.upper().strip()
def source_link_type(url): """ Get an URL and will return the URL type for display the true text in the wiki view. :param url: Ruleset source's URL :type url: str :return: A string of URL type (github, patreon or unknown) """ if ("github.com" or "www.github.com") in url: result = "...
def nameval(in_string): """ converts given string to key, value and separator triplets :param in_string: key/value pair :type in_string: str (unicode) :return: key, value and separator triplet :rtype: tuple """ idx = in_string.find("=") separator = '=' if idx >= 0: name ...
def account_from_role_arn(role_arn): """ Extracts an account number from a role arn, raises a ValueException if the arn does not match a valid arn format :param role_arn: The arn :return: The extracted account number """ role_elements = role_arn.split(":") if len(role_elements) < 5: ...
def doesnt_raise(function, message=""): """ The inverse of raises(). Use doesnt_raise(function) to test that function() doesn't raise any exceptions. Returns the result of calling function. """ if not callable(function): raise ValueError("doesnt_raise should take a lambda") try: ...
def balanced_paranthesis(exp): """Return True if exp has balanced parantheses, else False.""" pair = {')': '(', ']': '[', '}': '{'} stack = [] for i in exp: if i in pair.values(): stack.append(i) elif i in pair.keys(): if stack.pop() != pair[i]: re...
def get_nse_or_ntt_dtype(info, ext): """ For NSE and NTT the dtype depend on the header. """ dtype = [('timestamp', 'uint64'), ('channel_id', 'uint32'), ('unit_id', 'uint32')] # count feature nb_feature = 0 for k in info.keys(): if k.startswith('Feature '): nb_feature +...
def _resolution_to_timedelta(res_text: str) -> str: """ Convert an Entsoe resolution to something that pandas can understand """ resolutions = { 'PT60M': '60min', 'P1Y': '12M', 'PT15M': '15min', 'PT30M': '30min', 'P1D': '1D', 'P7D': '7D', 'P1M': '1...
def reverse( sequence ): """Return the reverse of any sequence """ return sequence[::-1]
def encode_to_7bit(value): """Encode to 7 bit""" if value > 0x7f: res = [] res.insert(0, value & 0x7f) while value > 0x7f: value >>= 7 res.insert(0, (value & 0x7f) | 0x80) return res return [value]
def check_if_bst(node, mini=float('-inf'), maxi=float('+inf')): """ Check if the given tree is Binary Search Tree (BST) Args: node: root node of the Tree. `node` arg must have `.left`, `.right` and `.data` variables mini: min value - should be omitted maxi: max value - should be omi...
def make_relative(det, box): """Make detections relative to the box. Used for the parameters of test_combine_slice_detections. """ x0, y0, x1, y1, p = det bx0, by0, *_ = box return x0 - bx0, y0 - by0, x1 - bx0, y1 - by0, p
def filter_size(detail): """Web app, feed template, additional info: (file) size""" info = detail['info'] size = '{} {}'.format(info['size'], info['unit']) return size
def _convert_concatenate(arg_list): """ Handler for the "concatenate" meta-function. @param IN arg_list List of arguments @return DB function call string """ return " || ".join(arg_list)
def get_triangle_bottom_midpoint(point_list): """Returns the midpoint of the top of a triangle regardless of the orientation.""" y = int(max([x[1] for x in point_list])) x = int((min([x[0] for x in point_list]) + max([x[0] for x in point_list])) / 2) return x, y
def _get_sort_and_permutation(lst: list): """ Sorts a list, returned the sorted list along with a permutation-index list which can be used for cursored access to data which was indexed by the unsorted list. Nominally for chunking of CSR matrices into TileDB which needs sorted string dimension-values for...
def build_output_file_pattern(out_fn): """Builds the string pattern "{OUTFN}-{PAGE_RANGE}.pdf". This is necessary if one wants to extract multiple page ranges and does not join the single results. Arguments: out_fn -- Output filename Returns: String value ...
def monomial_min(*monoms): """ Returns minimal degree for each variable in a set of monomials. Examples ======== Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`. We wish to find out what is the minimal degree for each of `x`, `y` and `z` variables:: >>> from sym...
def _vars_dir_for_saved_model( saved_model_path # type: str ): # type: (str) -> str """ Args: saved_model_path: Root directory of a SavedModel on disk Returns the location of the directory where the indicated SavedModel will store its variables checkpoint. """ return saved_model_path + "/va...
def sort_nesting(list1, list2): """Takes a list of start points and end points and sorts the second list according to nesting""" temp_list = [] while list2 != temp_list: temp_list = list2[:] # Make a copy of list2 instead of reference for i in range(1, len(list1)): if list2[i] > ...
def _count_lines(file_path): """Count lines in a file. A line counter. Counts the lines in given file with counter count counts. Args: file_path: `str` path to file where to count the lines. """ count = 0 with open(file_path, "r") as fobj: for line in fobj: count += 1 ...
def get_templates(conf): """Return an array of names of existing templates.""" try: return conf['templates'].keys() except KeyError: return []
def content_convert(source_wrapper): """Convert content from AppetiteApp to dict Converting the class to dict is needed for json logging and distribution """ new_source_wrapper = source_wrapper.copy() new_source_wrapper['content'] = [content.to_dict for content in source_wrapper['content']] r...
def mtime(filename): """Modication timestamp of a file, in seconds since 1 Jan 1970 12:00 AM GMT """ from os.path import getmtime try: return getmtime(filename) except: return 0
def lstrip_keep(text): """ Like lstrip, but also returns the whitespace that was stripped off """ text_length = len(text) new_text = text.lstrip() prefix = text[0 : (text_length - len(new_text))] return new_text, prefix
def get_mismatch_cts(pileup): """Returns pileup[0] with the pileup[1]-th element removed. e.g. if pileup[0] = [99, 0, 30, 14] and pileup[1] = 2, this'll return [99, 0, 14]. This corresponds to filtering the list of [A, C, G, T] aligned to a position to remove whichever of the four nucleotides corr...
def make_params(**kwargs): """ Helper to create a params dict, skipping undefined entries. :returns: (dict) A params dict to pass to `request`. """ return {k: v for k, v in kwargs.items() if v is not None}
def matchingByName (theDictionary, firstLetter): """Identifies students a name starting with firstLetter. Assumes student names are capitalized. :param dict[str, str] theDictionary: key: locker number / value: student name or "open" :param str firstLetter: The target letter by which to...
def num_diffs(state): """ Takes a state and returns the number of differences between adjacent entries. num_diffs(str) -> int """ differences = 0 for i in range(0, len(state) - 1): if state[i] != state[i+1]: differences += 1 return differences
def first_true(pred, iterable, default=None): """Returns the first true value in the iterable. If no true value is found, returns *default* source: https://docs.python.org/3/library/itertools.html """ # first_true([a,b,c], x) --> a or b or c or x # first_true([a,b], x, f) --> a if f(a) else b ...
def f_dir(obj): """Format public attributes of an object. Args: obj: object (Object) doc: get the documentation (bool) Returns: dicts of uncallables and callables (list) """ both = {i: i.__doc__ for i in dir(obj) if not i.startswith("_")} uncallables = {i: j for...
def min_scalar_prod(x, y): """Permute vector to minimize scalar product :param x: :param y: x, y are vectors of same size :returns: min sum x[i] * y[sigma[i]] over all permutations sigma :complexity: O(n log n) """ x1 = sorted(x) # make copies to preserve y1 = sorted(y) # the inpu...
def _null_cast(dic, key): """ Allows the user to load value, given key from the dictionary. If the key is not found, return "null". Args: dic (dict): Dictionary in look for (key, value) pair key (str): Key to look search in the dictionary Returns: type: str ...
def equally_space_times(num_ids, step=0): """ takes a list of times and returns an equally spaced ones """ assert len(num_ids) > 1, 'not enough snapshots to equally space them in time' if not step: step = (num_ids[-1] - num_ids[0]) / float(len(num_ids) - 1) ids_eq = [] t = num...
def get_int_from_roman_number(input): """ From http://code.activestate.com/recipes/81611-roman-numerals/ Convert a roman numeral to an integer. >>> r = range(1, 4000) >>> nums = [int_to_roman(i) for i in r] >>> ints = [roman_to_int(n) for n in nums] >>> print r == ints 1 >>> r...
def twelve_digit_serial_no(id): """ The function create a 12 digit serial number from any number with less than 11 digits""" f = str(10**(11 - len(str(id)))) twelve_digit_id = f + str(id) return int(twelve_digit_id)
def calc_regularization_loss(filtering_fn, reg_pl_names_dict, reg_model_name, feed_dict, sess, all_scopes=None): """Calculate regularization loss Args: filter...
def find_section(section, y): """Find the section closest to y""" best_i=-1 dist=1e5 for i in range(len(section)): d=min(abs(section[i][0]-y), abs(section[i][1]-y)) if d < dist: best_i=i dist=d return best_i
def index_from_weekday(weekday): """ Returns a numeric index for day of week based on name of day :param weekday: Name of day (e.g. 'Sunday', 'Monday', etc.) :return: numeric index """ weekday_map = { 'Sunday': 0, 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, ...
def find_free_place(places_available, desired_place): """ Find place in sequence that is available and nearby. This function checks if desired_place is in the list of places that are still available and returns desired_place if so. If not, it returns the closest, higher place that is. If there are no h...
def makesingle(text): """ Make multiple lines into a single line joined by a space. """ return " ".join( line.strip() for line in text.splitlines() if len(line.strip()) )
def slice_indices(depths, breaks): """Return a list of tuples""" d, b = depths, breaks lst = [[n for n, j in enumerate(d) if j >= i[0] and j < i[1]] for i in b] return(lst)
def zip_with(fn, xs, ys): """ Standard python zip with function. User can define custom zipping function instead of the standard tuple. """ return [fn(a, b) for (a, b) in zip(xs, ys)]
def get_bytes(s): """Returns the byte representation of a hex- or byte-string.""" if isinstance(s, bytes): b = s elif isinstance(s, str): b = bytes.fromhex(s) else: raise TypeError("s must be either 'bytes' or 'str'!") return b
def greatest_common_divisor(num_a: int, num_b: int) -> int: """ A method to compute the greatest common divisor. Args: num_a (int): The first number. num_b (int): Second number Returns: The greatest common divisor. """ if num_b == 0: return num_a print(f"...
def get_vert_order_from_connected_edges(edge_vertices): """ .. note:: Should probably be moved to mampy. """ idx = 0 next_ = None sorted_ = [] while edge_vertices: edge = edge_vertices.pop(idx) # next_ is a vert on the edge index. if next_ is None: next_ ...
def find_bandgaps(composition): """ Give as list like ['GaAs'] or ['Si', 'GaPN'] outputs bandgap in eVs in the form that input_ouput_management.SampledBandgaps needs: [[Bandgap1, Bandgap1], [Bandgap2, Bandgap2], etc] i.e. a list of lists. Used by the main run function.""" # this number isn'...
def has_variable(formula, variable): """ Function that detects if a formula contains an ID. It traverses the recursive structure checking for the field "id" in the dictionaries. :param formula: node element at the top of the formula :param variable: ID to search for :return: Boolean encoding if...
def initialize_dict_values(keys, default_value, dictionary=dict()): """Adds keys to the dictionary with a default value. If no dictionary is provided, will create a new one. :param keys: List of strings containing the dictionary keys :param default_value: default value to be associated with the keys ...
def canon_name_file(param): """Convert name+filename to canonical form. param a string of form "name,path_to_exe". Return a tuple (name, path_to_exe). Returns None if something went wrong. """ name_file = param.split(',') if len(name_file) == 2: return name_file return None
def transcribe(seq: str) -> str: """ transcribes DNA to RNA by replacing all `T` to `U` """ #.replace() function iterates through letters of seq & replaces "T" with "U" (effectively transcribing the DNA sequence) transcript = seq.replace("T", "U") return transcript
def convert_modules_to_external_resources(buck_modules, modules_with_resources): """ Converts modules to a map with resources to keep them outside of module jars """ result = {} for module in modules_with_resources: result["buck-modules-resources/{}".format(module)] = "{}_resources".format(buck_mod...
def lensort(lst): """ >>> lensort(['python', 'perl', 'java', 'c', 'haskell', 'ruby']) ['c', 'perl', 'java', 'ruby', 'python', 'haskell'] """ return sorted(lst, key=lambda x: len(x))
def unescape_latex_entities(text: str) -> str: """ Unescape certain latex characters. :param text: """ # Limit ourselves as this is only used for maths stuff. out = text out = out.replace("\\&", '&') return out
def find_triangles(edges): """ :param edges: :return: yield the triangles for each mapper """ mean_prob = sum([edge[2] for edge in edges]) / len(edges) result = [] done = set() # for each edge we have: src = edge[0], dst = edge[1], prob = edge[2] for n in edges: done.add(n) ...
def sort_key(attrs, node): """ Sort key for sorting lists of nodes. """ acc = 0 for i in range(len(attrs)): if attrs[i] in node.attrs: acc += 10**i return acc
def clean_str(str1: str) -> str: """ clean the string from ),;,\t and ' as not a wanted data :param str1: the string to clean :return:The new string with wanted data """ str1 = str1.replace(")", "") str1 = str1.replace(";", "") str1 = str1.replace("\t", "") str1 = str1.strip("'") ...
def pxci_to_bi(nstencil, N): """ Generates a translation list converting x center indicesex starting at 0, which includes padding bins and into bin indices. Parameters ---------- nstencil: integer Number of stencil points used N: integer Number of bins Returns -----...
def exist_files(filenames): """filenames: list of pathnames""" from os import listdir from os.path import exists,dirname,basename directories = {} exist_files = [] for f in filenames: if not dirname(f) in directories: try: files = listdir(dirname(f) if dirname(f) else ".") ...
def filter(dictionaries, filters=[]): """filter a list of dictionaries. return a filtered list.""" if not filters: return dictionaries if filters == ['Search']: return dictionaries filtered = [] for d in dictionaries: tests = [] for f in filters: test =...
def toggle_popover_tab1(n, is_open): """ :return: Open pop-over callback for how to use button for tab 1. """ if n: return not is_open return is_open
def get_reverse_bits(bytes_array): """ Reverse all bits in arbitrary-length bytes array """ num_bytes = len(bytes_array) formatstring = "{0:0%db}" % (num_bytes * 8) bit_str = formatstring.format(int.from_bytes(bytes_array, byteorder='big')) return int(bit_str[::-1], 2).to_bytes(num_bytes, by...
def file_extension(filename: str, file_type: str = "photo") -> str: """ Get the file extension of `filename`. Args: filename (str): Any filename, including its path. file_type (str): "photo", "book", or "any" Returns: Image (png, jp(e)g, ti(f)f), book (md, pdf) or *any* extensi...
def column(matrix, col): """Returns a column from a matrix given the (0-indexed) column number.""" res = [] for r in range(len(matrix)): res.append(matrix[r][col]) return res
def _parse_format(format): """Return names, format.""" assert format is not None if format.find(":") < 0: assert " " not in format return None, format names, fmt = [], "" for x in format.split(): name, type_ = x.split(":") assert len(type_) == 1, "Invalid type: %...
def calc_heuristic(neighbor_coord, target): """ Returns hueristic cost. Chebyshev distance used here. """ x1 = neighbor_coord[0] x2 = target[0] y1 = neighbor_coord[1] y2 = target[1] return max(abs(y2 - y1), abs(x2 - x1))
def remove_trailing_delimiters(url: str, trailing_delimiters: str) -> str: """Removes any and all chars in trailing_delimiters from end of url. """ if not trailing_delimiters: return url while url: if url[-1] in trailing_delimiters: url = url[:-1] else: br...
def countTotalCoresCondorStatus(status_dict): """ Counts the cores in the status dictionary The status is redundant in part but necessary to handle correctly partitionable slots which are 1 glidein but may have some running cores and some idle cores @param status_dict: a dictionary with the Mach...
def format_labels(labels): """ Convert a dictionary of labels into a comma separated string """ if labels: return ",".join(["{}={}".format(k, v) for k, v in labels.items()]) else: return ""
def _is_correct(ground_truth_label): """ Returns true if label is > 0, false otherwise :param int ground_truth_label: label :return: true or false :rtype: bool """ if ground_truth_label > 0: return True return False
def _bcd2char(cBCD): """ Taken from the Nortek System Integrator Manual "Example Program" Chapter. """ cBCD = min(cBCD, 153) c = (cBCD & 15) c += 10 * (cBCD >> 4) return c
def get_insertion_losses_from_prefix(expressions, tx_prefix, rx_prefix): """Get the list of all the Insertion Losses from prefix. Parameters ---------- expressions : list of Drivers to include or all nets reclist : list of Receiver to include. Number of Driver = Number of Receiver a...
def _reg2int(reg): """Converts 32-bit register value to signed integer in Python. Parameters ---------- reg: int A 32-bit register value read from the mailbox. Returns ------- int A signed integer translated from the register value. """ result = -(reg...
def get_single_key_value_pair(d): """ Get the key and value of a length one dictionary. Parameters ---------- d : dict Single element dictionary to split into key and value. Returns ------- tuple of length 2, containing the key and value Examples -------- ...
def get_vcf(config, var_caller, sample): """ input: BALSAMIC config file output: retrieve list of vcf files """ vcf = [] for v in var_caller: for s in sample: vcf.append( config["vcf"][v]["type"] + "." + config["vcf"][v]["mutat...
def check_if_won(board): """All combinations of winning boards""" if board[0] == board[1] == board[2] != " ": return True if board[3] == board[4] == board[5] != " ": return True if board[6] == board[7] == board[8] != " ": return True if board[0] == board[3] == board[6] != " "...
def merge_dictionaries(d1, d2): """Merge dictionaries of string to set. Return a dictionary that: - Keys are the union of the keys in both dictionaries - Values are the union of the sets of values in each dictionary """ for k, s in d2.items(): if k not in d1: d1[k...
def percentage(percent, whole): """ Returns percentage value. """ return (percent * whole) / 100.0
def apply_to_collection(data, fn): """ Applies a given function recursively to a tuple, list or dictionary of things with arbitrary nesting (including none). Returns the new collection. """ if isinstance(data, (tuple, list)): return type(data)(apply_to_collection(item, fn) for item in data) ...
def list_b_in_list_a(list_a, list_b): """ list_b_in_list_a(list_a, list_b) Whether list_b is subset of list_a Parameters: list_a: list list_b: list Return: flag: bool """ return set(list_b) <= set(list_a)
def make_xml_name(attr_name): """ Replaces _ with - """ return attr_name.replace('_', '-')
def to_str(l, rdic, char=False): """Given a sequence of indices, returns the corresponding string Arguments: l {list} -- List of indices rdic {dict} -- Dictionary mapping indices to strings Keyword Arguments: char {bool} -- Controls whether to add a whitespace between each ...
def concatOverlapPep(peptide, j, prefixPeptide): """ Called by self.createOverlap(), this function takes two peptides which have an identical prefix/suffix sequence and combines them around this like sequence. Eg: ABCDE + DEFGH = ABCDEFGH :param peptide: the peptide with matching suffix sequence :p...
def get_operator_priority(char: str) -> int: """ Used to get operator priority, or to check if char is correct operator :param char: Operator :return: Operator priority (positive), or -1 if char is not correct operator """ if char == '!' or char == '#': # '#' - unary minus return...
def EncodeAName(s): """ Handle * characters in MSI atom names """ if s.find('auto') == 0: s = s[4:] # If the atom name begins with *, then it is a wildcard if s[:1] == '*': # special case: deal with strings like *7 return 'X' # These have special meaning. Throw away the inte...