content
stringlengths
42
6.51k
def sanitize_keys_in_dict(d: dict) -> dict: """Recursively sanitize keys in dict from str to int, float and None. Args d (dict): d[name][charge][annotation] """ if not isinstance(d, dict): return d else: new_d = dict() for key, value in d.items(): ...
def change_dic_key(dic,old_key,new_key): """Change dictionary key with new key""" dic[new_key] = dic.pop(old_key) return dic
def get_spk_agent_one_hot_vec(context, agent_index_dict, max_n_agents): """ :param context: 1D: n_prev_sents, 2D: n_words :param agent_index_dict: {agent id: agent index} :param max_n_agents: the max num of agents that appear in the context (=n_prev_sents+1); int :return: 1D: n_prev_sents, 2D: max_n...
def check_part_err(part, key_name): """chec part field""" try: return part[key_name] except KeyError: #undefined field name print("Error\t:wrong field\nCHECK!!!\n") for field in part.items(): print(f"{field[0]:12}\t{field[1]}")
def remove_dups(arg_list): """ Method: remove_dups remove duplicates in a list Params: arg_list :: list :: the list to be processed """ no_dups = [] for arg in arg_list: if arg not in no_dups: no_dups.append(arg) return n...
def str_list(value): """Convert a literal comma separated string to a string list.""" if not value: return [] return value.split(",")
def get_all_individuals_to_be_vaccinated_by_area( vaccinated_compartments, non_vaccination_state, virus_states, area ): """Get sum of all names of species that have to be vaccinated. Parameters ---------- vaccinated_compartments : list of strings List of compartments from which individuals ...
def pad_sents(sents, pad_token): """ Pad list of sentences according to the longest sentence in the batch. The paddings should be at the end of each sentence. @param sents (list[list[str]]): list of sentences, where each sentence is represented as a list of words ...
def fibo_memo(n, mem): """ top-down approach """ if n == 0: return 0 if n == 1: return 1 if mem[n] is not None: return mem[n] mem[n] = fibo_memo(n-1, mem) + fibo_memo(n-2, mem) return mem[n]
def _pixel_addr(x, y): """Translate an x,y coordinate to a pixel index.""" if x > 8: x = x - 8 y = 6 - (y + 8) else: x = 8 - x return x * 16 + y
def adjust_factor(x, x_lims, b_lims=None): """ :param float x: current x value :param float x_lims: box of x values to adjust :param float b_lims: bathy adj at x_lims :rtype: float :returns: b = bathy adjustment """ if b_lims is None: return 0 if x < x_lims[0] or x > x_lims[...
def recall_pos_conf(conf): """compute recall of the positive class""" TN, FP, FN, TP = conf if (TN + FP) == 0: return float('nan') return TP/float(TP+FN)
def select_login_fields(fields): """ Select field having highest probability for class ``field``. :param dict fields: Nested dictionary containing label probabilities for each form element. :returns: (username field, password field, captcha field) :rtype: tuple """ username_field = ...
def to_ms(microseconds): """ Converts microseconds to milliseconds. """ return microseconds / float(1000)
def darken_color(c): """ Darken a color. Small utility function to compute the color for the border of the problem name badges. When no color is passed, a dark border is set. """ if not c: return '#000' # black r, g, b = int(c[1:3], 16), int(c[3:5], 16), int(c[5:], 16) ret...
def find_k_8(n): """Exact solution for k = 4""" if n == 1: return 1 cycle, rem = divmod(n - 1, 4) adjustment = cycle * 3 - 2 result = (pow(2, cycle * 4 - 2) + pow(2, adjustment)) * pow(2, rem) return result
def findPassingDistances ( distances, threshold ): """ This function takes a list of distances and a threshold and returns all indices of distances which pass the threshold, or -1 if no distances is below the threshold. Parameters ---------- list : distances The list of the distances to...
def _get_attention_sizes(resnet_size): """The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. """ choices = { 18: [False, [False, True], [True, False], False],...
def get_underline (title, underline_char): """ Given a string and a character (a string of length 1, although this is not enforced), return an "underline" consisting of the character repeated the same length as the title. title had better not be None. """ return underl...
def bgdrat_point(aminrl, varat_1_iel, varat_2_iel, varat_3_iel): """Calculate required C/iel ratio for belowground decomposition. When belowground material decomposes, its nutrient content is compared to this ratio to check whether nutrient content is sufficiently high to allow decomposition. This...
def check_not_finished_board(board: list): """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Return True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5',\ '*?????*', '*?????*', '*2*1***']) False >>> check_...
def putblock(b): """Puts a block""" print("PutBlock()") return True
def base_canonical_coords_to_pyrobot_coords(xyt): """converts from canonical coords from to pyrobot coords.""" return [xyt[1], -xyt[0], xyt[2]]
def process_what_to_run_concepts(pairs_to_test): """Process concepts and pairs to test. Args: pairs_to_test: a list of concepts to be tested and a target (e.g, [ ("target1", ["concept1", "concept2", "concept3"]),...]) Returns: return pairs to test: target1, concept1 target1, concept2...
def non_decreasing(L): """Return True if list L is non-decreasing.""" return all(x <= y for x, y in zip(L, L[1:]))
def check(n): """ check if number if of the form 1_2_3_4_5_6_7_8_9""" n = str(n) if len(n) != 17: return False else : bit = 1 for i in range(17): if i %2 == 0: if n[i] != str(bit): return False bit += 1 return T...
def IsInt(s): """ Is a string an integer number? @return boolean """ try: int(s) return True except ValueError: return False
def get_true_shooting(points, fga, tpfga, fta): """ Calculates true shooting percentage. :param int points: Points :param int fga: Field goals attempted :param int tpfga: Three point field goals attempted :param int fta: Free throws attempted :return: True shooting percentage :rtype: f...
def getProduct(row): """ Returns an array of the products of first element and the rest of the elements in row """ temp = row.split('\t') data = [] for i in temp[1:]: data.append(float(temp[0])*float(i)) return data
def cyclic_subgroup(a): """The elements of the cyclic subgroup generated by point""" G = [] t = a while True: G.append(t) t = a+t if t == a: break return G
def get_available_stuff(dim_length: int, useless_padding: int, box_length: int): """helper function of get available stuff for generate_crop_boxes Args: length (int): total length for height or width useless_padding (int): useless padding along length box_length (int): box length along ...
def parse_str(s): """Try to parse a string to int, then float, then bool, then leave alone""" try: return int(s) except ValueError: try: return float(s) except ValueError: if s.lower() == 'true': return True if s.lower() == 'false':...
def definition(): """ Snapshot of 1 to 1 teaching. Cost is more important than group, as changing a student's tutor destroys the old group. Distinct from ss_1to1, as this is used for the list screen whilst the other is used for finding differences. """ sql = """ select g.instance_id, g.cost...
def calculate_largest_square_filled_space_optimized2(matrix): """ A method that calculates the largest square filled with only 1's of a given binary matrix (space-optimized 2/2). Problem description: https://practice.geeksforgeeks.org/problems/largest-square-formed-in-a-matrix/0 time complexity: O(n...
def is_flat(obj): """Check whether list or tuple is flat, returns true if yes, false if nested.""" return not any(isinstance(x, (list, tuple)) for x in obj)
def parse_dot_key(data, key): """ Provide the element from the ``data`` dictionary defined by the ``key``. The key may be a key path depicted by dot notation. :param data: A dictionary :param key: A dictionary key string that may be a key path depicted by dot notation. For example "foo.bar"...
def int_to_roman(inp): """ Convert an integer to Roman numerals. """ # stolen from # https://code.activestate.com/recipes/81611-roman-numerals/ if not isinstance(inp, int): raise TypeError("expected integer, got %s" % type(inp)) if inp == 0: return "Z" if not 0 < inp < 4...
def numero_case(x, y, cote): """ Trouver le numero de la case du pixel (x,y) si le graph est en forme de damier noir et blanc et que les cases sont numerotees par leur numero vertical et horizontal en commencant par 0 """ nv = int(x / cote) nh = int(y / cote) return nv, nh
def add_spaces_to_lines(count, string): """Adds a number of spaces to the start of each line Doesn't add spaces to the first line, as it should already be fully indented""" all_lines = string.splitlines(True) new_string = all_lines[0] for i in range(1, len(all_lines)): new_string += ' ' ...
def extract_tests(api_response, defined_tests): """ Create and return a dict of test name to test data. If api_response is None, return a dict with an empty dict. api_response: the JSON response from the Proctor API in Python object form. defined_tests: an iterable of test name strings defining th...
def in_dict(key, dictionary): """ Inputs: key- the key to be checked for in the dictionary dictionary- the dictionary the key will be searched in Checks a dictionary to see if it contains a key. If it does, True is returned; False is returned otherwise. """ ...
def evaluate_example_targetid(goldtargets, prediction): """ (Unlabeled) target evaluation. """ tp = fp = fn = 0.0 for target in goldtargets: if target in prediction: tp += 1 else: fn += 1 for pred_target in prediction: if pred_target not in goldtargets...
def _pairwise(true, pred): """Return numerators and denominators for precision and recall, as well as size of symmetric difference, used in negative pairwise.""" p_num = r_num = len(true & pred) p_den = len(pred) r_den = len(true) return p_num, p_den, r_num, r_den
def get_mod_from_id(mod_id, mod_list): """ Returns the mod for given mod or None if it isn't found. Parameters ---------- mod_id : str The mod identifier to look for mod_list : list[DatRecord] List of mods to search in (or dat file) Returns ------- DatRecord or Non...
def prefixify(d: dict, p: str): """Create dictionary with same values but with each key prefixed by `{p}_`.""" return {f'{p}_{k}': v for (k, v) in d.items()}
def get_output_between(output, first, second): """Gets part of the output generated by the node.js scripts between two string markers""" start = output.find(first) end = output.find(second) return output[start + len(first) + 1:end - 1].decode("utf-8")
def lharmonicmean (inlist): """ Calculates the harmonic mean of the values in the passed list. That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list. Usage: lharmonicmean(inlist) """ sum = 0 for item in inlist: sum = sum + 1.0/item return len(inlist) / sum
def _percent_str(percentages): """Convert percentages values into string representations""" pstr = [] for percent in percentages: if percent >= 0.1: pstr.append('%.1f' %round(percent, 1)+' %') elif percent >= 0.01: pstr.append('%.2f' %round(percent, 2)+' %') ...
def filter_response(response, access_levels_dict, accessible_datasets, user_levels, field2access, parent_key=None): """ Recursive function that parses the response of the beacon to filter out those fields that are not accessible for the user (based on the access level). :response: beacon response :...
def handle_request(request): """Handles the HTTP request.""" headers = request.split('\n') filename = headers[0].split()[1] if filename == '/': filename = '/index.html' try: fin = open('htdocs' + filename) content = fin.read() fin.close() response = 'HTTP/1...
def isInt( obj ): """ Returns a boolean whether or not 'obj' is of type 'int'. """ return isinstance( obj, int )
def __replace_nbsps(rawtext: str) -> str: """Replace nbsps with whitespaces""" return rawtext.replace('\xa0', ' ')
def p_test_subs(t_pos, t_neg): """ Calculate proportion of positive outcomes under test condition :param t_pos: Positive results in Test group :param t_neg: Negative results in Test group :return p_test: Proportion of subjects w/ positive outcome under treatment/test condition """ total = ...
def time_fmt(seconds): """ Utilty function to convert duration to human readable format. Follows default format of the Unix `time` command. """ return "{:.0f}m{:.3f}s".format(seconds // 60, seconds % 60)
def convert_int_list(digit_list): """ given a digit list, convert it back to int list :param digit_list: digit list :return: integer list """ code_str = [] acsii_len = None acsii_code = "" acsii_counter = 0 for i in digit_list: if not acsii_len: acsii_len = i...
def niam(args): """Non-standard entry point.""" return {"greetings": "Hello from a non-standard entrypoint."}
def minimum(ints): """ Return the minimum in a list of integers. If the list is empty, return None. """ if ints == (): return None else: head, tail = ints min = minimum(tail) if min is None or head <= min: return head else: return ...
def ramp(start,end,n): """Return a linear ramp from start to end with n elements""" return [ (end-start)*x/(float(n)-1)+start for x in range(n) ]
def container_status_for_ui(container_statuses): """ Summarize the container status based on its most recent state Parameters ---------- container_statuses : list[V1ContainerStatus] https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1ContainerStatus...
def _normalize_output_configuration(config): """ Normalize output configuration to a dict representation. See `get_output_loggers()` documentation for further reference. """ normalized_config = { 'both': set(), 'stdout': set(), 'stderr': set() } if isinstance(config, str): i...
def f(x): """A function with an analytical Hilbert transform.""" return 1 / (x ** 2 + 1)
def fib(n: int) -> int: """ Calculates the n-th Fibonacci number in O(log(n)) time. See: [Exercise 1.19](https://bit.ly/3Bhv2JR) """ if n < 0: fib_neg = fib(-n) return fib_neg if (1 - n) % 2 == 0 else -fib_neg a, b, p, q = 1, 0, 0, 1 while n: if n % 2 == 0: ...
def _iou(box1, box2): """ Computes Intersection over Union value for 2 bounding boxes :param box1: array of 4 values (top left and bottom right coords): [x0, y0, x1, x2] :param box2: same as box1 :return: IoU """ b1_x0, b1_y0, b1_x1, b1_y1 = box1 b2_x0, b2_y0, b2_x1, b2_y1 = box2 i...
def GetPreviewResultsPathInGCS(artifacts_path): """Gets a full Cloud Storage path to a preview results JSON file. Args: artifacts_path: string, the full Cloud Storage path to the folder containing preview artifacts, e.g. 'gs://my-bucket/preview/results'. Returns: A string representing the full Clo...
def mybool(string): """ Method that converts a string equal to 'True' or 'False' into type bool Args: string: (str), a string as 'True' or 'False' Returns: bool: (bool): bool as True or False """ if string.lower() == 'true': return True if string.lower() == 'false'...
def grSize(val, n): """The number of bits in the Golomb-Rice coding of val in base 2^n.""" return 1 + (val >> n) + n
def normalize_quantity(qty, qty_unit: str): """ takes a qty and a unit (as a string) and returns the quantity in m3/year accepts: m3/sec m3/day m3/year Returns None if QUANTITY_UNITS doesn't match one of the options. """ if qty_unit is None: return None q...
def commalist(commastr): """Transforms a comma-delimited string into a list of strings""" return [] if not commastr else [c for c in commastr.split(',') if c]
def h(p1, p2): """Heuristic function""" x1, y1 = p1 x2, y2 = p2 return abs(x1 - x2) + abs(y1 - y2)
def tagIsHidden(tagName): """ Check if an tag isn't special for the generator """ if tagName=="Script": return True elif tagName=="Constructor": return True elif tagName=="Destructor": return True elif tagName=="Properties": return True elif tagName=="Declarations": return True else:...
def euler_from_quarterion(x, y, z, w): """ Convert quarterion into euler angles :param x,y,z,w: quaterion :type x,y,z,w: quaterion :return: euler angles (roll, pitch, yaw) """ import math t0 = +2.0 * (w * x + y * z) t1 = +1.0 - 2.0 * (x * x + y * y) X = math.degrees(math.atan2(t...
def midi_notes_to_tuples(notes): """ converts a sequence of pretty_midi notes into a list of (onset,pitch) elements """ seq = list() for n in notes: seq.append((n.start,n.pitch)) return seq
def dict_merge(*dict_list): """ Given zero or more dicts, shallow copy and merge them into a new dict, with precedence to dictionary values later in the dict list. Helpful mainly before Python 3.5. https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression https://docs.py...
def get_ngrams(sent, n=2, bounds=False, as_string=False): """ Given a sentence (as a string or a list of words), return all ngrams of order n in a list of tuples [(w1, w2), (w2, w3), ... ] bounds=True includes <start> and <end> tags in the ngram list """ ngrams = [] words=sent.split() if n==1: return words ...
def _sort_key_max_confidence(sample, labels): """Samples sort key by the maximum confidence.""" max_confidence = float("-inf") for inference in sample["inferences"]: if labels and inference["label"] not in labels: continue if inference["confidence"] > max_confidence: ...
def effectiveResolution(interpolation, sigma_det, feature_size, z, z1, focalLength): """ calculate effective resolution """ sigma_eff = interpolation*(sigma_det + feature_size*((z*focalLength)/z1)) return sigma_eff
def pluralize(n: int, text: str, suffix: str = 's') -> str: """Pluralize term when n is greater than one.""" if n != 1: return text + suffix return text
def cube_vertices(x, y, z, n): """ Return the vertices of the cube at position x, y, z with size 2*n. """ #def cube_vertices(self): # """ Return the vertices of the cube at position x, y, z with size 2*n. # # """ # return [ # x-n,y+n,z-n, x-n,y+n,z+n, x+n,y+n,z+n, x+n,y+...
def three_bytes(address): """Convert a 24 bit address to a string with 3 bytes""" return '%c%c%c' % ((address & 0xff), (address >> 8) & 0xff, (address >> 16) & 0xff)
def _lin(x, *p): """A generic line function. Return y = mx + b using p[0] = b, p[1] = m. Parameters ---------- x: real, array of reals Point(s) at which to evaluate function. p: array of size 2 The linear coefficients of the function: p = [b, m]. Returns -...
def seq_del(s, i): """ Returns a new sequence with i missing. Mysteriously missing from the standard library. """ return s[:i] + s[i+1:]
def encode_modified_utf8(u: str) -> bytes: """ Encodes a unicode string as modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param u: unicode string to be converted. :returns: A decoded bytearray. """ final_string = bytearray() for c in (ord(char) for char in u): ...
def _check_for_item(lst, name): """Search list for item with given name.""" filtered = [item for item in lst if item.name == name] if not filtered: return None else: return filtered[0]
def booleanize_if_possible(sample): """Boolean-ize truthy/falsey strings.""" if sample.lower() in ['true', 'yes', 'on', 1]: sample = True elif sample.lower() in ['false', 'no', 'off', 0]: sample = False return sample
def is_end_of_statement(chars_only_line): """ Return True if a line ends with some strings that indicate we are at the end of a statement. """ return chars_only_line and chars_only_line.endswith(('rightreserved', 'rightsreserved'))
def fibonacci(n): """ Calculate the Fibonacci number of the given integer. @param n If n <= 0 then 0 is assumed. @return fibonacci number. """ if n <= 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2)
def add_out(hout, out, par, x, xm, xp, uncert): """ Add entries in out list, according to the wanted uncertainty. Parameters ---------- hout : list Names in header out : list Parameter values par : str Parameter name x : float Centroid value xm : floa...
def _is_on_line(x, y, ax, ay, bx, by): """ Check if point `x`/`y` is on the line segment from `ax`/`ay` to `bx`/`by` or the degenerate case that all 3 points are coincident. >>> _is_on_line(0.5, 0.5, 0.0, 0.0, 1.0, 1.0) True >>> _is_on_line(0.0, 0.0, 0.0, 0.0, 1.0, 1.0) Tru...
def get_unique_operators(stabilizers: list) -> list: """ strip leading sign +/- from stabilizer strings """ operator_strings = [x[1:] for x in stabilizers] return list(set(operator_strings))
def generate_neighbor_nid(local_nid: bytes, neighbour_nid: bytes) -> bytes: """ Generates a fake node id adding the first 15 bytes of the local node and the first 5 bytes of the remote node. This makes the remote node believe we are close to it in the DHT. """ return neighbour_nid[:15] + local_...
def str_to_bool(s): """ This function converts a string of True or False into a boolean value. Args: s: string Returns: boolean value of s """ if s == 'True': return True elif s == 'False': return False
def group_per_category(bkgs): """ Groups a flat list of datasets into sublists with the same category E.g. [ ttjet, ttjet, ttjet, qcd, qcd ] --> [ [ttjet, ttjet, ttjet], [qcd, qcd] ] """ cats = list(set(bkg.get_category() for bkg in bkgs)) cats.sort() return [ [ b for b in bkgs if b.get_cate...
def unquote(input_str, specials, escape='\\'): """Splits the input string |input_str| where special characters in the input |specials| are, if not quoted by |escape|, used as delimiters to split the string. The returned value is a list of strings of alternating non-specials and specials used to break the str...
def calc_student_average(gradebook): """ Function that will take in a list of students and return a list of average grades for each student """ return [sum(grades)/len(grades) for grades in gradebook]
def calc_obj_multi_ss( objective, penalty_10=0, penalty_bal_ipo=0, penalty_oopo=0, coeff_10=0, coeff_bal_ipo=0, coeff_oopo=0): """ calculates objective function for single-panel structures considering the penalties for the design and manufacturing guid...
def extension(subdir): """Does a subdirectory use the .cpp or .cc suffix for its files?""" return 'cpp' if subdir.startswith('vendor') else 'cc'
def command_from_key(key): """Return the command correspondign to the key typed (like a giant dictionnary)""" dict_int_commands = {111: 'forward 30', 113: 'left 30', 114: 'right 30', 116: 'back 30'} dict_str_commands = {'a': 'sn?', ' ': 'takeoff', '+' : 'land', '8': 'up 30', '2': 'down 30', '6': 'cw 30', ...
def _int(value): """ Converts integer string values to integer >>> _int('500K') >>> 500000 :param value: string :return: integer """ value = value.replace(",", "") num_map = {"K": 1000, "M": 1000000, "B": 1000000000} if value.isdigit(): value = int(value) else: ...
def cum_size_distribution(areas, a): """ Return P[A > a] for the given set of areas. Extract areas from the hierarchical tree using areas = [tree.node[n]['cycle_area'] for n in tree.nodes_iter() \ if not tree.node[n]['external']]. """ return sum([1. for A in areas if A > a])/len(areas)
def remove_duplicates(annotations): """Removes duplicate annotations. This is mostly used for persons when same person can be both actor and director. Args: annotations (List): List of annotations. Returns: List: List of annotations without duplicates. """ return [ anno...