content
stringlengths
42
6.51k
def drqa_metric_max_over_ground_truths(metric_fn, prediction, ground_truths): """Given a prediction and multiple valid answers, return the score of the best prediction-answer_n pair given a metric function. """ scores_for_ground_truths = [] for ground_truth in ground_truths: score = metric_f...
def clip(x, min_x, max_x): """ clips x between min_x and max_x """ return max(min(x, max_x), min_x)
def validate_base_sequence(base_sequence, Nucltype='DNA'): """ return true if no other letters""" seq=base_sequence.upper() return len(seq)==(seq.count('T' if Nucltype=='DNA' else 'U')+seq.count('A')+seq.count('C')+seq.count('G')+seq.count('N'))
def outputstate_to_outcome(state_ket): """ :param state_ket: an output of the chip :return: a measurable outcome """ state_list = [] for m in state_ket: if m.isdigit(): state_list.append(m) state = tuple(state_list) if int(state[0]) == 0 and int(state[1]) == 0: ...
def get_target_data(sheet, target_column): """ Indicate different target columns for different sheets. :param sheet: string, the tab name. :param target_column: int-cid,int-location,int-holder, :return: a list with elements [cid, location, holder] """ tc = target_column.split(',') rows ...
def storage_locations_with_aips(storage_locations): """Return list of Storage Locations filtered to those with AIPs.""" return [loc for loc in storage_locations if loc.aips]
def join_host_strings(user, host, port=None): """ Turns user/host/port strings into ``user@host:port`` combined string. This function is not responsible for handling missing user/port strings; for that, see the ``normalize`` function. If ``port`` is omitted, the returned string will be of the form...
def argmax_pair(array, key): """Find an (unordered) pair of indices that maximize the given function""" n = len(array) mi, mj, m = None, None, None for i in range(n): for j in range(i+1, n): k = key(array[i], array[j]) if not m or k > m: mi, mj, m = i, j, ...
def bool_to_string(value: bool): """ boolean string to boolean converter """ if value: return "true" else: return "false"
def any_value(d): """Returns one of the values of a dict.""" return next(iter(d.values()))
def volume_tracker(volume, service, volume_tracker): """ volume_tracker: Going to create the volume json file with service names """ if volume in volume_tracker.keys(): volume_tracker[volume].append(service) # Keep Unique Values in list as there should not be same Search service on...
def strip_quotes(a): """Conditionally remove leading/trailing quotes from a string @type a: string @param a: a string potentially with quotes @rtype: string @return: same string without the leading and trailing quotes """ ln = len(a) if ln >= 2: strip_quotes = False if a[0] == '"' a...
def report_progress(typed, prompt, id, send): """Send a report of your id and progress so far to the multiplayer server.""" # BEGIN PROBLEM 8 "*** YOUR CODE HERE ***" num = 0 for num in range(len(typed)): if typed[num] != prompt[num]: break if num == len(typed) - 1 and typed...
def asbool(x): """Convert x to a boolean without rasing an exception. Return False instead if conversion fails""" try: return bool(int(x)) except: return False
def parse_value(hexvalue): """Parse decrypted payload to readable HA BLE data""" vlength = len(hexvalue) if vlength >= 3: temp = round(int.from_bytes(hexvalue[2:4], "little", signed=False) * 0.01, 2) humi = round(int.from_bytes(hexvalue[6:8], "little", signed=False) * 0.01, 2) print(...
def rotate(i_list: list,n:int) -> list: """ Rotate a list by N position. rotate([a,b,c,d,e,f,g,h],3). -> [f,g,h,a,b,c,d,e] rotate([a,b,c,d,e,f,g,h],2). -> [g,h,a,b,c,d,e,f] rotate([a,b,c,d,e,f,g,h],-2). -> [c,d,e,f,g,h,a,b] :param i_list: The source list to be rotated ...
def batches(batch_size, features, labels): """ Create batches of features and labels :param batch_size: The batch size :param features: List of features :param labels: List of labels :return: Batches of (Features, Labels) """ assert len(features) == len(labels) n_features = len(...
def table_name_suffix(load_table_s3_prefix: str) -> str: """ Table name suffix should be '__ct' if the S3 prefix is from change tracking. Parameters ---------- load_table_s3_prefix : str The load's prefix as determined by its S3 key. Returns ------- str "__ct" or "" dep...
def reynolds(v, d, nu): """ :param v: Velocity of the natural gas, m/s :param d: Pipe inner diameter, m :param nu: Kinematic viscosity, m2/s :return: Reynolds number, dimensionless """ return v*d/nu
def _merge_objects(obj1, obj2): """Recursive merge obj2 into obj1. Objects can be dicts and lists.""" if type(obj1) == list: obj1.extend(obj2) return obj1 for k2, v2 in obj2.iteritems(): v1 = obj1.get(k2) if type(v2) == type(v1) in (dict, list): _merge_objects(v1,...
def tolist_if_not(arr): """ Convert `arr` to list if it is not already. >>> import numpy as np >>> tolist_if_not([0]) [0] >>> tolist_if_not(np.arange(1)) [0] """ try: tolist = arr.tolist except AttributeError: return arr return tolist()
def find_neighbors(matrix, current, visited): """Find the neighbors of current that have not being visited. :param matrix: matrix to be used. :param current: tuple of (x,y) coordinates. :param visited: set of visited coordinates.""" # Placeholder variables m = matrix x, y = current neigh...
def sorted_json_string(json_thing): """Produce a string that is unique to a json's contents.""" if isinstance(json_thing, str): return json_thing elif isinstance(json_thing, list): return '[%s]' % (','.join(sorted(sorted_json_string(s) for s in json_t...
def get_segments(tokens, max_seq_len): """Segments: 0 for the first sequence, 1 for the second""" if len(tokens) > max_seq_len: raise IndexError("Token length more than max seq length!") segments = [] current_segment_id = 0 for token in tokens: segments.append(current_segment_id) ...
def err_match(msg, pattern_list): """error match function""" return any([p in msg for p in pattern_list])
def _2str(unit): """ Convert unit list to str """ if not isinstance(unit,list): raise TypeError('Input required as <list>!') return ' '.join([str(u) for u in unit])
def to_mal_priority(arg,no_raise=True): """ converts an arg to mal priority 0 = Low; 1 = Medium; 2 = High """ if arg in {0,1,2}: return arg elif arg in '012': return int(arg) try: return { "low":0, "medium":1, "high":2 }[arg...
def _non_executed_cells_count(cell_list): """The function takes a list of cells and returns the number of non-executed cells Args: cell_list(list): list of dictionary objects representing the notebook cells Returns: non_exec_cells: number of non-executed cells in the list ...
def get_sklearn_family(distribution): """ Translate statistical family to its equivalent in sklearn jargon. Parameters ---------- distribution """ family = distribution if family == "gaussian": family = "normal" elif "tweedie" in family: tweedie_p = float(family.spli...
def first(it): """Get the first element of an iterable.""" return next(iter(it))
def HimmelblauFunction(x, y): """ Himmelblau's function see Himmelblau's function - Wikipedia, the free encyclopedia http://en.wikipedia.org/wiki/Himmelblau%27s_function """ return (x**2 + y - 11)**2 + (x + y**2 - 7)**2
def rgb_to_int(r, g, b): """Convert color tuples to ints. Normally I could call int() on a pygame.Color object but there seems to be a bug in the __int__() method of pygame.Color objects. Until that is fixed I do the conversion manually. r, g, and b must be integers I could also use a 3-dimens...
def _create_skeleton_generator(gen_func): """Create an instance of a generator from a generator function without the proper stack, locals, or closure. Parameters ---------- gen_func : function The function to call to create the instance. Returns ------- skeleton_generator : gen...
def auth_set(hashed_sks, auth_set_indices, height, hashfun): """Return the authentication set defined by the given indices. Keyword arguments: hashed_sks -- the hased secret key components which form the leaves of the tree auth_set_indices -- A list of tuples (h, i) defini...
def _process_ratios(value): """Helper function to convert the GPS ratios in float format""" return float(value[0])/float(value[1])
def parse_qasm(qasm): """Parse qasm from a string. Parameters ---------- qasm : str The full string of the qasm file. Returns ------- circuit_info : dict Information about the circuit: - circuit_info['n']: the number of qubits - circuit_info['n_gates']: the...
def check_if_key_in_list_dict(list_obj, dict_key, dict_value): """ Helper method to help check if a specific dictionary is in a list by checking if a specific dict key is in said dictionary. Returns the index point where this dict was found. If it cannot find it, returns -1 """ for index, curr...
def init_returns(states): """ Generate dictionrary for saving returns of given states Parameters ---------- states : list of tuples List with all possible combinations of dealer card, player card, and whether or not the player has a usable ace Returns ------- R...
def merge_and_count(left, right): """Combine Step""" n_left = len(left) n_right = len(right) i = 0 j = 0 merged = [] split_inversions = 0 while i < n_left and j < n_right: if left[i] <= right[j]: merged.append(left[i]) i += 1 else: mer...
def group_names(names): """ Group names of signals by similarity of name. First all numbers are removed from the signal name. Then identical numberless signal names are grouped together. This function is used to cluster line on a plot. Parameters ---------- names : :obj:`list` of :obj...
def ByteString2String(Bstring): """ Convenience function to convert a byte string to string. """ return str(Bstring, 'utf-8')
def _battery_convert(value): """Battery is given as a value between 0 and 9.""" if value is None: return None return value * 10
def generateOutlinkVector(adjMatrix: list) -> list: """Takes the adjacency matrix of a network as arguments and returns the vector containing the number of outlinks each node has. The node i's outlink can be accessed by indexing with i. """ outlinkVector = [sum(i) for i in adjMatrix] return outl...
def skip_label(what): """Generate a "skip" label name.""" return f"skip {what}"
def str_maker(arr): """Make a string from list of integers.""" res = [] for num in arr: res.append(str(num)) output = ''.join(res) return output
def get_storage_mountpoint(job): """ Get mount point for fuse filesystem from job JSON """ if 'storage' in job: return job['storage']['mountpoint'] return None
def getXSTypeNumberFromLabel(xsTypeLabel): """ Convert a XSID label (e.g. 'AA') to an integer. Useful for visualizing XS type in XTVIEW. 2-digit labels are supported when there is only one burnup group. """ return int("".join(["{:02d}".format(ord(si)) for si in xsTypeLabel]))
def truncate_tra_dict_values(tra_dict): """We need to truncate the values in order to avoid precision errors. In some situations if import and export the guide, due Maya's precision limitations we may find some minimal values change. i.e: from 2.9797855669897326e-16 to 2.9797855669897321e-16 (Note th...
def present_in(needle, trup_haystack, index): """ Returns true if needle exists in the 'index' position of the truple haystack """ for i in trup_haystack: if i[index] is needle: return True return False
def _deslugify(string): """Deslugify string.""" return string.replace("_", " ").title()
def dec2bin(k, bitlength=0): """Decimal to binary""" return [1 if digit == '1' else 0 for digit in bin(k)[2:].zfill(bitlength)]
def lower_camel_case_from_underscores(string): """Generate a lower-cased camelCase string from an underscore_string""" components = string.split('_') string = components[0].lower() for component in components[1:]: string += component[0].upper() + component[1:].lower() return string
def set_emulated_vision_deficiency(type: str) -> dict: """Emulates the given vision deficiency. Parameters ---------- type: str Vision deficiency to emulate. **Experimental** """ return {"method": "Emulation.setEmulatedVisionDeficiency", "params": {"type": type}}
def create_header(t, n='', tar=False): """Create header for API request. Args: t: Authorization token n: Swarm node to make request on Returns: Request header in JSON """ if not tar: return({'Authorization': 'Bearer ' + t, 'X-PortainerAgent-Target': n, 'Content-Type...
def choose_node_mappings(node_mappings, i): """ Function: choose_node_mappings ------------------------------ Randomly chooses one mapping for each strategy and returns the dict of the list of seed noeds associated with each of them. node_mappings: A dictionary where the key is a name and the value is a a...
def consolidate(dict1, dict2): """ :param dict1: :param dict2: :return: @rtype dict """ d = dict(dict1) d.update(dict2) return d
def escape(string): """Returns the given HTML with ampersands, quotes and carets encoded.""" return (string.replace('&', '&amp;').replace('<', '&lt;') .replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
def str_to_bool(s): """ String to bool used to read config file Parameters ---------- s : str String to convert Returns ------- s : bool Boolean value of input string """ if s == 'True': return True elif s == 'False': return False else: ...
def replace_X_start_day(day): """Find the earliest legitimate day.""" day = day.lstrip('-') if day == 'XX' or day == '0X': return '01' if day == 'X0': return '10' return day.replace('X', '0')
def comparable(class_): """Adds rich comparison special methods (__ne__, __gt__, etc.) to a passed in class and returns the modified class. See ComparableMetaclass or ComparableMixin for other ways of running. """ ops = dict((s, 'self.__%s__(o)' % s) for s in ('eq', 'ne', 'lt', 'le'...
def prepare_spatial_data(spatial_data): """ Organizes keywords in spatial_data The results of the spatial data search does not differentiate between a search word that encodes a location, like a city name, and a "thing" the user is looking for, like "environment". This function analyzes the output of t...
def delta_X_Y(from_to, prop, compartments, totals, model=None): """Return number individuals to be moved from one compartment to another. Parameters: from_to (str): transition name consisting of two compartment names separated by an underscore (e.g. I_R) prop (float): proportion of ...
def remove_repeats(word_list): """ Remove repeated words in a list. :param word_list: :return: list """ seen = set() result = [] for item in word_list: if item not in seen: seen.add(item) result.append(item) return result
def decode(val): """Try to decode a string, and don't stop code execution if it fails. Args: val (str): Should be a string. Returns: str: Should also be a string. """ if val is None or str(val) == str(''): return None if str(str(val).strip()) == str('NULL'): re...
def handle_already_linked( media_list: list, offline_types: list = ["Offline", "None"] ) -> list: """Remove items from media-list that are already linked to a proxy. Since re-rendering linked clips is rarely desired behaviour, we remove them without prompting. If we do want to re-render proxies, we...
def get_center(res): """Computes center point of a resolution rectangle.""" return (round(res[0] / 2), round(res[1] / 2))
def get_user_from_request(request): """Returns a user or None with login or OAuth2 API""" user = None if hasattr(request, 'resource_owner'): user = request.resource_owner if hasattr(request, 'user'): if not request.user.is_anonymous: user = request.user return user
def solution(A): # O(N) """ Write a function to group together all ascending sublists within a list a. >>> solution([1, 2, 10, 10, 8, 12, 5, 23, 1]) [[1, 2, 10, 10], [8, 12], [5, 23], [1]] >>> solution([3, 4, 5, 12, 2, 3, 5, 2, 5, -1]) [[3, 4, ...
def seconds_in_units(seconds): """ Returns a tuple containing the most appropriate unit for the number of seconds supplied and the value in that units form. >>> seconds_in_units(7700) (2, 'hour') """ unit_limits = [("year", 365 * 24 * 3600), ("month", 30 * 24 * 36...
def get_valid_mod (mod): """Modifiers are full of junk we dont care about, remove them""" return int(mod) & (1 << 0 | 1 << 2 | 1 << 3 | 1 << 28)
def list_manipulation(lst, command, location, value=None): """Mutate lst to add/remove from beginning or end. - lst: list of values - command: command, either "remove" or "add" - location: location to remove/add, either "beginning" or "end" - value: when adding, value to add remove: remove ite...
def get_iou(pred_box, gt_box): """ pred_box : the coordinate for predict bounding box (x, y, w, h) gt_box : the coordinate for ground truth bounding box (x, y, w, h) return : the iou score """ # 1.get the coordinate of inters ixmin = max(pred_box[0], gt_box[0]) ixmax = min(pred_box[0...
def find_overtime(dates): """Given a list of weekly summaries, return the overtime for each week""" return sum([day - 40 for day in dates if day > 40])
def isolatedfile_to_state(filename): """For a '.isolate' file, returns the path to the saved '.state' file.""" return filename + '.state'
def _convert_and_validate_type(obj): """ Converts a shoedog string to its appropriate Python type or throws SyntaxError """ if obj[0] == "'" or obj[-1] == "'": if len(obj) < 2 or obj[0] != "'" or obj[-1] != "'": raise SyntaxError(f'Invalid filter object {obj} - is this a string?') ob...
def str2bool(v): """ Return conversion of JSON-ish string value to boolean. """ return v.lower() in ('yes', 'true', 'on', '1')
def validate_mapping(_, __, values): """ >>> validate_mapping(None, None, [('episode', 'TV Show'), ('movie', 'Movie')]) [('episode', 'TV Show'), ('movie', 'Movie')] >>> validate_mapping(None, None, [('wrong', 'TV Show'), ('movie', 'Movie')]) # doctest: +ELLIPSIS Traceback (most recent call last): ...
def ultima(palavra): """ Exibe a ultima parte da string """ return palavra[-1]
def round_to_pricetick(price: float, pricetick: float): """ Round price to price tick value. """ rounded = round(price / pricetick, 0) * pricetick return rounded
def _convert_to_seconds(time): """Will convert any time into seconds. If the type of `time` is not valid, it's returned as is. Here are the accepted formats:: >>> convert_to_seconds(15.4) # seconds 15.4 >>> convert_to_seconds((1, 21.5)) # (min,sec) 81.5 >>> convert_to_seconds((1,...
def _check_boolean(string): """Attempt to convert a string to a boolean variable if matches.""" if string in ['True', 'true']: return True elif string in ['False', 'false']: return False else: return string
def canFinish(numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ if not prerequisites: return True graph = {i:[] for i in list(range(numCourses))} for x, y in prerequisites: graph[y] += [x] d...
def sum_naturals(n): """Sum the first N natural numbers. """ total, k = 0, 1 while k <= n: total, k = total + k, k + 1 return total
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 int_x_to_str_Dx(damage_state_without_d_prefix): """ Function to convert damage states. For exmple the input is 2 and the expected result is D2. """ return "D" + str(damage_state_without_d_prefix)
def flatten(list_of_lists): """ Flatten a list of lists """ if len(list_of_lists) == 0: return list_of_lists if isinstance(list_of_lists[0], list): return flatten(list_of_lists[0]) + flatten(list_of_lists[1:]) return list_of_lists[:1] + flatten(list_of_lists[1:])
def persist_get_parameters(url, parameters): """ Attachs query paramaters to an url. """ first = True final_url = url for key, value in parameters.items(): if first: final_url = "%s?%s=%s" % (final_url, key, value) first = False else: final_url...
def encode(plaintext, shift): """Encode plaintext Encode the message with a given shift key. Offset each character in the message by 'shift' number of letters in the alphabet """ ciphertext = "" # shift each character for x in plaintext: if 97 <= ord(x) <= 122: # if character...
def getSingleChildTextByName(rootNode, name): """Returns the text of a child node found by name. Only one such named child is expected. """ try: nodeList = [e.firstChild.data for e in rootNode.childNodes if e.localName == name] if len(nodeList) > 0: return nodeList[0] ...
def cleantex(s): """ clean a latex expression Example: print( cleantex( vlatex(MM, symbol_names={Jxx:'J_{xx}'}))) """ D_rep={ '\\operatorname{sin}':'\\sin', '\\operatorname{cos}':'\\cos', '\\left(\\theta\\right)':'\\theta', '\\left[\\begin{matrix}':'\\begin{...
def prepare_hex_string(number, base=10): """ Gets an int number, and returns the hex representation with even length padded to the left with zeroes """ int_number = int(number, base) hex_number = format(int_number, 'X') # Takes the string and pads to the left to make sure the number of characte...
def is_negative_relation(rel): """ Negative relations describe ways that concepts are different or unrelated. In cases where we our goal is to determine how related concepts are, such as conceptnet5.builders.reduce_assoc, we should disregard negative relations. """ return rel.startswith('/r/...
def extractData(line): """Assume the first colon (:) separates the key from the value.""" separator = ':' line_data = line.strip().split(separator) key = line_data[0] # the value may contain a separator so will need to be reassembled from # possibly multiple elements value = separator.join(l...
def _feature_accuracy(feature_stats): """Computes accuracy from the supplied counters.""" return (feature_stats["correct"] / feature_stats["total"] * 100.0 if feature_stats["total"] != 0.0 else 0.0)
def fibonacci(n): """Given a positive int n, uses recursion to return the nth Fibonacci number.""" if n == 1 or n==2: return 1 elif n <= 0: return 0 else: return (fibonacci(n-1) + fibonacci(n-2))
def map_rcs_to_snake(nh, nv, row, col, spin): """Mapping (row, column, spin-type) to snake encoding. Args: nhoriz -- number of horizontal sites nvert -- number of vertical sites row -- row location of the qubit in the lattice col -- column location of the qubit in the lattice ...
def canonicalize_rules(rules): """ Canonicalize rules. New Rule objects are created. :param rules: Set of Rule objects :return: Set of Rule objects """ canonicalized_rules = set() for rule in rules: canonic_rule = rule.canonicalize() canonicalized_rules.add(canonic_rule) ...
def kilometers_to_miles(dist_in_km): """ Actually does the conversion of distance from km to mi. PARAMETERS -------- dist_in_km: float A distance in kilometers. RETURNS ------- dist_in_mi: float The same distance converted to miles. """ return (dist_in_km)/1.609344
def is_process(process): """Return ``True`` if passed object is Process and ``False`` otherwise.""" return type(process).__name__ == "Process"
def valid_solution(board): """ board: matrix of 9x9 elements representing a sudoku grid return: if board is a valid sudoku or not """ for row in board: if sorted(row) != [i for i in range(1, 10)]: # tests if rows contain every number return False for cell in range(len(row)): # tests if columns c...