content
stringlengths
42
6.51k
def _texture_path(texture_bricks_name): """ Parameter --------- texture_bricks_name : str name of the world main texture Return ------ texture_path: (str) path corresponding to the texture_bricks_name Raises ------ ValueError : raised if texture_bricks_name is unkwnonw...
def eval_files(prec: str = "50") -> list: """Obtain a list of pre-processed dataset file patterns for evaluation. Args: prec (str, optional): The percentage here should match with train_files. Returns: list: The TFRecord file patterns for evaluation during training. """ return ["gs...
def remove_whitespace(text): # type: (str) -> str """strips all white-space from a string""" if text is None: return "" return "".join(text.split())
def listi(list_, elem, default=None): """ Return the elem component in a list of lists, or list of tuples, or list of dicts. If default is non-None then if the key is missing return that. Examples: l = [("A", "B"), ("C", "D")] listi(l, 1) == ["B", "D"] l = [{"A":1, "B":2}, {"A"...
def make_key(element_name, element_type, namespace): """Return a suitable key for elements""" # only distinguish 'element' vs other types if element_type in ('complexType', 'simpleType'): eltype = 'complexType' else: eltype = element_type if eltype not in ('element', 'complexType', '...
def get_player_url(playerid): """ Gets the url for a page containing information for specified player from NHL API. :param playerid: int, the player ID :return: str, https://statsapi.web.nhl.com/api/v1/people/[playerid] """ return 'https://statsapi.web.nhl.com/api/v1/people/{0:s}'.format(str(p...
def _to_short_string(text: str, max_length: int = 75) -> str: """Caps the string at 75 characters. If longer than 75 it's capped at max_length-3 and '...' is appended Arguments: text {str} -- A text string Keyword Arguments: max_length {int} -- The maximum number of characters (default...
def store_on_fs(data, file_name): """ Store data in file named `file_name` """ if data: with open(file_name, "w") as f: f.write(str(data)) return True
def aggregate_function(a, b, func): """Function to implement aggregate functions.""" return_val = False if func == "max": a[func] = max(a[func], b) elif func == "min": a[func] = min(a[func], b) elif func == "sum": a[func] = a[func]+b elif func == "avg": a[func][0]...
def merge_nested_dict(dicts): """ Merge a list of nested dicts into a single dict """ merged_dict = {} for d in dicts: for key in d.keys(): for subkey in d[key].keys(): if key not in list(merged_dict.keys()): merged_dict[key] = {subkey: {}} ...
def __tokenize_text(text): """Convert text to lowercase, replace periods and commas, and split it into a list. >>> __tokenize_text('hi. I am, a, sentence.') ['hi', 'i', 'am', 'a', 'sentence'] """ return text.lower().replace(',', '').replace('.', '').split()
def _to_basestring(value): """Converts a string argument to a subclass of basestring. This comes from `Tornado`_. In python2, byte and unicode strings are mostly interchangeable, so functions that deal with a user-supplied argument in combination with ascii string constants can use either and shou...
def _get_ascii_token(token): """Removes non-ASCII characters in the token.""" chars = [] for char in token: # Try to encode the character with ASCII encoding. If there is an encoding # error, it's not an ASCII character and can be skipped. try: char.encode('ascii') except UnicodeEncodeError:...
def one_ribbon(l, w, h): """Compute needed ribbon for one present. Arguments l, w, and h are expected to be sorted for a correct result. """ return 2 * (l + w) + l * w * h
def fp_find_omega(omega_r, omega_theta, omega_phi, em, kay, en, M=1): """ Uses Boyer frequencies to find omega_mkn Parameters: omega_r (float): radial boyer lindquist frequency omega_theta (float): theta boyer lindquist frequency omega_phi (float): phi boyer lindquist frequency ...
def polylineAppendCheck(currentVL, nextVL): """Given two polyline vertex lists, append them if needed. Polylines to be appended will have the last coordinate of the first vertex list be the same as the first coordinate of the second vertex list. When appending, we need to eliminate one of these coo...
def get_leg_swing_offset_for_pitching(body_pitch, desired_incline_angle): """Get the leg swing zero point when the body is tilted. For example, when climbing up or down stairs/slopes, the robot body will tilt up or down. By compensating the body pitch, the leg's trajectory will be centered around the vertical ...
def factors(n): """returns the factors of n""" return [i for i in range(1, n // 2 + 1) if not n % i] + [n]
def split_config(raw): """Split configuration into overall and per-stage. Args: raw (list[dict]): pipeline configuration. Returns: - dict: overall settings under "overall" key. - list[dict]: per-stage configurations. """ for (i, entry) in enumerate(raw): if "overall...
def apply(f, *args, **kwargs): """Apply a function to arguments. Parameters ---------- f : callable The function to call. *args, **kwargs **kwargs Arguments to feed to the callable. Returns ------- a : any The result of ``f(*args, **kwargs)`` Examples ...
def _get_in_out_shape(x_shape, y_shape, n_classes, batch_size=None): """Returns shape for input and output of the data feeder.""" x_is_dict, y_is_dict = isinstance( x_shape, dict), y_shape is not None and isinstance(y_shape, dict) if y_is_dict and n_classes is not None: assert isinstance(n_classes, dict...
def featurizeDoc(doc): """ get key : value of metadata """ doc_features = [] for key in doc: doc_features.append("{0}: {1}".format(key, doc[key])) return doc_features
def to_bool_str(value): """ Converts 'something' to boolean. Raises exception for invalid formats Possible True values: 1, True, "1", "TRue", "yes", "y", "t" Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ... """ if str(value).lower() in (...
def insertion_sort(x): """ Goals: The goal is to sort the an array by starting with the left most element and moving left to right move an element back if it is less than the previous element until the list is completely ordered. Variables: x is the array inputed into the function. ...
def check_not_present(context, raw_data, raw_field): """ Verifies that a specified field is not present in a raw data structure. Args: context (str): The context of the comparison, used for printing error messages. raw_data (dict): Raw data structure we're checking a field from. raw...
def time_convert(sec): """ Converts seconds into hours, minutes and seconds :param sec: Seconds as a int :return: A good formatted time string """ mins = sec // 60 sec = sec % 60 hours = mins // 60 mins = mins % 60 return "{0}:{1}:{2}".format(int(hours), int(mins), sec)
def set_bit(num, offset): """ Set bit to at the given offset to 1 """ mask = 1 << offset return num | mask
def assignGroupToURI(uri: str) -> str: """Returns a group for a URI e.g. science museum, v&a, wikidata. Should operate on the normalised URI produced by `normaliseURI`.""" if "collection.sciencemuseumgroup" in uri: return "Science Museum Group Collection" elif "blog.sciencemuseum.org.uk" in uri: ...
def _repair_snr(snr): """ SNR in Octave ommits zeros at the end :return: """ snr = "{:.4f}".format(snr) while snr.endswith('0'): snr = snr[:-1] if snr.endswith('.'): snr = snr[:-1] return snr
def is_scalar(arg) -> bool: """ Return True if the arg is a scalar. """ return isinstance(arg, int) or isinstance(arg, float)
def get_file_type(extensions: list, filename: str) -> str: """ Checks if the extension of a given file matches a set of expected extensions. Args: extensions (list): a set of expected file extensions filename (str): a file name to test is extension is expected Raises: ValueErro...
def paginate(text: str): """Simple generator that paginates text.""" last = 0 pages = [] appd_index = 0 curr = 0 for curr in range(0, len(text)): if curr % 1980 == 0: pages.append(text[last:curr]) last = curr appd_index = curr if appd_index != len(...
def _check_shape_compile(shape): """check the shape param to match the numpy style inside the graph""" if not isinstance(shape, (int, tuple, list)): raise TypeError( f"only int, tuple and list are allowed for shape, but got {type(shape)}") if isinstance(shape, int): shape = (shap...
def find_place(lines, size_x): """ Finds the highest place at the left for a panel with size_x :param lines: :param size_x: :return: line with row, col, len """ for line in lines: if line['len'] >= size_x: return line
def parse_commit_message(message): """Given the full commit message (summary, body), parse out relevant information. Mimiron generates commit messages, commits, and pushes changes tfvar changes to remote. These generated commit messages contain useful information such as the service that was bumped, th...
def checkSyntax(value): """Check the syntax of a `Python` expression. :Parameters value: the Python expression to be evaluated """ if value[0] in ("'", '"'): # Quotes are not permitted in the first position return False try: eval(value) except (ValueError, Sy...
def sort_lists(sorted_indices, list_to_sort): """ given a list of indices and a list to sort sort the list using the sorted_indices order :param sorted_indices: a list of indices in the order they should be e.g. [0,4,2,3] :param list_to_sort: the list which needs to be sorted in the indice order fro...
def mongodb_str_filter(base_field, base_field_type): """Prepare filters (kwargs{}) for django queryset for mongodb where fields contain strings are checked like exact | startswith | contains | endswith >>> mongodb_str_filter(21, '1') '21' >>> mongodb_str_filter(21, '2') {'$regex': '^2...
def remove_return_string(line): """Helper method for subtokenizing comment.""" return line.replace('@return', '').replace('@ return', '').strip()
def data_format_to_shape( batch_length=None, sequence_length=None, channel_length=None, data_format='channels_first' ): """.""" shape = [batch_length, None, None] channel_axis = 1 if data_format == 'channels_first' else 2 sequence_axis = 2 if data_format == 'channels_fir...
def flip_end_chars(txt): """Flip the first and last characters if txt is a string.""" if isinstance(txt, str) and txt and len(txt) > 1: first, last = txt[0], txt[-1] if first == last: return "Two's a pair." return "{}{}{}".format(last, txt[1:-1], first) return "Incompatib...
def reset_op_debug_level_in_soc_info(level): """ :param level: op_debug_level, if level is 3 or 4, replace it with 0 :return: op_debug_level """ if level in ("3", "4"): level = "0" return level
def valid_user_input(ui: str) -> bool: """Determines if the passed string is a valid RPS choice.""" if ui == "rock" or ui == "paper" or ui == "scissors": return True return False
def slice_expr(collection, start, count): """ Lookup a value in a Weld vector. This will add a cast the start and stop to 'I64'. Examples -------- >>> slice_expr("v", 1, 2).code 'slice(v, i64(1), i64(2))' """ return "slice({collection}, i64({start}), i64({count}))".format( ...
def sort_format(src): """ format 1-2-3... to 00001-00002-00003... src should be convertable to int """ src_list= src.split('-') res_list= [] for elm in src_list: try: res_list.append('%05d' % int(elm)) except: res_list.append(elm) res= '-'.join(res...
def smart_truncate(content, length=100, suffix='...'): """ function to truncate anything over a certain number of characters. pretty much stolen from: http://stackoverflow.com/questions/250357/smart-truncate-in-python """ if not content or len(content) <= length: return content else: ...
def get_list_from_interval(input_interval, month_interval=True): """ Created 20180619 by Magnus Wenzer Updated 20180620 by Magnus Wenzer Takes an interval in a list and returns a list with the gange of the interval. Example: [2, 7] => [2, 3, 4, 5, 6, 7] """ if not input_interv...
def dialog_response(attributes, endsession): """ create a simple json response with card """ return { 'version': '1.0', 'sessionAttributes': attributes, 'response':{ 'directives': [ { 'type': 'Dialog.Delegate' } ...
def get_state_transitions_direct(actions): """ get the next state @param actions: @return: tuple (current_state, action, nextstate) """ state_transition_pairs = [] for action in actions: current_state = action[0] next_state = action[1][0] state_transition_pairs.append...
def format_num(num): """Return num rounded to reasonable precision (promille).""" if num >= 1000.0: res = "{:,}".format(round(num)) elif num >= 100.0: res = str(round(num, 1)) # res = "{:,.1f}".format(num) elif num >= 10.0: res = str(round(num, 2)) # res = "{:,.2f...
def get_colored_for_soi_columns(value_list): """ """ list_output = [] if value_list: for each_ in value_list: dictionary = {} dictionary['if'] = {"column_id":each_} dictionary['backgroundColor'] = "#3D9970" dictionary['color'] = 'black' ...
def is_task_complete(task, task_runs, redundancy, task_id_field='id', task_run_id_field='task_id', error=None): """ Checks to see if a task is complete. Slightly more optimized than doing: len(get_task_runs()) :param task: input task object :type task: dict :param task_runs: content from task...
def get_percent(value, minimum, maximum): """ Get a given value's percent in the range. :param value: value :param minimum: the range's minimum value :param maximum: the range's maximum value :return: percent float """ if minimum == maximum: # reference from qprogressbar.cpp ...
def indexer(cell): """utility function to return cells in the format the frontend expects""" col, row = (cell) return [row, col]
def is_leap_year(year): """ if year is a leap year return True else return False """ if year % 100 == 0: return year % 400 == 0 return year % 4 == 0
def molm2_to_molec_cm2(spc_array): """ Convert moles/m2 to molec/cm2 """ avo_num = 6.0221409e23 molec_per_m2 = spc_array * avo_num molec_per_cm2 = molec_per_m2 * 1e4 return molec_per_cm2
def filter(arr:list, func) -> list: """Filters items from a list based on callback function return Args: arr ( list ) : a list to iterate func ( function ) : a callback function Examples: >>> array = Array(1, 2, 3, 4) >>> array.filter(lambda item, index: item % 2 == 0) ...
def prepend_to_line(text, token): """Prepends a token to each line in text""" return [token + line for line in text]
def select(items, container, *, ctor=None): """ Returns `items` that are in `container`. :param ctor: Constructor for returned value. If `None`, uses the type of `items`. Use `iter` to return an iterable. """ if ctor is None: ctor = type(items) return ctor( i for i in item...
def count_fillin(graph, nodes): """How many edges would be needed to make v a clique.""" count = 0 for v1 in nodes: for v2 in nodes: if v1 != v2 and v2 not in graph[v1]: count += 1 return count / 2
def get_password_from_file(passfile_path, hostname, port, database, username): """ Parser for PostgreSQL libpq password file. Returns None on no matching entry, otherwise it returns the password. For file format see: http://www.postgresql.org/docs/current/static/libpq-pgpass.html """ if n...
def filter_logs(logs, project, config): """ When given a list of log objects, returns only those that match the filters defined in config and project. The filters in project take priority over config. :param logs: A list of log objects. Logs must be in the format returned by winlogtimeline.util.logs.par...
def get_current_players_cards(player_number, player_hands): """ Return the hand from the list of player_hands which corresponds to the player number. :param: player_number, player_hands (list of Hand objects) :return: Hand(obj) """ for tup in enumerate(player_hands, 1): if tup[0] == ...
def simplify3(string): """[1,2..4]+[6] -> [1,2..4,6]""" string = string.replace("]+[",",") return string
def check_min_permission_length( permission, minchars=None ): # pylint: disable=missing-function-docstring """ Adapted version of policyuniverse's _check_permission_length. We are commenting out the skipping prefix message https://github.com/Netflix-Skunkworks/policyuniverse/blob/master/policyuniverse/...
def month(day): """ Given a the number of days experienced in the current year it returns a month :param day: Current number of days in the year :return: str, month """ if 1 >= day <= 31: return "January" elif 31 >= day <= 59: return "February" elif 60 >= day <= 90: ...
def find_aliased_pin(pin, model, pin_aliases): """ Searches for aliased pins in the timing model. The check is done using data from pin_aliases dictionary. The dictionary has an entry for each aliased pin. Each entry has two fields: * names : a list of all the possible aliases * is_property...
def personal_top_three(scores): """ Return top three score from the list. if there are less than 3 scores then return in a decending order the all elements """ # sorted the list in a decending order sorted_scores = sorted(scores, reverse=True) # check if there are at least 3 elements...
def create_node_str(node_id): """Creates node for the GML file :param node_id: The id of the node """ node_str = "\tnode\n\t[\n\t\tid " + str(node_id) + "\n\t]\n" return node_str
def get_color_file_html_new_color(scope, color, dashed): """ return new color """ if scope != "": scope_infos = "SCOPE: "+scope else: scope_infos = "" if dashed: class_added = "dashed" else: class_added = "" colorText = "#lorem ipsum<br/>! = >< Delec<br/>Rum alt...
def klass(obj) -> str: """ returns class name of the object. Might be useful when rendering widget class names Args: obj: any python class object Returns: str: name of the class >>> from tests.test_app.models import Author >>> klass(Author) 'ModelBase' """ retur...
def create_section_data_block(data_length): """Create a block of data to represend a section Creates a list of the given size and returns it. The list will have every byte set to 0xff. This is because reserved bits are normally set to 1 Arguments: data_length -- amount of bytes needed for the data block Return...
def check_equal(list): """ Determines whether two lists are equal """ return list[1:] == list[:-1]
def invert_dictionary(dictionary): """ Invert a dictionary :param dictionary: :return inverted_dictionary: """ inverted_dictionary = dict() for k, v in dictionary.items(): inverted_dictionary[v] = k return inverted_dictionary
def conditions(ctx): """ Tests for registers to verify that our glitch worked """ if ctx['regs']['rax'] == 0: return True else: return False
def lcm(num1, num2, limit=10): """lcm: finds the least common multiple of two numbers Args: num1 (int): First number to calculate lcm of num2 (int): Second number to calculate lcm of Returns: int: the least common multiple (lcm) of num1 and num2 """ num1ls = [num1] num2ls = [num2] mult = list(range(2, ...
def sub_extension(fname, ext): """Strips the extension 'ext' from a file name if it is present, and returns the revised name. i.e. fname='datafile.dat', ext='.dat' returns 'datafile'. See: add_extension """ if fname.endswith(ext): return fname[:-len(ext)] else: return fname
def isHostile(movement): """ Parameters ---------- movement : dict Returns ------- is hostile : bool """ if movement['army']['amount']: return True for mov in movement['fleet']['ships']: if mov['cssClass'] != 'ship_transport': return True return F...
def _recover_type(v): """ recover "17" to 17. recover "[]" to []. recover "datetime(2020,1,1)" to datetime(2020,1,1). keep "abc" as str. :param v: str. :return: Any. """ try: nv = eval(v) except (NameError, SyntaxError): nv = v if callable(nv): nv = v...
def get_func_definition(sourcelines): """Given a block of source lines for a method or function, get the lines for the function block. """ # For now return the line after the first. count = 1 for line in sourcelines: if line.rstrip().endswith(':'): break count += 1 ...
def get_geo_url(geo_list): """ :param geo_list: list of (geo, geo_id) pair (smallest first) e.g. [(block%20group, *), (state, 01), (county, 02), (track, *), ] :return: url for geo query """ total_level = len(geo_list) url = "" for i in range(total_level): level, ...
def square_is(location, query, board): """Checks if the piece at location equals query. Returns false if location is out of bounds.""" x, y = location if y < 0 or y >= len(board): return False if x < 0 or x >= len(board[y]): return False return board[y][x] is query
def peptide_isoforms(peptide, m, sites, prev_aa, next_aa): """ Parameters ---------- peptide : list Peptide sequence m: modification label to apply sites : set Amino acids eligible for modification Returns ------- set of lists """ isoforms = [] if ('N-te...
def read_file_to_string(filepath): """ Read entire file and return it as string. If file can't be read, return "Can't read <filepath>" :param str filepath: Path of the file to read :rtype: str :return: Content of the file in a single string, or "Can't read <filepath>" if file can't be read. """ ...
def zero_prefix_int(num): """ zero_prefix_number(int) -> str\n Puts a zero in fron of 1 digit numbers.\n otherwise just returns the int """ strnum = str(num) if len(strnum) == 1: return '0'+strnum return strnum
def bubsort (a): """bubble sorter""" need = True while need: need = False for i in range(len(a)-1): if a[i] > a[i+1]: a[i], a[i+1] = a[i+1], a[i] need = True return a
def tuple_filter(tuple_obj, index): """Returns tuple value at the given index""" # Force typecast index into integer try: index = int(index) except ValueError: return None # Verify if tuple_obj is a tuple if isinstance(tuple_obj, tuple): try: return ...
def filter_priority(clouds): """Returns the cloud with the hightes priority""" priority = int(clouds[0]['priority']) qualified_cloud = clouds[0] for cloud in clouds: if int(cloud['priority']) < priority: priority = int(cloud['priority']) qualified_cloud = cloud ret...
def cyclic_index_i_plus_1(i: int, length: int, ) -> int: """A helper function for cyclic indexing rotor scans""" return i + 1 if i + 1 < length else 0
def life_counter(field): """ returns quanity of living squares """ hype = 0 for y in range(len(field)): for x in range(len(field[y])): if field[y][x] == 'o': hype += 1 return hype
def compute_M0_nl(formula, abundance): """Compute intensity of the first isotopologue M0. Handle element X with specific abundance. Parameters ---------- formula : pyteomics.mass.Composition Chemical formula, as a dict of the number of atoms for each element: {element_name: number_...
def recursive_for_default_attributes(attributes): """ Method to extract attributes from kind desctiption and complete the missing ones in the resource description """ att_http = list() for key in attributes.keys(): if type(attributes[key]) is dict: items = recursive_for_default_...
def proj4_str_to_dict(proj4_str): """Convert PROJ.4 compatible string definition to dict Note: Key only parameters will be assigned a value of `True`. """ pairs = (x.split('=', 1) for x in proj4_str.replace('+', '').split(" ")) return dict((x[0], (x[1] if len(x) == 2 else True)) for x in pairs)
def _startswithax(item): """ Helper function to filter tag lists for starting with xmlns:ax """ return item.startswith('xmlns:ax')
def subsequenceMatch(uctext, ucterm): """ #returns array of the indices in uctext where the letters of ucterm were found. # EG: subsequenceMatch("nothing", "ni") returns [0, 4]. subsequenceMatch("nothing", "a") # returns null. #simple subsequence match """ hits = [] texti = -1 termi = 0 ...
def get_cache_file(fm): """Generate proper filename based on fumen.""" # strip version str, strip ?, replace / with _ to make it safe for filenames # note: on windows filenames are case insensitive so collisions could occur, but this probably will never happen clean = fm.replace("v115@", "").replace("?"...
def create_bin_permutations(length): """Return sorted list of permutations of 0, 1 of length. I.e, 2 --> ['00', '01', '10', '11'] """ output = [] for num in range(0, length**2): perm = f'{num:b}' perm = perm.zfill(length) return output
def contains_three_consecutive_letters(password: str) -> bool: """ Return True if the password has at least one occurrence of three consecutive letters, e.g. abc or xyz, and False if it has no such ocurrences. """ characters = [ord(char) for char in password] return any( (a + 1) == b and...
def update_state_dict(original_state_dict, dataparallel=False): """ Add or keep 'module' in name of state dict keys, depending on whether model is using DataParallel or not """ sample_layer = [k for k in original_state_dict.keys()][0] state_dict = {} if not dataparallel and 'module' in samp...
def is_integer(val): """ Helper function that returns True if the provided value is an integer. """ try: int(val) except ValueError: return False return True