content
stringlengths
42
6.51k
def get_file_list(filenames, file_ext, proc_steps, success): """Gets file list This function takes the inputted filenames, requested file ext, and requested processing steps. The output file list includes information from images that were successfully uploaded. Args: filenames (list): list...
def xstr(s): """ Convert None to default ?-string, if necessary """ if s is None: return '?' return str(s)
def m2q(m: int) -> int: """ Convert month(1-index) to quarter(1-index) i.e. m2q(jan) is m2q(1) = 1 """ return ((m - 1) // 3) + 1
def _get_method_name(name_string, types): """ Returns the method name with the correct parsed types for the arguments :param str name_string: a string from a class dump that contains the name of the method without the types :param list types: a list of types for the arguments of the method :ret...
def colorize(output, color): """ returns a string with a ANSI color codes for purtier output. """ ansiYellow = '\x1B[1;33;40m' ansiRed = '\x1B[1;31;40m' ansiCyan = '\x1B[1;36;40m' ansiGreen = '\x1B[1;32;40m' ansiMagenta = '\x1B[1;35;40m' ansiReset = '\x1B[m' if colo...
def startswith(value: str, arg: str): """ Check if a value starts with some string """ return value.startswith(arg)
def manyfields(prefix: str, n: int): """ Make a dict for a ManyFields object Example: User( id=1, **manyfields('user', 1), ) => User(id=1, a='user-1-a', b='user-1-b', c='user-1-c', d='user-1-d', j={'user': '1-j'}) """ return { **{ k: f...
def reached_new_level(character: dict) -> bool: """ Check if character reached new level. :param character: a dictionary :precondition: character must be a dictionary :precondition: character must be a valid character created by character_creation function :postcondition: returns True if charac...
def mattrans(mat): """ Returns the transpose of an mxn matrix (list of lists) Arg: mat - A list/list of lists representing a vector/matrix (see 'matmul') Returns: mat_T - A transpose of shape n x m where mat has shape m x n. If mat has sh...
def is_nonalnum(astring): """ (str) -> Boolean Returns True if astring contains at least one non-alphanumeric character. else returns False. >>> is_nonalnum('') False >>> is_nonalnum('abc123') False >>> is_nonalnum('#123') True """ if len(astring) == 0: retu...
def powerTuplesToNumber(data, base): """Convert a power list to a decimal result.""" res = 0 for power, factor in data: res = res + factor * (base**power) return res
def stop_criterion(old_population, new_population, limit_to_converge): """ :param: old_population - populacao ao iniciar a iteracao :param: new_population - populacao ao fim da iteracao :param: limit_to_converge - limiar abaixo do qual iremos considerar que ambas as pop convergem :r...
def sentence_case(string: str) -> str: """ Return a string with its first character in Uppercase and the rest in lowercase """ if len(string) > 1: return f"{string[0].upper()}{string[1:].lower()}" elif len(string) == 1: return string[0].upper() ...
def matches(case, rule): """Match a test case against a rule return '1' if there's a match, 0 otherwise """ if len(case) != len(rule): return 0 match = 1 for i in range(len(case)): if rule[i] != "*" and case[i] != rule[i]: match = 0 break return match
def free_residents(residents_prefs_dict, matched_dict): """ In this function, we return a list of resident who do not have empty prefrences list and unmatched with any hospital. """ fr = [] for res in residents_prefs_dict: if residents_prefs_dict[res]: if not (any(res in mat...
def LoadBase(base_file): """Load the base file to store the last modified version.""" base_data = {} with open(base_file, encoding='utf-8') as file: for line in file: if line.startswith('#'): continue items = line.strip('\n').split('\t') result = '\t'.join(items[0:5]) # status, inpu...
def binary_to_decimal(number: int) -> int: """Return decimal version of the specified binary number.""" result = 0 for index, digit in enumerate(reversed(str(number))): if index == 0: result += int(digit) else: result += 2 ** index * int(digit) return int(result)
def _to_python_str(s): """ Convert to Python string """ if isinstance(s, bytes): return s.decode('utf-8') else: return s
def slugify(slug): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata, re slug = slug.lower() slug.replace('.', '_') slug = slug.replace(' ', '_') # import re # slug = unicodedata.normalize('NFKD', s...
def _merge_fix(d): """Fixes keys that start with "&" and "-" d = { "&steve": 10, "-gary": 4 } result = { "steve": 10, "gary": 4 } """ if type(d) is dict: for key in d.keys(): if key[0] in ('&', '-'): ...
def class_name(service_name: str) -> str: """Map service name to .pyi class name.""" return f"Service_{service_name}"
def calculate_critical_path(inits, evaluation_function=None): """ if the eval function is None, I assume it's a number or number like otherwise evaluation_function(Node.payload) will be added to the path cost """ paths = [] for x in inits: path_sum = 0 path = [] while...
def convert_role_id (role): """ Convert a user role parameter to the string that needs to be passed to system functions. :param role: The role parameter passed to the command. If this is None, no conversion is performed. :return The string identifier for the role. This will be empty if t...
def num_deriv(f, x, dx=1e-5): """ utility function for numerical derivatives """ return (0.5/dx) * (f(x+dx) - f(x-dx))
def KW_Variance(predictions, y_true): """Modification by Kuncheva et al. Expects a list of lists, containing predictions and a ground truth list.""" correct_count = [0 for i in range(len(y_true))] # initialize correct counts per sample final_score = 0 # score to return for i, y in enumerate(y_true): #...
def estimate_cells_in_series(voc_ref, technology='mono-Si'): """ Note: Could improve this by using the fact that most modules have one of a few different numbers of cells in series. This will only work well if single module voc_ref is given. Parameters ---------- voc_ref technology ...
def keywords_from_list(keywords): """Convert keywords from a list of strings into the appropriate format for creating a Mechanical Turk HIT. :param keywords: A list of keywords :type keywords: iterable :rtype: str or unicode """ return u','.join(keywords) if keywords else None
def _is_stdlib(s): """Imports from stdlib like import scala.concurrent.duration.Duration""" prefixes = { 'java.', 'javax.', 'javaw.', 'scala.' } for p in prefixes: if s.startswith('import ' + p): return True return False
def __slicer(my_str, sub): """ Remove everything in a string before a specified substring is found. Throw exception if substring is not found in string https://stackoverflow.com/questions/33141595/how-can-i-remove-everything-in-a-string-until-a-characters-are-seen-in-python Args: m...
def get_excludes(excludes): """ Prepare rsync excludes as arguments :param excludes: :return: """ _excludes = '' for exclude in excludes: _excludes += f'--exclude {exclude} ' return _excludes
def correct_index_dict(ref_seq: str) -> dict: """ Create a dictionary of corrected position for each position in a sequence Args: ref_seq : The reference sequence as an alignment, with possible upstream dashes. Returns: A dictionary of original positions to new positions. """ ...
def flatten_list(l): """ Unpacks lists in a list: [1, 2, [3, 4], [5, [6, 7]]] becomes [1, 2, 3, 4, 5, 6, 7] http://stackoverflow.com/a/12472564/3381305 """ if (l == []) or (l is None): return l if isinstance(l[0], list): return flatten_list(l[0]) + flatten...
def distance(point1, point2): """ calc distance between two 3d points """ return ((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2 + (point1[2]-point2[2])**2)**0.5
def strip(words): """ strip words """ if isinstance(words, str): words = [words] return [ word.strip() for word in words if word.strip() != "" ]
def standardize_phone(phone): """ First strips punctuation """ ccode=0 pattern=None if type(phone) is float: phone = str(int(phone)) else: phone = str(phone) tomatch="" phone = phone.replace("-", "").replace("(", "").replace(")", "").replace("+", "").replace(" ", "")....
def max4(x): """ >>> max4(20) 20.0 """ return max(1, 2.0, x, 14)
def gardner_limestone(Vp, A=1.359, B=0.386): """ Vp in km/sec """ Rho = A*Vp**B return Rho
def dict_2_list(dict_list, key_val): """Function: dict_2_list Description: Converts a dictionary array list to a array list, based on a key value passed to the function. Only those values for the key value will be put into the list. Arguments: (input) dict_list -> Dictionary ar...
def parse_specifier(specifier): """A utility to parse "specifier" Args: specifier (str): Returns: parsed_dict (OrderedDict): Like {'ark': 'file.ark', 'scp': 'file.scp'} >>> d = parse_specifier('ark,t,scp:file.ark,file.scp') >>> print(d['ark,t']) file.ark """ ...
def generate_cb_choices(list, checked=False): """Generates checkbox entries for lists of strings :list: pyhton list that shall be converted :checked: if true, selections will be checked by default :returns: A list of dicts with name keys """ return [{'name': m, 'checked': checked} for m in list...
def find_two_sum(arr, target): """ Finds the two (not necessarily distinct) indices of the first two integers in arr that sum to target, in sorted ascending order (or returns None if no such pair exists). """ prev_map = {} # Maps (target - arr[i]) -> i. for curr_idx, num in enumerate(arr): ...
def get_updated_tags(existing_tags, expected_tags): """ :type existing_tags: typing.Dict[str, str] :param existing_tags: key value dict represent existing tags :type existing_tags: typing.Dict[str, str] :param expected_tags: key value dict represent expected tags :rtype: typing.Dict[str, str] ...
def ctd_sbe52mp_condwat(c0): """ Description: OOI Level 1 Conductivity core data product, which is calculated using data from the Sea-Bird Electronics conductivity, temperature and depth (CTD) family of instruments. This data product is derived from SBE 52MP instruments and app...
def _has_value(json, key): """ Helper method for determining if a key exists within a given dictionary :param json: The JSON data (as a dict) to search through :param key: The key to search for :return: True if key is found in json, False if not. """ return key in json and json[key] is not...
def empty(value): """test if a value is empty >>> empty('') True >>> empty(' ') True >>> empty('\\n') True >>> empty('x') False >>> empty(1) False """ try: return not value or value.isspace() except AttributeError: return False # return h...
def rgb_tuple_to_hex_str(rgb, a=None): """ Return a hex string representation of the supplied RGB tuple (as used in SVG etc.) with alpha, rescaling all values from [0,1] into [0,255] (ie hex x00 to xff). Parameters: rgb - (r,g,b) tuple (each of r,g,b is in [0,1]) a - (default None) al...
def _process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (List of Dictionaries) raw structured data to process Returns: List of Dictionaries. Structured data to conform to the schema. """ # convert ints and floats for top-level keys ...
def add_metadata_columns_to_schema(schema_message): """Metadata _sdc columns according to the stitch documentation at https://www.stitchdata.com/docs/data-structure/integration-schemas#sdc-columns Metadata columns gives information about data injections """ extended_schema_message = schema_message ...
def fib_recursive(n): """ O(2^n) - Exponential (bad!!) IMPROVE WITH MEMOIZATION """ if n < 2: return n return fib_recursive(n-1) + fib_recursive(n-2)
def calculate_signal_strength(rssi): # type: (int) -> int """Calculate the signal strength of access point.""" signal_strength = 0 if rssi >= -50: signal_strength = 100 else: signal_strength = 2 * (rssi + 100) return signal_strength
def get_kl_weight(step, total_steps, warmup_steps=0): """ For KL annealing """ weight = 0.0 if step > warmup_steps: step = step - warmup_steps weight = min(0.5, step / total_steps) return weight
def say_hello(name): """Very simple example of passing variables to func's docstring.""" print(f'Hello, my friend, {name}!') return 42
def google_url(stringa): """Generate a valid google search URL from a string (URL quoting is applied). Example ------- >>> from dimcli.utils import google_url >>> google_url("malaria AND africa") 'https://www.google.com/search?q=malaria%20AND%20africa' """ from urllib.parse import quot...
def get_hash_salt(encrypted_password): """Given an encrypted password obtain the salt value from it. Args: encrypted_password (str): A password that has been encrypted, which the salt will be taken from. Returns: string: The encrypted password. Example: >>> from netutils.passw...
def _format_object_mask(objectmask, service): """Format new and old style object masks into proper headers. :param objectmask: a string- or dict-based object mask :param service: a SoftLayer API service name """ if isinstance(objectmask, dict): mheader = '%sObjectMask' % service else: ...
def get_checked_optional_value(dictionary, key): """ Checks that the given key exists in the dictionary and returns it possibly empty value """ if key in dictionary: value = dictionary[key] return value raise Exception("The config file is missing an entry with key {0}".format(key))
def create_ephemeral(text): """Send private response to user initiating action :param text: text in the message """ message = {} message['text'] = text return message
def union(*dicts): """ Union of two grammars """ items = [] for d in dicts: items.extend(d.items()) return dict(items)
def process_cutoff_line(list_): """Process a cutoff line.""" cutoffs = [] for i in [1, 2]: if list_[i] == 'None': cutoffs += [None] else: cutoffs += [float(list_[i])] return cutoffs
def preduce(policies, replaces): """Reduce a set of policies by removing all policies that are subsumed by another policy""" for p in set(replaces) & policies: policies -= set(replaces[p]) return policies
def rgb_to_yiq(rgb): """ Convert an RGB color representation to a YIQ color representation. (r, g, b) :: r -> [0, 255] g -> [0, 255] b -> [0, 255] :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value. :return: YIQ representa...
def _remove_empty_parts(tagged_parts_list): """ Remove all the empty parts in the list of tagged parts """ tagged_parts_list = [part for part in tagged_parts_list if len(part[0]) > 0] return tagged_parts_list
def simple_search(a, x): """Implement simple search to compare time complexity with binary_search.""" for i, each in enumerate(a): if each == x: return i else: return None
def calculate_progress(done_tracks, number_of_loved_tracks, print_progress=False): """Method that calculates and may print (changeable by print argument, False by default) progress of list creation in XX.XX% format.""" output = '{0:.2f}%'.format(done_tracks / number_of_loved_tracks * 100) if print_progr...
def add_input_files_lie(job, gromacs_config): """ Tell to Cerise which files are associated to a `job`. """ # Add files to cerise job for name in ['protein_top', 'ligand_file', 'topology_file']: if name in gromacs_config: job.add_input_file(name, gromacs_config[name]) prote...
def postprocess_obs_dict(obs_dict): """ Undo internal replay buffer representation changes: save images as bytes """ # for obs_key, obs in obs_dict.items(): # if 'image' in obs_key and obs is not None: # obs_dict[obs_key] = normalize_image(obs) return obs_dict
def str2dict(string): """ transform string "-a b " or "--a b" to dict {"a": "b"} :param string: :return: """ assert isinstance(string, str) r = {} param = "" value = [] for p in string.split(): if not p: continue if p.startswith("-"): if...
def no_rbac_suffix_in_test_filename(physical_line, filename, previous_logical): """Check that RBAC filenames end with "_rbac" suffix. P101 """ if "patrole_tempest_plugin/tests/api" in filename: if filename.endswith('rbac_base.py'): return if not filename.endswith('_rbac.py...
def Claret_LD_law(mu, c1, c2, c3, c4): """ Claret 4-parameter limb-darkening law. """ I = (1 - c1*(1 - mu**0.5) - c2*(1 - mu) - c3*(1 - mu**1.5) - c4*(1 - mu**2)) * mu return I
def merge_list_of_dicts(list_of_dicts): """ Merges a list of dicts to return one dict. """ result = {} for row in list_of_dicts: for k, v in row.items(): if isinstance(v, list): z = merge_list_of_dicts(result[k] + v if k in result else v) result[k...
def negativeIndex(length, index): """Helper function for interpreting negative array indexes as counting from the end of the array (just like Python). :type length: non-negative integer :param length: length of the array in question :type index: integer :param index: index to interpret :rtype: ...
def str2boolean(flag_str): """returns boolean representation of flag_str""" flag_S = flag_str.lower() if flag_S == "true": return True elif flag_S == "false": return False
def get_osd_dirs(dirs): """ Find all the /var/lib/ceph/osd/* directories. This is a bit tricky because we don't know if there are nested directories (the metadata reports them in a flat list). We must go through all of them and make sure that by splitting there aren't any nested ones and we are ...
def extract_options(options, prefix): """extract_options(dict(law=0, law_a=1, law_b=2, foo=3, foo_c=4), 'law') == {'a': 1, 'b': 2}""" return {k.replace(prefix+'_', ""):options[k] for k in options if k.find(prefix+'_')==0}
def odd(n): """Builds a set of cycles that a graph with odd vertices.""" assert n % 2 == 1 # Base case for complete graph such that V = {1, 2, 3}. cycles = [[1, 2, 3]] * 2 for i in range(5, n + 1, 2): a, b = i, i - 1 # Say the new vertices are {a, b}. Since the graph is fully conne...
def max_score(score_mat): """ Input: scoring matrix Output: tuple containing (maximum score value, [list of indexes for this score]) """ # Loop through the list of lists, saving the max value and locations max_seen = 0 max_list = [] for i in range(1,len(score_mat)): for j in rang...
def bilayer_select(bilayer): """ Select bilayer composition from either predefined selection (bilayer_type_dict) or inputted by the user in insane.py format. """ bilayer_type = {"Gram neg. inner membrane": "-u POPE:67 -u POPG:23 -u CDL2:10 -l POPE:67 -l POPG:23 -l CDL2:10", "Gram neg. outer membrane...
def __get_terraform_image(resource_def: dict) -> str: """ Check the skillet metadata (resource_def) for a label with key 'terraform_image', and if found use that docker image to execute our terraform commands :param resource_def: Skillet metadata as loaded from the .meta-cnc file :return: str c...
def check_mod(i: int, nums: list) -> bool: """Check, if first param is dividable without reminder by any of the second params list of numbers. :param i: int to be checked :param nums: list of ints to check against :return: Returns True or False """ for n in nums: if i % n == 0: ...
def _reference_name(class_name): """ Given the name of a class, return an attribute name to be used for references to instances of that class. For example, a Segment object has a parent Block object, referenced by `segment.block`. The attribute name `block` is obtained by calling `_container_na...
def remove_duplicate_in_list(alist): """Remove replacements on the list. Ex: [1, 1, 2, 2, 3, 3] => [1, 2, 3] :param alist: A list that contains the replacements. :return alist: A list without replacements. """ return list(set(alist))
def suffix_match(list1, list2): """ Find the length of the longest common suffix of list1 and list2. >>> suffix_match([], []) 0 >>> suffix_match('test', 'test') 4 >>> suffix_match('test', 'toast') 2 >>> suffix_match('test', 'best') 3 >>> suffix_match([1, 2, 3, 4], [1, 2, 4, 8...
def reorder_array(nums, key): """ :param nums:array :param key: criterion function True in front False at back :return: ordered array """ head = 0 end = len(nums) - 1 while head < end: if key(nums[head]): head += 1 else: if key(nums[end]): ...
def _string_id(*args): """Creates an id for a generic entity, by concatenating the given args with dots. Parameters ---------- *args: str The strings to concatenate Returns ------- basestring: an identifier to be used. """ def is_valid(entry): return ( ...
def naive_match(text, pattern): """ Naive implementation of a substring search algorithm. Time complexity is O(mn). Find occurrence of pattern in text. If pattern is not found in text, return -1. If pattern is found, returns the start of the index. Args: text (str): A string of text. ...
def segment(p1, p2): """ Parameters =========== p1 : list The first point. p2 : list The second point. Returns ========== A line segment of points represented in a quadruple. """ return (p1[0], p1[1], p2[0], p2[1])
def is_far_from_group(pt, lst_pts, d2): """ Tells if a point is far from a group of points, distance greater than d2 (distance squared) :param pt: point of interest :param lst_pts: list of points :param d2: minimum distance squarred :return: True If the point is far from all others. """ ...
def filter_by_interface(objects, interface_name): """ filters the objects based on their support for the specified interface """ object_paths = [] for path in objects.keys(): interfaces = objects[path] for interface in interfaces.keys(): if interface == interface_name: ...
def get_job_name(table_name: str, incremental_load: bool) -> str: """Creates the job name for the beam pipeline. Pipelines with the same name cannot run simultaneously. Args: table_name: a dataset.table name like 'base.scan_echo' incremental_load: boolean. whether the job is incremental. Returns: ...
def fib2(n): """Return Fibonacci series up to n""" result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a + b return result
def checkInput(value, possibleValues, allIfNone = 1): """check if value is a list of element in possibleValues if value is None return possibleValues if allIfNone, None else""" if value is None: return possibleValues if allIfNone else None if not isinstance(value, list): value = [value] ...
def merge_update_lists(xs, ys): """ Merge two update lists: - adding where `xs[i] is not None and ys[i] is not None` - copying `xs[i]` if `xs[i] is not None` - copying `ys[i]` otherwise """ assert len(xs) == len(ys), "%i %i" % (len(xs), len(ys)) ret = [] for x, y in zip(xs, ys): ...
def comp_hun(plyr1, plyr2): """ Do the actual computations for calc_hun. This is broken out from calc_hun so that computations can be done other functions. """ same = 0 diff = 0 for category in plyr1: try: pdata1 = plyr1[category] pdata2 = plyr2[category] ...
def argv_to_module_arg_lists(args): """Converts module ldflags from argv format to per-module lists. Flags are passed to us in the following format: ['global flag', '--module', 'flag1', 'flag2', '--module', 'flag 3'] These should be returned as a list for the global flags and a list of per-mod...
def get_nwis_state_lookup(wqp_lookups): """ Return a tuple (state_fips, lookup_dict) from wqp_lookup :param List of dict wqp_lookups: should be a lookup from a statecode query :rtype: tuple """ def get_state_fips(lookup): return lookup.get('value').split(':')[1] def get_state_name(...
def diff_3(arrA, arrB): """ Using XOR """ return list(set(arrA) ^ set(arrB))
def is_public(methodname): """Determines if a method is public by looking for leading underscore. pseudo-public methods are skipped""" return methodname[0] != "_" or methodname == "__str__" or methodname == "__init__" or methodname == "__eq__" or methodname == "__hash__"
def or_(a, b): """Logical OR a or b Return boolean **** args **** a, b: python objects on which a python logical test will work. """ if a or b: return True else: return False
def cache_get(cache, key, fcn, force=False): """Get key from cache, or compute one.""" if cache is None: cache = {} if force or (key not in cache): cache[key] = fcn() return cache[key]
def singularity_image_name_on_disk(name): # type: (str) -> str """Convert a singularity URI to an on disk simg name :param str name: Singularity image name :rtype: str :return: singularity image name on disk """ docker = False if name.startswith('shub://'): name = name[7:] el...