content
stringlengths
42
6.51k
def _per_shard_batch_size(global_batch_size, run_config, use_tpu): """Returns the batch size for each shard.""" if use_tpu: return global_batch_size // run_config.tpu_config.num_shards else: return global_batch_size
def parallel(*items): """ resistors in parallel, and thanks to duck typing and operator overloading, this happens to be exactly what we need for kalman sensor fusion. >>> assert parallel(1.0,2.0) == 1/(1/1.0+1/2.0) """ inverted = [item**(-1) for item in items] return sum(inverted...
def rsplit(text, sep=None, maxsplit=-1): """ Creates a tuple of the words in ``text``, using ``sep`` as the delimiter string. If ``maxsplit`` is given, at most maxsplit splits are done (thus, the tuple will have at most maxsplit+1 elements). If ``maxsplit`` is not specified or -1, then there is n...
def deep_str(obj, delim= ' '): """ Apply str also for lists """ if isinstance(obj, list): return delim.join(map(str, obj)) return str(obj)
def have_matching_types(a, b, type_or_types): """True if a and b are instances of the same type and that type is one of type_or_types. """ if not isinstance(a, type_or_types): return False return isinstance(b, type(a))
def get_altitude(pressure: float, sea_level_hPa: float = 1013.25) -> float: """ the conversion uses the formula: h = (T0 / L0) * ((p / P0)**(-(R* * L0) / (g0 * M)) - 1) where: h = height above sea level T0 = standard temperature at sea level = 288.15 L0 = standard temperatur elapse rat...
def insert_stone(board, player, x, y): """Return a copy of the board with a new stone in (x, y). Input: board : the game state as an n*n list (n likely == 8) player : which player's is placing the stone (black == 1, white == -1) x : the index in the row to place the stone y : the...
def get_bit_elements(vector, bit, value): """Return a list with the elements of vector that has bit with value.""" subvector = [] found = 0 max_found = len(vector)//2 for i in range(len(vector)): bin_i_rev = ("{:0" + str(2**bit) + "b}").format(i)[::-1] if int(bin_i_rev[bit]) == value...
def supply(request, page_name): """Supply the view_objects content.""" _ = request _ = page_name return {}
def get_stack_output_value(stack_outputs, output_key): """ Get output value from Cloudformation Stack Output. :return: OutputValue if that output exists, otherwise None """ return next((o.get("OutputValue") for o in stack_outputs if o.get("OutputKey") == output_key), None)
def get_targets(array): """Get Offload Targets""" targets = [] try: target_details = array.list_offload() except Exception: return None for targetcnt in range(0, len(target_details)): if target_details[targetcnt]["status"] == "connected": targets.append(target_de...
def find_element(e, l): """ return the positions of e in l as a list of 2-tuples l must be a list of sublists. e is an element potentially present in the sublists. find_element(1, [[3,2,1],[4],[0,1]]) -> [ (0,2), (2,1) ] find_element(1, []) -> [] find_element(1, [ [1,1], [1] ]) -> [ (0,0), (0,1...
def mk_rep_eqc(L_eq_classes): """Helper for bash_1 that finds the representative of a set of equivalent states. Given the final equivalence classes, make representatives for each; stick the repr. at the head of a pair. Thus, (repr, eql-class-with-repr) list is returned. """ Ll =...
def merge_without_sentry(a, p, q, r): """ an assist function to merge two array that has been sorted :param a: a array to sort :param p: index of array, p <= q < r, A[p..q] and A[q+1..r] has been sorted :param q: index of array, p <= q < r, A[p..q] and A[q+1..r] has been sorted :param r: index of a...
def get_encapsulated(str_line, encapsulator): """ Returns items found in the encapsulator, useful for finding units Args: str_line: String that has encapusulated info we want removed encapsulator: string of characters encapusulating info to be removed Returns: result: list of st...
def assign_value_if_none(value, default): """ Assign a value to a variable if that variable has value ``None`` on input. Parameters ---------- value : object A variable with either some assigned value, or ``None`` default : object The value to assign to the variable ``value`` if ``...
def parse_wiggle_header(header): """ :param header: :return: """ _, chrom, start, step = header.strip().split() foo, chrom = chrom.split('=') assert foo == 'chrom', 'Unexpected wiggle header: {}'.format(header) bar, start = start.split('=') assert bar == 'start', 'Unexpected wiggle h...
def path_element_to_string(path_element): """Convert a single path element to its escaped string representation.""" res = "" for char in path_element: if char == '\\': res += "\\\\" elif char == '/': res += "\\/" else: res += char return res
def numDateToYmd(numDate): """Convert numeric date (decimal year) to integer year, month, day""" year = int(numDate) isLeapYear = 1 if (year % 4 == 0) else 0 # Get rid of the year numDate -= year # Convert to Julian day daysInYear = 366 if isLeapYear else 365 jDay = int(numDate * daysInY...
def negND(v): """Returns negative of an nD vector""" return [-vv for vv in v]
def construct_sent(word, table): """Prints a random sentence starting with word, sampling from table. >>> table = {'Wow': ['!'], 'Sentences': ['are'], 'are': ['cool'], 'cool': ['.']} >>> construct_sent('Wow', table) 'Wow!' >>> construct_sent('Sentences', table) 'Sentences are cool.' """...
def calculate_score(given_answers: dict, correct_answers: dict) -> int: """Returns the number of correct answers. given_answers: {"question1": "X", "question2": "Y", ... "questionN": "Z"} correct_answers: {"question1": "A", "...
def tagmaptoaxismap(tagmap): """converts a tag: (score, axis) dict to a axis: [tag, tag, tag...] dict""" axismap = {} for tag, (score, axis) in tagmap.items(): if axis in axismap: axismap[axis].append(tag) else: axismap[axis] = [tag] if not axismap: axismap[(0,100)] = [] return axismap
def is_collinear(x1: float, y1: float , x2: float, y2: float, x3: float, y3: float) -> bool: """ Finds whether given three points are collinear. Parameters: x1, y1 : The x and y coordinates of first point x2, y2 : The x and y coordinates of second point ...
def add_default_values(message_dict, consume_schema_types): """ Method add default values for all properties in given message to correspond given json schema. See default value in schema or it would be None :param message_dict: properties with its values as dict :param consume_schema_types: jso...
def get_entries_by_value(sdrf_struct, key, value, _compare_func=lambda x,y: x==y): """ Returns idcs of matching values by a specified key in sdrf """ match_idcs = [] for idx, entry in enumerate(sdrf_struct): if key in entry: if type(entry[key]) == list: for e in e...
def freq_seq_chars(counts): """Calculate frequencies of characters (symbols) in a sequence based on characters' counts. Args: counts (list): result of the `count_seq_chars` function seqlen (int): length of a sequence Returns: A list of frequencies corresponding to alphabet E...
def comp_div_per_year(div, vol_list, DRP_list): """ return total dividends for this stock, including stocks from DRP """ return sum(div * (i[0] + i[1]) for i in zip(vol_list, DRP_list))
def fastFib(n, memo = None): """Assumes n is an int >= 0, memo used only by recursive calls Returns Fibonacci of n""" if memo == None: memo = {} if n == 0 or n == 1: return 1 try: return memo[n] except KeyError: result = fastFib(n-1, memo) + fastFib(n-2, memo) ...
def timestep(dtime, time, end_time): """ calculates the timestep for a given time Returns the timestep if the calculation isnt overstepping the endtime if it would overstep it returns the resttime to calculte to the endtime. :param dtime: timestep :param time: current time in simulation :p...
def getSpecificRating(ratings): """Returns rating dictionary with value (if available)""" rating = {} for resp in ratings: #print('resp',resp) for key in resp.keys(): val = resp[key] #print("Key", key, 'points to', val) if (key == 'Source' and val == 'Rott...
def get_nq_tokens(simplified_nq_example): """Returns list of blank separated tokens.""" if "document_text" not in simplified_nq_example: raise ValueError("`get_nq_tokens` should be called on a simplified NQ" "example that contains the `document_text` field.") return simplified_nq_exampl...
def bulk_save(iterable): """ Saves a objects in a given `iterable`. """ return [obj.save() for obj in iterable]
def img(url, alt_text=None): """Return formatted embedded image.""" alt = ' alt="{}"'.format(alt_text) if alt_text is not None else "" return '<img src="{}"{}></img>'.format(url, alt)
def mac_to_str(address): """Convert a MAC address to a readable/printable string Args: address (str): a MAC address in hex form (e.g. '\x01\x02\x03\x04\x05\x06') Returns: str: Printable/readable MAC address """ return ':'.join('%02x' % b for b in address)
def GetTypedefName(typename): """Determine typedef name of constructor for typename. This is just typename + "Constructor". """ return typename + 'Constructor'
def get_bone_name_for_blender(name): """Convert a bone name to a name that can be used by Blender: turns 'Bip01 R xxx' into 'Bip01 xxx.R', and similar for L. :param name: The bone name as in the nif file. :type name: :class:`str` :return: Bone name in Blender convention. :rtype: :class:`str` ...
def mean(numbers): """ Calculate mean of list of numbers """ return sum(numbers)/float(len(numbers))
def first_match(predicate, list): """ returns the first value of predicate applied to list, which does not return None >>> >>> def return_if_even(x): ... if x % 2 is 0: ... return x ... return None >>> >>> first_match(return_if_even, [1, 3, 4, 7]) 4 ...
def steps(number: int) -> int: """Return the number of steps to reach 1 for Collatz Conjecture""" if number < 1: raise ValueError(f"{number} is not a natural number") _n = number count = 0 while _n != 1: count += 1 if _n % 2 == 0: _n /= 2 elif _n != 1: ...
def is_rect_intersection(minlat, maxlat, minlon, maxlon, latitude, longitude): """ Checks if there is a radial intersection between a point radius boundary and a latitude/longitude point. :param: minlat : the minimum rectangular latitude :type: float :param: maxlat : the maximum rectangular latitude...
def restoreMember(memberType, name, extra, params, body): """Re-creates an XBL member element from parts created by iterateMembers.""" if memberType == "method": paramText = "" for param in params: paramText += """ <parameter name="%s"/>\n""" % param return """<m...
def name(who): """Return the name of player WHO, for player numbered 0 or 1.""" if who == 0: return 'Player 0' elif who == 1: return 'Player 1' else: return 'An unknown player'
def is_coroutine(function): """Returns True if the passed in function is a coroutine""" return function.__code__.co_flags & 0x0080 or getattr(function, '_is_coroutine', False)
def soft_thresh(x: float, lmb: float) -> float: """ This is a scalar version of torch.nn.functional.softshrink. x + lmb if x < -lmb Returns 0 if x \in [-lmb, lmb] x - lmb if x > lmb """ if x < lmb: return x + lmb elif x > lmb: ret...
def get_cluster(startclust, offset): """get the real starting cluster""" rst = 0 # BEGIN wxPirs while startclust >= 170: startclust //= 170 rst += (startclust + 1) * offset # END wxPirs return rst
def indent(block): """Indent each row of the given string block with ``n*2`` spaces.""" indentation = " " * 2 return "\n".join([indentation + s for s in block.split('\n')])
def pad(padlen): """Returns false padding for the given `padlen`gth""" return [False] * padlen
def make_ssh_cmd(cmd_name, host): """ Return a command running `cmd_name` on `host` with proper SSH configs. """ return "ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 %s '%s'" % (host, cmd_name)
def get_sublist_from_indices(orig_list, idxs): """ Returns a sublist from the indices. orig_list can be anthing that can be indexed and idxs are a list of indices. """ return [orig_list[idx] for idx in idxs]
def vis147(n): """ OOOO OOO OOOO OO OOO OOOO OO OOO OOOO O OO OOO 5 11 19 """ result = '' for i in range(n): result += 'O' * (n + 1) + '\n' result += 'O' * n return result
def count_tags_s2(tags_list1, tags_list2): """ :param tags_list1: The first list of tags :param tags_list2: The second list of tags :return: """ tags_s2 = 0 for tag1 in tags_list2: for tag2 in tags_list1: if not (tag1 == tag2): tags_s2+=1 return tags...
def search_open_parenthesis(word): """Search for open square bracket in a string Args: word (str): String to search. Returns: bool: True if the string contains open square bracket, False otherwise. """ return (word.count("(") - word.count(")")) != 0
def _process_bash_parameters(parameters): """ Returns a bash script formatted parameter string from a list of parameters. Example: [param1=1, param2=2] => 1 2 """ param_string = '' for param in parameters: if '=' in param: param = param.split('=', 1)[1] param_string +...
def partition_work(n_items, n_workers, start_index=0): """Given an index range and a number of workers to work on them, break the index range into approximately evenly sized sub-intervals. This is a helper function for :func:`run_task_in_chunks` used to compute the chunks. Parameters ---------...
def clip(st,length): """ will clip down a string to the length specified """ if len(st) > length: return st[:length] + "..." else: return st
def _sparse_ftrs_indices1(ftr_name): """Returns the name of the 1st axis indices for `ftr_name`""" return f"{ftr_name}_indices1"
def find_minrun(n): """ Find the minimum size that we should Taken directly from: <http://svn.python.org/projects/python/trunk/Objects/listsort.txt> """ r = 0 if not n >= 0: raise ValueError("array_size must be >= 0") while n >= 64: r |= n & 1 n >>= 1 return n + r
def grid_indices(qubit_id, n_dimensions, grid_length, spinless): """This function is the inverse of orbital_id. Args: qubit_id: The tensor factor to map to grid indices. n_dimensions: An int giving the number of dimensions for the model. grid_length (int): The number of points in one di...
def bai_of_bam(fn): """Return bai file of a bam""" return fn + ".bai"
def on_off_bool(value): """Convert on/off to True/False correspondingly.""" return value == 'on'
def check_availability(lower_bound: int, upper_bound: int, high_lower_bound: int, map_array: list, coordinates: tuple, size: int, scale_factor: int): """ Function checks if there is enough space on map to generate structure of given size at given coordinates Args: ...
def decode_int(s: bytes) -> int: """Decodes little endian encoded hex byte to little endian int Args: s (bytes): big endian encoded int Returns: int: little endian int """ return int(s[::-1].hex(), 16) if s else 0
def excel_to_python(command_string): """ Returns the python equivalent of many excel formula names """ d = { 'SUM' : 'np.sum', 'AVERAGE' : 'np.mean', 'MAX' : 'np.max', 'MIN' : 'np.min', 'MEDIAN' : 'np.median', 'MODE' :...
def sum_by_letter(list_of_dicts, letter): """ :param list_of_dicts: A list of dictionaries. :param letter: A value of the letter keyed by 'letter'. """ total = 0 for d in list_of_dicts: if d['letter'] == letter: total += d['number'] return total
def all_subsets(lst): """Metoda na vsechny podmnoziny""" #vlozime si na zacatku prazdnou mnozinu set = [[]] #Iterujeme kazdy prvek z listu for x in lst: #iterace vsech podmnozin for y in set: # pridani nove podmnoziny skladajici se z podmnoziny a prvku listu s...
def shape(a): """the shape of a matrix""" _rows = len(a) _cols = len(a[0]) if a else 0 return _rows, _cols
def Stars(amount_of_stars, is_flag): """Returns the amount of stars asked for""" if not is_flag: return ("*" * (amount_of_stars+4)) #Adds four extra stars to close the gaps elif is_flag: return ("*" * (amount_of_stars))
def _clean_sort(string): """Clean non-alphanumeric characteres and sort into a list.""" return sorted(char.casefold() for char in string if char.isalnum())
def create_html_email_href(email: str) -> str: """ HTML version of an email address :param email: the email address :return: email address for use in an HTML document """ return f'<a href="mailto:{email}">{email}</a>' if email else ""
def parse_reg_02h_byte(byte_val: int) -> int: """Net ID""" assert 0 <= byte_val < 256 return byte_val
def get_error_from_utilization(utilization, setpoint, current_instances): """ Consider scaling up if utilization is above the setpoint Consider scaling down if the utilization is below the setpoint AND scaling down wouldn't bring it above the setpoint Otherwise don't scale """ max_threshold = se...
def _funct(x, a, b): """ fit linear function to log log data""" return (a * x) + b
def indent_func_def(func_def): """Ensures max columns in a function signature follows style guide""" if len(func_def) < 80: return func_def parts = func_def.split(',') idx = func_def.index('(') params = parts[0] for x in parts[1:]: params += ',\n{}{}'.format(idx * ' ', x) ret...
def match_ch_type(name): """ return channel type based on channel name Parameters ---------- name : string name of channel Returns ------- out: string channel type """ out = 'seeg' if 'ecg' in name: out = 'ecg' if name in ['fz', 'cz']: out = ...
def _parse_checks_or_datapoints_series(results, field, owner_id=''): """Parse the `results` of an InfluxDB query on `field` This method is meant to only be invoked by the methods `_query_checks` and `_query_datapoints`. It returns the results of the corresponding query in a common format after backfill...
def render_operation_response(response): """ Renders the provided operation response. :param response: response to render :return: rendered string """ if response['successful']: if 'operation' in response and response['operation']: return 'Started: {}'.format(response['opera...
def expand(xs, batch_size): """Extend or truncate the list of prompts to the batch size.""" return (xs * batch_size)[:batch_size]
def profile_filename(cycle, run, batch, source='frank', basename='xrb'): """Returns string for profile table filename """ return f'profile_{source}_{batch}_{basename}{run}_{cycle}.txt'
def convert(seconds): """Converts seconds into readable format (hours, mins, seconds). Parameters ---------- seconds : float or int Number of seconds to convert to final format. Returns ------- str A string with the input seconds converted to a readable format. """ ...
def _get_plugin_id_set(plugin_info_list): """ Return a set with the ids from plugin info list. """ return {plugin_info.id for plugin_info in plugin_info_list}
def _filter_out_underscore(object_name): """Since class names don't allow underscore in names, we're parsing them out""" return object_name if "_" not in object_name \ else object_name.replace("_", "")
def generate_word_grams(text): """Generate a lookup of words mapped to the next occurring word, and we can use this to generate new text based on occurrence. """ words = text.split() wordgrams = {} # Add each word to the lookup for i in range(len(words) - 1): # Have lookup be all l...
def set_parameters(parameter_set): """Set the parameters given the parameter set name arg: string: parameter_set returns a dictionary of parameters """ LO_to_SSC_parameters = { # Original base paramter set: using NO3 directly from Live Ocean and # a linear fit to get Si from NO3 ...
def truncate_hour(tval): """Truncate tval to nearest hour.""" return((int(tval)/3600) * 3600)
def IsPrintable(byte): """Determines if a byte is printable. Args: byte: An integer potentially representing a printable character. Returns: A boolean indicating whether the byte is a printable character. """ return byte >= ord(' ') and byte <= ord('~')
def capitalize(string): """ helper function to create capitalized copy of string. """ return string[:1].upper() + string[1:]
def __convert_string_coordinate(value): """ Args: value (str): a coordinate value in string format Returns: float: converted coordinate value """ value, modifier = str(value).split(".")[0], "" if value[:1] == "-": value, modifier = value[1:], "-" integer_part, float...
def edit_distance(str1, str2): """ :param str1: string :param str2: string :return: int """ m = len(str1) n = len(str2) # Create a table to store results of subproblems dp = [ [0 for x in range(n + 1)] for x in range(m + 1) ] """ dp[i][j] : contains minimum number of edits ...
def get_local_id_from_curie_id(curie_id: str): """ This function returns the local ID from a CURIE ID, where a CURIE ID consists of "<Prefix>:<Local ID>". For example, the function would return "C3540330" for CURIE ID "umls:C3540330". """ assert ':' in curie_id return curie_id.split(':')[1]
def get_characters_mapping(X, f=None): """Determines all unique characters from the dataset. :param X: List of tokenized sentences. :param f: Preprocessing functions applied to every token before analysis. This function can be different from the one used with get_vocabulary :return dict mapping...
def dist(x1: float, y1: float, x2: float, y2: float) -> float: """Distance between two points.""" return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
def un_human_readable(value_str): """ Takes the output of IOR's HumanReadable() and converts it back to a byte value """ args = value_str.strip().split() if len(args) == 1 and args[0].endswith("%"): return float(args[0].rstrip("%")) elif len(args) != 2: raise Exception("Inval...
def check_expiration_year(val): """eyr (Expiration Year) - four digits; at least 2020 and at most 2030.""" return len(val) == 4 and 2020 <= int(val) <= 2030
def fill_rect( color: list, pixels: list, w: int, h: int, wb: int, hb: int, roi: list ) -> list: """[fills a rectangle full of a colors] Args: color (list): [list of rgb values representing a pixel] pixels (list): [list of pixels] w (int): [width of image] h (int...
def combinations(s, K): """ On entry: s sequence of items; K size of the combinations Returns: list of all possible K-combinations without replacement of s. """ N = len(s) assert K<=N, 'Error K must be less or igual than N' S = [[] for i in range(K+1) ] for n in range(1,N+1): ...
def create_exp_id(exp_network, num_layers, num_neurons, batch_size, num_epochs, learning_method, regularization): """Create identifier for particular experiment. Parameters ---------- exp_network...
def is_valid_username2(username): """ New username check function, old version is used by many others, stay put """ return (not username.startswith(' ')) and (not username.endswith(' '))
def flatten(l): """This function takes a list and flattens it if there are any other list elements in it INPUTS ======= l: any list RETURNS ======== list: flattened list EXAMPLES ========= >>> flatten(['2', '+', 'sin', '(', 'x', ')', '-', '3y', ['x', '2'], ['y', '3']]) ...
def is_retryable(txn, error): """Check if this transaction is one caused by database conflict. These transactions should not be caught in catch all exception expressions. :param txn: :param error: :return: """ # Emulate TransactionManager.is_retryable if txn is None: return ...