content
stringlengths
42
6.51k
def get_by_ids(use_ids, list_ids_tfrecords): """ :param use_data: list of path to tfrecords :param use_ids: list of ids :param list_ids_tfrecords: videos corresponding to each ids :return: """ ret_data = [] for ids in use_ids: ret_data = ret_data + list_ids_tfrecords[ids].tolis...
def load_w(dtype): """ Return the function name to load data. This should be used like this:: code = '%s(ival)' % (load_w(input_type),) """ if dtype == 'float16': return 'ga_half2float' else: return ''
def truncate_lines(str, num_lines, eol="\n"): """Truncate and remove EOL characters :param str: String to truncate :type str: `str` :param num_lines: Number of lines to process :type num_lines: `int` :param EOL: EOL char :type EOL: `char` :return: Joined string after truncation :rty...
def is_provider_redis(provider): """ Check if a provider configuration is a redis configuration """ return provider.get("type") is not None and provider.get("type") == "redis"
def __precision(prediction, expectation): """ prediction: list cut at-k pmid, each element should be a tuple (pmid,score) or (pmid) expectation: list of valid pmid return precision """ if len(prediction)==0: return 0 # assume 0 return sum([ 1 if pmid in expectation else 0 for pmid i...
def reverseDictWithDuplicates(D): """for testing, values are lists always """ reverseD = {} for k,v in D.items(): reverseD.setdefault(v, []).append(k) return reverseD
def int_to_str_add_zeros(number): """ Turn an int to a sting and make sure it has 6 digit (add zeros before if needed) """ if type(number) != int: print("File number should be an integer.\n") if number < 0: print("File number can't be negative.\n") elif number > 999999: ...
def fix_whitespace_for_phantom(text: str): """Transform output for proper display This is important to display pandas DataFrames, for instance """ text = text.replace(' ', r'&nbsp;') text = '<br>'.join(text.splitlines()) return text
def sanitize(data, some_property): """Strip whitespace from a dict value""" value = data.get(some_property, '') return value.strip() if value else None
def _detect(value, assumption): """ Definition format string """ if assumption == 'array': return value.startswith('[') and value.endswith(']') return False
def getNoMappedReadsStrCheck(inFile, outFiles): """File from map-reduce steps may carry no data. This is indicated by the string 'no_mapped_reads. This must be caught within the wrappers to know when not to exit the algorithm required by the wrapper and sebsequently exit gracefully. Given and input and ...
def flatten(nested_list): """ Flatten an arbitrarily nested list. Nesting may occur when anchors are used inside a YAML list. """ flattened = [] for l in nested_list: if isinstance(l, list): flattened.extend(flatten(l)) else: flattened.append(l) return...
def _slice_at_axis(sl, axis): """ Construct tuple of slices to slice an array in the given dimension. Parameters ---------- sl : slice The slice for the given dimension. axis : int The axis to which `sl` is applied. All other dimensions are left "unsliced". Returns ...
def ports_from_output_port_acts(output_port_acts): """Return unique port numbers from OFPActionOutput actions. Args: list of ryu.ofproto.ofproto_v1_3_parser.OFPActionOutput: output to port actions. Returns: set of port number ints. """ return {output_port_act.port for output_port_ac...
def is_dicom_file(filename): """ This function is used to check whether a file is in the DICOM format. We do this by checking that bytes 129 to 132 are DICM. See http://stackoverflow.com/questions/4792727/validating-dicom-file for more details """ try: with open(filename, 'rb') as ...
def check_occuring_variables(formula,variables_to_consider,allowed_variables) : """ Checks if the intersection of the variables in <formula> with the variables in <variables_to_consider> is contained in <allowed_variables> Parameters ---------- formula : list of list of integers The formula to cons...
def pfreduce(func, iterable, initial=None): """A pointfree reduce / left fold function: Applies a function of two arguments cumulatively to the items supplied by the given iterable, so as to reduce the iterable to a single value. If an initial value is supplied, it is placed before the items from the i...
def neg_relu(x_in, inf_point): """ negative relu fxn""" if x_in <= inf_point: return inf_point - x_in return 0
def harass_metric(damage_taken_p1: float, damage_taken_p2: float) -> float: """ A metric that looks at damage taken as a fraction of total damage dealt in lane. Formula: 1 - (damage_taken_p1/(damage_taken_p1 + damage_taken_p2)) :param damage_taken_p1: Damage taken by player one :param damage_taken...
def is_overlapping(bbox1, bbox2): """ :param bbox1: :param bbox2: :return: """ overlap = (max(bbox1[0], bbox2[0]), min(bbox1[1], bbox2[1]), max(bbox1[2], bbox2[2]), min(bbox1[3], bbox2[3])) return overlap[0] < overlap[1] and overlap[2] < overlap[3]
def iob_iobes(tags): """IOB -> IOBES """ new_tags = [] for i, tag in enumerate(tags): if tag == 'O': new_tags.append(tag) elif tag.split('-')[0] == 'B': if i + 1 != len(tags) and \ tags[i + 1].split('-')[0] == 'I': new_t...
def _match_event(key, value, event): """Return true if `key` and `value` exist within the given event.""" val = str(value).upper() if key in event: return str(event[key]).upper() == val return False
def find_largest_diff(list_of_nums): """Find the largest difference between *consecutive* numbers in a list. """ largest_diff = 0 for i in range(len(list_of_nums)-1): diff = abs(list_of_nums[i] - list_of_nums[i+1]) if diff > largest_diff: largest_diff = diff retu...
def _resolve_name(name, package, level): """Resolve a relative module name to an absolute one.""" bits = package.rsplit(".", level - 1) if len(bits) < level: raise ValueError("attempted relative import beyond top-level package") base = bits[0] return "{}.{}".format(base, name) if name else b...
def is_array(obj): """ Return True if object is list or tuple type. """ return isinstance(obj,list) or isinstance(obj,tuple)
def getRankAttribute(attribute, reverse = False): """ Takes as input an attribute (node or edge) and returns an attribute where each node is assigned its rank among all others according to the attribute values. The node/edge with lowest input value is assigned 0, the one with second-lowest value 1, and so on. Key...
def lat_to_km(latitude) -> float: """Expresses given latitude in kilometers to the north Args: latitude (float): Latitude in degrees. Returns: float: Latitude expressed in kilometers to the north """ km_north = 110.574 * latitude return km_north
def get_inband_info(cfg_facts): """ Returns the inband port and IP addresses present in the configdb.json. Args: cfg_facts: The "ansible_facts" output from the duthost "config_facts" module. Returns: A dictionary with the inband port and IP addresses. """ intf = cfg_facts['VOQ_...
def SelectDBSeveralFittest(n, db_list): """ Function: SelectDBSeveralFittest ================================= Select n fittest individual @param n: the number of fittest individuals @param db_list: the ordered list of fitnesses with associated unique ids obtained from the database ...
def goal_key(tup): """Sort goals by position first and by id second (transform str ids into ints)""" goal_id, goal_pos = tup if isinstance(goal_id, str): return goal_pos, int(goal_id.split("_")[0]) return goal_pos, goal_id
def nameCheck(teamName): """ Checks names to ensure consistent naming :param teamName: str, team name to be checked :return: str, corrected team name """ switch = { 'Central Florida': 'UCF', 'Gardner Webb': 'Gardner-Webb', 'Wisconsin Milwaukee': 'Milwaukee', 'Conn...
def map2matrix(matrix_size, index): """Map index in a time series to the corresponding index in the matrix. :param matrix_size: :param index: :return: index in the matrix """ row_index = index // matrix_size[1] col_index = index % matrix_size[1] matrix_index = (row_index, col_index) ...
def url_map(x): """ Standardizes a URL by ensuring it ends with a '/' and does not contain hash fragments. """ if '#' in x: x = x[:x.index('#')] x = x if x[-1] == '/' else (x + '/') return x
def convert_fish_cmd_to_zsh_cmd(cmd: str) -> str: """ Convert given fish cmd to zsh cmd :param cmd: Fish cmd :return: Zsh cmd """ return cmd.replace('; and ', '&&').replace('; or ', '||')
def _get_dicom_comment(dicom_file): """ Returns the contents of the comment field of a DICOM file. Args: dicom_file <dicom.dataset>: Opened DICOM file Returns: image_comment <str>: DICOM comment """ if hasattr(dicom_file, 'ImageComments'): return dicom_file.ImageComments ...
def adstockGeometric(x, theta): """ :param x: :param theta: :return: numpy """ x_decayed = [x[0]] + [0] * (len(x) - 1) for i in range(1, len(x_decayed)): x_decayed[i] = x[i] + theta * x_decayed[i - 1] return x_decayed
def ismagic (l): """ test if combination is magic """ return ( l[0]+l[1]+l[2] == l[3]+l[4]+l[5] == l[6]+l[7]+l[8] == l[0]+l[3]+l[6] == l[1]+l[4]+l[7] == l[2]+l[5]+l[8] == l[0]+l[4]+l[8] == l[2]+l[4]+l[6] )
def mac_addr(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' % ord(chr(x)) for x in address)
def _convert_to_int_list(check_codes): """Takes a comma-separated string or list of strings and converts to list of ints. Args: check_codes: comma-separated string or list of strings Returns: list: the check codes as a list of integers Raises: ValueError: if conversion fails ...
def map_phred33_ascii_to_qualityscore(phred33_char: str) -> float: """Maps a ASCII phred33 quality character to a quality score >>> map_phred33_ascii_to_qualityscore("#") 2 >>> map_phred33_ascii_to_qualityscore("J") 41 """ return ord(phred33_char) - 33
def mixup(x1,x2,y1,y2,mix_ratio): """ MIXUP creates a inter-class datapoint using mix_ratio """ x = mix_ratio * x1 + (1-mix_ratio) * x2 y = mix_ratio * y1 + (1-mix_ratio) * y2 return (x,y)
def filter_loan_to_value(loan_to_value_ratio, bank_list): """Filters the bank list by the maximum loan to value ratio. Args: loan_to_value_ratio (float): The applicant's loan to value ratio. bank_list (list of lists): The available bank loans. Returns: A list of qualifying bank loa...
def add(x, y=None): """Add two integers. This is the function docstring. It should contain details about what the function does, its parameters (inputs), and what it returns (if anything). There are several standard formats, but this one follows the numpy docstring style. These docstrings can ...
def update_parameters(parameters, grads, learning_rate): """ Update parameters using gradient descent Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients, output of L_model_backward Returns: parameters -- python diction...
def _repeat_f(repetitions, f, args): """Auxiliary function for function par_search() This function executes ``f(*args)`` repeatedly (at most ``repetitions`` times) until the return value is a result differnt from None. It returns the pair ``(result, n)``, where ``result`` is the result of th...
def _wrap_string_values(_where_value): """This function wraps values going in the WHERE clause in single-quotes if they are not integers. .. versionchanged:: 3.4.0 Renamed the function to adhere to PEP8 guidelines. :param _where_value: The value to be evaluated and potentially wrapped in single-quo...
def filter_data_points(x, y, xmin, xmax, ymin, ymax): """ Remove points outside the axes limits """ xnew, ynew = [], [] for xi, yi in zip(x, y): if xi is None or yi is None: continue elif xmin <= xi <= xmax and ymin <= yi <= ymax: xnew.append(xi) y...
def determine_edge_label_by_layertype(layer, layertype): """Define edge label based on layer type """ edge_label = '""' return edge_label
def double_quote(text): """Safely add double quotes around given text e.g. to make PostgreSQL identifiers. Identical to pglib's `PQescapeInternal` with `as_ident = True`. See: https://github.com/postgres/postgres/blob/master/src/interfaces/libpq/fe-exec.c#L3443 That also makes it the same as the P...
def memcached_connection(run_services, memcached_socket): """The connection string to the local memcached instance.""" if run_services: return 'unix:{0}'.format(memcached_socket)
def hexi(WIDTH, INT): """ Converts int to hex with padding """ assert WIDTH > 0 return ('%0' + str(WIDTH) + 'X') % INT
def _concatenate(*args): """ Reduces a list of a mixture of elements and lists down to a single list. Parameters ---------- args : tuple of (object or list of object) Returns ------- list """ lst = [] for arg in args: if isinstance(arg, list): for elem in arg: lst.append(elem) ...
def leastload(loads): """Always choose the lowest load. If the lowest load occurs more than once, the first occurance will be used. If loads has LRU ordering, this means the LRU of those with the lowest load is chosen. """ return loads.index(min(loads))
def show_exercises(log, date): """Show all exercises for given workout date""" all_exercises_during_workout = [] for item in log: if item["date"] == date: for k, _ in item["exercises"].items(): all_exercises_during_workout.append(k) return all_exercises_during_worko...
def hailstone(n): """Print out the hailstone sequence starting at n, and return the number of elements in the sequence. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ # similar to hw01, but asked for a recursive solution here print(n) if n == 1: ...
def equation_id(equation): """This function determines which kind of equation has been entered. It analyses the equation with each possible operator to find a match. It then isolates the numbers and sends them to the corresponding functions. These functions return the solution, and this function returns that...
def split_tag(image_name): """Split docker image by image name and tag""" image = image_name.split(":", maxsplit=1) if len(image) > 1: image_repo = image[0] image_tag = image[1] else: image_repo = image[0] image_tag = None return image_repo, image_tag
def single_or(l): """Return True iff only one item is different than ``None``, False otherwise. Note that this is not a XOR function, according to the truth table of the XOR boolean function with n > 2 inputs. Hence the name ``single_or``.""" # No i = iter(l) return any(i) and not any(i)
def move_items_back(garbages): """ Moves the items/garbage backwards according to the speed the background is moving. Args: garbages(list): A list containing the garbage rects Returns: garbages(list): A list containing the garbage rects """ for garbage_rect in garbages: # Loop...
def normalize(item): """ lowercase. """ item = item.lower() return item
def unflatten_mapping(mapping): """Unflatten a dict with dot-concatenated keys to a dict of dicts Examples -------- >>> x = {'a1.b1.c1': 1, ... 'a1.b2': 2, ... 'a2.b1': 3} >>> unflatten_mapping(x) # doctest: +SKIP {'a1': {'b1': {'c1': 1}, 'b2': 2}, 'a2': {'b1': 3}} ...
def is_between(value, min_value, max_value): """ (number, number, number) -> bool Precondition: min_value <= max_value Return True if and only if value is between min_value and max_value, or equal to one or both of them. >>> is_between(1.0, 0.0, 2) True >>> is_between(0, 1, 2) False ...
def generate_module_dictionary(category_to_process, data): """ This Function generates module dictionary from the JSON. We select specific modules we need to process, and use them. Module indices are mention in the list 'category_to_process' 'data' is the json, which we use to extra...
def squeeze_axes(shape, axes, skip='XY'): """Return shape and axes with single-dimensional entries removed. Remove unused dimensions unless their axes are listed in 'skip'. >>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC') ((5, 2, 1), 'TYX') """ if len(shape) != len(axes): raise ValueError("...
def _get_ngrams(n, text): """Calculates n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ngram_set.add(tuple(t...
def time_to_string(secondsInput): """Convert time in seconds to a string description.""" string = "" prior = False # Used to ensure if the preceding period has a value that the following are all included. # Creates the desired time calculations days = secondsInput / (24 * 3600) hours = (second...
def uniq(string): """Removes duplicate words from a string (only the second duplicates). The sequence of the words will not be changed. >>> uniq('This is a test. This is a second test. And this is a third test.') 'This is a test. second And this third' """ words = string.split() return ' '....
def quotify(text: str, limit: int = 1024): """ Format text in a discord quote, with newline handling """ converted = text.strip().replace("\n", "\n> ") ret = f"> {converted}" if len(ret) > limit: ret = ret[: limit - 3] + "..." return ret
def _build_var_list_str(var_names): """ Builds the string that contains the list of variables in the parameterized variable format for SQL statements. Args: var_names ([str]): The list of var names, likely the keys in the dict returned by `_prep_sanitized_vars()`. Returns: (str...
def build_url_kwargs(url, **kwargs): """ Builds a url with query and kwargs Expects kwargs to be in the format of key=value :param url: :param kwargs: :return: """ if len(kwargs) == 0: return url url += '?' for key, val in kwargs.items(): url += key + '=' + va...
def load_data(data_dir, files): """ Loads all references sentences and all hypothesis sentences for all the given data files in the given directory. Returns two aligned lists. :param data_dir: the root directory of the transcript files :param files: a list of file names :return: references_list...
def groupby_tx(exons, sambamba=False): """Group (unordered) exons per transcript.""" transcripts = {} for exon in exons: if sambamba: ids = zip(exon['extraFields'][-3].split(','), exon['extraFields'][-2].split(','), exon['extraFields'][-1].spli...
def add_toffoli_to_line(local_qasm_line, qubit_1, qubit_2, target_qubit): """ Add a single Toffoli gate application to the given line of qasm. Args: local_qasm_line: The line of qasm qubit_1: The first control qubit qubit_2: The second control qubit target_qubit: The target ...
def is_html_like(text): """ Checks whether text is html or not :param text: string :return: bool """ if isinstance(text, str): text = text.strip() if text.startswith("<"): return True return False return False
def validate(raw): """ Checks the content of the data provided by the user. Users provide tickers to the application by writing them into a file that is loaded through the console interface with the <load filename> command. We expect the file to be filled with coma separated tickers :class:`string...
def scan_for_agents(do_registration=True): """Identify and import ocs Agent plugin scripts. This will find all modules in the current module search path (sys.path) that begin with the name 'ocs_plugin\_'. Args: do_registration (bool): If True, the modules are imported, which likely...
def strictly_decreasing(values): """True if values are stricly decreasing.""" return all(x > y for x, y in zip(values, values[1:]))
def construct_geometry_filter(filter_type, coords): """ :param filter_type: determine whether the Point or Polygon filter is desired :param coords: either a list of two coordinates, or a list of lists of two coordinates :return: a geojson geometry filter """ filter = { "type": "GeometryF...
def swallow(err_type, func, *args, **kwargs): """ Swallow an exception. swallow(KeyError, lambda: dictionary[x]) vs try: dictionary[x] except KeyError: pass """ try: return func(*args, **kwargs) except err_type: pass
def valid_bidi(value): """ Rejects strings which nonsensical Unicode text direction flags. Relying on random Unicode characters means that some combinations don't make sense, from a direction of text point of view. This little helper just rejects those. """ try: value.encode("idna") ...
def _percent_identity(a, b): """Calculate % identity, ignoring gaps in the host sequence """ match = 0 mismatch = 0 for char_a, char_b in zip(list(a), list(b)): if char_a == '-': continue if char_a == char_b: match += 1 else: mismatch += 1 ...
def epsilon(n): """ Compute Jacobi symbol (5/n). """ if n % 5 in [1, 4]: return 1 elif n % 5 in [2, 3]: return -1 else: return 0
def initialize_counts(nS, nA): """Initializes a counts array. Parameters ---------- nS: int Number of states nA: int Number of actions Returns ------- counts: np.array of shape [nS x nA x nS] counts[state][action][next_state] is the number of times that doing "a...
def is_tachycardic(heart_rate, patient_age): # test """Checks to see if heart rate is tachycardic considering age Args: heart_rate (int): heart rate of specified patient patient_age (int): age of specified patient Returns: str: tachycardic or not tachycardic """ if 1 <= pa...
def km_to_mile(km): """ Converts Kilometers to Miles """ try: return float(km) / 1.609344 except ValueError: return None
def compute_x_mod_power_of_2(x, k): """return x % (2^k) in O(1) 77 % 8 = 5 100 1101 = 77 8 = 2^3. so 77/8 is 77 right shift 3 bits. the "shifted off" 3 bits is the remainder """ return x & ((1 << k) - 1)
def write(triple, writer): """Write a file using the input from `gentemp` using `writer` and return its index and filename. Parameters ---------- triple : tuple of int, str, str The first element is the index in the set of chunks of a file, the second element is the path to write to...
def get_final_aggregation(thing_list, operation): """Generate the HTTP response content according to the operation and the result thing list Args: thing_list(list): the list of thing description operation(str): one of the five aggregation operations Returns: dict: formatted result ...
def find_closest_point(p, qs): """ Return in index of the closest point in 'qs' to 'p'. """ min_dist = None min_i = None for i, q in enumerate(qs): dist = abs(q-p) if min_dist is None or dist < min_dist: min_dist = dist min_i = i return min_i
def build_deed_url(license_code, version, jurisdiction_code, language_code): """ Return a URL to view the deed specified by the inputs. Jurisdiction and language are optional. language_code is a CC language code. """ # UGH. Is there any way we could do this with a simple url 'reverse'? The URL r...
def y_of(square: str) -> int: """Returns y coordinate of an algebraic notation square (e.g. 'f4').""" return int(square[1]) - 1
def validate_projectfilesystemlocation_type(projectfilesystemlocation_type): """ Validate ProjectFileSystemLocation type property Property: ProjectFileSystemLocation.Type """ VALID_PROJECTFILESYSTEMLOCATION_TYPE = "EFS" if projectfilesystemlocation_type not in VALID_PROJECTFILESYSTEMLOCATION_T...
def filter_case_insensitive(names, complete_list): """Filter a sequence of process names into a `known` and `unknown` list.""" contained = [] missing = [] complete_list_lower = set(map(str.lower, complete_list)) if isinstance(names, str): names = [names, ] for name in names: if...
def combine_rel_error(poly_rel_err): """Returns a simplified expression for a given relative error bound. The input should be of the type [(Monomial, n)] where n's are integers. This function multiplies all monomials by corresponding n's and finds the maximum value of n's. The result is ([Monomial]...
def split_levels(fields): """ Convert dot-notation such as ['a', 'a.b', 'a.d', 'c'] into current-level fields ['a', 'c'] and next-level fields {'a': ['b', 'd']}. """ first_level_fields = [] next_level_fields = {} if not fields: return first_level_fields, next_level_f...
def good_suffix_mismatch(i, big_l_prime, small_l_prime): """ Given a mismatch at offset i and given L/L' and l' :param i: the position of mismatch :param big_l_prime: L' :param small_l_prime: l' :return: the amount of shift """ length = len(big_l_prime) assert i < length if i ==...
def remove_name_counter(name_in): """ Tensorflow adds a counter to layer names, e.g. <name>/kernel:0 -> <name>_0/kernel:0. Need to remove this _0. The situation gets complicated because SNN toolbox assigns layer names that contain the layer shape, e.g. 00Conv2D_3x32x32. In addition, we may get a...
def _strip_major_version(version: str) -> str: """ >>> _strip_major_version('1.2.3') '2.3' >>> _strip_major_version('01.02.03') '02.03' >>> _strip_major_version('30.40') '40' >>> _strip_major_version('40') '' """ return ".".join(version.split(".")[1:])
def format_name(f_name, l_name): """ This is a docstring. Take the first and last name and format it to return the title case version of the name.""" if f_name == "" or l_name == "": return "You didn't provide valid inputs." # Whenno valid inputs are given == this exits the function formated_f_n...
def quicksort(arr): """ >>> quicksort(arr) [-23, 0, 1, 1, 2, 6, 7, 10, 23, 53, 53, 235, 256] >>> from string import ascii_letters >>> quicksort(list(reversed(ascii_letters))) == sorted(ascii_letters) True """ length = len(arr) if length in (0, 1): return arr pi = 0 le...