content
stringlengths
42
6.51k
def str_aec(text, color): """Returns text wrapped by the given ansi color code""" AEC_COLORS = { 'black': (0, 30), 'red': (0, 31), 'green': (0, 32), 'yellow': (0, 33), 'blue': (0, 34), 'purple': (0, 35), 'cyan': (0, 36), 'light_gray': (0, 37), ...
def _lr_schedule(epoch, base_lr, peak_lr, n_warmup_epochs, decay_schedule={}): """Learning rate schedule function. Gives the learning rate as a function of epoch according to additional settings: base_lr: baseline unscaled learning rate at beginning of training. peak_lr: scaled learning at ...
def pad(s): """ PKCS#5 padding """ c = 16 - (len(s) % 16) # Char to pad by while len(s) % 16 != 0: s += chr(c) return s
def jwt_create_response_payload( token, user=None, request=None, issued_at=None ): """ Return data ready to be passed to serializer. Override this function if you need to include any additional data for serializer. Note that we are using `pk` field here - this is for forward compatibility ...
def get_function_name(fcn): """Returns the fully-qualified function name for the given function. Args: fcn: a function Returns: the fully-qualified function name string, such as "eta.core.utils.function_name" """ return fcn.__module__ + "." + fcn.__name__
def subtract(value, arg): """subtract the arg from the value.""" try: return int(value) - int(arg) except (ValueError, TypeError): try: return value - arg except Exception: return ''
def readEndfINTG( string, ndigit ) : """Special case in ENDF: line of all integers, used to represent sparse correlation matrix.""" ix = int( string[:5] ) iy = int( string[5:10] ) try : i1, i2 = { 2 : [ 11, 65 ], 3 : [ 11, 63 ], 4 : [ 11, 66 ], 5 : [ 11, 65 ], 6 : [ 10, 66 ] }[ndigit] exce...
def lcs_length(x,y): """See CLRS section 15.4""" m = len(x) n = len(y) c = [[0]*n]*m for i in range(1, m): c[i][0] = 0 for j in range(n): c[0][j] = 0 for i in range(1, m): for j in range(1, n): if x[i] == y[j]: c[i][j] = c[i-1][j-1] + 1 ...
def translate_type(string): """Depreciated, Now must be enabled in functions that use it Too slow to be default, and conversions can lose information Takes a string and converts it float or a int if possible """ # This is way too greedy try: if string.isdigit(): return...
def get_total_energy(orbit, pot_energy_model, parameters): """ Returns total energy (value of Hamiltonian) of a phase space point on an orbit get_total_energy(orbit, pot_energy_model, parameters) returns the total energy for a Hamiltonian of the form KE + PE. Parameters ---------- orbit : ...
def parameterize_cases(argnames, cases): """ This is used for parametrizing pytest test cases. argnames: a comma separated string of arguments that the test expects. cases: a dictionary of test cases. """ argnames_list = [i.strip() for i in argnames.split(',')] argvalues = [tuple(i[k] for k...
def eval_fn(config_state): """ :param config_state: """ # Grid search: simply run all configurations for a fixed number of epochs (e.g., 10) stop_list = [] for config_id in config_state: if len(config_state[config_id]['train_loss']) == 10: stop_list.append(config_id) ...
def cubic_ease_in_ease_out(t, b, c, d): """ Accelerate until halfway, then decelerate. """ t /= d/2 if t < 1: return c / 2 * t * t * t + b t -= 2 return c/2 * (t * t * t + 2) + b
def do(*args): """ Returns the last argument passed to it. This is useful because arguments are evaluated from left to right before a function call. This can enable "imperative" style in a lambda expression. For example: """ return args[-1]
def is_backmutation(var): """ Check if SNP var is annotated as a backmutation. Args: var: A variant string representing a SNP Returns: True if marked as a backmutation, False otherwise. """ if '!' in var: return True return False
def _bsj_junction_to_bed(info_str, gene_id_mapping=None): """junction: chr|gene1_symbol:splice_position|gene2_symbol:splice_position|junction_type|strand junction types are reg (linear), rev (circle formed from 2 or more exons), or dup (circle formed from single exon) """ seq_name, ...
def linear_search(arr, value): """ :param arr: array/list to search a value in :param value: value to be searched in the array/list :return: index -> returns -1 if value not found else return the index of the first occurrence of the value in arr """ for index, item in enumerate(arr): if ...
def bayesian (p_h, p_o_h, p_o_not_h) : """Calculate the probability of hypothesis `h` given the new observation `o`, where :: - `p_h` is the probability before the new observation was made, - `p_o_h` is the probability of the observation when the hypothesis `h` is true, - `p_...
def get_diff_set(a_list, b_list): """Get results of a - b""" a_dict = {tpl[0]: tpl for tpl in a_list} b_dict = {tpl[0]: tpl for tpl in b_list} result_set = list() for ik, t in a_dict.items(): if ik not in b_dict.keys(): result_set.append(t) return set(result_set)
def substract_3x3(a,b) : """ substract the matrix3x3 A by the matrix3x3 B""" a1= a[0][0]-b[0][0] a2= a[0][1]-b[0][1] a3= a[0][2]-b[0][2] aa= [a1,a2,a3] b1= a[1][0]-b[1][0] b2= a[1][1]-b[1][1] b3= a[1][2]-b[1][2] bb= [b1,b2,b3] c1= a[2][0]-b[2][0] c2= a[2][1]-b[2][1] c3= a[2][2]-b[2][2] cc= [c1,c2,c3] retu...
def greatest_product(array: list): """given array return the greatest product possible in O(N)""" if len(array) < 2: return None # error we need at least two for product elif len(array) == 2: return array[0] * array[1] # only option greatest = 0 second_greatest = 0 least = 0 second_least = 0 for number...
def generate_class(ic): """ Generate a .style-<i> class from the input tuple. eg. >>> generate_class((0,"#fcae42")) ".style-0 { background-color: #fcae42; }" """ (i,c) = ic return ".style-" + str(i) + " { background-color: " + c + "; }"
def binary_to_hex(hex_format, binary_string) -> str: """ Convert a binary string to a hexadecimal string. :param hex_format: hexadecimal format - "{0:0>X}" or "{0:0>2X}" etc. :param binary_string: binary string - for example, '1110'. :return: hexadecimal string - for example '0E', 'F'. """ ...
def get_multiplier(factor): """ Convert the factor into a number. :param factor: the string 'mb', 'm', or 'k' :return: 10000000, 1000000, 1000 or 1 """ if factor.lower() == 'mb': return 10000000 elif factor.lower() == 'm': return 1000000 elif factor.lower() == 'k': ...
def is_valid_triangle(triangle_sides): """Returns a boolean inicating whether the triangle sides can form a valid triangle. Args: triangle_sides (tuple): The three sides to a triangle. Returns: (bool): True if the triangle_sides can form valid triangle. """ return ( ...
def filter_used_routes(transfers_pair, routes): """This function makes sure we filter routes that have already been used. So in a setup like this, we want to make sure that node 2, having tried to route the transfer through 3 will also try 5 before sending it backwards to 1 1 -> 2 -> 3 -> 4 v...
def build_gt_id2annotations(gt: dict) -> dict: """Build image to annotation dictionary based on the ground truth dataset. Arguments: gt {dict} -- COCO dataset of ground truth annotations. Returns: id_to_annotation {dict} -- Image IDs to ground-truth annotations. """ id_to_annotatio...
def emo_transf(emo): """transforms emotion expression to general format""" return '_'.join(emo.split())
def _new_versions(quay, conda): """Calculate the versions that are in conda but not on quay.io.""" sconda = set(conda) squay = set(quay) if quay else set() return sconda - squay
def robot_paint(grid, painted_locations, current, instruction_list): """Makes robot paint given location on grid. Updates and returns grid, painted_locations. """ painted_locations.add(current) if instruction_list[0] == 0: grid[current[0]][current[1]] = '.' elif instruction_list[0] == 1: ...
def parked_vehicles(psvList): """ Get number of successfully parked vehicles. Args: psvList (list): List of parking search vehicle objects Returns: int: Number of parked vehicles """ return sum(1 for psv in psvList if psv.is_parked())
def gamma_meanvariance_to_alphabeta(mean, variance): """Alpha-beta python style. E.g. k-theta wikipedia style.""" return [variance/mean, mean*mean/variance]
def egcd(a, b): """Helper function to run the extended euclidian algorithm""" if a == 0: return b, 0, 1 g, y, x = egcd(b % a, a) return g, x - (b // a) * y, y
def bytes_to_int(d): """Convert a list of bytes to an int Bytes are in LSB first. >>> hex(bytes_to_int([0, 1])) '0x100' >>> hex(bytes_to_int([1, 2])) '0x201' """ v = 0 for i,d in enumerate(d): v |= d << (i*8) return v
def reverse_letter(string: str) -> str: """This function returns reversed string with alphabetic characters.""" my_string = '' for item in string: if item.isalpha(): my_string += item return ''.join(map(str, list(reversed(my_string))))
def supported_arches_for_api(emulator, api): """Returns a list of supported archs for this emulator and api.""" arches = [] for arch, apis in emulator["supports"].items(): if api in apis: arches.append(arch) return arches
def _periods(years): """Get a list of periods for a given set of years, i.e. couples of start & stop years. """ periods = [] n = len(years) for i in range(n - 1): periods.append((years[i], years[i+1])) if len(years) > 2: periods.append((years[0], years[-1])) if len(years)...
def is_kind_of_class(obj, a_class): """ returns True if the object is an instance of a class ; otherwise False """ return isinstance(obj, a_class)
def e_pq_on_string(p,q,string): """ apply the excitation operator a^+_p a_q on a string This gives new string and a phase factor. It must have been checked that q is in string and p is not! """ if q not in string: """ annihilate vacuum """ return 0,0 if p in string a...
def fizz_buzz(start=1, end=100): """ Returns a list between start and end (inclusive) with the following values: 'Fizz' for every 3rd item 'Buzz' for every 5th item 'FizzBuzz' for every 15th item Just the number for everything else """ fizzbuzz = lambda i: 'FizzBuzz' if i % 15 == 0 ...
def exec_kwargs(kwargs: dict) -> dict: """Calls any value of kwargs that represents a callable and updates value to the callable's return value""" for kw, val in kwargs.items(): if callable(val): kwargs[kw] = val() return kwargs
def get_label_name(label, dict_keys, lower=True): """ Return label name from a dict keys. Because label name is different in relion star file and xmipp star file. """ if lower: label_name = [key for key in dict_keys if label in key.lower()] else: label_name = [key for key in dict...
def toComplexes(results): """ For convenience, turn a list of numbers into complex numbers [real(r1), imag(r1), real(r2), imag(r2), ... , real(rn), imag(rn)] = r1, r2, ... , rn """ return [results[i]+results[i+1]*1j for i in range(0, len(results), 2)]
def metrics_from_mdl(mdl): """ Return a set() representing the metrics in the given MDL JSON object. Each entry is a tuple of either: ('entity', entity_name, metric_name) or ('role', role_name, metric_name) """ metrics = set() for entity_def in mdl['metricEntityTypeDefinitions']: for metric_d...
def url_to_qvalue(url: str) -> str: """Get q value from Wikidata url. http://www.wikidata.org/entity/Q494 -> Q494 """ return url.split("/")[-1]
def crop_from_quad(quad): """Return (left, top, right, bottom) from a list of 4 corners.""" leftmost = min([corner[0] for corner in quad]) topmost = min([corner[1] for corner in quad]) rightmost = max([corner[0] for corner in quad]) bottommost = max([corner[1] for corner in quad]) return (leftmo...
def _text2number_array(txt): """helper function""" rtn = [] try: for x in txt.split(","): rtn.append(float(x)) return rtn except: return None
def split(l, counts): """ >>> split("hello world", []) ['hello world'] >>> split("hello world", [1]) ['h', 'ello world'] >>> split("hello world", [2]) ['he', 'llo world'] >>> split("hello world", [2,3]) ['he', 'llo', ' world'] >>> split("hello world", [2,3,0]) ['he', 'llo', ...
def _validate_list_of_dict(list_of_dict): """ Validates that obj is a list containing dictionaries with entries for 'pr' and 'issue' """ return isinstance(list_of_dict, list) and 'pr' in list_of_dict[0] and 'issue' in list_of_dict[0]
def is_palindrome(number): """Check if number is the same when read forwards and backwards.""" if str(number) == str(number)[::-1]: return True return False
def parse_cqp(cqp): """Try to parse a CQP query, returning identified tokens and a boolean indicating partial failure if True. """ sections = [] last_start = 0 in_bracket = 0 in_quote = False in_curly = False escaping = False quote_type = "" for i in range(len(cqp)): ...
def pretty_str(label, arr): """ Generates a pretty printed NumPy array with an assignment. Optionally transposes column vectors so they are drawn on one line. Strictly speaking arr can be any time convertible by `str(arr)`, but the output may not be what you want if the type of the variable is not a...
def isAddress(address): """ Check if a string is an address / consists of hex chars only Arguments: string - the string to check Return: Boolean - True if the address string only contains hex bytes """ address = address.replace("\\x","") if len(address) > 16: return False return set(address.upper()) <= s...
def lerp(r, v1, v2): """"Linear intrpolation between v1, v2""" v1x, v1y = v1 v2x, v2y = v2 return (v1x + r * (v2x - v1x), v1y + r * (v2y - v1y))
def xtype_from_derivation(derivation): """Returns the script type to be used for this derivation.""" if derivation.startswith("m/84'"): return 'p2wpkh' elif derivation.startswith("m/49'"): return 'p2wpkh-p2sh' else: return 'p2pkh'
def to_lterm(t): """ back to our usual term form""" if not isinstance(t, tuple): return t h, bs = t cs = map(to_lterm, bs) ds = list(cs) return (h, ds)
def value_to_string(value, name): """Translates values (e.g. lists, ints, booleans) to strings""" def last(name): *prefix, base = name.split(".") return base if isinstance(value, list): return "x".join(map(str, value)) if isinstance(value, bool): return last(name) if va...
def tvi(b3, b4, b6): """ Transformed Vegetation Index (Broge and Leblanc, 2001). .. math:: TVI = 0.5 * (120 * (b6 - b3) - 200 * (b4 - b3)) :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :param b6: Red-edge 2. :type b6: numpy.ndar...
def _index_tuple_literal_eval(string: str): """Evaluates a string literal of form 'recipe_num, malt', and returns a tuple (recipe_num(int), malt(str)).""" rec_malt = string[1:-1].split(', ') rec = int(rec_malt[0]) malt = ', '.join(rec_malt[1:]) return rec, malt
def vpc_subnet_base_path(vpc_id): """Special case of subnet resource path""" return f'/v1/%(project_id)s/vpcs/{vpc_id}/subnets'
def remove_quotes(string): """Strip leading/trailing quotes from string, which VSCode strangely adds to arguments.""" if len(string) > 0 and string[0] == string[-1] and string[0] in ('"', "'"): return string[1:-1] if len(string) > 1 and string[0] == "b" and string[1] == string[-1] and string[1] in (...
def generate_labels(items, prefix='__'): """Given an array of items (e.g. events, intervals), create a synthetic label for each event of the form '(label prefix)(item number)' Parameters ---------- items : list-like A list or array of events or intervals prefix : str This prefix...
def buildPacketsInfo(count, total): """ Helper function to calculate data related with packets received from an asset Request parameters (all required): - count: number of packets of the type (up, down, lost) to calculate data for - total: number of packets in total Returns: - JSON w...
def _nmap(arg): """ Used by map call to return offspring field """ return arg['offspring']
def isfloat(value): """ Check if string can be parsed to a float. """ try: float(value) return True except ValueError: return False
def isvalid_ssl(sub, brackets): """ checks if substring is valid SSL IP7 """ valid = False if '[' in sub or ']' in sub: return "invalid" if sub[0] == sub[2] and sub[1] != sub[0]: if brackets == False: return "validaba" else: return "validbab" r...
def underride(d, **options): """Add key-value pairs to d only if key is not in d. d: dictionary options: keyword args to add to d :return: modified d """ for key, val in options.items(): d.setdefault(key, val) return d
def getValue(results, keys): """Borrowed from https://github.com/AlienVault-OTX/OTX-Python-SDK/tree/master/examples/is_malicious""" try: if type(keys) is list and len(keys) > 0: if type(results) is dict: key = keys.pop(0) if key in results: ...
def subsumes(paradigm_cell, morpheme): """Check if a vocabulary item subsumes the features in a paradigm cell. >>> cell = [['Nom', '+1', '-pl'], ['Acc', '+3', '-pl']] >>> subsumes(cell, [['+1', '-pl']]) True >>> subsumes(cell, [['+3', '-pl']]) True >>> subsumes(cell, [['+3'], ['+1']]) T...
def fahrenheit_to_celsius(value: float) -> float: """ returns round((value - 32) / 1.8, 2) Convert fahrenheit degrees to celsius degrees. Up to 2 point over zero. :param value: fahrenheit degrees :type value: float :returns: celsius value :rtype: float :Example: ...
def return_bounding_box_2d(x, y, xsize, ysize): """Return the bounding box :param x: x center :param y: y center :param xsize: x size :param ysize: y size :return: list(x1, y1, x2, y2) where (x1, y1) and (x2, y2) are the coordinates of the diagonal points of the ...
def getFromDict(dict, key, default): """ get value by key returns the value in dict or default value if no key in dict """ if key in dict: return dict[key] else: return default
def call_succeeded(response): """Returns True if the call succeeded, False otherwise.""" #Failed responses always have a success=False key. #Some successful responses do not have a success=True key, however. if 'success' in response.keys(): return response['success'] else: return T...
def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> kelvin_to_celsius(273.354, 3) ...
def list_of_dict_to_list(data, key): """Given a list of dicts, return a list of values for a given key. Crashes badly if the key is not present in each dict entry. @param data: the list of dicts @type data: lsit of dict @param key: the key to look for in the dict @type key: str @return: th...
def _escape_filename(filename): """Turns a file into a string representation with correctly escaped backslashes""" str_repr = str(filename) str_repr = str_repr.replace("\\", "\\\\") return str_repr
def concat_params(params): """Return list of params from list of (pname, ptype).""" name_and_types = [": ".join(p) for p in params] return ", ".join(name_and_types)
def is_substring(sub, main): """Check if a string is a substring of another.""" sub, main = sub.lower(), main.lower() subs = [] for i in range(0, len(main) - len(sub)): subs.append(main[i: i + len(sub)]) if sub in subs: return True return False
def parse_fastq_seqid(line): """Extracts read identifier and end identifier from different formats of FASTQ sequence IDs Args: line (str): sequence identifier from FASTQ file Returns: read_id (str): read identifier end_id (str): end identifier (if any) or empty string """ i...
def find_parts_to_upload(part_status): """ Given a string of the form "1001110", where 1 and 0 indicate a status of completed or not, return the part numbers that aren't completed. """ return [i+1 for i,c in enumerate(part_status) if c=='0']
def generate_primes(lower_limit, upper_limit): """Function to generate prime numbers from a given interval param lower_limit: int variable to store lower limit value param upper_limit: int variable to store upper limit value return: list of prime numbers """ if not isinstance(lower_limit, int)...
def get_list(elements): """ Return a list from set, tuple or single item :param elements: list, tuple, set, single obj :return: """ if isinstance(elements, list): return elements if isinstance(elements, set) or isinstance(elements, tuple): return list(elements) else: ...
def all_substrings(string): """ Function that gets all the substrings in a row. string: string return: list """ string = string.lower() substrings_list = [] substrings_list.append(string[0]) for character in range(len(string)): if ( ord(string[character]) >= 97...
def next_fib(a, b, n): """ returns produces the nth fibonacci numbers following a, b""" while n > 0: a, b = b, a+b n = n - 1 return b
def merge_sort(array): """merge sort""" n = len(array) if n > 1: mid = n // 2 left = array[:mid] right = array[mid:] merge_sort(left) merge_sort(right) i, j, k = 0, 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: ...
def prism_item_in_list(qury_item, list_of_items_to_check): """ Compare a single prism specifiation to a list of PRISM files returned by pyPRISMClimate.prism_iterator """ for item_to_check in list_of_items_to_check: matches = [item_to_check[key] == key_contents for key, key_contents in qury_...
def heading(section, guidance=""): """ Add a section heading and optionally some additional guidance for how to interpret the section. inputs ------ section : (str) the title of the section guidance : (str) guidance to be added in italics after the section heading default :...
def get_power_level(x, y, serial): """returns power level for the given x, y, and serial""" rack_id = x + 10 power = (((rack_id*y) + serial) * rack_id) if power > 99: return (power // 100) % 10 - 5 else: return -5
def iscomment(s): """ Tests if the argument is a string. Parameters ---------- s : string """ return s.startswith('#')
def _escape_special_chars(content): """No longer used.""" content = content.replace("\N{RIGHT-TO-LEFT OVERRIDE}", "") if len(content) > 300: # https://github.com/discordapp/discord-api-docs/issues/1241 content = content[:300] + content[300:].replace('@', '@ ') return content
def get_dtype(col_type, col_repr): """ Return the pandas type of a column based on the json schema for the dataset. Parameters ---------- col_type: str The abstract type of the data column (e.g. ``"finite"``, ``"countable/ordered"``, etc). col_repr: object Either a stri...
def filter_none(x): """ Recursively removes key, value pairs or items that is None. """ if isinstance(x, dict): return {k: filter_none(v) for k, v in x.items() if v is not None} elif isinstance(x, list): return [filter_none(i) for i in x if x is not None] else: return x
def get_config_interfaces_name_by_type(config_interfaces, type_str): """ Extract interface names matching specific type from Interface config :param config_interfaces: Interfaces config dict :param type_str: Type string to match :return: List of Interface names matching type_str """ interfac...
def d_stp(t_ref, t_in_situ, ds): """ Calculates viscosity from Mostafa H. Sharqawy 12-18-2009, MIT (mhamed@mit.edu) (Sharqawy M. H., Lienhard J. H., and Zubair, S. M., Desalination and Water Treatment, 2009) Viscosity used as input into Stokes-Einstein equation t_ref: reference temperature ...
def _find_nonkeepers(node): """ Return True for nodes we will delete. """ if 'fig_value' in node[1]: if 'dont_delete_me' not in node[1]: return True return False
def card_text(cardlist): """ Returns a string representing the cards in the list. """ return '[' + ' '.join(str(c) for c in cardlist) + ']'
def convert_spreadsheet_to_unix(val): """ This function converts a date from an Excel spreadsheet (which is an integer) into the number of seconds since the Unix epoch (which is also an integer). """ # Return answer .. return 86400 * (val - 25569)
def flip(f, b, a): """``flip :: (a -> b -> c) -> b -> a -> c`` Takes its (first) two arguments in the reverse order of `f`. """ return f(a, b)
def _tuple_from_tuple_or_dict(ob, fields): """Given a tuple/list/dict, return a tuple. Also checks tuple size. >> # E.g. >> _tuple_from_tuple_or_dict({"x": 1, "y": 2}, ("x", "y")) (1, 2) >> _tuple_from_tuple_or_dict([1, 2], ("x", "y")) (1, 2) """ error_msg = "Expected tuple/key/dict wit...
def num_neighbours(lag=1): """ Calculate number of neigbour pixels for a given lag. Parameters ---------- lag : int Lag distance, defaults to 1. Returns ------- int Number of neighbours """ win_size = 2 * lag + 1 neighbours = win_size**2 - (2 * (lag - 1) + 1...