content
stringlengths
42
6.51k
def trunc(x): """truncates a value to 2 (useful if behavior unchanged by increases)""" if x>2.0: y=2.0 else: y=x return y
def get_orientation(width, height): """ returns the orientation of an image. Returns ------- orientation : str 'landscape', if the image is wider than tall. 'portrait', otherwise. """ return 'landscape' if width > height else 'portrait'
def ZscoreNormalization(x, mean, std): """Z-score normaliaztion""" x = (x - mean) / std return x
def cohort_to_int(year, season, base=16): """cohort_to_int(year, season[, base]) Converts cohort tuple to a unique sequential ID. Positional arguments: year (int) - 2-digit year season (int) - season ID Keyword arguments: base (int) - base year to treat as 0 Returns: (int) - integer representing the number of seasons since the beginning of the base year """ return 3*(year - base) + season
def build_like(operator="AND", **kwargs): """Generates an SQL WHERE string. Will replace None's with IS NULL's. Keyword Args: Containing SQL search string Eg: ``{"foo": "x", "bar": None}`` Returns: Tuple containing string that can be used after LIKE in SQL statement, along with a list of the values. Eg. ("foo like ? AND bar IS NULL", [ "x%" ]) """ vals = [] query = [] for k in kwargs: if kwargs[k] is None: query.append(k + " IS NULL") else: query.append(k + " LIKE ?") vals.append(kwargs[k] + '%') if query: return ((" %s " % operator).join(query), vals) else: return (None, [])
def is_file_path(name): """Checks whether name is file path""" return name.startswith('/')
def get_link_status(predicted_spans, predicted_antecedents, gold_to_cluster_id, non_anaphoric): """ :param predicted_spans: from get_prediction() :param predicted_antecedents: :param gold_to_cluster_id, non_anaphoric: from get_gold_to_cluster_id() :return: dict of gold spans indicating wrong(False) or correct(True) link """ link_status = [] for doc_i in range(len(predicted_spans)): status_dict = {} # Only for gold mentions spans = predicted_spans[doc_i] for span_i, antecedent_i in enumerate(predicted_antecedents[doc_i]): span_cluster_id = gold_to_cluster_id[doc_i][spans[span_i]] if span_cluster_id == 0: continue if antecedent_i == -1: status_dict[spans[span_i]] = (spans[span_i] in non_anaphoric[doc_i]) else: antecedent_cluster_id = gold_to_cluster_id[doc_i][spans[antecedent_i]] status_dict[spans[span_i]] = (span_cluster_id == antecedent_cluster_id) link_status.append(status_dict) return link_status
def IRATaxCredit(earned_p, earned_s, MARS, AutoIRA_credit, ira_credit, c05800, e07300, iratc): """ Computes nonrefundable automatic enrollment in IRA tax credit. """ # not reflected in current law and records modified with imputation if AutoIRA_credit is True: iratc = max(0., ira_credit) else: iratc = 0. return iratc
def net_pack(triple, # Map PGSQL src/include/utils/inet.h to IP version number. fmap = { 4: 2, 6: 3, }, len = len, ): """ net_pack((family, mask, data)) Pack Postgres' inet/cidr data structure. """ family, mask, data = triple return bytes((fmap[family], mask or 0, 0 if mask is None else 1, len(data))) + data
def best_choice(func): """ Given a function, finds the input that gives the maximum output :param func: The function that will be used :return tuple: """ results = [func(x) for x in range(61)] l, m = 0, 0 for i in range(61): if results[i] > m: m = results[i] l = i return l, m
def enclose_param(param: str) -> str: """ Replace all single quotes in parameter by two single quotes and enclose param in single quote. .. seealso:: https://docs.snowflake.com/en/sql-reference/data-types-text.html#single-quoted-string-constants Examples: .. code-block:: python enclose_param("without quotes") # Returns: 'without quotes' enclose_param("'with quotes'") # Returns: '''with quotes''' enclose_param("Today's sales projections") # Returns: 'Today''s sales projections' enclose_param("sample/john's.csv") # Returns: 'sample/john''s.csv' enclose_param(".*'awesome'.*[.]csv") # Returns: '.*''awesome''.*[.]csv' :param param: parameter which required single quotes enclosure. """ return f"""'{param.replace("'", "''")}'"""
def bin2int(binList): """Take list representing binary number (ex: [0, 1, 0, 0, 1]) and convert to an integer """ # initialize number and counter n = 0 k = 0 for b in reversed(binList): n += b * (2 ** k) k += 1 return n
def verify_notebook_name(notebook_name: str) -> bool: """Verification based on notebook name :param notebook_name: Notebook name by default keeps convention: [3 digit]-name-with-dashes-with-output.rst, example: 001-hello-world-with-output.rst :type notebook_name: str :returns: Return if notebook meets requirements :rtype: bool """ return notebook_name[:3].isdigit() and notebook_name[-4:] == ".rst"
def GetKDPPacketHeaderInt(request=0, is_reply=False, seq=0, length=0, key=0): """ create a 64 bit number that could be saved as pkt_hdr_t params: request:int - 7 bit kdp_req_t request type is_reply:bool - False => request, True => reply seq: int - 8 sequence number within session length: int - 16 bit length of entire pkt including hdr key: int - session key returns: int - 64 bit number to be saved in memory """ retval = request if is_reply: retval = 1<<7 |retval retval = (seq << 8) | retval retval = (length << 16) | retval #retval = (retval << 32) | key retval = (key << 32) | retval return retval
def _translate_slice(exp, length): """ Given a slice object, return a 3-tuple (start, count, step) for use with the hyperslab selection routines """ start, stop, step = exp.indices(length) # Now if step > 0, then start and stop are in [0, length]; # if step < 0, they are in [-1, length - 1] (Python 2.6b2 and later; # Python issue 3004). if step < 1: raise ValueError("Step must be >= 1 (got %d)" % step) if stop < start: # list/tuple and numpy consider stop < start to be an empty selection return 0, 0, 1 count = 1 + (stop - start - 1) // step return start, count, step
def packRangeBits(bitSet): """Given a set of bit numbers, return the corresponding ulUnicodeRange1, ulUnicodeRange2, ulUnicodeRange3 and ulUnicodeRange4 for the OS/2 table. >>> packRangeBits(set([0])) (1, 0, 0, 0) >>> packRangeBits(set([32])) (0, 1, 0, 0) >>> packRangeBits(set([96])) (0, 0, 0, 1) >>> packRangeBits(set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 65, 98])) (4294967295, 1, 2, 4) >>> packRangeBits(set(range(128))) (4294967295, 4294967295, 4294967295, 4294967295) >>> 0xffffffff 4294967295 """ bitNum = 0 bitFields = [] for i in range(4): bitField = 0 for localBitNum in range(32): if bitNum in bitSet: mask = 1 << localBitNum bitField |= mask bitNum += 1 bitFields.append(bitField) assert bitNum == 128 ur1, ur2, ur3, ur4 = bitFields return ur1, ur2, ur3, ur4
def utility(z,mp): """ utility function Args: z(float): total assets mp (dictionary): given parameters Returns: float: utility of assets """ return (z**(1+mp['theta']))/(1+mp['theta'])
def two_sided_f(count1, count2, sum1, sum2): """computes an F score like measure""" # check input if not (sum1 and sum2): print("got empty sums for F scores") return 0 if sum1 < count1 or sum2 < count2: print("got empty sums for F scores") return 0 # calculate precision = count2 / sum2 recall = count1 / sum1 if precision + recall == 0: return 0 return 2 * (precision * recall) / (precision + recall)
def get_file_extension(filename: str) -> str: """Returns the file extension if there is one""" if '.' in filename: return filename.split('.')[-1] else: return ''
def get_iso_size(target): """Returns the file size of the target URL in bytes.""" if target.startswith("http"): return int(requests.get(target, stream=True) .headers["Content-Length"]) else: return 0
def apply_threshold(pred_prob_labels, threshold): """Sends every prediction in the list below the threshold (exclusive) to zero and everything above it (inclusive) to one. In the parlance of this file, turns predicted probablistic labels into predicted labels. Returns a list.""" return list(map(lambda pred: 1 if pred >= threshold else 0, pred_prob_labels))
def read(f, size): """Reads bytes from a file. Args: f: File object from which to read data. size: Maximum number of bytes to be read from file. Returns: String of bytes read from file. """ return f.read(size)
def pop(stack): """ Retrieves the last element from the given stack and deletes it, which mutates iti Parameters ---------- stack : list The stack (in list form) to be operated on Returns ------- value : char The value at the end of the given stack """ return stack.pop()
def query_tw_username(username): """ES query by Twitter's author.username Args: username (str) Returns: ES query (JSON) """ return { "query": { "bool": { "filter": [ {"term": {"doctype": "tweets2"}}, {"match": {"author.username": username}}, ] } } }
def format_faces_string(faces): """ format faces keywords """ print(faces) faces_str = ' '.join((str(val) for val in faces)) return faces_str
def invmod(a, p, maxiter=1000000): """The multiplicitive inverse of a in the integers modulo p: a * b == 1 mod p Returns b. (http://code.activestate.com/recipes/576737-inverse-modulo-p/)""" if a == 0: raise ValueError('0 has no inverse mod %d' % p) r = a d = 1 for i in range(min(p, maxiter)): d = ((p // r + 1) * d) % p r = (d * a) % p if r == 1: break else: raise ValueError('%d has no inverse mod %d' % (a, p)) return d
def update_reload_stats(reload, ammo, factor, enemy): """ :param reload: number of reloads available to the user. :param ammo: ammo available for the guns :param factor: factor by which the ammo needs to be increased :param enemy: enemy name :return: """ if reload != 0: print("\nLooks like you have run out of ammo. Let's make the reload quick") ammo += factor reload -= 1 print("You have " + str(ammo) + " rounds in your shotgun after reload") print("You have " + str(reload) + " reload s left.") else: print("Looks like you have run out of ammo. Good luck with the " + enemy + "!!") return reload, ammo
def get_occurrences(word, lyrics): """ Counts number of times a word is contained within a list Paramaters ---------- word : String Word to look for lyrics : String[] List of words to search through Returns ------- int num of occurences """ found = 0 for w in lyrics: if word in w: found = found + 1 return found
def inverse_mod(a, b): """ Taken from https://shainer.github.io/crypto/math/2017/10/22/chinese-remainder-theorem.html """ d = b x0, x1, y0, y1 = 0, 1, 1, 0 while a != 0: (q, a), b = divmod(b, a), a y0, y1 = y1, y0 - q * y1 x0, x1 = x1, x0 - q * x1 return x0 % d
def longestPalindrome( s): """ :type s: str :rtype: str """ n = len(s) table = [[0 for x in range(n)] for y in range(n)] print(table) # All substrings of length 1 are palindrones maxLength = 1 i = 0 # loop through list make all matricies true while (i < n): table[i][i] = True i = i + 1 # check for sub-string start = 0 i = 0 while i < n -1: if (s[i] == s[i + 1]): table[i][i + 1] = True start = i maxlength = 2 i = i+1 # Check for lengths greater than 2 # k is length of substring k = 3 while k <= n: # Fix the starting index i = 0 print(table) while i < (n - k + 1): # Get the ending index of # substring from starting # index i and length k j = i + k -1 # checking for sub-string from # i'th index to j'th index iff # st[i+1] to st[(j-1)] is a # palindrome if (table[i + 1][j - 1] and s[i] == s[j]): table[i][j] = True if (k > maxLength): if ( k > maxLength): start = i maxLength = k i = i + 1 k = k + 1 print(s[start:start+maxLength]) return s[start:start+maxLength]
def get_matchlog_str(table_type): """ Get valid strings to get matchlog data""" matchlog_dict = { "Scores & Fixtures": "schedule", "Shooting": "shooting", "Goalkeeping": "keeper", "Passing": "passing", "Pass Types": "passing_types", "Goal and Shot Creation": "gca", "Defensive Actions": "defense", "Possession": "possession", "Miscellaneous Stats": "misc", } return matchlog_dict[table_type]
def nlbs(t9): """Finds the library number tuples in a tape9 dictionary. Parameters ---------- t9 : dict TAPE9 dictionary. Returns ------- decay_nlb : 3-tuple Tuple of decay library numbers. xsfpy_nlb : 3-tuple Tuple of cross section & fission product library numbers. """ decay_nlb = [] xsfpy_nlb = [None, None, None] for n, lib in t9.items(): if lib["_type"] == "decay": decay_nlb.append(n) elif lib["_subtype"] == "activation_products": xsfpy_nlb[0] = n elif lib["_subtype"] == "actinides": xsfpy_nlb[1] = n elif lib["_subtype"] == "fission_products": xsfpy_nlb[2] = n decay_nlb.sort() return tuple(decay_nlb), tuple(xsfpy_nlb)
def fibonacci(strategy, n): """ Computes fibonacci using different strategies """ def classic_fb(n): """ Classic recursion approach """ if n == 0: return 0 elif n == 1: return 1 else: return classic_fb(n - 1) + classic_fb(n - 2) def binet_fb(n): """ Binet's Fibonacci Number Formula http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html """ import math return ( (1 + math.sqrt(5)) ** n - ( 1 - math.sqrt(5)) ** n) / (2**n*math.sqrt(5)) strategy_dict = {'classic': classic_fb, 'binet': binet_fb} return strategy_dict[strategy](n)
def isdatatype(object): """ Convinience method to check if object is data type. """ return isinstance(object, (str, int, bool, float, type(None)))
def echo(arg=None, state=None): """ We "echo" the arg back into the state so when our remote caller comes to pick the state back up they see we have actually done some work. """ if arg is None: arg = 1 if (arg % 10000) == 0: print("Running", arg) return arg
def _set_current_port(app_definition, service_port): """Set the service port on the provided app definition. This works for both Dockerised and non-Dockerised applications. """ try: port_mappings = app_definition['container']['docker']['portMappings'] port_mappings[0]['servicePort'] = service_port except (KeyError, IndexError): app_definition['ports'][0] = service_port return app_definition
def less_than_100(a:int, b: int) -> bool: """Determin if the sum of two numbers is less than 100.""" return sum((a,b,)) < 100
def max_difference_loc(L): """max difference loc will accept a list and return the location of the values that create the largest difference in which the larger value must come after the smaller one output will be a string with the first argument being the location of the small value and the second argument being the location of the larger value """ maxdiff = abs(L[1] - L[0]) loc = [] for i in range(len(L)): for j in range(i+1,len(L)): if L[j] - L[i] >= maxdiff: if j > i: loc = [i,j] maxdiff = L[j] - L[i] return loc
def camelCaseIt(snake_str): """ transform a snake string into camelCase Parameters: snake_str (str): snake_case style string Returns camelCaseStr (str): camelCase style of the input string. """ first, *others = snake_str.split('_') return ''.join([first.lower(), *map(str.title, others)])
def pod_condition_for_ui(conds): """ Return the most recent status=="True" V1PodCondition or None Parameters ---------- conds : list[V1PodCondition] https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1PodCondition.md """ if conds is None: return None maxCond = max(conds, key=lambda c: (c.last_transition_time, c.status == 'True')) return {"status": maxCond.status, "type": maxCond.type}
def get_filter_arg_owner(f, arg): """Convert integer to process owner string.""" arg_types = { 0x01: "self", 0x02: "pgrp", 0x03: "others", 0x04: "children", 0x05: "same-sandbox" } if arg in arg_types.keys(): return '%s' % (arg_types[arg]) else: return '%d' % arg
def format_mask(bit_offset, bit_width): """ Convert a bit offset and width into a mask. .e.g bit_offset5, bit_width=4 will convert to 0x1C0 """ return "0x%x" % (((1<<bit_width)-1)<<bit_offset)
def encode_event(timestamp, name, type): """Returns a string-encoded event representation. Example: '2021-03-27 12:21:50.624783+01:00,prepare,start'""" return f"{timestamp},{name},{type}"
def unwrap_filter(response, category): """ Strips one layer of aggregations (named by <category>) from a ElasticSearch query response, leaving it still in proper ES response format. :param response: An Elasticsearch aggregation response dictionary. :param category: Name of the topmost aggregation in the response. :returns: The same response, with one level of aggregation removed. """ unwrapped = response.copy() unwrapped['aggregations'] = response['aggregations'][category] return unwrapped
def get_soundex(token): """Get the soundex code for the string""" token = token.upper() soundex = "" # first letter of input is always the first letter of soundex soundex += token[0] # create a dictionary which maps letters to respective soundex codes. Vowels and 'H', 'W' and 'Y' will be represented by '.' dictionary = {"BFPV": "1", "CGJKQSXZ":"2", "DT":"3", "L":"4", "MN":"5", "R":"6", "AEIOUHWY":"."} for char in token[1:]: for key in dictionary.keys(): if char in key: code = dictionary[key] if code != soundex[-1]: soundex += code # remove vowels and 'H', 'W' and 'Y' from soundex soundex = soundex.replace(".", "") # trim or pad to make soundex a 4-character code soundex = soundex[:4].ljust(4, "0") return soundex
def myfloat(value, prec=6): """ round and return float """ return round(float(value), prec)
def process_data(data): """ bin data into day & tweet count """ labels = list(set(row["date"] for row in data)) labels.sort() values = [] for label in labels: count = sum(1 for row in data if row["date"] == label) values.append(count) return labels, values
def windows_ebic_quote(data): """100% secure""" data = data.replace('"', '""') return '"' + data + '"'
def out_of_china(lng, lat): """ """ return not (lng > 73.66 and lng < 135.05 and lat > 3.86 and lat < 53.55)
def maybe_instantiate(class_or_object): """Helper for :class:`ConfigType`. We want to allow passing uninstantiated classes ``String`` (instead of ``String()``) but we also want to allow instantiated ones as in ``List(String)``. I.e. the user can pass either a :class:`ConfigType` derived class, or an instantiated :class:`ConfigType` object. """ if isinstance(class_or_object, type): return class_or_object() else: return class_or_object
def digitize(n): """Convert integer to reversed list of digits.""" stringy = str(n) return [int(s) for s in stringy[::-1]]
def add(x, y): """ This function sums up two numbers. Parameters ---------- x : float The first number to be added. y : float The second number to be added. Returns ------- sum : float The sum of x and y. """ sum = x + y return sum
def insert_all(position, elements, list): """Inserts the sub-list into the list, at the specified index. Note that this is not destructive: it returns a copy of the list with the changes. No lists have been harmed in the application of this function""" return list[:position] + elements + list[position:]
def static_get_type_attr(t, name): """ Get a type attribute statically, circumventing the descriptor protocol. """ for type_ in t.mro(): try: return vars(type_)[name] except KeyError: pass raise AttributeError(name)
def _title_from_func_name(func_name): """Generates title for step from function name. Use only if given function name is in snake_case. """ return " ".join(func_name.split("_")).capitalize() + "."
def recursive_dict_update(d, u): """Recursive update() for nested dicts.""" for k, v in u.items(): if isinstance(v, dict): d[k] = recursive_dict_update(d.get(k, {}), v) else: d[k] = v return d
def format_size(size): """Return file size as string from byte size.""" for unit in ('B', 'KB', 'MB', 'GB', 'TB'): if size < 2048: return "%.f %s" % (size, unit) size /= 1024.0
def cleanPoints(points): """Delete the doublons but loose the order.""" return list(set(points))
def greyscale_image_from_color_image(image): """ Given a color image, computes and returns a corresponding greyscale image. Returns a greyscale image (represented as a dictionary). """ result = { 'height': image['height'], 'width': image['width'], 'pixels': [], } for p in image['pixels']: v = round(.299 * p[0] + .587 * p[1] + .114 * p[2]) result['pixels'].append(v) return result
def to_float(dataarray): """to_float. Ensures input array elements are in correct form of float to be accepted by scipy.stats.pearsonr (I genuinely don't know exactly why it complains). Args: dataarray (numpy array/list): An input array of what you think are sensible floats but cause scipy.stats.pearsonr to complain. Returns: array: an array of floats in the right form to stop scipy.stats.pearsonr complaining. """ output = [float(x) for x in dataarray] return output
def sum_risk_level(marked_locations): """ Sum risk level of all points combined :param points: marked points :return: sum of risk level """ counter = 0 for row in marked_locations: for point, is_lowest, _ in row: if is_lowest: counter += 1 + point return counter
def supress_none_filter(value): """Jinja2 filter to supress none/empty values.""" if not value: return '-' else: return value
def parse_line_update_success(tokens): """Parses line which logs stats for a successful write/update request.""" latency = float(tokens[2]) name = tokens[1] name_server = int(tokens[4]) local_name_server = int(tokens[5]) return latency, name, name_server, local_name_server
def title_string_solver(title) -> str: """Returns the string after stripping unnecessay data.""" return " ".join(title.split()[:-1]) if len(title.split()) > 1 else title.strip()
def remove_gaps(sequences): """ Function that removes any gaps ('-') from the protein sequences in the input. The descriptors cannot be calculated if a '-' value is passsed into their respective funtions so gaps need to be removed. Removing the gaps has the same effect as setting the value at the index of the sequence to 0 and has no effect on the descriptors calculation. Input can be string, list of array of sequences. Parameters ---------- sequences : str/list/np.ndarray string of 1 protein sequence or array/list of protein sequences. Returns ------- protein_seqs : np.ndarray returns the same inputted protein sequences but with any gaps ('-') removed. """ is_string=False #bool needed to ensure correct output format if input is str if isinstance(sequences, str): is_string = True sequences = [sequences] #convert single string into 1 element list #concatenate multiple sequences into 1 iterable list if isinstance(sequences, list) and \ len(sequences)>1: # for i in range(0,len(protein_seqs)): # protein_seqs[i] = ''.join(protein_seqs[i]) sequences = [''.join(sequences)] #iterate through sequences, removing any gaps ('-') for row in range(0, len(sequences)): try: sequences[row] = sequences[row].replace("-","") except: raise ValueError('Error removing gaps from sequences at index {} '.format(row)) #if input was str then join list of sequences into one str if is_string: sequences = ''.join(sequences) return sequences
def str2floatlist(str_values, expected_values): """Converts a string to 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) if len(values) < expected_values: return None for i in range(len(values)): values[i] = float(values[i]) #print('Read values: ' + repr(values)) return values
def ccall_except(x): """ >>> ccall_except(41) 42 >>> ccall_except(0) Traceback (most recent call last): ValueError """ if x == 0: raise ValueError return x+1
def _sabr_implied_vol_hagan_A4_fhess_by_underlying( underlying, strike, maturity, alpha, beta, rho, nu): """_sabr_implied_vol_hagan_A4_fhess_by_underlying See :py:func:`_sabr_implied_vol_hagan_A4`. :param float underlying: :param float strike: :param float maturity: :param float alpha: must be within [0, 1]. :param float beta: must be greater than 0. :param float rho: must be within [-1, 1]. :param float nu: volatility of volatility. This must be positive. :return: value of factor. :rtype: float. """ one_minus_beta = 1.0 - beta one_minus_beta_half = one_minus_beta / 2.0 one_minus_beta2 = one_minus_beta ** 2 two_minus_beta = 2.0 - beta three_minus_beta = 3.0 - beta five_minus_beta_half = (5.0 - beta) / 2.0 factor1 = underlying ** (-three_minus_beta) numerator1 = one_minus_beta2 * (alpha ** 2) * (-two_minus_beta) denominator1 = 24.0 * (strike ** one_minus_beta) term1 = numerator1 * factor1 / denominator1 factor2 = underlying ** (-five_minus_beta_half) numerator2 = rho * beta * nu * alpha * (-three_minus_beta) denominator2 = 16.0 * (strike ** one_minus_beta_half) term2 = numerator2 * factor2 / denominator2 return -(term1 + term2) * maturity * one_minus_beta
def model_evapotranspiration(isWindVpDefined = 1, evapoTranspirationPriestlyTaylor = 449.367, evapoTranspirationPenman = 830.958): """ - Name: EvapoTranspiration -Version: 1.0, -Time step: 1 - Description: * Title: Evapotranspiration Model * Author: Pierre Martre * Reference: Modelling energy balance in the wheat crop model SiriusQuality2: Evapotranspiration and canopy and soil temperature calculations * Institution: INRA Montpellier * ExtendedDescription: According to the availability of wind and/or vapor pressure daily data, the SiriusQuality2 model calculates the evapotranspiration rate using the Penman (if wind and vapor pressure data are available) (Penman 1948) or the Priestly-Taylor (Priestley and Taylor 1972) method * ShortDescription: It uses to choose evapotranspiration of Penmann or Priestly-Taylor - inputs: * name: isWindVpDefined ** description : if wind and vapour pressure are defined ** parametercategory : constant ** datatype : INT ** default : 1 ** min : 0 ** max : 1 ** unit : ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547 ** inputtype : parameter * name: evapoTranspirationPriestlyTaylor ** description : evapoTranspiration of Priestly Taylor ** variablecategory : rate ** default : 449.367 ** datatype : DOUBLE ** min : 0 ** max : 10000 ** unit : mm ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547 ** inputtype : variable * name: evapoTranspirationPenman ** description : evapoTranspiration of Penman ** datatype : DOUBLE ** variablecategory : rate ** default : 830.958 ** min : 0 ** max : 10000 ** unit : mm ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547 ** inputtype : variable - outputs: * name: evapoTranspiration ** description : evapoTranspiration ** variablecategory : rate ** datatype : DOUBLE ** min : 0 ** max : 10000 ** unit : mm ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547 """ evapoTranspiration = None if isWindVpDefined == 1: evapoTranspiration = evapoTranspirationPenman else: evapoTranspiration = evapoTranspirationPriestlyTaylor return evapoTranspiration
def concat_str(string_list): """ Concatenate all the strings in a possibly-nested list of strings @param str|list(str|list(...)) string_list: this string list. @rtype: str >>> list_ = ['the', 'cow', 'goes', 'moo', '!'] >>> concat_str(list_) 'the cow goes moo !' >>> list_ = ['this', 'string', 'is', 'actually', [['made'], 'up'], 'of', 'several', 'strings'] 'this string is actually made up of several strings' """ if isinstance(string_list, str): return string_list else: return ''.join([concat_str(elem) for elem in string_list])
def generate_green_cmtsolutions(py, cmtsolution_directory, output_directory): """ convert the raw cmtsolution files to tau=0. """ script = f"ibrun -n 1 {py} -m seisflow.scripts.source_inversion.make_green_cmtsolution --cmtsolution_directory {cmtsolution_directory} --output_directory {output_directory}; \n" return script
def twos_complement(number: int) -> str: """ Take in a negative integer 'number'. Return the two's complement representation of 'number'. >>> twos_complement(0) '0b0' >>> twos_complement(-1) '0b11' >>> twos_complement(-5) '0b1011' >>> twos_complement(-17) '0b101111' >>> twos_complement(-207) '0b100110001' >>> twos_complement(1) Traceback (most recent call last): ... ValueError: input must be a negative integer """ if number > 0: raise ValueError("input must be a negative integer") binary_number_length = len(bin(number)[3:]) twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:] twos_complement_number = ( ( "1" + "0" * (binary_number_length - len(twos_complement_number)) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number
def check_login(session): """ Function to check if the specified session has a logged in user :param session: current flask session :return: Boolean, true if session has a google_token and user_id """ # Check that session has a google_token if session.get('google_token') and session.get('user_id'): return True return False
def new_module(source_dir: str, prepend_text=None): """Creates a new module file consisting of all functions that reside in a given folder. This tool is intended to receive the path of a given folder where the individual function .py files reside, and it will retrieve the content of each of those .py files, and will put all of the content together in a single file in the "modules" directory (hard-coded within this script). The new single 'module' file will have the same name as the given "source_dir" folder + the ".py" extension. Additionally, the 'prepend_text' parameter can be used to add notes or import statements to the top of the module file (underneath the header, but before the functions are defined). Reference: https://stackoverflow.com/questions/47518669/create-new-folder-with-pathlib-and-write-files-into-it Args: source_dir (str): Reference the path of the directory where the function .py files reside prepend_text (str, optional): Use this parameter in order to add text underneath the banner but before all of the functions, e.g. "from scapy.all import *". Defaults to None. """ import pathlib source_dir_pathobj = pathlib.Path(source_dir).resolve() if not source_dir_pathobj.is_dir(): print('The given source_dir is not a directory.') return dest_dir_pathobj = pathlib.Path().home() / "Temp/pyplay/IMPORT_functions/Python_3.8_Tools/modules/" def new_module_header(source_dir_name: str): def format_header_block_plus(string: str): """Returns a header for use with my function files. Example: #######################################\n ########### ARRAY FUNCTIONS ###########\n #######################################\n """ newstring = "" newstring += "{0:#<39}".format("") + "\n" newstring += "{0:#^39}".format(f" {string} ") + "\n" newstring += "{0:#<39}".format("") + "\n\n" return newstring header_name = source_dir_name.replace('_', ' ').upper() new_header = format_header_block_plus(header_name) return new_header header_content = new_module_header(source_dir_pathobj.name) all_funcs_content_from_source_dir = ''.join([ e.read_text() for e in source_dir_pathobj.glob('*') if e.is_file() and e.name.endswith('.py')]) if prepend_text: full_content = header_content + prepend_text + all_funcs_content_from_source_dir else: full_content = header_content + all_funcs_content_from_source_dir new_module_name = source_dir_pathobj.name + '.py' module_filepath = dest_dir_pathobj / new_module_name with module_filepath.open('w') as f: f.write(full_content)
def get_pysam_outmode(fname: str): """ Based on the filename returns wz etc. :param fname: the output filename :return: string pysam mode """ mode = "wz" if fname.endswith("gz") else "w" return mode
def get_answer_value(answer, question_type=None): """ Get value of an answer based on it's question type - backend answers include question type since surveysystem #359 - public answers or legacy answers require question_type arg """ qtype = None if 'type' in answer: qtype = answer['type'] else: qtype = question_type if not qtype: raise ValueError('No type defined for anwser: {}'.format(answer)) # please keep below in the order types listed in survey.h if qtype == 'INT': return answer['value'] if qtype == 'MULTICHOICE': return answer['text'].split(',') if qtype == 'MULTISELECT': return answer['text'].split(',') if qtype == 'LATLON': return [answer['lat'], answer['lon']] if qtype == 'DATETIME': return answer['time_begin'] if qtype == 'DAYTIME': return answer['time_begin'] if qtype == 'TIMERANGE': return [answer['time_begin'], answer['time_end']] if qtype == 'UPLOAD': raise ValueError('"{}" type is not supported!'.format(qtype)) if qtype == 'TEXT': return answer['text'] if qtype == 'CHECKBOX': return answer['text'] if qtype == 'HIDDEN': return answer['text'] if qtype == 'TEXTAREA': return answer['text'] if qtype == 'EMAIL': return answer['text'] if qtype == 'SINGLECHOICE': return answer['text'] if qtype == 'SINGLESELECT': return answer['text'] if qtype == 'FIXEDPOINT': return answer['value'] if qtype == 'FIXEDPOINT_SEQUENCE': ret = [] parts = answer['value'].split(',') for part in parts: val = float(part) # could raise ValueError ret.append(val) return ret if qtype == 'DAYTIME_SEQUENCE': ret = [] parts = answer['value'].split(',') for part in parts: val = int(part) # could raise ValueError ret.append(val) return ret if qtype == 'DATETIME_SEQUENCE': ret = [] parts = answer['value'].split(',') for part in parts: val = int(part) # could raise ValueError ret.append(val) return ret if qtype == 'DURATION24': return answer['value'] if qtype == 'QTYPE_DIALOG_DATA_CRAWLER': return answer['text'] if qtype == 'QTYPE_SHA1_HASH': return answer['text'] if qtype == 'QTYPE_UUID': return answer['text'] raise ValueError('Unkown or unsupported question type "{}"'.format(qtype))
def vect3_scale(v, f): """ Scales a vector by factor f. v (3-tuple): 3d vector f (float): scale factor return (3-tuple): 3d vector """ return (v[0]*f, v[1]*f, v[2]*f)
def get_note_category(note): """get a note category""" if 'category' in note: category = note['category'] if note['category'] is not None else '' else: category = '' return category
def to_hass_level(level): """Convert the given FutureNow (0-100) light level to Home Assistant (0-255).""" return int((level * 255) / 100)
def _get_var(s): """ Given a variable in a variable assigment, return the variable (sometimes they have the negation sign ~ in front of them """ return s if s[0] != '~' else s[1:len(s)]
def format_bytes(n): """ Format bytes as text >>> format_bytes(1) '1 B' >>> format_bytes(1234) '1.23 kB' >>> format_bytes(12345678) '12.35 MB' >>> format_bytes(1234567890) '1.23 GB' >>> format_bytes(1234567890000) '1.23 TB' >>> format_bytes(1234567890000000) '1.23 PB' (taken from dask.distributed, where it is not exported) """ if n > 1e15: return "%0.2f PB" % (n / 1e15) if n > 1e12: return "%0.2f TB" % (n / 1e12) if n > 1e9: return "%0.2f GB" % (n / 1e9) if n > 1e6: return "%0.2f MB" % (n / 1e6) if n > 1e3: return "%0.2f kB" % (n / 1000) return "%d B" % n
def _passes_cortex_depth(line, min_depth): """Do any genotypes in the cortex_var VCF line passes the minimum depth requirement? """ parts = line.split("\t") cov_index = parts[8].split(":").index("COV") passes_depth = False for gt in parts[9:]: cur_cov = gt.split(":")[cov_index] cur_depth = sum(int(x) for x in cur_cov.split(",")) if cur_depth >= min_depth: passes_depth = True return passes_depth
def is_cscyc_colname(colname): """Returns 'True' if 'colname' is a C-state cycles count CSV column name.""" return (colname.startswith("CC") or colname.startswith("PC")) and \ colname.endswith("Cyc") and len(colname) > 5
def error_responses_filter(responses): """ :param responses: :return: """ return [each for each in filter(lambda r: r.status_code >= 400, responses)]
def fnAngleModular(a,b): """ Modular arithmetic. Handling angle differences when target flies from one quadrant to another and there's a kink in the az angles Created: 29 April 2017 """ diffabs = abs(b) - abs(a); return diffabs
def _convert_time(points): """Convert time points from HH:MM format to minutes.""" minutes = [] for point in points: hours, mins = str(point).split(':') minutes.append(int(hours) * 60 + int(mins)) return minutes
def filter_by_date(data, date_field, compare_date): """Summary Args: data (TYPE): Description date_field (TYPE): Description compare_date (TYPE): Description Returns: TYPE: Description """ return [record for record in data if record[date_field] >= compare_date]
def wears_jacket(temp, raining): """Returns true if the temperature is less than 60 degrees OR it is raining >>> wears_jacket(90, False) False >>> wears_jacket(40, False) True >>> wears_jacket(100, True) True """ """BEGIN PROBLEM 1.1""" return raining or temp < 60 """END PROBLEM 1.1"""
def _ParseDomainOpsetVersions(schemas): """ Get max opset version among all schemas within each domain. """ domain_opset_versions = dict() for domain_version_schema_map in schemas.values(): for domain, version_schema_map in domain_version_schema_map.items(): # version_schema_map is sorted by since_version in descend order max_version = next(iter(version_schema_map)) if domain not in domain_opset_versions: domain_opset_versions[domain] = int(max_version) else: domain_opset_versions[domain] = max( domain_opset_versions[domain], int(max_version) ) return domain_opset_versions
def not_pattern_classifier(data, pattern_threshold): """Return an array mask failing our selection.""" return data["key_pattern"] <= pattern_threshold
def read_ccloud_config(config_file): """Read Confluent Cloud configuration for librdkafka clients Configs: https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md """ conf = {} with open(config_file) as fh: for line in fh: line = line.strip() if len(line) != 0 and line[0] != "#": parameter, value = line.strip().split("=", 1) conf[parameter] = value.strip() return conf
def searchFoodByText(query): """ # --- GET method pake query """ # Initialize data data = {} # Do querying and check for the result # Currently using dummy data result = { 'success' : True, 'message' : 'Some message', 'data' : [ { 'id': 0, 'name': 'Tahu', 'city': 'Jakarta', 'image': 'localhost' }, { 'id': 0, 'name': 'Tahu', 'city': 'Jakarta', 'image': 'localhost' } ] } if not result: return {'success' : False, 'message' : f'Query {query} doesnt match any object.'} data = result return data
def get_pep_dep(libname: str, version: str) -> str: """Return a valid PEP 508 dependency string. ref: https://www.python.org/dev/peps/pep-0508/ >>> get_pep_dep("riot", "==0.2.0") 'riot==0.2.0' """ return f"{libname}{version}"
def get_brand(api_data) -> str: """ Returns plain text """ brand = api_data['brand'].strip() if brand is None or brand == "": brand = "n/a" return brand
def polynomial_mul_polynomial(a, b): """ Multiplication function of two polynomials. :param a: First polynomial. :param b: Second polynomial. :return: The result of multiplication two polynomials """ number_type = type(a[0]) if a else type(b[0]) if b else float len_a, len_b = len(a), len(b) c = [number_type(0)] * (len_a + len_b) for i in range(len_a): for j in range(len_b): c[i + j] += a[i] * b[j] return c
def find_routes(routes, uri, is_sub_page=False): """ Returns routes matching the given URL, but puts generator routes at the end. """ res = [] gen_res = [] for route in routes: metadata = route.matchUri(uri) if metadata is not None: if route.is_source_route: res.append((route, metadata, is_sub_page)) else: gen_res.append((route, metadata, is_sub_page)) return res + gen_res
def get_bezier3w_point(point_a,point_b,point_c,w,t): """gives the point t(between 0 and 1) on the defined bezier curve with w as point_b influence""" return (point_a*(1-t)**2+2*w*point_b*t*(1-t)+point_c*t**2)/((1-t)**2+2*w*t*(1-t)+t**2)
def end_substr(original, substr): """Get the index of the end of the <substr>. So you can insert a string after <substr> """ idx = original.find(substr) if idx != -1: idx += len(substr) return idx
def parse_pg_dsn(dsn): """ Return a dictionary of the components of a postgres DSN. >>> parse_pg_dsn('user=dog port=1543 dbname=dogdata') {"user":"dog", "port":"1543", "dbname":"dogdata"} """ # FIXME: replace by psycopg2.extensions.parse_dsn when available # https://github.com/psycopg/psycopg2/pull/321 return {c.split("=")[0]: c.split("=")[1] for c in dsn.split() if "=" in c}
def get_key_and_value_by_insensitive_key_or_value(key, dict): """ Providing a key or value in a dictionary search for the real key and value in the dictionary ignoring case sensitivity. Parameters ---------- key: str Key or value to look for in the dictionary. dict: dict Dictionary to search in. Returns ------- real key, real value: (str, str) or (None, None) The real key and value that appear in the dictionary or a tuple of Nones if the input key is not in the dictionary. """ lower_key = key.lower() for real_key, real_value in dict.items(): if real_key.lower() == lower_key or real_value.lower() == lower_key: return real_key, real_value return None, None