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: ...
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, ...
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) ...
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....
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))) + ...
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] ...
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 e...
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 ...
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...
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 numb...
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 ...
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) >>> packRangeBi...
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 pr...
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(lam...
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 stac...
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"}}, {"mat...
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...
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("\...
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 =...
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...
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 a...
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 num...
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): ...
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'] = s...
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 t...
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, ...
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: ...
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_t...
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 aggregati...
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...
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 ...
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...
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 sc...
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 ret...
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 in...
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: ...
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: ...
def model_evapotranspiration(isWindVpDefined = 1, evapoTranspirationPriestlyTaylor = 449.367, evapoTranspirationPenman = 830.958): """ - Name: EvapoTranspiration -Version: 1.0, -Time step: 1 - Description: * Title: Evapotranspiration Model * Author: Pier...
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', 'st...
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}; ...
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' >>> ...
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('use...
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 wi...
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[...
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...
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] c...
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_da...
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 PROB...
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 sorte...
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...
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' : [ ...
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...
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: ...
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/psyco...
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 Dic...