content
stringlengths
42
6.51k
def find_first(value, vector): """Find the index of the first occurence of value in vector.""" for i, v in enumerate(vector): if value == v: return i return -1
def invertMove(move): """--> inverted move. (0 becomes1 and 1 becomes 0)""" if move == 0: return 1 else: return 0
def rgb_maximize(r, g, b, scale=255): """ Calculates full luminosity RGB values from rgb chromacity coordinates :param r: Red ratio :param g: Green ratio :param b: Blue ratio :param scale: Output R,G,B values scale :return: RGB tuple """ ratio = scale / max(r, g, b) return tuple(int(...
def serialize_key(key) -> str: """Convert a key to its string representation. String inputs are assumed to be already properly serialized. """ if not isinstance(key, str): key = repr(key) return key
def match(line, keyword): """ If the first part of line (modulo blanks) matches keyword, returns the end of that line. Otherwise checks if keyword is anywhere in the line and returns that section, else returns None""" line = line.lstrip() length = len(keyword) if line[:length] == keyword: ...
def sanitize_resource_name(name): """ Each AWS::IAM::Role resource name will have the same name from roles.json file. Cloudformation doesn't allow dash character '-', so replace '-' with 'Dash'. """ return f'{name.replace("-", "Dash")}Resource'
def theta_to_T(theta,p,p0=1000.): """Calculate (virtual) temperature [K], from (virtual) potential temperature, theta, [K] and pressure p [mbar] using Poisson's equation. Standard pressure p0 at sea level is 1000 mbar or hPa. Typical assumptions for dry air give: R/cp = (287 J/kg-K) / (1004 J...
def isutf8(data): """Simple heuristic to determine if a bytestring uses standard unicode encoding""" try: data.decode('UTF-8') except UnicodeDecodeError: return False else: return True
def single(mjd, hist=[], **kwargs): """cadence requirements for single-epoch Request: single epoch mjd: float or int should be ok hist: list, list of previous MJDs """ # return len(hist) == 0 sn = kwargs.get("sn", 0) return sn <= 1600
def convert_password(password): """Stores password as system_metadata items. Password is stored with the keys 'password_0' -> 'password_3'. """ CHUNKS = 4 CHUNK_LENGTH = 255 password = password or '' meta = {} for i in range(CHUNKS): meta['password_%d' % i] = password[:CHUNK_LEN...
def get_object_env_key(account, container, obj): """ Get the keys for env (env_key) where info about object is cached :param account: The name of the account :param container: The name of the container :param obj: The name of the object :returns a string env_key """ env_key = 'swift.ob...
def _sample_value(dictionary): """ Selects a value from a dictionary, it is always the same element. """ return list(dictionary.values())[0]
def dict_merge_values(d1, d2, default=0): """ Return a new dict of {key: (value1, value2); ...} """ d = {} for k,v in d1.items(): d[k] = (v, default) for k,v in d2.items(): d[k] = (d.get(k, (default,default))[0], v) return d
def find_from(board, word, y, x, seen): """Can we find a word on board, starting at x, y?""" # This is called recursively to find smaller and smaller words # until all tries are exhausted or until success. # Base case: this isn't the letter we're looking for. if board[y][x] != word[0]: pr...
def search_string(string_value, value_1, value_2): """Return search list result.""" start_string = "" end_string = "" middle_string = "" start_true = True end_true = False middle_true = False search_list = [] for character in string_value: if value_1 == character: ...
def inp_search_token_value(lines, token): """Get the value of a token from a list""" for i in range(0, len(lines)): if lines[i]==token: return lines[i+1] return False
def MODULE_PATH(analysis_module): """Returns the "module_path" used as a key to look up analysis in ACE.""" return '{}:{}'.format(analysis_module.__module__, analysis_module.__name__ if isinstance(analysis_module, type) else type(analysis_module).__name__)
def bit_on(num: int, bit: int) -> int: """Return the value of a number's bit position. For example, since :math:`42 = 2^1 + 2^3 + 2^5`, this function will return 1 in bit positions 1, 3, 5: >>> [bit_on(42, i) for i in range(clog2(42))] [0, 1, 0, 1, 0, 1] """ return (num >> bit) & 1
def coerce_to_int(s): """ Turn a string into an integer. """ try: return int(s) except ValueError: return int(s.lower() not in ("false", "no", "off"))
def giip(area=40, res_height=20, porosity=0.25, avg_water_saturation=0.4, gas_vol_factor=0.00533): """Returns the estimate for gas initially in place (SCF) given the area (acres), reservoir height (ft), porosity (fraction), average water saturation (fraction), and the gas formation volume factor (RCF/SCF).""" ...
def solve(st): """Return True if a string is palindrome after rotating to left.""" def is_palindrome(st): return str(st) == str(st)[::-1] if is_palindrome(st) is True: return True st_list = list(str(st)) for i in range(0, len(st_list)): last = st_list.pop() st_list.in...
def dim_pad(n,BDIM): """ return smallest multiple of BDIM larger than n """ mult=int((n+BDIM-1)/BDIM) return mult*BDIM
def normint(n,m): """coefficient of int^m x^n dx""" c=1 for i in range(m): c*=n+i+1 return c
def get_model_name(url): """ Return a model short name based on its endpoint. Examples -------- >>> url = ('http://omgsrv1.meas.ncsu.edu:8080/thredds/dodsC/fmrc/sabgom/' ... 'SABGOM_Forecast_Model_Run_Collection_best.ncd') >>> get_model_name(url) 'fmrc-SABGOM_Forecast_Model_Run_C...
def distance(x1, x2, y1, y2): """Returns the distance between two coords""" return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
def condify_name(name, name_replacements=None): """Given a name, replace the package name with its entry, if any, in the dict name_replacements, otherwise make the package name lowercase and replace, underscores with hyphens.""" if name_replacements is None: name_replacements = {} return nam...
def caesar_encode(p_offset, p_input_text): """ Encode a text using caesar method with an specific offset :param p_offset: offset that will be used with the alphabet :param p_input_text: text that will be cyphered :return: the text cyphered """ alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" outp...
def word_len(word): """Returns the word lenght, minus any color codes.""" if word[0] == '\x1b': return len(word) - 11 # 7 for color, 4 for no-color return len(word)
def _get_position(a, n): """ returns position of substring :n: as "start", "end" or "middle" """ position = a.index(n) if position == 0: return ("start", position) elif position+len(n) == len(a): return ("end", position) else: return ("middle", position)
def makeBarcode(barcode): """ Construct label with sampleName as human readable and barcode """ lines = [] lines.append("^XA") # start of label # download and store format, name of format, # end of field data (FS = field stop) lines.append("^DFFORMAT^FS") lines.append("^LH0,0") # label hom...
def _final_states(x): """ Get the final states if `x` is a dictionary. Args: x: A dictionary of states or others. Returns: `x` if `x` is not a dictionary, otherwise, a list of values in `x`. """ if isinstance(x, dict): ret = [] for k, v in x.items(): ret.append(...
def bbox(vertices): """Compute bounding box of vertex array. """ if len(vertices)>0: minx = maxx = vertices[0].co.x miny = maxy = vertices[0].co.y minz = maxz = vertices[0].co.z for v in vertices[1:]: if v.co.x < minx: minx = v.co.x e...
def linux_folder_path(folder_path): """assert folder_path ending with '/' """ folder_path = folder_path.replace('\\', '/').replace(' ', '\ ') if folder_path.endswith('/'): pass else: folder_path = folder_path + '/' return folder_path
def build_new_activity_notification(course_name, activity_name, activity_type): """ Build the notification message with the variables from the JSON response. :param activity_type: The type of the activity. Either quiz or assignment. :type activity_type: str :param course_name: The name of the cours...
def index_of_value(a,value): """ Get value of index that is closest to value in the array/list a. """ return min(range(len(a)),key=lambda i: abs(a[i] - value))
def to_slice(k, forty_five_deg, D_dimensions_to_check): """ :param k: axis idx. :param forty_five_deg: bool determining if to slice in 45 deg. :param D_dimensions_to_check: The dimensions to check by the user. :return: When to slice the volume (in which axis/45 deg angles). """ if k not in D...
def private_url(method: str) -> str: """Return the private URL for a given method.""" return f"private/{method}"
def uniqueDictListWithOrder(lst): """ Return new list with preserved the original order of the list. It works only with list of dicts. """ used = set() result = [] for elem in lst: key = frozenset(elem.items()) if key in used: continue result.append(elem)...
def split_into_tags(tags_block): """Split tag block into lines representing each tag.""" tags_block_lines = tags_block.split("\n")[1:] splitted_tags_block = [] i = 0 for line in tags_block_lines: if len(splitted_tags_block) <= i: splitted_tags_block.append([]) line = line...
def average_precision_at_k(targets, ranked_predictions, k=None): """Computes AP@k given targets and ranked predictions.""" if k: ranked_predictions = ranked_predictions[:k] score = 0.0 hits = 0.0 for i, pred in enumerate(ranked_predictions): if pred in targets and pred not in ranked_...
def get_context_data(data) -> dict: """Look for 'context' item in 'queries' item.""" if "queries" in data: if "context" in data["queries"]: if isinstance(data["queries"], list): return data["queries"][0]["context"] else: return data["queries"]["con...
def hourBasedAverageAllOwls(array): """ array = [ (hour, distance, idx, owlId), ... ] """ arraySorted = sorted(array, key=lambda x: x[0]) lastHour = -1 distance = 0 amountOwls = 0 distPerHour = [] currentHour = -1 for idx, entry in enumerate(arraySorted): cu...
def base_n(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz", pad=-1): """ Parameters ---------- num : int b : int Base numerals : str pad : int """ number = (((num == 0) and numerals[0]) or (base_n(num // b, b, numerals, pad).lstrip(numerals[0]) + ...
def ref(subject, name): """Return a named reference to the given state.""" if hasattr(subject, "__ref__"): return subject.__ref__(name) else: return subject
def poly_f(x, c): """Calculate the value of the f(x) based on the polynomial method provided by the question: f(t) = c[k-1] * pow(t, k-1) + c[k-2] * pow(t, k-2) + ... + c[0] * 1 """ f_x = 0 for i in range(len(c)): f_x += pow(x, i) * c[i] return f_x
def replace_dict_values(source, replacements): """Creates a copy of the source dictionary and replaces all values specified in a replacement list :param source: The source dictionary :param replacements: The replacements. This is a list of key/value tuples, where dots in the key describe the hierarchy ...
def _process_chunk(fn, chunk): """Processes a chunk of an iterable passed to map. Runs the function passed to map() on a chunk of the iterable passed to map. This function is run in a separate process. """ return [fn(*args) for args in chunk]
def tab_to(num_tabs, line): """Append tabs to a line of text to reach a tab stop. Args: num_tabs: Tab stop to obtain (0 = column 0, 1 = column 8, etc.) line: Line of text to append to Returns: line with the correct number of tabs appeneded. If the line already extends past ...
def config_loader_mock_no_creds(config_key): """Return mocked config values.""" if config_key == "energy_recorder.api_url": return "http://pod-uri:8888" elif config_key == "energy_recorder.api_user": return "" elif config_key == "energy_recorder.api_password": return "" else:...
def _count_words(s): """count the number of words in a paragraph Args: [String] s Return: [INT] number of words in the string """ return len(s.split(" "))
def computeLastHitValues(blocks): """ given the query length and 'blocks' string from a last hit return the: match length the blocks string looks something like this: "73,0:1,15,0:1,13,0:1,9" where integer elements indicate lenghts of matches and colon separated elements...
def my_UniformSeligProfileFunction(eps): """Essentially, return all the profile specific arguments which define the airfoil profile at a given epsilon as a dictionary of KEYWORD: VALUE pairs The leading edge, twist, rotation, leading edge, and chord parameters do not need to be passed to this function,...
def factorial(n): """ Defined my own factorial just in case using python2.5 or less. :param n: :return: """ if n>0 and n<2: return 1 if n>=2: return n*factorial(n-1)
def humanize_timedelta(seconds): """Creates a string representation of timedelta.""" hours, remainder = divmod(seconds, 3600) days, hours = divmod(hours, 24) minutes, seconds = divmod(remainder, 60) if days: result = '{}d'.format(days) if hours: result += ' {}h'.format(h...
def is_there_a_global(name): """ Simple utility to interrogate the global context and see if something is defined yet. :param name: Name to check for global definition in this module. :returns: Whether the target ``Name`` is defined in module globals and is not falsy. """ gl = ...
def correct_barcode(barcode, mismatch_map): """ Correct an observed raw barcode to one of a list of whitelists of mismatches. Args: barcode (string): barcode sequence to be corrected mismatch_map (list of dict dict): list of dict of mismatched sequences to real sequences Returns:...
def _unescape_entities(text): """ unescape offending tags < > " & """ text = text.replace(b'&lt;', b'<') text = text.replace(b'&gt;', b'>') text = text.replace(b'&quot;', b'"') text = text.replace(b'&amp;', b'&') return text
def dtypes2pg(dtype): """Returns equivalent PostgreSQL type for input `dtype`""" mapping = { 'float64': 'numeric', 'int64': 'numeric', 'float32': 'numeric', 'int32': 'numeric', 'object': 'text', 'bool': 'boolean', 'datetime64[ns]': 'timestamp', } r...
def convert_one_hot (num, range): """ Convert num in range 1-range to 1-hot encoding """ encoding = [0]*range encoding[num - 1] = 1 return encoding
def _find_files(metadata): """ .. versionadded:: 3001 Looks for all the files in the Azure Blob container cache metadata. :param metadata: The metadata for the container files. """ ret = {} for container, data in metadata.items(): if container not in ret: ret[containe...
def is_value(s): """Test if parameter is a number or can be interpreted as a number""" s = str(s) return s.isdigit() or (len(s) == 1 and s[0] in "AJQK")
def atoi(num_str): """ Helper function which converts a string to an integer, or returns None. """ try: return int(num_str) except: pass return None
def covariance(co_elements, first_set, second_set, first_set_avg, second_set_avg): """ Description A function which returns the covariance between two elements. Arguments :param co_elements: Number of co-elements. :type co_elements: int :param first_set: The f...
def extend_dict(d1, d2): """Extends d1 with d2, removing duplicates from d1""" d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) return dict(**{o: d1[o] for o in d1_keys - intersect_keys}, **d2)
def Nu(Ra, Pr): """ Calculation of Nusselt number for natural convection. See eq. 4.7-4 and Table 4.7-1 in C. J. Geankoplis Transport Processes and Unit Operations, International Edition, Prentice-Hall, 1993 Parameters ---------- Ra : float Raleigh number Pr : float Pr...
def has_solution(cell): """Return True if cell is marked as containing an exercise solution.""" cell_text = cell["source"].replace(" ", "").lower() first_line = cell_text.split("\n")[0] return ( cell_text.startswith("#@titlesolution") or "to_remove" in first_line and "explanation...
def absmax(x): """ Returns ``abs(x).b`` for an interval, or ``abs(x)`` for anything else. """ if hasattr(x, '_mpi_'): return abs(x).b return abs(x)
def _str(byte, codec=None): """convert bytes to string using the given codec (default is 'ascii')""" if codec is False or not hasattr(byte, 'decode'): return byte return byte.decode(codec or 'ascii')
def query_to_string(query_result: list) -> list: """Converts a query result in a well formatted list of rows Args: query_result (list): query result to be converted Returns: list: the corrisponding list of rows """ result = [] for row in query_result: result.append([val...
def lstripw(string, chars): """Strip matching leading characters from words in string""" return " ".join([word.lstrip(chars) for word in string.split()])
def _collection_sample_limits(limits): """ Assure that the limit values are not None and have reasonable values """ build = lambda gran, coll : {'granule': gran, 'collection': coll} bound = lambda lower, value, upper : min(max(lower, value), upper) default_granule_limit = 10 default_collect...
def round_channels(channels, divisor=8): """ Round weighted channel number (make divisible operation). Parameters: ---------- channels : int or float Original number of channels. divisor : int, default 8 Alignment value. Returns: ------- int ...
def flatten_properties(props): """ Fetch data data from api metadata properties """ ret = dict() for key, val in props.items(): if type(val) == dict: sub_props = flatten_properties(val) for subkey, subval in sub_props.items(): ret[key + '/' + subkey] = subval ...
def find_largest_prime_factor(number): """Returns largest prime factor of `number` Args: number (int) : The number to be factorised Returns: number (int) : The largest prime factor of `number` """ i = 2 while i * i < number: while number % i == 0: number = n...
def dict_to_str(dictionary): """Get a `str` representation of a `dict`. Args: dictionary: The `dict` to be represented as `str`. Returns: A `str` representing the `dictionary`. """ return ', '.join('%s = %s' % (k, v) for k, v in sorted(dictionary.items()))
def bitcount(num): """ Count the number of bits in a numeric (integer or long) value. This method is adapted from the Hamming Weight algorithm, described (among other places) at http://en.wikipedia.org/wiki/Hamming_weight Works for up to 64 bits. :Parameters: num : int The ...
def parse_quant(quant): """ Normalise quanitifers """ if quant.startswith('}{'): quant = quant.strip('}{ ') if ',' in quant: return quant.replace(',', ':') else: return quant return quant
def get_dict_from_list(list_of_dicts, key_value, key='id'): """ Returns dictionary with key: @prm{key} equal to @prm{key_value} from a list of dictionaries: @prm{list_of_dicts}. """ for dictionary in list_of_dicts: if dictionary.get(key) == None: raise Exception("No key: " + key ...
def window_validator(value): """ Supported window values: 4, 8, 16 """ if not value.isnumeric: raise TypeError("Select a valid vlaue.") elif int(value) in (4, 8, 16): return int(value) else: raise TypeError("Select a valid vlaue.")
def pair_prob_hg(k, N, Nx, Ny): """ Calculate the probability to draw k times type(Ny) out of N elements (whereof Ny type(Ny)s), when drawing Nx times in total. Same as hypergemoetric distribution """ if (k > Nx) or (k > Ny): print("Given 'k' must be <= Nx and <= Ny.") import ma...
def merge_fn1(seq, i, ht, key, count): """Merges new extra data to existing extra data in a node.""" if ht is None: return {key: count} if key in ht: ht[key] += count else: ht[key] = count return ht
def red(text): """ Return this text formatted red """ return '\x0304%s\x03' % text
def depigmentation(rpedwi): """ RPEDWI: RPE DEPIGMENTATION AREA W/I GRID 0=None 1=Quest 2=<I2 3=<O2 4=<1/2 DA 5=<1DA 6=<2DA 7=>2DA 8=CG Returns: 0, 1, 88 """ if rpedwi == 0: return 0 elif 1 <= rpedwi <= 7: ...
def QuatMult(q1, q2): """Performs a quaternion product.""" q10, q1x, q1y, q1z = q1 q20, q2x, q2y, q2z = q2 Q0 = (q10*q20 - q1x*q2x - q1y*q2y - q1z*q2z) Qx = (q10*q2x + q1x*q20 + q1y*q2z - q1z*q2y) Qy = (q10*q2y - q1x*q2z + ...
def FindDBLocations(DB, Aminos): """ Find all occurrences of this peptide in the database. Return DB indices. """ PrevPos = -1 LocationList = [] while (1): Pos = DB.find(Aminos, PrevPos + 1) if Pos == -1: break LocationList.append(Pos) PrevPos = Po...
def MergeDicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict. Precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def get_letter(constellation): """ Return the correct letter. """ if constellation == 'Starlink': return 'A' elif constellation == 'OneWeb': return 'B' elif constellation == 'Kuiper': return 'C' else: print('Did not recognize constellation')
def setbit(byte, offset, value): """ Set a bit in a byte to 1 if value is truthy, 0 if not. """ if value: return byte | (1 << offset) else: return byte & ~(1 << offset)
def intersection_idx(lists): """ intersection of multiple lists. Returns intersection and corresponding indexes Args: lists: list of lists that need to intersect Returns: intersect_list: list of intersection result """ idx_dict_list = [] # create index dictionary for l in lists:...
def array11(arr, index): """ :return: number of times 11 occurs in arr """ if index >= len(arr): return 0 if arr[index] == 11: return 1 + array11(arr, index+1) else: return array11(arr, index+1)
def map_range(value, from_min, from_max, to_min, to_max): """Performs a linear interpolation of a value within the range of [from_min, from_max] to another range of [to_min, to_max]. """ from_range = from_max - from_min to_range = to_max - to_min value_scaled = (value - from_min) / float(fro...
def cohens_d(mu_1, mu_2, std): """ Compute the standardized effect size as difference between the two means divided by the standard deviation. Parameters ---------- mu_1 : float Mean of the first sample. mu_2 : float Mean of the second sample. std : float > 0 Pooled...
def get_mutations(by_lineage): """ Extract common mutations from feature vectors for each lineage :param by_lineage: dict, return value from process_feed() :return: dict, common mutations by lineage """ result = {} for lineage, samples in by_lineage.items(): # enumerate features ...
def make_list(arg): """Return a list with arg as its member or arg if arg is already a list. Returns an empty list if arg is None""" return (arg if isinstance(arg, list) else ([arg] if arg is not None else []))
def calculate_fuel(mass): """Calculates the fuel necessary for the provided mass.""" return (mass // 3) - 2
def value_to_string(value, fmt): """ Convert numerical value to string with a specific format """ return "{value:>{fmt}}".format(value=value, fmt=fmt).strip()
def bykey(d, key_name): """Return d[key_name] (as opposed to the normal behavior, d['key_name']""" try: return d[key_name] except KeyError: return ''
def rgb2hex(rgb): """Convert RGB to Hex color.""" h = "#%02x%02x%02x" % (int(rgb[0]), int(rgb[1]), int(rgb[2])) return h
def _non_projective(u, v, w, x): """ Checks if an edge pair is non-projective """ mnu = min(u, v) mxu = max(u, v) mnw = min(w, x) mxw = max(w, x) if mnu < mnw: return (mxu < mxw) and (mxu > mnw) elif mxu > mxw: return (mnu > mnw) and (mnu < mxw)
def map_stype(mode: str): """Map the scattering type in PDFConfig to the stype in the meta in the parser.""" if mode in ('xray', 'sas'): stype = 'X' elif mode == 'neutron': stype = 'N' else: raise ValueError( "Unknown: scattering type: {}. Allowed values: 'xray', 'neu...