content
stringlengths
42
6.51k
def bucket_key_to_s3_path(bucket, key): """ Takes an S3 bucket and key combination and returns the full S3 path to that location. """ return f"s3://{bucket}/{key}"
def _filter_labels(text, labels, allowed_labels): """Keep examples with approved labels. :param text: list of text inputs. :param labels: list of corresponding labels. :param allowed_labels: list of approved label values. :return: (final_text, final_labels). Filtered version of text and labels ...
def parse(css): """Parse a CSS style into a dict.""" result = {} for declaration in css.split(";"): if declaration: key, value = declaration.split(":") result[key] = value.strip() return result
def toState(t,r_i): """ 1 -> 1 -1 -> 0 """ s = 0 for x in t: s *= 2 if r_i == 1: if x.real>0: s+=1 else: if x.imag>0: s+=1 r_i = 1 -r_i return s
def compact(input, maxlen=70): """Creates a compact string from a dict.""" output = "" for item in input.items(): if (len(output.split("\n")[-1]) + len(item)) >= maxlen: output += "\n" output += "{} ".format(item) return output
def _ocp_lib(name): """ Generate a Python library target name. """ return "%s-lib" % name
def ensure_boolean(val): """Ensures a boolean value if a string or boolean is provided For strings, the value for True/False is case insensitive """ if isinstance(val, bool): return val elif isinstance(val, str): return val.lower() == 'true' else: return False
def RGBtoYCoCg(R, G, B): """ convert RGB to YCoCg color The YCoCg color model was developed to increase the effectiveness of the image compression. This color model comprises the luminance (Y) and two color difference components (Co - offset orange, Cg - offset green). :param R: red value (0;255) ...
def parse_line(text: str) -> str: """Parses one line into a word.""" text = text.rstrip() if text[0] == "+": return text[1:] if text[0] == "@" or text[0] == "!" or text[0] == "$": w = text.split("\t")[1] if "#" in w: return w.split("#")[0].rstrip() else: ...
def safe_div(x: int, y: int): """ Computes x / y and fails if x is not divisible by y. """ assert isinstance(x, int) and isinstance(y, int) assert y != 0 assert x % y == 0, f'{x} is not divisible by {y}.' return x // y
def convert_to_dict(my_tuple): """Convert a given tuple of (value, key) tuples to a dictionary. Args: my_tuple (tuple): A tuple of (value, key) tuples Returns: Dict: A dictionary mapping each tuple key to its value. """ return dict((y, x) for x, y in my_tuple)
def quickSort(alist): """ Quick sort algrithm, In-place version. """ def partition(alist, left, right): pivot = alist[right - 1] i = left - 1 for j in range(left, right): if alist[j] < pivot: i += 1 (alist[i], alist[j]) = (alist[j], al...
def MixinRepository(wrapped, instance, args, kwargs): """ Signals that a repository is a mixin repository (a repository that contains items that help in the development process but doesn't contain primitives used by other dependent repositories). Mixin repositories must be activated on top of o...
def wmlfindin(element, scopeElement, wmlItor): """Find an element inside a particular type of scope element""" for itor in wmlItor.copy(): if element == itor.element: if itor.scopes: if scopeElement == itor.scopes[-1].element: return itor elif ...
def save_data(data, labels, path): """ Save images and labels. The variables 'data' and 'labels' refer to the processed images and labels. The string 'path' corresponds to the path where the images and labels will be saved. """ # Number of images. n_data = len(d...
def to_lower(string: str) -> str: """ Converts :string: to lower case. Intended to be used as argument converter. Returns ------- :class:`str` string to lower case """ return string.lower()
def camel_to_snake(s): """ Convert a camelCasedName to a snake_cased_name :param s: the camelCasedName :return: the snake_cased_name """ return "".join(["_" + c.lower() if c.isupper() else c for c in s]).lstrip("_")
def get_max_diff(lst: list) -> int: """ Parameters ----------- lst: price list. Returns --------- out: the max diff Notes ------ """ if len(lst) < 2: return 0 minv = lst[0] diff = lst[1] - minv for i in range(2, len(lst)): if lst[i-1] < m...
def num2coords(i, gridwidth=10): """ Coordinates of variable i in a Gibbs grid Parameters ---------- i : int Position of variable in ordering gridwidth : int Width of the grid Returns ------- length_coord, width_coord (coordinates) """ length_coord = i %...
def extend_list_x(list_x, list_y): """ THE FUNCTION GETS 2 LISTS AND ADD LIST_Y TO LIST_X :param list_x: the first list :type list_x: list :param list_y: the second list :type list_y: list :return: [list_y (+) list_x] :rtype: list """ # THE SOLUTION IS THAT...
def chk(condition, message='Check failed', exc=RuntimeError): """Check a condition, raise an exception if bool(condition)==False, else return `condition`.""" if not condition: raise exc(message) return condition
def derive_error_dict(error_obj): """Get the error dict from an object :param error_obj: Error object :type error_obj: :return: Error dict :rtype: `dict` """ tdict = dict(error_obj.__dict__) tdict.pop("_sa_instance_state", None) return tdict
def _make_exact(h): """Make sure h is an exact representable number This is important when calculating numerical derivatives and is accomplished by adding 1 and then subtracting 1.. """ return (h + 1.0) - 1.0
def convertCharToInt(value): """ Converts a string of length 1 (char) to an int. """ try: value = int(value) except ValueError: error_template = ("convertCharToInt received '{0}' when num " "expected") raise ValueError(error_template.format(value)) if va...
def strike_through(text): """Replace ~~foo~~ with <s>foo</s> to support strike-through in output""" text = text.split('\n') for line_i, line in enumerate(text): if '~~' not in line: continue line = line.split('~~') parts = [] for part_i, part in enumerate(line): ...
def funnels_as_ini_section(funnels): """from a list of funnels, gives back a dict that can be exported to a file that RTW can understand """ section_content = {} for name, funnel in funnels.items(): section_content[name+ "Pos"] = round(funnel.position) for name, funnel in funnels.items()...
def remove_by_idxs(ls, idxs): """Remove list of indexes from a target list at the same time""" return [i for j, i in enumerate(ls) if j not in idxs]
def select_vertex_statement(vertex_type, name): """Return a SQL statement to select a vertex of given type by its `name` field.""" template = "(select from {vertex_type} where name = '{name}')" args = {"vertex_type": vertex_type, "name": name} return template.format(**args)
def Sum2num(a,b): """ Given two numbers add them and return a value """ sum = a + b return sum
def words(text): """ Split the given text into a list of words, see :meth:`python:str.split`. :param text: The input string :type text: str :return: The list of words in the text :rtype: list """ return text.split()
def check_values_on_diagonal(matrix): """ Checks if a matrix made out of dictionary of dictionaries has values on diagonal :param matrix: dictionary of dictionaries :return: boolean """ for line in matrix.keys(): if line not in matrix[line].keys(): return False return Tru...
def split_text_segment_id(text_segment_id): """ Get the bnc part and fragment id given a text segment id. """ bnc_part, frg_n = text_segment_id.split('-') assert len(bnc_part) == 3, text_segment_id assert frg_n.startswith('fragment') return bnc_part.upper(), int(frg_n[8:])
def _concat_lists_safe(A, B): """ Safely concatenate two lists if one or both may be None """ if A is None and B is None: return None elif isinstance(A, list) and B is None: return A elif isinstance(B, list) and A is None: return B elif isinstance(A, list) and isinstance(B, ...
def find_spans(raw): """ Return spans of text which don't contain <PAD> and are split by <PAD> """ pads = [idx for idx, char in enumerate(raw) if char == '<PAD>'] if len(pads) == 0: spans = [(0, len(raw))] else: prev = 0 spans = [] for pad in pads: if ...
def set_stats_windows(config): """Set window sizes for averaging stats.""" windows = config["settings"].get("stats_windows", 0.1) if not isinstance(windows, list): windows = [windows] if not 1 in windows: windows.append(1) return windows
def swap_min_max(x, min_col, max_col): """Swap columns if necessary """ if x[min_col] < 0 and x[max_col] < 0: if abs(x[min_col]) > abs(x[max_col]): return x[max_col], x[min_col] else: return x[min_col], x[max_col] else: if x[min_col] > x[max_col]: ...
def preimage_func(f, x): """Pre-image a funcation at a set of input points. Parameters ---------- f : typing.Callable The function we would like to pre-image. The output type must be hashable. x : typing.Iterable Input points we would like to evaluate `f`. `x` must be of a type acce...
def scale_values_based_on_eich_peak(lead_list, gamma=0.5): """ scale values on the Y-axis :param lead_list: list of the value :param gamma: scaling factor :return: rescaled list """ new_lead_list = [] for xy_pair in lead_list: new_y_value = xy_pair[1] * gamma ...
def filter_stories(stories, triggerlist): """ Takes in a list of NewsStory instances. Returns: a list of only the stories for which a trigger in triggerlist fires. """ storylist = list() for story in stories: for T in triggerlist: if T.evaluate(story): stor...
def foldl(f, z, xs): """``foldl :: (b -> a -> b) -> b -> [a] -> b`` Applied to a binary operator, a starting value (typically the left-identity of the operator), and a list, reduces the list using the binary operator, from left to right. The list must be finite. """ from functools import redu...
def cf_gamma(u, a=1, b=2): """ Characteristic function of a Gamma random variable - shape: a - scale: b """ return (1 - b * u * 1j)**(-a)
def _same_scope_binary_operation(probs_table_a, pribs_table_b, func, default): """ Apply a mathematical operation between the two factors with the same variable scope. NB: this function assumes that the variables corresponding to the keys in the two different dicts have the same order. :param dict...
def event_split(string, event_type): """Return a list of event type and event action. Args: string (str): The supplied string that will be splitted. event_type (str): The event type (execute, log, set, etc). Returns: list: A list of the splitted string Examples: >>> is...
def find_intercept_point(m, c, x0, y0): """ find an intercept point of the line model with a normal from point (x0,y0) to it :param m slope of the line model :param c y-intercept of the line model :param x0 point's x coordinate :param y0 point's y coordinate :return intercept point "...
def getBands(x): """Get the bands from the list-string.""" return ( x.replace('"', "") .replace("'", "") .replace(" ", "") .replace("[", "") .replace("]", "") .split(",") )
def Find_the_bbox(annotations): """ input: annotations -> the coco format annotations output: bbox -> a list of bbox cordinates , i.e:[0,155,23,56] """ bbox_0 = 1000 bbox_1 = 1000 bbox_2 = 0 bbox_3 = 0 for annotation in annotations: bbox_0 = int( min(...
def rebuild_command(args): """Rebuilds a unicode command string prepared to be stored in a file """ return "%s\n" % (u" ".join(args)).replace("\\", "\\\\")
def remove_empty_lines(text): """remove empty lines""" assert (len(text) > 0) assert (isinstance(text, list)) text = [t.strip() for t in text] if "" in text: text.remove("") return text
def _neg(vec): """Return -vec.""" return [(-coeff, deg) for coeff, deg in vec]
def remove_greeting(text): """ Given an email like text return the text without the greeting part, e.g., "Hi Darling, ..." :param text: :return: """ import re if len(text) <= 0: return text parts = text.split("\n") first = parts[0] if len(parts[0]) >0 else parts[1] res ...
def parse_map(_map): """ Returns a dictionary where from you can look up which center a given orbiter has """ orbits = {} for orbit in _map.split("\n"): center, orbiter = orbit.split(")") orbits[orbiter] = center return orbits
def seqfeat2shadefeat(msa,seqref=None,idseqref=True): """ converts SeqFeature records for every sequence in msa to our style feature list """ features=[] #In texshade [1,1] will be colored as one residue. this is different from biopython where [1,1] selects nothing! for m,i in zip(msa,range(len(...
def metric_prefix(s): # type: (str) -> int """Parse a metric prefix as a number.""" s_old = s s = s.strip().lower() if s == "": return 1 if s == "k": return 1000 if s == "m": return 1000 ** 2 if s == "g": return 1000 ** 3 if s == "t": return 10...
def _to_generic_pyver(pyver_tags): """Convert from CPython implementation to generic python version tags Convert each CPython version tag to the equivalent generic tag. For example:: cp35 -> py3 cp27 -> py2 See https://www.python.org/dev/peps/pep-0425/#python-tag """ return [...
def find_matching_paren(s: str, startpos: int) -> int: """Given a string "prefix (unknown number of characters) suffix" and the position of the first `(` returns the index of the character 1 past the `)`, accounting for paren nesting """ opening = 0 for i, c in enumerate(s[startpos:]): i...
def is_leaf_node(node): """Check if this node is leaf node or not.""" check = lambda x,y: (type(x[y]) != list and type(x[y]) != dict) if type(node) == list: indexes = range(len(node)) elif type(node) == dict: indexes = node.keys() else: return True for idx in indexes: if not check(node...
def __replace_argument(args, index, new_arg): """ Replace one argument from within an argument tuple Parameters ---------- args : tuple tuple of arguments index : int position of the argument within the tuple new_arg value of the new argument Returns...
def get_states(path): """ Method to return an array containing all the states for a specified path """ states = [] if path == 1: # PATH 1 states = ["0_off_start", "1_on", "2_rgb", "3_bright", "4_rgb_bright", "5_off_end", "6_invalid"] elif path == 2: # P...
def pos_to_col_row(pos, m): """ Given position and m (number of columns) returns the corresponding col, row on the chess board """ row = pos / m col = pos % m return col, row
def fibonacci(n): """ Function for nth fibonacci, space optimized""" a = 0 b = 1 if n < 0: print("Incorrect input") elif n == 0: return 0 elif n == 1: return b else: for i in range(1, n): c = a + b a = b b = c return...
def euler_totient(n): """Euler's totient function or Phi function. Time Complexity: O(sqrt(n)).""" result = n; for i in range(2, int(n ** 0.5) + 1): if n % i == 0: while n % i == 0: n //= i result -= result // i if n > 1: result -= result // n;...
def _intersection_homogenous(homog_line_0, homog_line_1): """Find point of intersection of two lines in homogenous coordinates""" # NB: renamed from '_intersection' eps = 1e-13 a,b,c=homog_line_0 u,v,w=homog_line_1 D=float(b*u-v*a) if abs(D)<eps: # parallel lines return None,...
def is_integer(text): """ Tests to see if a string contains an integer """ if text.isdigit(): return True elif text[0] == '-': # Check for negative numbers if text[1:].isdigit(): return True else: return False
def clean_ingredients(dish_name, dish_ingredients): """ :param dish_name: str :param dish_ingredients: list :return: tuple of (dish_name, ingredient set) This function should return a `tuple` with the name of the dish as the first item, followed by the de-duped `set` of ingredients as the seco...
def create_match_instance_pairs(plant_match_in): """ sort match index instances removing ambiguous matches and creating match 'B', 'I' dict """ ## collect all plant name match instances indices just_indices = [int(indices) for plant_match_in_set in plant_match_in for indices in plant_match_in_set[1]] a...
def money(cost): """Turn numbers into dollar amounts.""" cost = float(cost) # # Rounds the number to the hundreths # cost = round(cost, 2) cost = str(cost) if len(cost) > 1: # # Changes the way the number is displayed based on decimal placement # if cost[-...
def apply_entries(checkpoint, entries): """Recursively modifies `checkpoint` with `entries` values.""" for field, value in entries.items(): # Access the last dict (if nested) and modify it. to_edit = checkpoint bits = field.split('.') for bit in bits[:-1]: to_edit = t...
def worker_key(i): """ helper function for making worker key """ return "worker{0}".format(i)
def get_cmd_args(argv): """ Take the `argv` arguments apart and split up in arguments and options. Options start with `-` and can be stacked. Options starting with `--` cannot be stacked. """ args = [] options = [] i = 1 while (i < len(argv)): if argv[i].strip()[0] == ...
def viewkeys(obj, **kwargs): """ Function for iterating over dictionary keys with the same set-like behaviour on Py2.7 as on Py3. Passes kwargs to method.""" func = getattr(obj, "viewkeys", None) if not func: func = obj.keys return func(**kwargs)
def has22(list_one:list)->bool: """Returns True if the list contains a 2 next to a 2. Otherwise, the function returns False . >>>has22([1,2,2,3]) True >>>has22([1,2,3,4]) False """ if ', 2, 2' in str(list_one): return True elif list_one[0] ==...
def decay_every_scheduler(step, steps_per_decay, decay_factor): """Gives a scaling factor based on scheduling with a decay every n-steps. Args: step: int; Current step. steps_per_decay: int; How often to decay. decay_factor: float; The amount to decay. Returns: Scaling factor applied to the lear...
def get_gain(camcol, band, run=None): """ data.sdss3.org/datamodel/files/BOSS_PHOTOOBJ/frames/RERUN/RUN/CAMCOL/frame.html """ GAIN_CCD = { 0: {"u": 1.62, "g": 3.32, "r": 4.71, "i": 5.165, "z": 4.745}, 1: {"u": [1.595, 1.825], "g": 3.855, "r": 4.6, "i": 6.565, "z":...
def is_number(x): """ Takes a word and checks if Number (Integer or Float). """ try: # only integers and float converts safely num = float(x) return True except: # not convertable to float return False
def mean(num_list): """ Computes the mean of a list Parameters ---------------- num_list: list List to calculate mean of Returns ---------------- mean: float Mean of list of numbers """ #sum = 0.0 #for num in num_list: # sum += num #mean = sum/le...
def mode_str_to_int(modestr): """ :param modestr: string like 755 or 644 or 100644 - only the last 6 chars will be used :return: String identifying a mode compatible to the mode methods ids of the stat module regarding the rwx permissions for user, group and other, special flags and file system flags, i.e. w...
def generate_prediction_models(csv_dict, durations_min): """ For each duration in minutes since a door was last closed, generate a machine learning model that describes - based on all the data and history from this location - what the probability is that the house is now unoccupied. "Labels" can be gen...
def solve(n, arr, d, days): """ Solve the problem here. :return: The expected output. """ prefix = [0 for _ in range(n)] prefix[0] = arr[0] for i in range(1, n): prefix[i] = prefix[i - 1] + arr[i] def presum(_q, _r): assert _r < n if _q == 0: return p...
def num(val): """Return val as an int, float, or bool, depending on what it most closely resembles.""" if isinstance(val, (float, int)): return val elif val in ('True', 'False'): return val == 'True' elif isinstance(val, str): try: return int(val) except ...
def nested_map(x, f): """Map the function f to the nested structure x (dicts, tuples, lists).""" if isinstance(x, list): return [nested_map(y, f) for y in x] if isinstance(x, tuple): return tuple([nested_map(y, f) for y in x]) return f(x)
def isvlan(value): """Checks if the argument is a valid VLAN A valid VLAN is an integer value in the range of 1 to 4094. This function will test if the argument falls into the specified range and is considered a valid VLAN Args: value: The value to check if is a valid VLAN Returns: ...
def p_laLcsDistance(x, y): """ calculates the length of the longest common subsequence of the two arguments with a dynamic programming algorithm """ # speed up (our data often matches exactly) if x == y: return 1.0 if not x or not y: return 0.0 # algorithm from Goodrich and Tamas...
def fix_default_param(defparam, classname): """ 'fixes' default parameters from C to what python expectes """ if (classname + '::') == defparam[0:len(classname)+2:]: return defparam[len(classname)+2::] if defparam[len(defparam)-1] == "f": return defparam[0:len(defparam)-1] return defpara...
def format_name(raw_name): """Removes _ and URLS from raw_name Args: raw_name(string): The name to format """ return raw_name.replace('_', ' ').replace(' URLS', '')
def make_buffers(size=32): """return a list of payloads""" buffers = [] # we'll use `size` for the number of payloads in the list and the # payloads' length for i in range(size): # prefix payload with a sequential letter to indicate which # payloads were lost (if any) buff = ...
def get_robots_sn(robots_list): """ Get the sn for the robots_list, :param robots_list: which robots need to get sn :return: robots_sn_dict = {sn:robot_obj, ...} """ robots_sn_dict = {} for robot_obj in robots_list: sn = robot_obj.get_sn() robots_sn_dict[sn] = robot_obj r...
def insertion_sort(list_: list) -> list: """Returns a sorted list, by insertion sort method :param list_: The list to be sorted :type list_: list :rtype: list :return: Sorted list, by insertion sort method """ for i in range(1, len(list_)): selected_element = list_[i] j = i...
def hex_str_to_int(value: str) -> int: """ convert a hexadecimal string to integer '0x1b1b' -> 6939 """ return int(value, 16)
def merge_dicts(original: dict, other: dict) -> dict: """Merge two dicts (in place), overwriting values in original. :param original: The original dict values being used. :param other: The dict to overwrite with. :return: The overwritten dict. """ for k, v in other.items(): if k in orig...
def generate_access_id(registration_id): """Generate an id in format required by ADaMS API.""" return f'in{registration_id}'
def fix_spans(d, prev_sentence_len): """This function updates the spans in d and shifts them by a value equal to prev_sentence_len""" for key, val in d.items(): if type(val) == list: if type(val[0]) is int: sent_index, span = val index_1, index_2 = span ...
def format_write_request(address, value): """ Format a write request based on an address and the value to write to the FPGA. :param address: address at which to write date. :param value: data to write to the address. :return: formatted request. """ if address >= 2**(4 * 8): raise Va...
def _disk_type(disk_info): """get the type of the disk. :return: the type of the disk :rtype: str """ # @todo from sal_zos.disks.Disks import StorageType if disk_info["rota"] == "1": if disk_info["type"] == "rom": # @todo return StorageType.CDROM return "CDROM" ...
def tuple_to_int(t): """ Creates a copy of a tuple, populated with int casts of its elements. @param t: The tuple to cast. @return: A copy of the tuple with int elements. """ mytmplist = [] for element in t: mytmplist.append(int(element)) return tuple(mytmplist)
def prefetch(contig, start, end, fetch_start,fetch_end,molecule_iterator_args): """ Prefetch selected region Prefetches AlleleResolver """ new_kwarg_dict = {} for iterator_arg, iterator_value in molecule_iterator_args.items(): if iterator_arg in ('molecule_class_args','fragment_clas...
def _is_cache_function(func): """Determines if a function is cached or not""" return hasattr(func, "cache_info")
def create_graph_from_lambda(f, xrange): """Takes a function as an input with a specific interval xrange then creates a list with the output y-points. Inefficient, but useful if f is a simple math function not involving NumPy. :param f: The function to evaluate. :type f: lambda :param xrange: T...
def update_average(old_avg: float, old_num: int, new_avg: float, new_num: int): """Updates the old average with new data. Params: - old_avg (float): The current average value - old_num (int): The number of elements contributing to the current average - new_avg (float): The new average value ...
def fix_ip_checksum_fast(packet: bytes) -> bytes: """ Overwrite IPv4 checksum with zero for EthernetII packet if it has the length of an EthernetII packet :param packet: EthernetII + IPv4 packet :return: The whole packet where checksum is overwritten with b"\x00\x00" or unmodified packet it it is too sh...
def bonus_letter(puzzle: str, view: str, letter: str) -> bool: """Return True iff the letter is a consonant that appears in the puzzle but not view. >>> bonus_letter('apple', 'a^^le', 'p') True >>> bonus_letter('banana', 'ba^a^a', 'b') False >>> bonus_letter('apple', '^pp^e', 'a') False ...