content
stringlengths
42
6.51k
def filter_none_grads(grads_and_vars): """Filter None grads.""" return [(grads, vs) for (grads, vs) in grads_and_vars if grads is not None]
def build_outside_cell(cell_num, mat_num, density, surface_num, universe, comment): """Create a cell which encompasses everything outside it.""" cell_card = "{} {} {} {} u={} imp:n=1 {}".format(cell_num, mat_num, round(density, 5), surface_num, universe, comm...
def cpu_str2num(cpu_str): """ Parses a string containing CPU % utilization and returns a float. e.g., "14.5%" -> 14.5 """ return float(cpu_str[:-1])
def box_area(box): """ Calculates the area of a bounding box. Source code mainly taken from: https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/ `box`: the bounding box to calculate the area for with the format ((x_min, x_max), (y_min, y_max)) return: the b...
def _gerrit_user_to_author(props, username=u"unknown"): """ Convert Gerrit account properties to Buildbot format Take into account missing values """ username = props.get("username", username) username = props.get("name", username) if "email" in props: username += u" <%(email)s>" % ...
def get_mimetype(response): """ Extract MIME type from given response (usually a HEAD request), or None """ try: return response.headers["Content-Type"] except: # KeyError return None
def parse_timedelta_from_form(data_dict, key_root): """Parse values from a timedelta form element, and return the value in minutes Parameters ---------- data_dict: dict Dictionary of posted form data key_root: string The shared part of the name attribute of the inputs to parse....
def get_coordinates(bounding_box, bounding_box_type=''): """Create bounding box coordinates for the map.""" coordinates = [] if bounding_box_type == "box": coordinates.append([bounding_box[1], bounding_box[0]]) coordinates.append([bounding_box[1], bounding_box[2]]) coordinates.append...
def precision_at_position_1(sort_data): """ calculate precision at position 1 Precision= (Relevant_Items_Recommended in top-k) / (k_Items_Recommended) Args: sort_data: List of tuple, (score, gold_label); score is in [0, 1], glod_label is in {0, 1} Return: precision_at_position_1 "...
def get_role_name(account_id): """Shortcut to insert the `account_id` into the iam string.""" return "arn:aws:iam::{0}:role/lambda_basic_execution".format(account_id)
def get_verb_root(regular_verb): """ Get the regular verb root/stem via indexing of the inputted verb """ verb_root = regular_verb[:-3] return verb_root
def get_pid_file_present(directory, appliance): """Get whether a PID file exists""" try: with open(directory + appliance + '.pid', "r") as f: pid = f.readline() except IOError as err: return False, None return True, pid
def extract_properties_values_of_type_dict_from_json(data, keys): """Extracts properties values of type `dict` from the JSON data. .. note:: Each of key/value pairs into JSON conventionally referred to as a "property". More information about this convention follow `JSON Schema document...
def get_overlapping_weights(vocab, comparison_vocab): """ Accepts a pair of dictionary that stores token:weight and gets the values for tokens that are in both vocabularies. Args: vocab (dict): token:weight pairs extracted from a corpus. comparison_vocab (dict): The vocabulary to be checked....
def _KeyValueToDict(pair): """Converts an iterable object of key=value pairs to dictionary.""" d = dict() for kv in pair: (k, v) = kv.split('=', 1) d[k] = v return d
def addElementInTuple(arr, elt): """ :param list arr: The list to manipulate arr format -> [(x,x,{}), (x,x,{}), (x,x,{})] :param dict elt: The element to insert """ arrs = [] for tpl in arr: tpl[2].update(elt) arrs.append(tpl) return arrs
def record_read_in_group(read_calls, my_call, my_phred, my_umi, read_name): """ Add call data from read to read_calls dictionary of name -> call. """ my_call_data = [my_call, my_phred, my_umi] #, my_start # do we already have a call from this read pair? if read_name in read_calls: asser...
def is_fermat_probable_prime(n, base=2): """is_fermat_probable_prime(n [, base]) -> 0|1|2 Return a three-state flag (either 0, 1 or 2) that integer ``n `` is either a prime or Fermat pseudoprime, as witnessed by one or more integer bases. Arguments --------- n Integer to be test...
def marketing(number: int, div1: int, div2: int) -> str: """ Args: number: The number to check div1: The first divisor div2: The second divisor Returns: The correct string. Examples: >>> marketing(5, 2, 3) "5" >>> marketing(10, 2, 3) "Ernst" >>> mark...
def velocity2speed(velocity): """ Turns a vector into a scalar. Is never negative. """ speed = 0 for i in velocity: speed += abs(i) return speed
def beginsField(line): """ Does the given (stripped) line begin an epytext or ReST field? """ if line.startswith("@"): return True sphinxwords = """ param params return type rtype summary var ivar cvar raises raise except exception """.split() for word in sphinxwords: ...
def file_ext_2_bar_size(file_ext): """ :param file_ext: :return: """ ret = { 'day': 86400, '5': 300, 'lc1': 60, 'lc5': 300, }[file_ext] return ret
def concatenate(str1, str2): """ concatenate str1 and str2""" return str(str1) + str(str2)
def check_references(reference: str, text: str) -> bool: """ Checks if the specified reference is in the list of references in the index card. """ return reference in text.split('/')
def geometric_series(common_ratio, number_of_images, first_term=1): """ This will provide the geometric series for the integration. Last values of the series has to be less than or equal to number of images ex: number_of_images = 100, first_term =1 common_ratio = 2, geometric_series = 1, 2, 4, ...
def _xrt_component_package(name, package): """ Get component package filename from base XRT package filename. Args: name (str): Package component name like 'xrt' or 'aws'. package (str): Package filename. Returns: Component package filename. """ return package[::-1].rep...
def rotate_axes(position, axes): """Rotate axes in position Examples -------- >>> rotate_axes([1, 2, 3], "xy") (1, 2, 3) >>> rotate_axes([1, 2, 3], "yz") (2, 3, 1) """ missing_axes = set('xyz') - set(axes) for a in missing_axes: axes += a assert len(axes) == 3 m...
def remove_namespace_from_string(name): """ Removes namespace from given string. Does not matter if the given name is a short or long one :param name: str :return: str """ sub_name = name.split('.') if not sub_name: return '' return sub_name[-1]
def urljoin(*args): """ Joins given arguments into a url. Trailing but not leading slashes are stripped for each argument. """ return "/".join([str(x).rstrip('/') for x in args])
def to_box(coords): """Canonicalize a set of coords to ensure the are upper left corner to lower right.""" if coords[0] > coords[2]: coords[0], coords[2] = coords[2], coords[0] if coords[1] > coords[3]: coords[1], coords[3] = coords[3], coords[1] return coords
def checkstack(the_string): """checks for pytex""" import inspect thestack = [] for bit in inspect.stack(): for b in bit: thestack.append(str(b)) as_string = ' '.join(thestack) return as_string.lower().count(the_string) > 1
def get_dirs_and_files(key_list, prefix): """ Return a 2-tuple of sets. The first set in the 2-tuple contains directory names and the second set contains files names. Example with an object_key of /static/. The leading slash from / get_dirs_and_files('/static/', ['static/css/ads.css', 'static/js/ma...
def get_inputs(node, kwargs, with_shapes=False): """Helper function to get inputs""" name = node["name"] proc_nodes = kwargs["proc_nodes"] index_lookup = kwargs["index_lookup"] graph_shapes = kwargs["graph_shapes"] inputs = node["inputs"] attrs = node.get("attrs", {}) input_nodes = [] ...
def write(scope, filename, lines, mode=['a']): """ Writes the given string into the given file. The following modes are supported: - 'a': Append to the file if it already exists. - 'w': Replace the file if it already exists. :type filename: string :param filename: A filename. :typ...
def _construct_name(date, n): """Helper method to construct a name including the directory path""" name = "".join((date, "-img-", "{:03d}".format(n), ".jpg")) return name
def parallel(sys1, *sysn): """ Return the parallel connection sys1 + sys2 (+ ... + sysn) Parameters ---------- sys1 : scalar, StateSpace, TransferFunction, or FRD *sysn : other scalars, StateSpaces, TransferFunctions, or FRDs Returns ------- out : scalar, StateSpace, or TransferFun...
def scalar(typename): """ Returns scalar type from ROS message data type, like "uint8" from "uint8[100]". Returns type unchanged if already a scalar. """ return typename[:typename.index("[")] if "[" in typename else typename
def is_IPv4(ip_string): """Returns true if the string is an IPv4: 4 digits < 255, separated by dots""" digit_list = ip_string.split(".") if len(digit_list) != 4: return False for d in digit_list: if int(d) > 255: return False return True
def set_nth_bit(n: int, i: int) -> int: """ Set the n-th bit. >>> bin(set_nth_bit(0b100000, 0)) '0b100001' >>> bin(set_nth_bit(0b100001, 0)) '0b100001' """ return n | (1 << i)
def get_word_size(similarity_threshold): """ http://www.bioinformatics.org/cd-hit/cd-hit-user-guide.pdf -n 5 for thresholds 0.7 ~ 1.0 -n 4 for thresholds 0.6 ~ 0.7 -n 3 for thresholds 0.5 ~ 0.6 -n 2 for thresholds 0.4 ~ 0.5 """ if similarity_threshold >= 0.7: return 5 elif s...
def get_call_type(workflow_metadata): """Finds run type of Cromwell workflow's task metadata, single end or paired end. Args: workflow_metadata (dict): A dict representing the workflow metadata. Returns: call_type (string): String to represent which type of call was run for MultiSample SS2...
def summerB(n: int) -> int: """ Iterates over the multiples only. Uses a set to avoid repeats. """ total = 0 fizzvisits = set() for i in range(0, n, 3): total += i fizzvisits.add(i) for j in range(0, n, 5): if j not in fizzvisits: total += j return tot...
def ll_to_utm(longitude, latitude, projection): """ Convert longitude latitude to UTM :param longitude: :param latitude: :param projection: the projection to use :return: tuple result, (easting, northing) """ return projection(longitude, latitude)
def has_homophones(pro, word): """True if word can drop either of first two letters and get a homophone both ways. pro: dictionary of pronuncations word: string """ if not (word in pro and word[1:] in pro and word[0]+word[2:] in pro): return False return pro[word]==pro[word[1:]]==pro...
def getChapterAt(cur_cIndex, cur_chapters): """ helper function for getting a chapter object at a desired location within a nested list of chapter dicts params: cur_cIndex: array of indices into cur_chapters cur_chapters: array of chapter dict objects (which individually may or may not have ...
def is_unsigned(value, bits): """Returns whether the given value is the Python equivalent of an unsigned with the given length.""" return not (value & ~(2**bits-1))
def patch_html(html): """Patch anchor elements to specify the target attribute The links created by the tagstatlink option will fail to open when viewed within a frame. Even if that weren't the case, I don't think we want them to open up in the frame inside a metaci test result page. This adds...
def find_bracket_position(generated_text, _type_start, _type_end): """ Find the bracket position in generated text, return a dictionary, bracket and their corresponding position list """ bracket_position = {_type_start: list(), _type_end: list()} for index, char in enumerate(generated_text): ...
def filter_ranges_by_gapsize(ranges, max_gap_size=0): """ Go over all ranges and those that should form 1 longer range, glue them E.g. [(0, 16), (16, 20), (24, 28), (32, 36), (36, 40), (48, 52)] becomes: [(0, 20), (24, 28), (32, 40), (48, 52)] Note, this code does the same as Osca...
def GC_skew(seq, window = 100): """Calculates GC skew (G-C)/(G+C) for multuple windows along the sequence. Returns a list of ratios (floats), controlled by the length of the sequence and the size of the window. Does NOT look at any ambiguous nucleotides. """ # 8/19/03: Iddo: added lowercase ...
def transpose(*args, errors = True): """ ================================================================================================= transpose(*args, errors) Given an arbitarary number of lists, flip the row and column space of those lists. =============================...
def TimelineName(name, source_type, value_type): """Constructs the standard name given in the timeline. Args: name: The name of the timeline, for example "total", or "render_compositor". source_type: One of "cpu", "gpu" or None. None is only used for total times. value_type: the type of value. For exam...
def cost(z): """ Cost function. """ return z[0] * 1.3
def get_dataset_by_id(activity_id, data): """get the dataset specified by an activity id from a database""" dataset = [i for i in data if i['id'] == activity_id][0] return dataset
def stations_by_river(stations): """ Groups stations by the river they are on. Args: stations: list of MonitoringStation objects Returns: A dictionary mapping river names (string) to a list of MonitoringStation objects """ ret = {} for s in stations: river = s.river ...
def merge_dicts(*dicts): """Ordered merge of dicts, with right overriding left.""" d = {} for newdict in dicts: d.update(newdict) return d
def ms_to_samples(ms, fs): """ Compute milliseconds to number of samples. Parameters ---------- ms: number Milliseconds fs: number Sampling rate Returns ------- n_samples: int Number of samples """ return ms * fs / 1000.0
def PNT2Tidal_Pv10(XA): """ TaylorT2 0PN Quadrupolar Tidal Coefficient, v^10 Phasing Term. XA = mass fraction of object """ return 72-66*XA
def calc_gsd_cross(altitude, focal_length, pixel_dim_cross): """ ground sample distance (gsd) is the distance between pixel centers measured on the ground. https://en.wikipedia.org/wiki/Ground_sample_distance Returns ------- double : meters per pixel ...
def ang2str(angle_deg): """Convert an angle in degrees to a unicode string with appropriate units. """ try: angle_deg = float(angle_deg) angle_arcsec = angle_deg*3600.0 if angle_arcsec<60.0: text = u'{:.2f}"'.format(angle_arcsec) elif angle_arcsec>=60.0 and angle_...
def setval_block(val_dct, setval_sign='='): """ write the .zmat setval block to a string """ setval_str = '\n'.join([ '{:<5s}{}{:>11.6f}'.format(name, setval_sign, val) for name, val in val_dct.items()]) return setval_str
def get_dense_json_path(data_dir: str, data_type: str, split: str = '1.0') -> str: """ Call as get_dense_json_path(data_dir=data_dir, data_type=data_type) :param data_dir: :param data_type: :param split: :return: """ json_path = f"{d...
def chrtran(text, tosearch, toreplace): """ chrtran """ for j in range(0, len(tosearch)): c = toreplace[j] if j in range(0, len(toreplace)) else "" text = text.replace(tosearch[j], c) return text
def get_loc(instr): """ Retrieve location from instruction Note: The return value has side effect :param instr: instruction tuple :return: location of the instruction """ return instr[-2]
def _make_divisible(channel_size, divisor=None, min_value=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet....
def knapsack(w, n, vals, wts): """Find the maximum value possible using n weights up to 'w' -- include weight only once :param w: Given weight :param n: Number of weights/values :param vals: List of values of n items :param wts: List of weights of n items :returns: Maximum value possible ""...
def remove_comments_in_ini_section(ini_section, cmt_string='###'): """ Remove comments in ini section. where comment is the sentence rting the special string combination such as '###' :param ini_section: :param cmt_string: :return: """ ini_out = ini_section for key in ini_section: ...
def format_proxy_advice(proxy_advice_dict: dict) -> str: """ Ignoring proxy advice """ proxy_advice_str = '' return proxy_advice_str
def generate_column_names_per_user(number_options=3): """ This function generates a list which will be used for columns, Arguments: number_options -- this determines the number of options a forecaster has to fultill (by default=3) Returns: column_names -- a list containing the column n...
def meta_S2string(S2str): """ get meta information of the Sentinel-2 file name Parameters ---------- S2str : string filename of the L1C data Returns ------- S2time : string date "+YYYY-MM-DD" S2orbit : string relative orbit "RXXX" S2tile : string til...
def compute_score_for_coagulation(platelets_count: int) -> int: """ Computes score based on platelets count (unit is number per microliter). """ if platelets_count < 20_000: return 4 if platelets_count < 50_000: return 3 if platelets_count < 100_000: return 2 if plate...
def creator_instrument(lower, upper): """ Generates the aproximated instrument string based in the frequencies, to use directly with CallistoSpectrogram """ lower = int(lower) upper = int(upper) if lower>=1200 and upper<=1800 : return "BLEN5M" if lower>=110 and upper<=870 : return "BLEN7M" ...
def prepends(file, pre, suf): """ Check if filename starts with/ends with stuff. :param file: File to check. :type file: str :param pre: Prefix(es) to check. :type pre: str or list or tuple :param suf: Suffix(es) to check. :type suf: str or list or tuple """ return file.starts...
def cell(data, label, spec): """ Format the cell of an HTML table Parameters ---------- data : string string representation of cell content label : string optional cell label, used for tooltips spec : dict options for the formatters Returns ------- str...
def _convert_unit(size_string): """ Convert given string to size in megabytes :param string size_string: Size with unit :returns integer: Converted size from given unit :rtype integer: """ size, unit = size_string.split(' ') if 'M' in unit: return int(float(size)) elif 'G' i...
def report_summary_string(inlist, delim=" "): """Report summary string from a list of values E.g. 5 5 5 2 3 2 would be summarized as 5*3 2*2 3*1 Parameters ---------- inlist : list List of strings or values that can be coerced as strings, to be summarized delim : str C...
def splitattr(url): """splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].""" words = url.split(';') return words[0], words[1:]
def getUrl(sIpAddress): """Returns the full cgi URL of the target""" return 'http://' + sIpAddress + '/cgi-bin/xml-cgi'
def rpad(s, l): """ add spaces to the end of s until it is length l """ s = str(s) return s + " "*max(0, (l - len(s)))
def clamp(x, lo, up): """Clamp ``x`` to be ``lo <= x <= up``.""" assert lo <= up return lo if x < lo else up if x > up else x
def left_forward(char, k, counts, alphabet=None): """Return the index of the k-th char in the list of all char of the studied text, ordered as in given alphabet or lexicographical order. Alphabet can be interpolated from counts, that is a dict character:count in text, by use the lexicographical order. ...
def isascii(text): """check text is all ascii character. Python 3.6 does not support str.isascii() """ return all(ord(c) < 128 for c in text)
def check_balanced(input_str): """ Checks if input string is balanced paranthesis """ stack = list() balanced = True for char_ in input_str: if char_ == '(': stack.append(char_) elif char_ == ')': if len(stack) == 0: balanced = False ...
def get_real_tag(origin_tag): """ Get real tag """ if origin_tag == "O": return "O" return origin_tag[0:len(origin_tag) - 2]
def get_modified_columns(fields, fields_to_replace): """ This method updates the columns by adding prefix to each column if the column is being replaced and joins it with other columns. :param fields: list of fields of a particular table :param fields_to_replace: dictionary of fields of a table wh...
def fibonacci_sequence(end_number): """ :param end_number: number under which we want finding terms in the Fibonacci sequence :return: list of terms in the Fibonacci sequence """ new_list = [1, 2] while True: num = new_list[-1] + new_list[-2] if num >= end_number: ...
def transform(legacy_data: dict) -> dict: """ Extract-Transform-Load (ETL) is a fancy way of saying, "We have some crufty, legacy data over in this system, and now we need it in this shiny new system over here, so we're going to migrate this." :param legacy_data: :return: """ data = ...
def count_lines(filename): """Count the number of lines in a source file Return a pair (n0, n1), where n0 is the total number of lines, while n1 is the number of non-empty lines """ with open(filename) as f: lines = f.readlines() n0 = len(lines) n1 = 0 for line...
def format_cached_datasets_coverage_string(cache_coverage: dict) -> str: """ Return a textual representation of information about cached, locally available data sets. Useful for CLI / REPL applications. :param cache_coverage: :return: """ if not cache_coverage: return 'No information...
def search_step(f, x_k, alf, p_k): """ This function performs an optimization step given a step length and step direction INPUTS: f < function > : objective function f(x) -> f x_k < tensor > : current best guess for f(x) minimum alf < float > : step length p_k < tensor > : s...
def parseDoc(api, graphs): """ did regex, this approached seems to work better """ doc = {"params":{}, "graphs":"", "summary":"", "issues":"", "returns":""} key = None subkey = None for line in api["doc"].split("\n"): linestr = line.strip() if linestr.startswith('|'): ...
def create_datatable_header(data_map): """Returns a string containing the table header in html format. Args: data_map (list): list of sublists containing sequentially: the name of the column (str), the index representing the column position in the array (int), the da...
def unhex(x): """Ensure hexidecimal strings are converted to decimal form""" if x == '': return '0' elif x.startswith('0x'): return str(int(x, base=16)) else: return x
def Chord( x, y0, y1): """; --------------------------------------------------------------------------- ; Function Chord( x, y0, y1 ) ; ; Compute the area of a triangle defined by the origin and two points, ; (x,y0) and (x,y1). This is a signed area. If y1 > y0 then the area ; will be positive...
def _build_bit_string_set(b_strings, dif_qubits, dif_values): """ Creates a new set of bit strings from b_strings, where the bits in the indexes in dif_qubits match the values in dif_values. Args: b_strings: list of bit strings eg.: ['000', '011', ...,'101'] dif_qubits: list of integers wit...
def get_coordinates(axis_value, ranges): """Get coordinates pairs from axis_value and other_values.""" start, end = ranges return [(axis_value, other_value) for other_value in range(start, end + 1)]
def egcd(a, b): """Extended Euclid's algo""" if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b / a) * y, y)
def validate_is_int(val): """"Validate value is in a valid int format. :param val: Value to test :return : boolean """ try: int(val) return True except ValueError: return False
def dict_remove(the_dict, item): """Remove an item from a dictionary.""" del the_dict[item] return the_dict
def _get_key(class_reference, property_name): """Get the key for the given class and property name.""" try: return class_reference.__deserialize_key_map__.get(property_name, property_name) except AttributeError: return property_name