content
stringlengths
42
6.51k
def get_subcoord(isb, iLevel=0): """ isb : cardinal of the sub-block inside the memory (or root) block iLevel : level of bipartition """ ibb = isb % 8 scoord_r = (ibb % (2**1))/(2**0) scoord_ph = (ibb % (2**2))/(2**1) scoord_th = (ibb % (2**3))/(2**2) """ Depending on...
def simplifyRoles(roles): """Sorts and removes duplicates from a role list.""" return sorted(set(roles))
def to_update_kwargs(attributes): """ For an attribute dictionary, make a default update expression for setting the values Notes: Use an expression attribute name to replace that attribute's name with reserved word in the expression, reference can be found here: http://docs.aws.amazon.com/amazondyn...
def generate_option(value): """ Generate option to pass to babel_extract() from a TEMPLATES['OPTION'] value setting. babel_extract() options are meant to be coming from babel config files, so everything is based on strings. """ if isinstance(value, bool): return 'true' if value else...
def saludar(nombre): """Esta funcion saluda""" return f"Hola, {nombre}!"
def wrap_pm180(valin): """ Wraps a value (float) to a -180 to 180 degree range. Parameters ---------- valin: float Input value in degrees Returns ------- valout : float Example ------- # e.g., 200 degrees corresponds to -160 degrees when limited to [-...
def add_unique(list,elt): """Add an element uniquely to a list """ # Since we can't use set(), which uses memory addresses as hashes # for any creation or order-sensitive operation in models # instead we use lists and rather than foo = set(); foo.add(x) # we use foo = []; add_unique(foo,x) i...
def get_nb_active_users(sc, response): """Get number of active users, using https://api.slack.com/methods/users.getPresence""" if not response['ok']: return 0 users = [m['id'] for m in response['members']] nb = 0 for user in users: response = sc.api_call( "users.getPresen...
def fetch_execute(instructions): """ Read a list of machine instructions until we read an instruction for a second time (infinite loop) or jump to a instruction index outside the bounds of the input list, at which point we return the accumulator value (modified by 'acc' operations) and the index `i` whi...
def absent_or_null(element, act): """Return False only if act[element] is valid and not None""" if not act: return True elif element not in act: return True elif act[element]: return False return True
def min_operations(target): """ Return number of steps taken to reach a target number input: target number (as an integer) output: number of steps (as an integer) """ step = 0 while target !=0: if target%2!=0: target -=1 else: target = target/2 ...
def is_unary(s: str) -> bool: """Checks if the given string is a unary operator. Parameters: s: string to check. Returns: ``True`` if the given string is a unary operator, ``False`` otherwise. """ return s == '~'
def exportCSV(dictionary, itemSeperator=",", lineSeperator="\n"): """ Generate a CSV string from a dictionary :param dictionary: A properly formatted python dictionary :param itemSeperator: The seperator that is used to identify individual items :param lineSeperator: The seperator that is used to i...
def wiki_direction(wiktionary_dict): """ Extract information from Wiktionary in one direction for the computation of descriptive statistics. :rtype: dict :return: lemma_pos2translations for (form, None) -> translations """ lemma_pos2translations = dict() for lemma, translations in wikti...
def set_memberP( c, s): """ method set_memberP c is a char ,implemented as a string of length 1 s is a "set of char", implemented as a string. """ if c in s: return True else: return False
def simulation(playfield: list) -> list: """Simulate a playfield for one generation step.""" _playfield_height = len(playfield) _playfield_width = len(playfield[0]) new_playfield = [] for _line in range(_playfield_height): _new_line = [] for _cell in range(_playfield_width): ...
def data_record_db_val_from_raw_val(data_hash: str) -> bytes: """convert a python record spec into the appropriate lmdb value Parameters ---------- data_hash : string hash of the data sample Returns ------- bytestring Byte encoded db record val. """ record_val = f'{...
def blute(N, M): """ >>> blute(2, 2) 2 >>> blute(2, 3) 18 """ from itertools import permutations nums = range(M) count = 0 for a in permutations(nums, N): for b in permutations(nums, N): if all(a[i] != b[i] for i in range(N)): count += 1 r...
def distance_squared(x0, y0, x1, y1): """squared of distance between x0,y0 and x1,y1""" dx = x1 - x0 dy = y1 - y0 dx *= dx dy *= dy return dx + dy
def get_column_name(column): """ gets the pure column name from given column name with ordering info. for example: +age -> age age -> age -age -> age :param str column: column name to extract pure name from it. :rtype: str """ if column.startswith(('-', '+')): return...
def _l2_derivative(weights): """The derivative of the L2 norm.""" # NOTE: Include this in report # https://math.stackexchange.com/questions/2792390/derivative-of- # euclidean-norm-l2-norm return weights
def next_power_of_2(n): """Return the smallest power of 2 greater than or equal to n""" n -= 1 n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 n += 1 return n
def x2trace(distance, interval): """Return the trace number closest to a given distance. The input distance is effectively dimesionless given that the interval is proportional to it. NB: Not sure if the returned trace is a python index or gpr trace but that needs to be specified here. Attributes: dis...
def lwrap(l, w=None): """docstring for lwrap""" result = [] o = w or '"' for elem in l: result.append(o + elem + o) return result
def power(x, n): """Compute the value x**n for integer n.""" if n == 0: return 1 else: return x * power(x, n-1)
def exp_required(level: int) -> int: """ Computes EXP required for current level - EXP Required: (8 * Level^3) / 4 """ BASE_EXP = 8 amount = BASE_EXP * (level ** 3) return round(amount / 4)
def expandName(dataframe, column, names): """ Expand a Spark dataframe column of `MapType` into separate columns specified by the `mapping` .. code-block:: python +--------------------+-----------------------------------+ | attachment_uuid| content| +---...
def _jsbool(prop): """quick and dirty conversion of a value into a javascript boolean""" return prop and 'true' or 'false'
def format_short_year(datestr, timestr): """Join those strings with a space""" return str(datestr + " " + timestr)
def strip(token, str): """ strip the token from both the beginning and the end of str :param token: :param str: """ if str.lower().strip() == token: return '' if str.lower().startswith(token+' '): str = str[len(token):] if str.lower().endswith(' ' + token): str =...
def time_in_range(start, end, x): """Return true if x is in the range [start, end]""" if start <= end: return start <= x <= end else: return start <= x or x <= end
def make_gym(a, b, c, d): """Returns a pokemon gym (represented by list) of the four pokemons a, b, c, d.""" return [a, b, c, d]
def memoize(f): """ A decorator that caches the return value for each call to f(args). Then when called again with some arguments, we can just look it up. CREDIT: Peter Norvig's Udacity CS212 Course on Design of Computer Programs. All credit goes to him. """ cache = {} def _f(*args): ...
def activity_selection(start, finish): """ implementation of activity selection algorithm """ # assumes that the activities # are already sorted according to their finish time # first activity is always selected lst = [0] k = 0 for pid in range(1, len(start)): # If this activity has ...
def factorial(n: int) -> int: """Return the factorial of n, an exact integer >= 0 By definition, the factorial is defined as follow: factorial(n) = n * factorial(n - 1), factorial(0) = factorial(1) = 1 >>> factorial(4) 24 >>> factorial(10) 3628800 >>> factorial(25) 1551121004333098...
def dict2line(the_dict, the_glue): """create string from dictionary""" def impl(key, val, glue): if val: return ' ' + key + glue + str(val) return ' ' + key return ''.join([impl(k, v, the_glue) for k, v in the_dict.items()]).strip()
def estimateDirection(CurrentCourse,DestCourse): """ returns the positive or negative value in which direction one have to steer to get on the course to the target. """ CourseCorrection = DestCourse - CurrentCourse if (CourseCorrection == 180): return 180 if (CourseCorrection > 180): return -...
def strtobool_safe(value): """Returns a `bool` based on `value` Wrapper around `distutils.util.strtobool` Returns `False` if any `Exception` occurs """ try: from distutils.util import strtobool result = bool(strtobool(value)) except: result = False return result
def ansirgb(red: int, green: int, blue: int) -> str: """ This function converts RGB values to ANSI color codes. @param red: Red value of RGB 0-255. @type red: int. @param green: Green value of RGB 0-255. @type green: int. @param blue: Blue value of RGB 0-255. @type blue: int. @...
def seconds2days(seconds): """Accepts a value in seconds and returns its value in days.""" return seconds/(60.0*60.0*24.0)
def indexName(dictname, key): """Return the underlying key used for key-based access to an item identified by key in the dictlist named dictname. """ return (dictname,"X",key)
def get_account_volumes(acct_id, all_vols, **output_dict): """ Get a list of volumes and the account id """ vol_dict = {} response_json = output_dict['ListVolumes'] for vol in response_json['result']['volumes']: if all_vols is False: if vol['accountID'] == acct_id: ...
def append_to_title(title: str, append_title: str) -> str: """ Append a title to a title avoiding duplication in title text, i.e. 'Steps Steps'. :param title: Title to append to. :param append_title: Other title to append to the title. :return: The appended title without title duplication. """ ...
def _convert_ddb_list_to_list(conversion_list): """Given a dynamodb list, it will return a python list without the dynamodb datatypes Args: conversion_list (dict): a dynamodb list which includes the datatypes Returns: list: Returns a sanitized list without the dynamodb ...
def i_to_red(i, normalize=False): """Convert a number between 0.0 and 1.0 to a shade of red. Parameters ---------- i : float A number between 0.0 and 1.0. normalize : bool, optional Normalize the resulting RGB values. Default is to return integer values ranging from 0 to 255...
def html2text(html, sub='', sup=''): """Convert html to plain text >>> html2text('<div><a>hello,</a><p>world</p></div><span>i miss you</span>') 'hello,world\\n\\ni miss you' """ def split_block(html): """ Returns: element,front,prefix,content,suffix,back """ ...
def _parse_bool(value): """ Parse a query string value into a bool """ return value and value.lower() != "false"
def urljoin(*path): """Joins the passed string parts into a one string url""" return '/'.join((part.strip('/') for part in path))
def is_passive_user(vars, history_len=2): """Check history_len last human utterances on the number of tokens. If number of tokens in ALL history_len uterances is <= 3 tokens, then consider user passive - return True. """ user_utterances = vars["agent"]["dialog"]["human_utterances"][-history_len:] us...
def parse_cmd(cmd): """This function converts a list to str. If a command is passed as list it is converted to str. For pyrpipe v0.0.5 onwards the get_shell_output function uses shell=True """ if isinstance(cmd,list): return " ".join(cmd) return cmd
def get_subs_minichp(p_nom, q_nom, v_tes): """ Calculate BAFA subsidy for mini chp devices. Parameters ---------- p_nom : chp el. power in kW q_nom : chp th. power in kW v_tes : volume of thermal energy storage in liter Returns ------- bafa_subs_chp : subsidy for mini-chp "...
def _find_traces(traces, trace_type, item_id): """Find traces for a script or automation.""" return [ trace for trace in traces if trace["domain"] == trace_type and trace["item_id"] == item_id ]
def get_median_pivot_idx(A, start_idx, stop_idx): """ >>> get_median_pivot_idx([8, 2, 4, 5, 7, 1], 0, 6) 2 >>> get_median_pivot_idx([4, 5, 6, 7], 0, 4) 1 >>> get_median_pivot_idx([3, 8 ,2, 5, 1, 4, 7, 6], 3, 8) 3 >>> get_median_pivot_idx([1, 3, 5, 2, 4, 6], 3, 6) 4 :param A: ...
def iter2d_collate_fn(batch): """Collate function for scene-aware ScanNet object classification.""" total_objects = sum([ex["num_queries"] for ex in batch]) return { "file_path": [ex["file_path"] for ex in batch], "filename": [ex["filename"] for ex in batch], "num_queries": [ex["num_...
def StartsWith(this, that): """Checks whether an items of one iterable are a prefix of another. Args: this: An iterable that needs to be checked. that: An iterable of which items must match the prefix of `this`. Returns: `True` if `that` is a prefix of `this`, `False` otherwise. """ this_iter = ...
def ComptonRotationAngle(azimuth): """Reference frame rotation so that MuellerMatrixCompton holds Args: azimuth(num): scattering azimuth (degree) Returns: angle: rotation of the axes in degrees """ # First component axis perpendicular to the scattering plane return azimuth - 90
def filter(fields, delimiter, filterlist): """two lists are given and according to positions they are zipped into tuples, if a value exists in the filter list (can also be string or a list of strings) than it has to be in it""" comparison_pairs = list(zip(fields, filterlist)) for cp in comparison_p...
def get_edge(starting_node, ending_node, edges_dictionary): """ Get the edge_document which connects starting_node with ending_node. :param starting_node: osm_id :param ending_node: osm_id :param edges_dictionary: {starting_node_osm_id -> [edge_document]} :return: edge: edge_document """ ...
def default_log_config(verbose: bool) -> dict: """ Setup default config. for dictConfig. :param verbose: level: DEBUG if True, INFO if False :return: dict suitable for ``logging.config.dictConfig`` """ log_level = 'DEBUG' if verbose else 'INFO' return { 'version': 1, 'disabl...
def sim_to_label(similarity): """Convert similarity to edge label. Parameters ---------- similarity : float Similarity between two answers. Returns ------- str Label of the edge. Similarity in percentage i.e 90%. """ return str(round(similarity*100)) + '%'
def get_sel_programmer_info(arduino_info): """.""" sel_programmer = arduino_info['selected'].get('programmer') programmer_info = arduino_info['programmers'].get(sel_programmer, {}) return programmer_info
def get_filepath(fileorpath): """Get the actual file path of fileorpath if it's a FileUpload object.""" if hasattr(fileorpath, 'path'): # FileUpload return fileorpath.path return fileorpath
def invert_dict(dictionary): """ Invert a dict object. """ return {v:k for k, v in dictionary.items()}
def intf_id_from_uni_port_num(port_num): """ Extract the PON device port number from a virtual UNI Port number :param port_num: (int) virtual UNI / vENET port number on OLT PON :return: (int) PON Port number (note, this is not the PON ID) """ return (port_num >> 11) & 0xF
def _must_positive_intvalue(value: str) -> int: """String must be an integer value > 0 - if not use default""" try: intval = int(value) if intval < 1: intval = 1 return intval except: return 1
def is_overflow_position(dimension, position): """ Check whether the given position is an overflow position for any board with the given dimension. - True if and only if the position is in the overflow row of the given board. ASSUMPTIONS - The given position is a proper...
def is_player_on_team(player, team): """ take a player string and team list and check whether the player is on team do this by adding the player to the team, then returning True if the player shows up 2 or more times """ team.append(player) return team.count(player) >= 2
def check_GHS_data(request_json): """This function checks to see if GHS safety information data is available in the pubchem data file for a chemical""" if 'Fault' in request_json: # first key in dict will be Fault if no GHS heading in json data return 'No GHS data available' else: ret...
def sum_square_diff(ceiling, vol=0): """ Returns the difference between the sum of the squares and the square of the sum for all natural numbers up to and including ceiling. """ return sum(range(ceiling+1))**2 - sum(x**2 for x in range(ceiling+1))
def fizzbuzz(n): """Returns the sum of all numbers < n divisible by 3 or 5. This iterative approach will work really well, and if it gets the job done reasonably quickly, that's all we should ask for. If you want to write this in one line, the following will work: return sum([i for i in range(n) if i % 3...
def _flatten(src_list: list) -> list: """Flatten a list of lists.""" return [item for sublist in src_list for item in sublist]
def binnify(test, lower, upper, bins): """Compute a bin index for the 'sounding' raster display.""" # No, I don't remember why this works. It's not hard to figure out though. bins -= 1 ul = upper-lower bs = ul/bins return max(0, int(round(min(bins, bins*(test-lower)/ul), 0)))
def julian_day(year, month=1, day=1): """Given a proleptic Gregorian calendar date, return a Julian day int.""" janfeb = month < 3 return (day + 1461 * (year + 4800 - janfeb) // 4 + 367 * (month - 2 + janfeb * 12) // 12 - 3 * ((year + 4900 - janfeb) // 100) // 4 ...
def aslist(val): """Converts a comma-separated value string into a list :param val: value to convert, either a single value or a comma-separated string :return: list representation of the value passed in :rtype: list of strings """ if val is None: return [] if isinstance(val, list)...
def make_paragraphs(text): """Transform a string with linefeeds in html paragraphs.""" paragraphs = text.split('\n') html = '</p><p>'.join(paragraphs) return('<p>{}</p>'.format(html))
def parseInt(s, ret=0): """Parses a value as int.""" if not isinstance(s, str): return int(s) elif s: if s[0] in "+-": ts = s[1:] else: ts = s if ts and all([_ in "0123456789" for _ in ts]): return int(s) return ret
def is_specific_url(url): """ This api has a tendency to give you the url for the general list of things if there are no entries. this separates "people/" from "people/123456" """ return url[-1] != '/'
def outputCoords(x:int,y:int) -> str: """ Converts 2D list indexes into Human-Readable chess-board coordinates x and y correspond to the indexes such that it looks like this: `dataList[x][y]` """ columnCheck = ["A","B","C"] column = columnCheck[y] row = str(x+1) return column+row
def part2(lines): """ >>> part2([+1, -1]) 0 >>> part2([+3, +3, +4, -2, -4]) 10 >>> part2([-6, +3, +8, +5, -6]) 5 >>> part2([+7, +7, -2, -7, -4]) 14 """ running_sum = 0 memory = {0} while True: for value in lines: running_sum += int(value) ...
def get_bradycardia_level(bpm): """ Returns the bradycardia level for the corresponding bpm :param bpm: the revealed bpm :return: the level """ if bpm > 60: return 0 elif bpm > 50: return 1 else: return 2
def max_sub_array(arr): """ TIME COMPLEXITY : O(n) SPACE COMPLEXITY : O(1) """ for i in range(len(arr) - 1): summation = arr[i] + arr[i + 1] arr[i + 1] = max(summation, arr[i + 1]) return max(arr)
def generate_example_id(passage_id, collection_mode): """ Identifier assigned to a task instance in HIT This is necessary if a HIT has different collection modes for a single passage """ return '_'.join([passage_id, collection_mode])
def weibull_hazard_rate(alpha: float, beta: float, age_years: float) -> float: """ alpha: A value > 1 indicates that failure rates increases over time (e.g. an ageing process). beta: The larger this value, the more 'spread out' the distribution is. age_years: The age of an item subject to failur...
def get_latitude_direction(latitude_degrees): """ Returns the direction for the given latitude degrees. :param latitude_degrees: The degrees (not minutes) as an integer. :return: String containing the possible latitude directions (N, S). """ if latitude_degrees is None: raise ValueError(...
def median(arr): """ Calculates the median of a list of numbers. Usage: median([3, 4, 5, 6, 7]) # 5 """ arr.sort() if len(arr) % 2 == 1: return arr[len(arr) // 2] else: mid1 = len(arr) // 2 mid2 = mid1 - 1 return (arr[mid1] + arr[mid2]) / 2
def dict_from_bids(file_path): """ Return a dictionary based on the file_path BIDS keys and values. """ local_dict = {} # remove file extension, but beware a leading ./ if "." in file_path[1:]: local_dict['ext'] = file_path[file_path.rfind("."):] file_path = file_path[:file_path.rfind("...
def update_frame_count(c): """ Keeps track of the frame counter. """ fc = 0 for fr in c: fc += 1 return fc
def unpack_int(buffer, ptr, length): """ Unpack an int of specified length from the buffer and advance the pointer """ return ( int.from_bytes(buffer[ptr:(ptr+length)], 'little', signed=False), ptr + length )
def swap(record): """ Swap (token, (ID, URL)) to ((ID, URL), token) Args: record: a pair, (token, (ID, URL)) Returns: pair: ((ID, URL), token) """ token = record[0] keys = record[1] return (keys, token)
def complement(l, universe=None): """ Return the complement of a list of integers, as compared to a given "universe" set. If no universe is specified, consider the universe to be all integers between the minimum and maximum values of the given list. """ if universe is not None: unive...
def create_compound(attributes): """Convert node attributes to dictionary structure needed for a compound.""" data = { # Use black color if none provided. "color": attributes.get("color", (0, 0, 0)), "properties": { # Use (0, 0) for structure if none provided, "st...
def filter_month(string, month): """ Filter month. Keyword arguments: string -- the string to perform the filtration on month -- the month used as the filter """ if month in string: return True else: return False
def get_affix(text): """ This method gets the affix information """ return " ".join( [word[-4:] if len(word) >= 4 else word for word in text.split()])
def update_output_div(input_value: str) -> str: """ Update output div. :param input_value: str. Value to be returned. :return: str. Value. """ return f"Output: {input_value}"
def camelize(s): """ >>> camelize('camel_case') 'CamelCase' """ return ''.join(ele.title() for ele in s.split('_'))
def _power_of_two(target): """Finds the next greatest power of two """ cur = 1 if target > 1: for i in range(0, int(target)): if (cur >= target): return cur else: cur *= 2 else: return 1
def flatten_param(param): """ Turn a parameter that looks like this param[name_one][name_two][name_three] into this param_name_one_name_two_name_three """ param = param.replace(']', '').replace('[', '_').replace('<','').replace('>','') if param.startswith('_'): param = param.replace('_'...
def t(ket, pa, bonds): """Hopping between sites ket and ket+1, given the parameters. If the chain is not periodic, the hopping between the last and first sites is identically zero.""" if ket == pa['chainlength'] and pa['boundary'] == 'open': return 0 else: return pa['t0'] - pa[...
def length(list): """Return the number of items in the list.""" if list == (): return 0 else: _, tail = list return 1 + length(tail)
def newton_raphson(f, df, guess, value, tol=1e-3, m=1, max_iters = 1e12): """ Simple newton solver for nonlinear functions given the knowledge of the derivative Parameters ---------- f: function(x, value) function of the problem, with one parameter and the target value df: function(x) ...