content
stringlengths
42
6.51k
def _format_defs(defs): """Write a dictionary with all the definitions used in the module. """ ans = 'DEFS = {\n' for key in defs: ans += "'%s': [\n" % key for item in defs[key]: ans += ' %s,\n' % repr(item) ans += '],\n' ans += '}' return ans
def flat(lst): """ [(1,2), (3,4)] -> [1, 2, 3, 4]""" return sum([list(item) for item in lst], [])
def _stream_cmd(job_id: str) -> str: """Returns a CLI command that, if executed, will stream the logs for the job with the supplied ID to the terminal. """ items = ["gcloud", "ai-platform", "jobs", "stream-logs", job_id] return " ".join(items)
def retrieve_keys(management, storageacct_name): """retrieve primary and secondary keys.""" try: storage_keys = management.get_storage_account_keys(storageacct_name) primary_key = storage_keys.storage_service_keys.primary secondary_key = storage_keys.storage_service_keys.secondary return primary_key, secondary_key except: return None, None
def get_string_for_language(language_name): """ Maps language names to the corresponding string for qgrep. """ language_name = language_name.lower().lstrip() if language_name == "c": return "tc-getCC" if language_name in ('c++', 'cxx'): return "tc-getCXX" return language_name
def _extend_docstring_3d(docstring): """Change docstring to include 3D numpy support.""" # the indentation must be this way, since tabs are included in the string # if one more tab is added, the replacement is not correctly done to_replace = """x: np.ndarray (1d or 2d array) First time series. y: np.ndarray (1d or 2d array) Second time series. """ # noqa replace_by = """x: np.ndarray (1d, 2d, or 3d array) First time series or panel of time series. Indices are (n_instances, n_variables, n_series). If index is not present, n_variables=1 resp n_series=1 is assumed. y: np.ndarray (1d or 2d, or 3d array) Second time series or panel of time series. Indices are (n_instances, n_variables, n_series). If index is not present, n_variables=1 resp n_series=1 is assumed. """ # noqa docstring = docstring.replace(to_replace, replace_by) to_replace = """Returns ------- float """ # noqa replace_by = """Returns ------- float if x, y are both 1d or 2d distance between single series x and y 2d np.ndarray if x and y are both 3d (i, j)-th entry is distance between i-th instance in x and j-th in y """ # noqa docstring = docstring.replace(to_replace, replace_by) return docstring
def parse_float(m, default = 0.0): """parse_float :param m: :param default: """ if type(m) == int: return m elif type(m) == str: try: return float(m) except: return default else: raise Exception('error input %s, cannot parse' % m)
def filter_not_empty_values(value): """Returns a list of non empty values or None""" if not value: return None data = [x for x in value if x] if not data: return None return data
def format_placeholders_args(args, filename=None, handle=None): """Formats `args` with Infinitepush replacements. Hack to get `str.format()`-ed strings working in a BC way with bytes. """ formatted_args = [] for arg in args: if filename and arg == b'{filename}': formatted_args.append(filename) elif handle and arg == b'{handle}': formatted_args.append(handle) else: formatted_args.append(arg) return formatted_args
def find_with(f, iter, default=None): """Find the value in an iterator satisfying f(x)""" return next((x for x in iter if f(x)), default)
def extract_port(url): """Returns the port number out of a url""" for prefix in ['http://', 'https://']: if prefix in url: url = url.replace(prefix, '') break else: prefix = '' url = url.split('/')[0] url = url.split(':') if len(url) > 1: return int(url[1]) elif prefix == 'https://': return 443 else: return 80
def TryConvert(fn, val): """Try to convert a value ignoring errors. This function tries to apply function I{fn} to I{val}. If no C{ValueError} or C{TypeError} exceptions are raised, it will return the result, else it will return the original value. Any other exceptions are propagated to the caller. @type fn: callable @param fn: function to apply to the value @param val: the value to be converted @return: The converted value if the conversion was successful, otherwise the original value. """ try: nv = fn(val) except (ValueError, TypeError): nv = val return nv
def Str2FloatList(str_values, expected_nvalues=3): """Convert a string into a list of values. It returns None if the array is smaller than the expected size.""" import re if str_values is None: return None values = re.findall("[-+]?\d+[\.]?\d*", str_values) valuesok = [] for i in range(len(values)): try: valuesok.append(float(values[i])) except: return None if len(valuesok) < expected_nvalues: return None print('Read values: ' + repr(values)) return valuesok
def choose(color): """ Used to convert the png into 4 color. """ r, g, b, a = color if r < 90: return (0, 0, 0, 255) if r >= 77 and r < 160: return (134, 30, 214, 255) if r >= 160 and r < 208: return (172, 143, 239, 255) else: return (255, 255, 255, 255)
def tuple_key(tup): """Return a sort key for mixed int/string tuples. Strings sort first. """ def generator(): for item in tup: try: yield (1, int(item)) except ValueError: yield (0, item) return tuple(generator())
def UC_C(C_kgmm, A_catch): """ Convert concentration from units of kg/mm to mg/l. Divide answer by 10**6 to convert from mg/mm to mg/l Args: C_kgmm: Float. Concentration in kg/mm A_catch: Float. Catchment area in km2 Returns: Float. Concentration in mg/l """ C_mgl = C_kgmm/A_catch return C_mgl
def overlap(box1, box2): """ Check the overlap of two boxes """ endx = max(box1[0] + box1[2], box2[0] + box2[2]) startx = min(box1[0], box2[0]) width = box1[2] + box2[2] - (endx - startx) endy = max(box1[1] + box1[3], box2[1] + box2[3]) starty = min(box1[1], box2[1]) height = box1[3] + box2[3] - (endy - starty) if (width <= 0 or height <= 0): return 0 else: Area = width * height Area1 = box1[2] * box1[3] Area2 = box2[2] * box2[3] ratio = Area / (Area1 + Area2 - Area) return ratio
def find(r): """around 0.3ms""" if r.find(b"response") != -1: return True return False
def reverse_insort_pos(a, x): """ find position to insert item x in list a, keep it reverse sorted """ lo = 0 hi = len(a) while lo < hi: mid = (lo + hi) // 2 if x > a[mid]: hi = mid else: lo = mid + 1 # makes sure to insert to the left if (lo < len(a)): while lo > 0 and a[lo - 1] == x: lo -= 1 return lo
def es_subcadena(adn1, adn2): """ (str, str) -> boolean funcion que nos permite definir la subcadena de una secuencia dada >>> es_subcadena('atcgta', 'gta') True >>> es_subcadena('atcg', 'tta') False :param adn1: str con la cadena 1 :param adn2: str con la cadena 2 :return: si la secuencia de la cadena 2 es subcadena de l secuencia de la cadena 1 """ if int == type(adn2): raise TypeError(str(adn2) + ' no es pueden enteros') if int == type(adn1): raise TypeError(str(adn1) + ' no se pueden enteros') if float == type(adn1): raise TypeError(str(adn1) + ' no se pueden enteros') if adn2 in adn1: return True elif adn2 not in adn1: return False
def get_masked_password(password: str, secret: str, given_secret: str) -> str: """ Use secret correctness as a password mask. For each correct secret character, password character in the same position will be exposed. """ if len(password) != len(secret): raise ValueError("Password and secret should be the same length") masked_password = "" for index in range(len(secret)): try: is_same_character = secret[index] == given_secret[index] except IndexError: masked_password += "*" continue if is_same_character: masked_password += password[index] continue masked_password += "*" return masked_password
def ip_to_int(ip): """ convert ip(ipv4) address to a int num :param ip: :return: int num """ lp = [int(x) for x in ip.split('.')] return lp[0] << 24 | lp[1] << 16 | lp[2] << 8 | lp[3]
def parse_metadata(metadata_list): """Parse the metadata from a set of strings to a dictionary""" if not metadata_list: return {} metadata = {} # Loop through the list of metadata values for pair in metadata_list: # Split the key part from the value key_path, value = pair.split("=", 1) # Split the key up if it is a dotted path keys = key_path.split(".") current_data = metadata # Loop through all but the last key and create the dictionary structure for key in keys[:-1]: if key not in current_data: current_data[key] = {} current_data = current_data[key] # Finally, set the actual value key = keys[-1] # Properly process list types if "," in value: value = value.split(",") current_data[key] = value return metadata
def apnumber(value): """ Borrowed with love and adapted from django.contrib.humanize: https://github.com/django/django/blob/master/django/contrib/humanize/templatetags/humanize.py For numbers 1-9, returns the number spelled out. Otherwise, returns the number. This follows Associated Press style. """ try: value = int(value) except (TypeError, ValueError): return value if not 0 <= value < 10: return value return ('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine')[value]
def to_3_list(item): """ Converts item into a 3 item list :param item: var :return: list<var, var, var> """ if not isinstance(item, list): item = [item] * 3 return item
def cubic_objective(x, a, b, c, d): """Cubic objective function.""" return a*x**3 + b*x**2 + c*x + d
def get_model_name(name, batch_size, learning_rate, epoch): """ Generate a name for the model consisting of all the hyperparameter values Args: config: Configuration object containing the hyperparameters Returns: path: A string with the hyperparameter name and value concatenated """ path = "./model_{0}_bs{1}_lr{2}_epoch{3}".format(name,batch_size,learning_rate, epoch) return path
def funcion_factorial(n: int ): """El factorial de un numero. Parameters ---------- n : int Numero entero `n`. Returns ------- int Retorna el factorial del numero `n` """ facto= 1 for i in range(1,n+1): facto = facto * i return facto
def defvalkeys(js, key, default=None): """ Returns js[key] if set, otherwise default. Note js[key] can be None. Key is array of keys. js[k1][k2][k3]... :param js: :param key: :param default: :param take_none: :return: """ if js is None: return default if not isinstance(key, (tuple, list)): key = key.split(".") try: cur = js for ckey in key: cur = cur[ckey] return cur except: pass return default
def join_str(str_ls, sep=None): """ join a list of strings""" if sep is None: sep = '' return sep.join([w for w in str_ls if w is not None])
def coerce_date_dict(date_dict): """ given a dictionary (presumed to be from request.GET) it returns a tuple that represents a date. It will return from year down to seconds until one is not found. ie if year, month, and seconds are in the dictionary, only year and month will be returned, the rest will be returned as min. If none of the parts are found return an empty tuple. """ keys = ['year', 'month', 'day', 'hour', 'minute', 'second'] retVal = { 'year': 1, 'month': 1, 'day': 1, 'hour': 0, 'minute': 0, 'second': 0} modified = False for key in keys: try: retVal[key] = int(date_dict[key]) modified = True except KeyError: break except TypeError: break return modified and retVal or {}
def _depgrep_rel_disjunction_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node from the disjunction of several other such lambda functions. """ # filter out the pipe tokens = [x for x in tokens if x != "|"] # print 'relation disjunction tokens: ', tokens if len(tokens) == 1: return tokens[0] elif len(tokens) == 2: return (lambda a, b: lambda n, m=None, el=None: a(n, m, el) or b(n, m, el))( tokens[0], tokens[1] )
def porridge_for_the_bears(were_you_robbed): """ Did Goldie Locks break in and rob you? Parameters ---------- were_you_robbed : bool The question is in the title Returns ------- p_bear_emo, m_bear_emo, b_bear_emo : string The emotional status of the three bears """ if were_you_robbed: p_bear_emo = 'angry' m_bear_emo, b_bear_emo = 'sad', 'sad' else: p_bear_emo, m_bear_emo, b_bear_emo = 'angry', 'happy', 'happy' return p_bear_emo, m_bear_emo, b_bear_emo
def valid_account_id(account_id): """Returns True if account_id is valid Returns False if account_id is not valid """ valid = True # Valid length valid = valid and len(account_id) == 64 # Valid characters valid_chars = '_ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' tmp_account_id = str(account_id.upper()) for valid_char in valid_chars: tmp_account_id = tmp_account_id.replace(valid_char, '') valid = valid and len(tmp_account_id) == 0 return valid
def value_to_print(value, optype): """String of code that represents a value according to its type """ if (value is None): return "NULL" if (optype == 'numeric'): return value return u"'%s'" % value.replace("'", '\\\'')
def fixstyle(obj): """Try to convert styles into a dictionary""" if obj: if isinstance(obj, list): lengths = [len(x) for x in obj] if min(lengths) == max(lengths) == 2: obj = dict(obj) elif isinstance(obj, dict) and 'styles' in obj: obj['styles'] = dict(obj['styles']) return obj
def extract_filename(string, remove_trailing_ftype=True, trailing_type_max_len=7): """ removes path (in front of the file name) and removes the file-type after the '.' (optional). returns: path & file_name""" A = string.replace("\\","/").split("/") path = ("/".join(A[:-1]))+"/" if len(path)==1: path="" B=A[-1] if remove_trailing_ftype: file_name = ".".join(B.split(".")[:-1]) if len(file_name)==0 or len(B)-len(file_name)>(trailing_type_max_len+1): file_name = B else: file_name=B return path, file_name
def class_of(obj): """Return the class or type of the input object as a string.""" if obj is None: return 'None' if hasattr(obj,'__class__'): return obj.__class__.__name__ return str(type(obj))
def extract_parameter_value_from_url(param_dic, key, default): """ """ if key in param_dic: val = param_dic[key] else: val = default return val
def repunit(number): """ Returns True if number is repunit """ while number > 9: if number % 10 != 1: return False else: number = number // 10 return number == 1
def hex_to_rgb(rgb_string): """ Takes #112233 and returns the RGB values in decimal """ if rgb_string.startswith('#'): rgb_string = rgb_string[1:] red = int(rgb_string[0:2], 16) green = int(rgb_string[2:4], 16) blue = int(rgb_string[4:6], 16) return (red, green, blue)
def ERR_TOOMANYTARGETS(sender, receipient, message): """ Error Code 407 """ return "ERROR from <" + sender + ">: " + message
def shared_lib_name(group_name: str) -> str: """Given a group name, return the actual name of its extension module. (This just adds a suffix to the final component.) """ return '{}__mypyc'.format(group_name)
def pad_sents(sents, pad_idx): """ @param sents (list[list[int]]): @param pad_idx (int): Pad ID @return sents_padded (list[list[int]]): sents with padding according to max_sent_len """ max_len = 0 sents_padded = [] for sent in sents: max_len = max(max_len, len(sent)) for sent in sents: sent_padded = sent sent_padded.extend([pad_idx for i in range(max_len - len(sent))]) sents_padded.append(sent_padded) return sents_padded
def parse_user(line): """ Parses a user in MovieLens format userID::gender::age::occupation::zip Parameters ---------- line : str The line that contains user information Returns ------- list : list A list containing userID, gender, age, occupation, zip """ fields = line.strip().split("::") return [str(fields[0]), str(fields[1]), str(fields[2])]
def plausible_file_extension(s): """given some string, likely a mime-type, return either a .SOMETHING extension, or an empty string""" ext = "" l = len(s) for i in range(l-1, -1, -1): if s[i].isalpha(): ext = s[i] + ext else: break return ext
def _interpolate(a,b,v): """interpolate values by factor v""" return a + (b-a) * v
def readall(fd): """My own read loop, bc the one in python3.4 is derpy atm: http://bugs.python.org/issue21090#msg231093 """ from os import read result = [] lastread = None while lastread != b'': try: lastread = read(fd, 4 * 1024) except OSError as error: if error.errno == 5: # pty end-of-file -.- break else: raise result.append(lastread) return b''.join(result).decode('US-ASCII')
def first_of(value, arg=10): """ Only returns first X of list """ if not value: return value count = int(arg) if len(value) > arg: return value[:arg] else: return value
def test_ppm(h, f): """PPM (portable pixmap)""" if len(h) >= 3 and \ h[0] == 'P' and h[1] in '36' and h[2] in ' \t\n\r': return 'ppm'
def rensure(items, count): """Make sure there are `count` number of items in the list otherwise just fill in `None` from the beginning until it reaches `count` items.""" fills = count - len(items) if fills >= 1: return [None] * fills + items return items
def get_fixture_name(fixture_fun): """ Internal utility to retrieve the fixture name corresponding to the given fixture function . Indeed there is currently no pytest API to do this. :param fixture_fun: :return: """ try: # pytest 3 custom_fixture_name = fixture_fun._pytestfixturefunction.name except AttributeError: try: # pytest 2 custom_fixture_name = fixture_fun.func_name except AttributeError: custom_fixture_name = None if custom_fixture_name is not None: # there is a custom fixture name return custom_fixture_name else: obj__name = getattr(fixture_fun, '__name__', None) if obj__name is not None: # a function, probably return obj__name else: # a callable object probably return str(fixture_fun)
def find_all_indexes(text, pattern): """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found. O(1) if item is the first that is checked O(n*m) where n is the length of the pattern and m is the length of the text""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) first_i = [] if pattern == "": return [i for i in range(len(text)) ] elif len(pattern) == 1: return [i for i, char in enumerate(text) if char == pattern ] t_index = 0 p_index = 0 while t_index < len(text): print((t_index, p_index), (len(text), len(pattern))) if text[t_index] == pattern[p_index]: if p_index == len(pattern) - 1: first_i.append(t_index - p_index) t_index -= p_index - 1 p_index = 0 p_index += 1 t_index += 1 elif text[t_index] != pattern[p_index]: if p_index != 0: t_index -= p_index - 1 p_index = 0 else: t_index += 1 return first_i
def get_pos_association_dict(volumestokeep, outfiles_partititon): """ Converts 3d index to numeric index """ index = 0 _3d_to_numeric_pos_dict = dict() for i in range(outfiles_partititon[0]): for j in range(outfiles_partititon[1]): for k in range(outfiles_partititon[2]): _3d_to_numeric_pos_dict[(i,j,k)] = index index += 1 return _3d_to_numeric_pos_dict
def limit(value, min_val, max_val): """Returns value clipped to the range [min_val, max_val]""" return max(min_val, min(value, max_val))
def _nested_delete(document, key): """ Method to delete a key->value pair from a nested document Args: document: Might be List of Dicts (or) Dict of Lists (or) Dict of List of Dicts etc... key: Key to delete Return: Returns a document that includes everything but the given key """ if isinstance(document, list): for list_items in document: _nested_delete(document=list_items, key=key) elif isinstance(document, dict): if document.get(key): del document[key] for dict_key, dict_value in document.items(): _nested_delete(document=dict_value, key=key) return document
def S_downsample_data(_data_list, _factor=1): """ Returns a two dimensional data set with a reduced number of samples. Use the sample skipping factor to get required result, the factor tells how many samples to skip for one data sample. """ ds_data = [] ds = len(_data_list) skip_count = _factor for i in range(ds): if skip_count < _factor: skip_count += 1 else: ds_data.append((_data_list[i][0], _data_list[i][1])) skip_count = 0 return ds_data
def char_size(c): """Get `UTF8` char size.""" value = ord(c) if value <= 0xffff: return 1 elif value <= 0x10ffff: return 2 raise ValueError('Invalid code point')
def update(old, new, priority='new'): """ Update a nested dictionary with values from another This is like dict.update except that it smoothly merges nested values This operates in-place and modifies old Parameters ---------- priority: string {'old', 'new'} If new (default) then the new dictionary has preference. Otherwise the old dictionary does. Examples -------- >>> a = {'x': 1, 'y': {'a': 2}} >>> b = {'x': 2, 'y': {'b': 3}} >>> update(a, b) # doctest: +SKIP {'x': 2, 'y': {'a': 2, 'b': 3}} >>> a = {'x': 1, 'y': {'a': 2}} >>> b = {'x': 2, 'y': {'b': 3}} >>> update(a, b, priority='old') # doctest: +SKIP {'x': 1, 'y': {'a': 2, 'b': 3}} """ for k, v in new.items(): if k not in old and isinstance(v, dict): old[k] = {} if isinstance(v, dict): if old[k] is None: old[k] = {} update(old[k], v, priority=priority) else: if priority == 'new' or k not in old: old[k] = v return old
def collect_uppercase_words(tokens): """Given list of tokens, collect only uppercase words""" return [1 for token in tokens if token.isupper()]
def all_true(iterable): """ Helper that returns true if the iterable is not empty and all its elements evaluate to true. """ items = list(iterable) return all(items) if items else False
def from_size(n): """ Constructs a zeroed, *n* sized vector clock. """ return (0,) * n
def keypath_drop_last(keypath: str) -> str: """Drop the last part of a keypath. If it only has one part, empty string is returned. If it's empty string, empty string is returned. Args: keypath (str): The keypath to drop last from. Returns: str: A new keypath with last component dropped or empty string. """ if keypath == '': return '' parts = keypath.split('.') parts.pop() return '.'.join(parts)
def add_to_table(name, table): """Add a string to the table Args: name (str): the same to add to the table table (bytearray): the table to add to Returns: int: the start index of the name in the table """ start_point = len(table) for character in name: table.append(ord(character)) # closing \0' character table.append(0) return start_point
def common_get(obj, key, default): """Can be used to access an element via the index or key. Works with numpy arrays, lists, and dicts. Args: ``obj`` (list,array,dict): Mapping ``key`` (int): Index or key of the element to retrieve ``default`` (object): Default return value if ``key`` not found Returns: ``obj[key]`` if ``key`` in ``obj``, otherwise ``default`` """ if isinstance(obj, dict): return obj.get(key, default) else: return obj[key] if key < len(obj) else default
def zeropad(anint): """Convert an integer to a two character string.""" intstr = str(anint) if len(intstr) == 1: intstr = '0' + intstr return intstr
def _hex_to_rgb(value): """Convert a hex-formatted color to rgb, ignoring alpha values.""" value = value.lstrip("#") return [int(value[i:i + 2], 16) for i in range(0, 6, 2)]
def svpwat(t): """e = svpwat(t) Calculates the water vapor mixing ratio Inputs: (all vectors of same length) t = dry bulb temperature(s) (K) Outputs: e = saturation vapor pressure with respect to a plane surface of ice (mb) RLT, 010710 """ A0 = 0.999996876e0 A1 = -0.9082695004e-2 A2 = 0.7873616869e-4 A3 = -0.6111795727e-6 A4 = 0.4388418740e-8 A5 = -0.2988388486e-10 A6 = 0.2187442495e-12 A7 = -0.1789232111e-14 A8 = 0.1111201803e-16 A9 = -0.3099457145e-19 B = 0.61078e+1 T = t - 273.16 E = A0 + T*(A1 + T*(A2 + T*(A3 + T*(A4 + T*(A5 + T*(A6 + T*(A7 + T*(A8 + T*A9)))))))) E = B/pow(E,8) return E
def extract_extension(filename, extension): """ filters out files with specific extensions like .py or .txt or even entire filenames """ if not extension: return filename # reverse filename filename = filename[::-1] extracted = "" for char in filename: extracted = extracted + char # reverse backwards file extension if extracted[::-1] == extension: return True
def _days_in_month(year, month): """Return the number of days in the given (year, month). """ DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] is_leap = (year % 4 == 0) and ((year % 100 != 0) or (year % 400) == 0) days = DAYS_IN_MONTH[month - 1] if month == 2: days += is_leap return days
def insertion_sort(items): """Sorts a list of items. Uses inserstion sort to sort the list items. Args: items: A list of items. Returns: The sorted list of items. """ for j in range(1, len(items)): key = items[j] # Insert items[j] into the sorted sequence items[0..j-1] i = j - 1 while 0 <= i and key < items[i]: items[i + 1] = items[i] i = i - 1 items[i + 1] = key return items
def with_progress(iterable, desc=None, total=None, leave=True): """ Return an iterator which prints the iteration progress using tqdm package. Return iterable intact if tqdm is not available. """ try: from tqdm import tqdm # workarounds for tqdm bugs def _it(iterable, desc, total, leave): if total is None: try: total = len(iterable) except Exception: total = 0 for el in tqdm(iterable, desc=desc, total=total, leave=leave): yield el if leave: print("") return _it(iterable, desc, total, leave) except ImportError: return iterable
def insertion_sort_loops_combined(items: list) -> list: """ Args: items: Returns: Examples: >>> items = [random.randrange(0, 100) for _ in range(100)] >>> assert(insertion_sort_loops_combined(items.copy()) == sorted(items)) """ for unsorted_start_idx in range(1, len(items)): insertion_val = items[unsorted_start_idx] # Shift elements greater than `insertion_val` one position to the right insertion_idx = unsorted_start_idx while insertion_idx > 0 and items[insertion_idx - 1] > insertion_val: items[insertion_idx] = items[insertion_idx - 1] insertion_idx -= 1 items[insertion_idx] = insertion_val return items
def generate_parameters_string(parameters): """Generates the parameters string from the parameters dictionary Parameters ---------- parameters : dict The parameter values, keyed by parameter name Returns ------- str A string with the parameters to the CLI call """ flag_params = ['rev_comp_barcode', 'rev_comp_mapping_barcodes', 'rev_comp'] str_params = ['max_bad_run_length', 'min_per_read_length_fraction', 'sequence_max_n', 'phred_quality_threshold', 'barcode_type', 'max_barcode_errors'] result = ["--%s %s" % (sp, parameters[sp]) for sp in str_params] if parameters['phred_offset'] != 'auto': result.append("--phred_offset %s" % parameters['phred_offset']) for fp in flag_params: if parameters[fp]: result.append("--%s" % fp) return ' '.join(result)
def v(n): """compute u value of the lhs matrix""" return ((n ** 2) * (n + 1)) / 2
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: O(n) Space Complexity: O(n) """ if not nums or len(nums) == 0: return 0 sum_so_far = 0 # from wherever we starting to where we are (array) max_sum_so_far = float('-inf') # negative infinity! for num in nums: sum_so_far += num # add it to the sum so far if sum_so_far > max_sum_so_far: # check if num should be added max_sum_so_far = sum_so_far # if so, update max, sum keeps on elif sum_so_far < 0: # if it brings it below the max sum_so_far = 0 # start algorithm over return max_sum_so_far
def format_xi_stats(users_as_nodes, exp, xi_mean, xi_std, tot): """Formats the curvature estimates for logging. Args: users_as_nodes: Bool indicating which interaction graph was generated. If True (False), a user-user (item-item) interaction graph was generated. exp: Boolean indicating if the interaction graph distances are on an exponential scale. xi_mean: Float containng the mean of the curvatures of the sampled triangles. xi_std: Float containng the standard deviation of the curvatures of the sampled triangles. tot: Int containing the total number of legal sampled triangles. Returns: String storing the input information in a readable format. """ stats = 'User-user stats:' if users_as_nodes else 'Item-item stats:' if exp: stats += ' (using exp)' stats += '\n' stats += '{:.3f} +/- {:.3f} \n'.format(xi_mean, xi_std) stats += 'out of {} samples.'.format(tot) return stats
def lambda_lr_schedule(epoch): """Multiplicative Factor for Learning Rate Schedule. Computes a multiplicative factor for the initial learning rate based on the current epoch. This method can be used as argument ``lr_lambda`` of class :class:`torch.optim.lr_scheduler.LambdaLR`. The schedule is inspired by the Resnet CIFAR-10 schedule suggested here https://keras.io/examples/cifar10_resnet/. Args: epoch (int): The number of epochs Returns: lr_scale (float32): learning rate scale """ lr_scale = 1. if epoch > 180: lr_scale = 0.5e-3 elif epoch > 160: lr_scale = 1e-3 elif epoch > 120: lr_scale = 1e-2 elif epoch > 80: lr_scale = 1e-1 return lr_scale
def canvas(with_attribution=True): """ Placeholder function to show example of docstring (NumPy format) Replace this function and doc string for your own project Parameters ---------- with_attribution : bool, Optional, default: True Set whether or not to display who quote is from Returns ------- quote : str Compiled quote including string and optional attribution """ quote = "The code is but a canvas to our imagination." if with_attribution: quote += "\n\t - Adapted by H.D.T" return quote
def convert_to_demisto_severity(ib_severity="medium", tp_score_based=False, score=0): """ Converts the IllusionBLACK Threat Parse score for an attacker to demisto incident severity Args: ib_severity: IllusionBLACK severity. Some events do not have threat parse score. tp_score_based: If score is based on Threat Parse cumulative score score: The cumulative Threat Parse score Returns: The demisto incident severity ranging from 1 to 4 """ severity = 1 if tp_score_based: severity = score // 25 severity = 1 if severity < 1 else severity severity = 4 if severity > 4 else severity else: if ib_severity == "low": severity = 2 elif ib_severity == "medium": severity = 3 elif ib_severity == "high": severity = 4 return severity
def min_value(a, b): """ Compute min of a pair of two ints. """ return b ^ ((a ^ b) & -(a < b))
def _or(newscore: float, oldscore: float, howold: int) -> float: """Logical 'or', but with float scores An internal utility function to weight old scores and 'or' them, i.e., add them to new scores to calculate the matches if there are misses Adds the two scores, but limits the return value to 1.0 The howold value weights down the old score like: - 0: divide by 2 - 1: divide by 3 - 2: divide by 4 This is so that howold can be the loop index variable Args: newscore (float): the full match score oldscore (float): a previous score howold (int): how far back we are going Returns: float: the 'or'-ed score """ if newscore < 0.0 or newscore > 1.0: ValueError("newscore %f must be >= 0.0 and <= 1.0" % newscore) if oldscore < 0.0 or oldscore > 1.0: ValueError("oldscore %f must be >= 0.0 and <= 1.0" % oldscore) if howold < 0: ValueError("howold %d must be >= 0") return min(1.0, newscore + oldscore/(2+howold))
def extract(dic, lis): """ Devuelve una lista con el valor que se encuentra en dic para cada elemento de lis """ r = [] for l in lis: r.append(dic[l]) return r
def connect_bases(char1, char2): """ For two aligned bases, get connecting symbol. Bases on whether bases match, mismatch or are part of a gap. Args: char1, char2 (str): Two aligned bases. """ if char1 == '-' or char2 == '-': return ' ' if char1 == char2: return '|' return '.'
def get_alt_support_by_color(is_in_support): """ ***NOT USED YET*** :param is_in_support: :return: """ if 248 <= is_in_support <= 256: return 1 elif 48 <= is_in_support <= 55: return 0
def transfer_weights(model, weights=None): """ Always trains from scratch; never transfers weights :param model: :param weights: :return: """ print('ENet has found no compatible pretrained weights! Skipping weight transfer...') return model
def consistentCase(description): """Converts snake_case strings to CameCase""" splitted = description.split('_') out = ''.join([word[0].upper() + word[1:] for word in splitted]) return out
def non_null_size(filename): """ Control if the file has nonzero size and exists """ from os.path import getsize, isfile return isfile(filename) and (getsize(filename) > 0)
def remove_trailing_prefs(proposal_record, preferences): """ Function trims each preference list by eliminating possibilities indexed after accepted proposal Takes in two dictionaries: proposal_record and preference_lists Returns updated preference_lists For example: Inputs of proposal_record = { 'A': ['C', 'B'], - proposed to C and accepted proposal from B 'B': ['A', 'D'], - proposed to A and accepted proposal from D 'C': ['D', 'A'], - proposed to D and accepted proposal from A 'D': ['B', 'C'], - proposed to B and accepted proposal from C } preferences = { 'A': ['C', 'B', 'D'], - remove all prefs that rank lower than B 'B': ['A', 'C', 'D'], 'C': ['D', 'B', 'A'], 'D': ['B', 'A', 'C'], - remove 'A' since 'D' is removed from A's list } Outputs => preferences = { 'A': ['C', 'B'], 'B': ['A', 'C', 'D'], 'C': ['D', 'B', 'A'], 'D': ['B', 'C'], } """ for proposer in proposal_record: proposee = proposal_record[proposer][0] proposee_prefs = preferences[proposee] proposer_ranking = proposee_prefs.index(proposer) successors = proposee_prefs[proposer_ranking+1:] # Updated proposee's preferences, removing successors preferences[proposee] = proposee_prefs[:proposer_ranking+1] # Iterate over successors, deleting proposee from own preference list for successor in successors: if proposee in preferences[successor]: preferences[successor].remove(proposee) return preferences
def signum(x): """Sign of `x`: ``-1 if x<0, 0 if x=0, +1 if x>0``.""" if x < 0: return -1 elif 0 < x: return +1 else: return 0
def is_dark(hsv, threshold=0.15): """Check if a color is close to black""" return hsv[2] <= threshold
def _getFilterID(tuples, value): """ Given a the tuples generated by getTuples and a value, will return a list of gmlIDs associated with the value specified. """ value = str(value) filter_id = [] for item in tuples: if item[0] == value: filter_id.append(item[1]) if not filter_id: raise Exception('Feature attribute value %s was not found in the feature collection.' % value) return filter_id
def _filter_empty_field(data_d): """ Remove empty lists from dictionary values Before: {'target': {'CHECKSUM': {'checksum-fill': []}}} After: {'target': {'CHECKSUM': {'checksum-fill': ''}}} Before: {'tcp': {'dport': ['22']}}} After: {'tcp': {'dport': '22'}}} """ for k, v in data_d.items(): if isinstance(v, dict): data_d[k] = _filter_empty_field(v) elif isinstance(v, list) and len(v) != 0: v = [_filter_empty_field(_v) if isinstance(_v, dict) else _v for _v in v ] if isinstance(v, list) and len(v) == 1: data_d[k] = v.pop() elif isinstance(v, list) and len(v) == 0: data_d[k] = '' return data_d
def val_test_func(item): """Test func for check_valid.""" return item != 'BAD'
def getattr_silent(obj, attr): """ This turns of verbose logging of missing attributes for huggingface transformers. This is motivated by huggingface transformers objects that print error warnings when we access unset properties. """ reset_verbose = False if getattr(obj, 'verbose', False): reset_verbose = True obj.verbose = False val = getattr(obj, attr, None) if reset_verbose: obj.verbose = True # fix strange huggingface bug where `obj.verbose = False` causes val to change from None to "None" if val == "None": val = None return val
def is_composite_sampler(sampler_type): """Composite samplers return a [key, val, ...] list as opposed to just a val.""" composite_samplers = ["regnet_sampler"] return sampler_type in composite_samplers
def flattenDict(flattenable, flattenKey): """ turns a list into a flatstring on the first value""" flatstring = "" if type(flattenable) == list: for tag in flattenable: if flattenKey in tag: flatstring = tag[flattenKey] elif type(flattenable) == dict: if flattenKey in flattenable: flatstring = flattenable[flattenKey] return flatstring
def restrict_to_range(x: int, lower_bound: int, upper_bound: int): """ Takes an integer x and restricts its range by the following: - If x is above the upper_bound, make x the upper_bound. - If x is below the lower_bound, make x the lower_bound. - Otherwise leave x the same. """ return min(max(x, lower_bound), upper_bound)
def chomp_empty(seq): """Return slice of sequence seq without trailing empty tuples.""" n = len(seq) while (n > 0) and seq[n - 1] == (): n -= 1 return seq[:n]
def enum(word_sentences, tag_sentences): """ enumerate words, chars and tags for constructing vocabularies. """ words = sorted(list(set(sum(word_sentences, [])))) chars = sorted(list(set(sum([list(word) for word in words], [])))) tags = sorted(list(set(sum(tag_sentences, [])))) return words, chars, tags