content
stringlengths
42
6.51k
def _get_pip_deps(conda_env): """ :return: The pip dependencies from the conda env """ if conda_env is not None: for dep in conda_env["dependencies"]: if isinstance(dep, dict) and "pip" in dep: return dep["pip"] return []
def read_box_line(line, box, dim): """Read box info from a line.""" raw = line.strip().split() box[f'{dim}lo'] = float(raw[0]) box[f'{dim}hi'] = float(raw[1]) if len(raw) > 2: if dim == 'x': box['xy'] = float(raw[2]) elif dim == 'y': box['xz'] = float(raw[2]) ...
def sort_order(object_description: dict, key_count: int = 5, ascending: bool = True): """ .. _color_sort sort_order ---------------- Sort items in a dictionary according to value Parameters ---------- object_description: dict A dictionary whose values need sorting key_count:...
def shard_tensor(x, num_cores): """Apply XLA sharding to a tensor `x`.""" del num_cores return x
def build_order_clause(order_by): """order_by could be a list, tuple or string.""" if not order_by: return '' if type(order_by) not in (tuple, list): order_by = (order_by,) subclause_list = [] for subclause in order_by: if type(subclause) in (tuple, list): subclause = ' '.join(subclause) ...
def create_table(rst_table, caption=None, align=None, widths=None, width=None): """ This method is available within ``.. exec::``. It allows someone to create a table with a caption. The ``rst_table`` """ try: rst = [".. table:: {}".format(caption or "")] if align: r...
def sanitize(string): """ Catch and replace invalid path chars [replace, with] """ replace_chars = [ ['\\', '-'], [':', '-'], ['/', '-'], ['?', ''], ['<', ''], ['>', ''], ['`', '`'], ['|', '-'], ['*', '`'], ['"', '\''], ['.', ''], ['&', 'and'] ] for ch in repl...
def evaluate(labels, predictions): """ Given a list of actual labels and a list of predicted labels, return a tuple (sensitivity, specificty). Assume each label is either a 1 (positive) or 0 (negative). `sensitivity` should be a floating-point value from 0 to 1 representing the "true positive ...
def _to_sRGB(component): """ Convert linear Color to sRGB """ component = 12.92 * component if component <= 0.0031308 else (1.055 * (component**(1/2.4))) - 0.055 return int(255.9999 * component)
def generate_sns_event(message, topic, subject): """ Generates a SNS Event :param str message: Message sent to the topic :param str topic: Name of the Topic :param str subject: Subject of the Topic :return dict: Dictionary representing the SNS Event """ return { "Records": [{ ...
def is_ip(addr): """Determine if a string is really an ip, or a hostname instead. Args: addr (str): The ip address string to check Returns: bool: Whether or not `addr` is a valid ip. """ if '.' not in addr: return False parts = addr.split('.') for part in parts: ...
def get_protein_dcid(mint_aliases): """Takes a string from the mint database, return the dcid of the protein. Args: mint_aliases: a line contains the aliases of the protein. The capitalized "display_long" name is the dcid of the participant protein. mint_aliases example: 'psi-mi:rpn3_yeast(d...
def validate_endpoints(closed): """ Check that the `closed` argument is among [None, "left", "right"] Parameters ---------- closed : {None, "left", "right"} Returns ------- left_closed : bool right_closed : bool Raises ------ ValueError : if argument is not among valid...
def get_glo_cod_phs_bis_list(batches): """ Obtain the GLO code phase bias for the receiver used. This is unknown for the moment """ cod_phs_bis_list = {} return cod_phs_bis_list
def get_max_speed(highway): """ return the corresponding max speed in kmph """ if highway == 'mortorway': return 100 elif highway == 'mortorway_link': return 60 elif highway == 'trunk': return 80 elif highway == 'trunk_link': return 40 elif hig...
def _get_tuple_state_names(num_states, base_name): """Returns state names for use with LSTM tuple state.""" state_names = [ ("{}_{}_c".format(i, base_name), "{}_{}_h".format(i, base_name)) for i in range(num_states) ] return state_names
def evidence_from_inversion_terms( chi_squared, regularization_term, log_curvature_regularization_term, log_regularization_term, noise_normalization, ): """Compute the evidence of an inversion's fit to the datas, where the evidence includes a number of \ terms which quantify the complexity o...
def get_binary2source_entity_mapping(source2binary_mapping_full): """ for each binary functions, aggregate all source functions mapping to this function""" binary2source_entity_mapping_simple_dict = {} binary2source_entity_mapping_line_dict = {} unresolved_binary_address = [] binary2source_function_...
def flip_bit(b: str) -> str: """ Flip the bit. 0 -> 1 and 1 -> 0 :param b: Bit to be flipped :return: Flipped bit """ return "0" if b == "1" else "1"
def combine_histories(existing_history: dict, new_history: dict) -> dict: """Combines model training history objects, such that the new history from a more recent training session is appended to the existing history from a previous training session. Args: existing_history: Model training history fr...
def refine_bound(ul, br): """Adjust bound""" ul[0] = min(ul[0], br[0] - 5) ul[1] = min(ul[1], br[1] - 5) br[0] = max(br[0], ul[0] + 5) br[1] = max(br[1], ul[1] + 5) return ul, br
def solver_problem1(position): """input position and return min fuel cost of alignment""" min_fuel = float("Inf") for i in range(min(position), max(position)): dist = [0] * len(position) dist = [abs(position[j] - i) for j in range(len(position))] min_fuel = min(min_fuel, sum(dist)) ...
def getFirstValid(opts, default): """Returns the first valid entry from `opts`, or `default` if none found. Valid is defined as ``if o`` returns true.""" for o in opts: if o: return o return default
def decode_run_length(encoded_string): """Again, aware this could be much cleaner. In a hurry right now.""" string = "" for x in range(0, len(encoded_string), 2): num, char = encoded_string[x], encoded_string[x + 1] string += "".join([char] * int(num)) return string
def get_dataset_json(met, version): """Generated HySDS dataset JSON from met JSON.""" return { "version": version, "label": met['data_product_name'], "location": met['location'], "starttime": met['sensingStart'], "endtime": met['sensingStop'], }
def type_eq(cdm_column_type, submission_column_type): """ Compare column type in spec with column type in submission :param cdm_column_type: :param submission_column_type: :return: """ if cdm_column_type == 'time': return submission_column_type == 'character varying' if cdm_colum...
def depth_name(depth_index): """ Returns the name of the depth map for index: 0-48 """ if depth_index < 10: return 'depth_map_000{}.pfm'.format(depth_index) else: return 'depth_map_00{}.pfm'.format(depth_index)
def filter_by_support(ck_and_support, min_support): """ filter by support :param ck_and_support: {ck_frozenset: support_int, ..., ..} :param min_support: float * length of datas :return: """ lk = [] lsupport = [] for c, s in ck_and_support.items(): if s >= min_support: ...
def parse_class_name(uri: str): """Parse the class name in a URI. The input is expected to be of the form 'http://sbols.org/v3#Component' or 'http://example.com/ApplicationSpecificClass'. This function would return 'Component' and 'ApplicationSpecificClass' respectively. """ if '#' in uri: ...
def identity( instance_id, primitive_id ): """ :param instance_id: 1-based instance id :param primitive_id: 1-based primitive id # unsigned identity = ( instance_id << 16 ) | (primitive_id << 8) | ( buildinput_id << 0 ) ; """ buildinput_id = primitive_id return ( instance_id << 16 ) | (p...
def maximize(pyramid): """Recursively find the sum of the maximum path for the pyramid""" row = len(pyramid) - 2 #last row remains unchanged while row >= 0: numItems = row + 1 for i in range(numItems): maxNext = pyramid[row+1][i] if maxNext < pyramid[row+1][i+1]: ...
def cast_nested_dict(d, original_type, new_type): """Cast items in a nested dict to a new type. Converts all leaves of type `original_type` to type `new_type` Args: d (dict): nested dict to cast original_type (type): old type to convert new_type (type): new type to apply to leaf no...
def str_to_int_list(message): """ Turns a string into a list of utf8 encoded bytes. """ return list(message.encode('utf8'))
def modsqrt(a, p): """Compute the square root of a modulo p when p % 4 = 3. The Tonelli-Shanks algorithm can be used. See https://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm Limiting this function to only work for p % 4 = 3 means we don't need to iterate through the loop. The highest n such that p ...
def is_int(val): """Check if a value is an integer, with support for alternate integer types such as Numpy integers. Args: val: Value to check. Returns: True if ``val`` is castable to an int. """ return val == int(val)
def clear_dobson_paddy(relevance, accuracy): """ Calculate the certainity level using the approach presented in Clear, Adrian K., Simon Dobson, and Paddy Nixon. "An approach to dealing with uncertainty in context-aware pervasive systems." UK/IE IEEE SMC Cybernetic Systems Conference. 2007. :para...
def get_number_edited_reads(row): """ SAILOR reports the total coverage and edit fraction in the 'info' column. Use these two numbers to get the number of edited reads. """ total_reads, edit_type, fraction = row['info'].split('|') return round(int(total_reads) * float(fraction))
def bbox2points(bbox): """ From bounding box yolo format to corner points cv2 rectangle """ [x, y, w, h] = bbox xmin = int(round(x - (w / 2))) xmax = int(round(x + (w / 2))) ymin = int(round(y - (h / 2))) ymax = int(round(y + (h / 2))) mid = ymin + (ymax - ymin)/2 global r_st...
def time_handling(year1, year1_model, year2, year2_model): """ This function is responsible for finding the correct files for the needed timespan: year1 - the start year in files year1_model - the needed start year of data year2 - the last year in files year2_model - the needed last year o...
def get_brand_details(brand): """ Any special reason they can't all just be called logo.png? (since they're already in namespaced subdirectories) Sure would cut down on unproductive complexity here. """ return { "braini": {"name": "BRAIN-I", "logo": "braini-lg-gray.png"}, "scidas...
def any_params(d, k): """ Shortcut function for finding truthy values in a |dict| If the |dict| `d` contains truthy values at one or more of the keys in `k`, returns |True|. Otherwise, |False|. Parameters ---------- d |dict| -- Dictionary of values to evaluate. k iterable ...
def obscure(item, start=3, end=3): """ Replaces middle of string with * :param item: string - to be obscured string :param start: int - how many letters to leave from start :return: obscured string - how many letters to leave from end """ # ignore None if item is None: return Non...
def localHostOrDomainIs(host, hostdom): """ :param str host: the hostname from the URL. :param str hostdom: fully qualified hostname to match against. :return: true if the hostname matches exactly the specified hostname, or if there is no domain name part in the hostname, but the unqualified hos...
def digitsNumber(v): """ Return the number of digit for a given Float or Integer. Negative Sign is removed. Digits after the decimal sign are removed too. """ try: return len(str(abs(int(v)))) except Exception as inst: print(inst.args) return 0
def get_index_csv_data(data, entry_dict): """Get index of .csv header entries""" indices = {} for entry_key in entry_dict: indices[str(entry_key)] = data[0].index(entry_dict[entry_key]) return indices
def expand_long_bytes(dtraces, longer_than=900, divide_by=500, max_expand=16): """Turn long-lasting bytes into multiple bytes. Oh, it's too bad we don't have a clock signal. We just have to guess: is a $0D that lasts 1200ns a single $0D byte or several $0D bytes in a row? This function takes bytes that hang ar...
def get_dim(edgelist): """Given an adjacency list for a graph, returns the number of nodes in the graph. """ node_dict = {} node_count = 0 for edge in edgelist: p, q = edge[ :2] if p not in node_dict: node_dict[p] = True node_count += 1 if q not in...
def extract_json_from_line(line): """Extracts the JSON from a line of JS that we know has a { in it. It's assumed that this line has already had .strip() called on it (i.e. it has no leading or trailing whitespace). """ # The -1 in the slicing operation below removes the trailing semicolon # (...
def is_sorted(array): """ Check if array of numbers is sorted :param array: [list] of numbers :return: [boolean] - True if array is sorted and False otherwise """ for i in range(len(array) - 1): if array[i] > array[i + 1]: return False return True
def to_list(var): """Transform element into list""" if isinstance(var, (list, tuple)): return var return [var]
def moneyline(outcomes): """ gets both teams moneyline """ a_ml = None h_ml = None for outcome in outcomes: price = outcome["price"] if outcome["type"] == "A": a_ml = price["american"] else: h_ml = price["american"] return [a_...
def lowercase(raw_text: str) -> str: """ >>> lowercase("This is NeW YoRk wIth upPer letters") 'this is new york with upper letters' """ return raw_text.lower()
def remove_regions(d, regions): """Convert PPE/rep regions to NAs""" for pos in d: for reg in regions: if int(pos) >= reg[0] and int(pos) <= reg[1]: d[pos] = ["NA", "NA", "NA", "NA"] #print("PPE REGION") else: continue return d
def get_segment_ids(tokens, max_seq_length): """Segments id : 0 for the first sequence, 1 for the second""" if len(tokens)>max_seq_length: raise IndexError("Token length more than max seq length!") segments = [] first_sep = True current_segment_id = 0 for token in tokens: segment...
def _tag_in_string(source: str, start: str, end: str) -> bool: """Determine if a specific tag is in a string. :param source: String to evaluate :param start: String that marks the start of a tag :param end: String that marks the end of a tag :returns: Decision """ if start not in source: ...
def string_to_int(message): """ Converts string message into integer. - **Arguments** :message: String message """ ord_list = [] for x in range(0, len(message)): ord_list.append(ord(message[x])) return ord_list
def bytes_to_human(bytes, suffix="B"): """ Original Code: Scale bytes to its proper, human readable format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{...
def removeBorderSpaces(inputStr): """ Function that removes trailing and leading whitespaces Argument: -inputStr (str) Returns: A str of inputStr without leading and trailing whitespaces """ if len(inputStr) == 0: return str() if inputStr[0] == ' ': return ...
def forces_in_dataset(dataset): """Check if forces in displacement dataset.""" if dataset is None: return False if type(dataset) is not dict: raise RuntimeError("dataset is wrongly made.") if "first_atoms" in dataset: # type-1 for d in dataset["first_atoms"]: if "f...
def compare_rgb_colors_tolerance(first_rgb_color, second_rgb_color, tolerance): """ Compares to RGB colors taking into account the given tolerance (margin for error) :param first_rgb_color: tuple(float, float, float), first color to compare :param second_rgb_color: tuple(float, float, float), second col...
def nth_occurence(ls, val, n): """Returns the index of the nth occurance of a value in a list.""" return [i for i, x in enumerate(ls) if x == val][n - 1]
def linecode_maker(line): """return the linecode and the line. The two-character line code that begins each line is always followed by three blanks, so that the actual information begins with the sixth character.""" linecode = line.split(" ", 1)[0] return linecode, line
def execOnce(resultTupleList, code): """ Run the code once, ignoring the result list and updating the global namespace. """ exec(code, globals()) return resultTupleList
def has_flag(flag, cmd): """Return true if a cmd contains a flag or false if not.""" return bool(next((x for x in cmd if x.startswith(flag)), False))
def cont_tuple_to_tuple_cont(container): """Converts a container (list, tuple, dict) of tuple to a tuple of container.""" if isinstance(container, dict): return tuple(dict(zip(container, val)) for val in zip(*container.values())) elif isinstance(container, list) or isinstance(container, tuple): ...
def sort_peaks(peaks, sep="|"): """Sort peak combinations by first sign and month. Examples: >>> sort_peaks(['0(+)', '0(-)', '12(+)|0(+)', '12(+)|0(-)', '6(-)', '3(+)']) ['0(+)', '3(+)', '12(+)|0(+)', '12(+)|0(-)', '0(-)', '6(-)'] """ pos_indices = [] neg_indices = [] for i, p...
def translate(s: str, src: str, dest: str) -> str: """ Converts characters from `s` that appear in `src` with the characters at corresponding positions in `dest` """ if len(src) != len(dest): raise RuntimeError("impossible error") for a, b in zip(src, dest): s = s.replace(a, b) return s
def store_nugget_nodes(gold_nuggets, sys_nuggets, m_mapping): """ Store nuggets as nodes. :param gold_nuggets: :param sys_nuggets: :param m_mapping: :return: """ # Stores time ML nodes that actually exists in gold standard and system. gold_nodes = [] sys_nodes = [] # Store t...
def flatten_categories(categories): """Flatten category descriptions out into a list Args: categories (list of dict): List containing category objects. Returns: descriptions (list): List of category descriptions """ return [cat['description'] for cat in categories]
def get_names(shp): """Read data file and return a string of valid names >>> get_names('ga.shp') 'Appling Atkins ... White' """ # stub for future use return 'A B C'
def get_last_id(file_name): """Retrieve last status ID from a file""" try: with open(file_name) as f: last_id = int(f.read()) return last_id except IOError: return 0
def mod(x:float, y:float, z:float=0.0) -> float: """ Return the remainder on division of x by y with offset z. Note, float value is returned """ return x - ((x - z) - (x - z) % y)
def transform(text, transformations): """ Replaces every occurrenc of transformation[0] with transformation[1] for every transformation in transformations. Input arguments: text -- text we are transforming transformations -- list of transformations Each transformation has: ...
def pop_order_at_loc(tpos, loc): """If there is an order at loc in tpos, remove and return it tpos: A list of (turn, power, order) tuples Returns: (power, order) if found, else (None, None) """ for i, (_, power, order) in enumerate(tpos): order_loc = order.split()[1] if loc.split("/"...
def interpolate(x1: float, x3: float, y1: float, y2: float, y3: float): """ Interpolation function. :param x1: :param x3: :param y1: :param y2: :param y3: :return: """ return (y2 - y3) / (y1 - y3) * (x1 - x3) + x3
def sn2recipe(scenario: list) -> list: """ Extract scenario item to recipe Parameters ---------- scenario: list use only index 1 0: number, 1: items (order and recipe), 2:judge Returns ---------- subOrder: list 0: mainOrder, 1-end:subOrders ...
def strip_output_logs(output): """Strips logs such as 'Add user ... ' etc from output returned by env_up. Returns env description. """ return output.strip().split('\n')[-1]
def generate_voucher_number(number): """ NEED AN INTEGER generate_voucher_number(number objects) """ sno = '' number = int(number)+1 number = str(number) if len(number)<2: sno = '00000'+number elif len(number)<3: sno = '0000'+number elif len(number)<4: sno =...
def find_indexes_where_lists_differ(list1: list, list2: list) -> list: """This function returns the indexes where the two input lists differ. THe input lists are expected to have same length Args: list1 (list): first input list list2 (list): second input list Returns: out_list (list)...
def get_filename(url): """ Get the filename of a url """ return url[url.rfind("/")+1:]
def Le(tC,hC,rho,DAB): """ Lewis number: thermal conductivity/(heat capacity)/(humid vapor density)/(DAB) Paramters: tC, thermal conductivity in W/m/K hC, heat capacity in J/mol/K rho, molar density of humid vapor in mol/m^3 DAB, diffusion of component A in B in...
def _avoid_wrapping(value): """ Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces. """ return value.replace(" ", "\xa0")
def CI_calc(mean, SE, CV=1.96): """ Calculate confidence interval. :param mean: mean of data :type mean: float :param SE: standard error of data :type SE: float :param CV: critical value :type CV:float :return: confidence interval as tuple """ try: CI_down = mean - C...
def resolvePattern(pat): """handle a leading `#` or `@` in a pattern """ pat = pat.strip() if not pat or pat.startswith('#'): return [] elif pat.startswith('@'): raw = pat[1:] return [ raw, f'!packages/**/{raw}', f'!**/node_modules/**/{raw...
def compact_list(lst): """ Compact a list removing all non truthful values """ return [item for item in lst if item]
def disjoint_2(array_one: list, array_two: list, array_three: list) -> bool: """ BIG-O Notation: O(n^3) :param array_one: list of item :param array_two: list of item :param array_three: list of item :return: bool """ for a in array_one: for b in array_two: if a == ...
def organiser_email(meta): """Get email from organiser text.""" v = meta.get('organiser') or '' if type(v) == dict: return v.get('email', '') return ''
def convert_string_to_bool(string_value): """ simple method used to convert a tring to a bool :param string_value: True or False string value :type string_value: string - required :return: bool True or False :rtype bool """ if string_value == 'True': return True else: ...
def save(sizes: list, hd: int) -> int: """ Your task is to determine how many files of the copy queue you will be able to save into your Hard Disk Drive. Input: Array of file sizes (0 <= s <= 100) Capacity of the HD (0 <= c <= 500) Output: Number of files that can be fully saved in...
def truncate(f, digits): """truncate. Args: f: digits: """ return ("{:.30f}".format(f))[:-30+digits]
def isWord(s): """ See if a passed-in value is an identifier. If the value passed in is not a string, False is returned. An identifier consists of alphanumerics or underscore characters. Examples:: isWord('a word') ->False isWord('award') -> True isWord(9) -> Fals...
def truncate(text: str, desired_length: int, *, suffix: str = "...") -> str: """ Truncates text and returns it. Three periods will be inserted as a suffix. Parameters ---------- text The text to truncate. desired_length The desired length. suffix The text to insert b...
def config_ids(sid, uid, aid): """ Identifiers for the next AT*CONFIG command Parameters: sid -- current session id uid -- current user id aid -- current application id """ assert all(map(lambda x: type(x) == int, (sid, uid, aid))) return sid, uid, aid
def reverse_str(name: str) -> str: """ Reverses a string """ name_lst = list(name) name_lst.reverse() ret = '' for i in range(len(name_lst)): ret += name_lst[i] return ret
def get_env_variables_and_values(env_dict): """ This method get all the environment variables which starts with ENV_ and create a dict with the key as the name after ENV_ and value as the environment value Args: env_dict (dict): This is the real enviorment variable dict Returns: en...
def normalize_sublang_args(args): """ Transform the command line arguments we have into something that conforms to the retrieve_language_resources interface. This mostly means using the given lang parameter as the default lang, overridable by the different sublang args. """ return { "video_l...
def parse(content, esc): """ type(content) = str """ d = {} for c in content.split(esc): c = c.split(esc[::-1]) if len(c) == 1: section = c[0] content = '' elif len(c) == 2: section = c[0] content = c[1] else: ...
def strtobool(val): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in ('y', 'yes...
def getDistancesBetween( ls ) : """ Given a sorted list of items, return the distances between each item. Ex: Given [1, 2, 6, 11], returns[ 1, 4, 5 ] """ toRet = [] intLs = [ int(x) for x in ls ] for i in range(1, len(intLs)) : toRet.append( intLs[i] - intLs[i-1] ) return to...
def fix_illegal_name(name_str): """Repair names that will cause a RuntimeError These include names starting with a number and empty strings. Most (maybe all?) other problems will be fixed by converting illegal characters to underscores. """ if not name_str: return "_" elif name_str[0]....