content
stringlengths
42
6.51k
def flatten(nested_list: list) -> list: """ Flatten an input list which could have a hierarchical multi nested list :param nested_list: The source list :return: The flatten list """ if len(nested_list) == 0: return [] if type(nested_list[0]) is list: return flatten(nested_list[0]) + flatten((nested_list[1:])) return [nested_list[0]] + flatten(nested_list[1:])
def iteration_speed_lower_bound(l, k, time_arr): """ Compute almost-lower bound. Parameters ---------- l : float Lambda (exponential rate). k : int Graph's degree. time_arr : list of float #iter -> completion time fo such iteration. Returns ------- list of float """ lb = [] for t in time_arr: lb.append(t * l / (1 + sum(1 / i for i in range(1, k + 1)))) return lb
def create_payment_msg(identifier, status): """Create a payment payload for the paymentToken.""" payment_msg = {'paymentToken': {'id': identifier, 'statusCode': status}} return payment_msg
def ReadStampFile(path): """Return the contents of the stamp file, or '' if it doesn't exist.""" try: with open(path, 'r') as f: return f.read().rstrip() except IOError: return ''
def tokenize_description(description, has_name): """ Splits comma-separated resource descriptions into tokens. :param description: String describing a resource, as described in the ion-test-driver CLI help. :param has_name: If True, there may be three tokens, the first of which must be the resource's name. Otherwise, there may be a maximum of two tokens, which represent the location and optional revision. :return: If `has_name` is True, three components (name, location, revision). Otherwise, two components (name, location) """ components = description.split(',') max_components = 3 if not has_name: max_components = 2 if len(components) < max_components: revision = 'master' else: revision = components[max_components - 1] if len(components) < max_components - 1: raise ValueError("Invalid implementation description.") if has_name: return components[0], components[max_components - 2], revision else: return components[max_components - 2], revision
def checkParamsNum(funcName,distribName,runDistribName,distribParams,correctNum): """See if the correct number of parameters was supplied. More than one number may apply Args: | funcName (string): distribution name | distribName (string): distribution name | distribParams ([float]): list of distribution parameters (see below) | correctNum ([int]): list with the possible numbers of parameters Returns: | True if the requirements are matched Raises: | No exception is raised. """ proceed = True if not len(distribParams) in correctNum: print('{} Variates Generation:\n {} {} {} {} {}'.format(distribName, 'Wrong number of parameters (run ', funcName, "('", runDistribName, "') for help) ")) proceed = False # print(distribParams, correctNum, proceed) return proceed
def is_dataarray(obj, require_attrs=None): """ Check whether an object is a DataArray. Parameters ---------- obj: anything The object to be checked. require_attrs: list of str, optional The attributes the object has to have in order to pass as a DataArray. Returns ------- bool Whether the object is a DataArray or not. """ require_attrs = require_attrs or [ "values", "coords", "dims", "name", "attrs", ] return all([hasattr(obj, name) for name in require_attrs])
def format_test_case(test_case): """Format test case from `-[TestClass TestMethod]` to `TestClass_TestMethod`. Args: test_case: (str) Test case id in format `-[TestClass TestMethod]` or `[TestClass/TestMethod]` Returns: Test case id in format TestClass/TestMethod. """ return test_case.replace('[', '').replace(']', '').replace( '-', '').replace(' ', '/')
def roundup(x: int): """ Round to the next hundred :param x: raw value :return: rounded value """ return x if x % 100 == 0 else x + 100 - x % 100
def closeyear(year): """ Find how many years away was the closest leap year to a specific year. :type year: number :param year: The year to check for. """ # Return the specific year return int(year % 4)
def last_level(root): """ Given a root node, return the leaf nodes at the last level (ONLY). :param root: root node :return: list of last level leaf nodes """ out = [] return out
def breaking_spaces(value): """ Convert non-breaking spaces to regular spaces. Args ---- value (str): input value Returns ------- str: the input string, now with regular spaces """ return value.replace("\u00A0", " ")
def units_stub(have, want): """ Finds the conversion multiplier needed. """ # Add more prefixes? pref = {'yocto': 1e-24, 'micro': 1e-6, 'milli': 1e-3, 'centi': 1e-2, 'deci': 1e-1, 'deka': 1e1, 'hecto': 1e2, 'kilo': 1e3, 'mega': 1e6} h = None w = None for p in pref.keys(): if have[:len(p)] == p: h = pref[p] if want[:len(p)] == p: w = pref[p] if h is None: h = 1.0 if w is None: w = 1.0 ret = h / w return ret
def str_join(lst, sep=' '): """join(list, [sep]) -> string Behaves like string.join from Python 2.""" return sep.join(str(x) for x in lst)
def _keys_equal(x, y): """ Returns 'True' if the two keys are equal by the laws of HTTP headers. """ return x.lower() == y.lower()
def is_num(arg): """ Args: arg: input object that going to check if it is a number. Returns: true is input is number, else return false. """ try: float(arg) return True except ValueError: return False
def get_screen(ui_file, name): """ Function to get current screen object from json file. ui_file: Json file as a dict, name: name of screen """ for screen in ui_file["uis"]: if screen["name"] == name: return screen else: pass print("ERROR: no screen with the name " + name + " found")
def f_to_k(temp): """ Converts Fahrenheit to Kelvin. """ return (temp + 459.67) * 5/9
def get_index_grouped_by_label(labels): """Get (an array of) index grouped by label. This array is used for label-level sampling. It aims at MNIST and CelebA (in Jesse et al. 2018) with 10 labels. Args: labels: a list of labels in integer. Returns: A (# label - sized) list of lists contatining indices of that label. """ index_grouped_by_label = [[] for _ in range(10)] for i, label in enumerate(labels): index_grouped_by_label[label].append(i) return index_grouped_by_label
def parse_comma_list(args): """Convert a comma-separated list to a list of floating-point numbers.""" return [float(s.strip()) for s in args.split(',')]
def person_link(person, **kwargs): """Render a link to a Person If person is None or a string, renders as a span containing '(None)'. """ if isinstance(person, str): # If person is a string, most likely an invalid template variable was referenced. # That normally comes in as an empty string, but may be non-empty if string_if_invalid # is set. Translate strings into None to try to get consistent behavior. person = None title = kwargs.get("title", "") cls = kwargs.get("class", "") with_email = kwargs.get("with_email", True) if person is not None: plain_name = person.plain_name() name = ( person.name if person.alias_set.filter(name=person.name).exists() else plain_name ) email = person.email_address() return { "name": name, "plain_name": plain_name, "email": email, "title": title, "class": cls, "with_email": with_email, } else: return {}
def transform_state(sim_state): """ Convert {'x_position': 0.008984250082219904, 'x_velocity': -0.026317885259067864, 'angle_position': -0.007198829694026056, 'angle_velocity': -0.03567818795116845} from the sim into what my brain expects ['cart_position', 'cart_velocity', 'pole_angle', 'pole_angular_velocity'] """ s = sim_state return { "cart_position": s["x_position"], "cart_velocity": s["x_velocity"], "pole_angle": s["angle_position"], "pole_angular_velocity": s["angle_velocity"], }
def match_treatment_and_region_id(x): """ Doc. Parameters ---------- x : dataframe for apply, axis=1. Returns ------- bool for apply, axis=1, and dataframe selection. """ if x['treatment'][:3] in x['region_id']: return True else: return False
def isSequence(sequence): """**Determine whether sequence is a sequence**.""" try: sequence[0:-1] return True except TypeError: return False
def isempty(s): """Return True if s is nothing but white space, False otherwise""" return len(''.join(s.split())) == 0
def tf_frame_join(*args): """ Function for joining a frame list into a string path. Opposite to tf_frame_split. :param args: (string|list) Strings or List of strings for path components to be joined into a single TF Frame. :return: (string) A fully formed TF frame """ tf_path = '' for arg in args: if isinstance(arg, list): tf_path += '/' + '/'.join(arg) elif isinstance(arg, str): tf_path += '/' + arg return tf_path[1:]
def pad_program(bytecode): """ Returns bytecode padded with zeros to a length of 256. """ return bytecode + '\x00' * (256 - len(bytecode))
def str2longitude(value): """convert a str to valid longitude""" if "." not in value: value = value[:2] + "." + value[2:] return float(value)
def reverse_grammar(pgrammar): """reverses the order of the keys appearing in the parsed grammar.""" pgrammar = dict(reversed(list(pgrammar.items()))) return pgrammar
def _is_blank(i): """Return True if given a blank node identifier, False otherwise.""" return i.startswith('_:')
def test(request,P,C): """ used to debug database pool issues """ rt= {} return rt
def get_url(host, pre_protocol=None): """Generate URL based on the host. :param str host: Host from which to generate the URL (e.g. google.com:443). :param str pre_protocol: Protocol passed in the GET Path. Example request: GET https://127.0.0.1/robots.txt HTTP/1.1 Host: 127.0.0.1:323 Then, pre_protocol will be `https`. Defaults to `None`. :return: URL with domain and protocol (e.g. https://google.com). :rtype: str """ port_protocol = {'443': 'https', '22': 'ssh', '21': 'ftp', '20': 'ftp', '113': 'irc', '80': 'http'} protocol = '' url = host.strip() if not url.startswith('['): # A port is specified in the domain and without IPV6 if ':' in url: _, port = url.rsplit(':', 1) if port in port_protocol: # Do we know the protocol? protocol = port_protocol[port] + '://' else: if not url.endswith(']'): # IPV6 url with Port, [::1]:443 _, port = url.rsplit(':', 1) if port in port_protocol: # Do we know the protocol? protocol = port_protocol[port] + '://' # If GET path already specifies a protocol, give preference to that protocol = pre_protocol or protocol or 'http://' # Default protocol set to http return protocol + url
def _ros2_type_to_type_name(ros2_type): """ from std_msgs.msg import String # ros2 _ros2_type_to_type_name(String) # --> "std_msgs/String" """ try: first_dot = ros2_type.__module__.find(".") return ros2_type[0:first_dot] + "/" + ros2_type.__name__ except: # this shouldn't happen but try harder, don't crash the robot for something silly like this return str(ros2_type).replace("<class '", "").replace("'>", "")
def index_of_nth_base(gappedseq, n): """Return the index of the nth non-gapped base in the sequence where n=0 is the first.""" nongapped = 0 for i, b in enumerate(gappedseq): if b == '-': continue if nongapped == n: return i nongapped += 1 raise ValueError( "Could not find {0}'th non-gapped base in sequence".format(n))
def MD5_f4(b, c, d): """ Forth ternary bitwise operation.""" return (c ^ (b | (~d))) & 0xFFFFFFFF
def encode(asm: str) -> (int): """Converts a single assembly instruction to machine language. If not valid returns -1 Preconditions: None Postconditions: * Assume that the instruction is syntactically valid, but the instruction may contain an invalid instruction name, and should return -1 else return a correct machine language. * If valid, and 'DAT' is contained simply loads the value into the next available mailbox. If there is only 'DAT', then the default value is zero """ mnemonic = ['HLT', 'ADD', 'SUB', 'STA', 'LDA', 'BRA', 'BRZ', 'INP', 'OUT'] try: if asm.find('DAT') != -1: return int(asm[3:]) if asm[:3] in mnemonic: opcode = mnemonic.index(asm[:3]) if len(asm) > 3: operand = int(asm[3:]) return opcode * 100 + operand return opcode * 100 else: return -1 except: return -1
def tupletuple_to_dict(tupletuple): """Convert a tuple of tuples to dict >>> tupletuple = (('A', 'Value1'), ('B', 'Value2')) >>> d = tupletuple_to_dict(tupletuple) >>> d['A'] 'Value1' >>> d['B'] 'Value2' """ d = {} for t in tupletuple: (key, value) = t d[key] = value return d
def file_contents(file_path): """ Returns the contents of the file at `file_path`. """ try: with open(file_path, 'r') as f: contents = f.read() except IOError as e: contents = '\n %s' % e return contents
def handle_integers(params): """Handle floats which should be integers Args: params: dict, parameters from hyperband search space Returns: new_params: dict, parameters with corrected data types """ new_params = {} for k, v in params.items(): if v.__class__ == float and int(v) == v: new_params[k] = int(v) else: new_params[k] = v return new_params
def tie2string(tie): """Return a string repr of a tie.""" if tie: return "T" else: return ""
def union(g1, g2): """ Create a union of two lists, without duplicates. :return list: the union of the two lists """ return g1 + list(set(g2) - set(g1))
def cast_int(str): """a helper method for converting strings to their integer value Args: str: a string containing a number Returns: the integer value of the string given or None if not an integer """ if str!="" and str!=None: v = int(str) else: v = None return v
def string_dict(ds, headline='DICTIONARY:', offset=25): """ format the dictionary into a string :param dict ds: {str: val} dictionary with parameters :param str headline: headline before the printed dictionary :param int offset: max size of the string name :return str: formatted string >>> string_dict({'a': 1, 'b': 2}, 'TEST:', 5) 'TEST:\\n"a": 1\\n"b": 2' """ template = '{:%is} {}' % offset rows = [template.format('"{}":'.format(n), ds[n]) for n in sorted(ds)] s = headline + '\n' + '\n'.join(rows) return s
def export_shard_uuid(uuid): """Sharding of the UUID for the import/export :param uuid: UUID to be sharded (v4) :type uuid: str :return: Sharded UUID as a subfolder path :rtype: str """ import os return os.path.join(uuid[:2], uuid[2:4], uuid[4:])
def _gen_alternatives(alts): """Generate alternatives strings; takes in a list of pairs (alias-name, actual-name)""" res = "" for (alias, actual) in alts: rule = f"/usr/bin/{alias} {alias} /usr/bin/{actual}" if not res: res = f"update-alternatives --install {rule} 100 " else: res += f" \\\n --slave {rule}" return res
def group_edge_pairs(edges): """ Group pairs of forward and reverse edges between nodes as tuples in a list together with single directed edges if any :param edges: list of edges :type edges: :py:list :return: paired edges :rtype: :py:list """ pairs = [] done = [] for e in edges: if e in done: continue reverse_e = e[::-1] if reverse_e in edges: pairs.append((e, reverse_e)) done.append(reverse_e) else: pairs.append(e) done.append(e) return pairs
def add_colors(my_color_list): """Adds color pixels from a list. Avoids white.""" added_color = {"R": 0.0, "G": 0.0, "B": 0.0} for idx, my_color in enumerate(my_color_list): added_color["R"] += my_color["R"] added_color["G"] += my_color["G"] added_color["B"] += my_color["B"] is_white = sum([added_color[pixel] for pixel in ["R", "G", "B"]]) >= 2.9 if is_white: added_color[["R", "G", "B"][idx % 3]] = 0.0 return added_color
def recall(tp: int, fn: int, zero_division: int = 0) -> float: """Calculates recall (a.k.a. true positive rate) for binary classification and segmentation. Args: tp: number of true positives fn: number of false negatives zero_division: int value, should be one of 0 or 1; if both tp==0 and fn==0 return this value as s result Returns: recall value (0-1) """ # originally recall is: tpr := tp / (tp + fn + eps) # but when both masks are empty this gives: tp=0 and fn=0 => tpr=0 # so here recall is defined as tpr := 1 - fnr (false negative rate) if tp == 0 and fn == 0: return zero_division return 1 - fn / (fn + tp)
def get_height_from_ratio(width, ratio_w, ratio_h): """ Used to calculate thumbnail height from given width and ratio """ return width * ratio_h / ratio_w
def render_path(path, context): """ Replace variables in path with values. """ # Check for tokens delineated by "+" (e.g.: +variable+) if '+' not in path: return path for token, value in context.items(): path = path.replace('+' + token + '+', value) return path
def select_3_without_duplicates(items): """ Generate selections of 3 items without allowing duplicates.""" results = [] for i in range(len(items)): for j in range(i + 1, len(items)): for k in range(j + 1, len(items)): results.append(items[i] + items[j] + items[k]) return results
def cal_conversion_rate(X_total, X_converted): """Conversion rate for a specific group""" X_cr = X_converted / X_total if X_total != 0 else 0 return X_cr
def trim_hash_from_symbol(symbol): """If the passed symbol ends with a hash of the form h[16-hex number] trim this and return the trimmed symbol.""" # Remove the hash off the end tokens = symbol.split('::') last = tokens[-1] if last[0] == 'h': tokens = tokens[:-1] # Trim off hash if it exists trimmed_name = "::".join(tokens) # reassemble return trimmed_name else: return symbol
def count(input_, condition=lambda x: True): """Count the number of items in an iterable for a given condition For example: >>>count("abc") 3 >>>count("abc", condition=lambda x: x=="a") 1 """ return sum(condition(item) for item in input_)
def create_dirs(dir_name): """ create subdirectory names for a given dir, to be used by os.makedirs, Return a list of subdirectory names.""" primer3_input_DIR = dir_name + "/primer3_input_files/" primer3_output_DIR = dir_name + "/primer3_output_files/" bowtie2_input_DIR = dir_name + "/bowtie2_input/" bowtie2_output_DIR = dir_name + "/bowtie2_output/" mfold_input_DIR = dir_name + "/mfold_input/" mfold_output_DIR = dir_name + "/mfold_output/" return [primer3_input_DIR, primer3_output_DIR, bowtie2_input_DIR, bowtie2_output_DIR, mfold_input_DIR, mfold_output_DIR]
def convert_cntk_layers_to_ell_layers(layersToConvert): """Walks a list of CNTK layers and returns a list of ELL Layer objects that is used to construct a Neural Network Predictor""" ellLayers = [] for layerObject in layersToConvert: layerObject.process(ellLayers) return ellLayers
def encode_variable(d, i, j): """This function creates the variable (the integer) representing the fact that digit d appears in position i, j. Of course, to obtain the complement variable, you can just negate (take the negative) of the returned integer. Note that it must be: 1 <= d <= 9, 0 <= i <= 8, 0 <= j <= 8.""" assert 1 <= d <= 9 assert 0 <= i < 9 assert 0 <= j < 9 # The int() below seems useless, but it is not. If d is a numpy.uint8, # as an element of the board is, this int() ensures that the generated # literal is a normal Python integer, as the SAT solvers expect. return int(d * 100 + i * 10 + j)
def describe_out_port_map(tree_depth, n_tree): """ Assumption: All PEs have output ports No crossbar for output """ # Dict of dicts # Key_1: Tree_id # Key_2: lvl # Key_3: pe_id # Val: Set of banks out_port_map= {} """ # two banks for PEs at all level except level 2 # four banks for level 2 PEs for tree in range(n_tree): base_bank= tree*(2**tree_depth) for rev_lvl in range(tree_depth): lvl= tree_depth-rev_lvl for pe in range(2**rev_lvl): if lvl != 2: # Two banks per PE start= base_bank + pe*(2**lvl) + 2**(lvl-1) - 1 end= base_bank + pe*(2**lvl) + 2**(lvl-1) + 1 else: # lvl=2, four banks per PE start= base_bank + pe*(2**lvl) + 2**(lvl-1) - 2 end= base_bank + pe*(2**lvl) + 2**(lvl-1) + 2 banks= set(range(start,end)) out_port_map[(tree,lvl,pe)]= banks """ # 2 banks for 1st level, 4 banks for 2nd level and so on for tree in range(n_tree): base_bank= tree*(2**tree_depth) for rev_lvl in range(tree_depth): lvl= tree_depth-rev_lvl for pe in range(2**rev_lvl): start= base_bank + pe*(2**lvl) end= base_bank + (pe+1)*(2**lvl) banks= set(range(start,end)) out_port_map[(tree,lvl,pe)]= banks return out_port_map
def offensive_contribution(team_yards, player_yards): """ Calculate a percentage for the percentage of team yards that a player contributes to. Input: - Dataframe to use in the calculation Output: - New dataframe column with the desired contribution score """ contribution = player_yards / team_yards if contribution > 1.0: return 1.0 else: return contribution
def get_links(sp_config): """ Returns a list of (resource, pattern) tuples for the 'links' for an sp. """ links = sp_config.get('links', []) if type(links) is dict: links = links.items() return links
def strip_bucket_prefix(prefix): """Remove any leading or trailing "/" characters.""" return '/'.join(x for x in prefix.split('/') if x)
def count_vowels(word): """ Returns the number of vowels (a, e, i, o, u) in a string using recursion Examples: >>> count_vowels('Autodifferentiation') 10 >>> count_vowels("avada kedavra") 6 >>> count_vowels("STAMPEDE") 3 >>> count_vowels("stpd") 0 >>> count_vowels('A '*350) 350 """ vowel = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'] if word == "": return 0 elif word[0] in vowel: return count_vowels(word[1:]) + 1 else: return count_vowels(word[1:])
def linspace(start, end, num=50): """ Return equally spaced array from "start" to "end" with "num" vals. """ return [start+i*((end-start)/float(num-1)) for i in range(num)]
def get_style(param): """Checks parameter style for simpler scenarios""" if 'style' in param: return param['style'] # determine default return ( 'simple' if param['in'] in ['path', 'header'] else 'form' )
def is_tuple_or_list(val): """ Checks whether a variable is a list or a tuple :param val: The variable to check :return: True if the variable is a list or a tuple, otherwise False """ return isinstance(val, (list, tuple))
def coerce_operands(a, b): """Return the two arguments coerced to a common class. If one is int, then try to interpret the other as an int as well. If this is successful, return both as ints. Otherwise, return both as strs. If both are already strs then they are returned unchanged. """ try: if isinstance(a, int): return a, int(b) if isinstance(b, int): return int(a), b except ValueError: pass return str(a), str(b)
def length(v): """Calculate the length (a.k.a. norm) of the given vector.""" return sum(x ** 2 for x in v) ** 0.5
def choose_ncv(k): """ Choose number of lanczos vectors based on target number of singular/eigen values and vectors to compute, k. """ return max(2 * k + 1, 20)
def max_filter(seq, default=None): """Returns the max value from the sequence.""" if len(seq): return max(seq) return default
def is_empty(module, container_name, facts, debug=False): """ Check if container can be removed safely. To be removed, a container shall not have any container or device attached to it. Current function parses facts to see if a device or a container is attached. If not, we can remove container Parameters ---------- module : AnsibleModule Object representing Ansible module structure with a CvpClient connection container_name : str Name of the container to look for. facts : dict Facts from CVP collected by cv_facts module debug : bool, optional Activate debug logging, by default False """ is_empty = True not_empty = False # test if container has at least one device attached for device in facts['devices']: if device['parentContainerName'] == container_name: return not_empty return is_empty
def _HELP_convert_RMSD_nm2angstrom(RMSD_nm): """ Helpfunction for plot_HEATMAP_REX_RMSD(): convert RMSD values: RMSD_nm -> RMSD_anstrom Args: RMSD_nm (list): rmsd values in nm Returns: RMSD (list) rmsd values in angstrom """ RMSD = [x*10 for x in RMSD_nm] return RMSD
def this_gen(length: int): """Generates a text penis at a given length""" if (length <= 1998 and length >= 0): this_thing = "8" for _ in range(length): this_thing += "=" this_thing += "D" return this_thing elif (length >= -1998 and length < 0): new_length = -length this_thing = "D" for _ in range(new_length): this_thing += "=" this_thing += "8" return this_thing else: return "Sorry bud, but my dick won't fit in here. **_: )_**"
def sum_2d_dicts(dict1, dict2): """ :param dict1: {thrs_0: {'TP': x0, 'FP': y0, 'FN': z0}, ... , thrs_N: {'TP': xN, 'FP': yN, 'FN': zN}} :param dict2: {thrs_0: {'TP': x0, 'FP': y0, 'FN': z0}, ... , thrs_N: {'TP': xN, 'FP': yN, 'FN': zN}} :return: dict2 = dict1 + dict2 """ for d_one in dict1: for d_two in dict1[d_one]: dict2[d_one][d_two] = dict2[d_one][d_two] + dict1[d_one][d_two] return dict2
def mean(arr, support=None): """ Calculate the mean of an array :param arr: input list of data :return: """ if support is not None: return sum(arr)/sum(support) else: return sum(arr)/len(arr)
def _list_to_mqtt_values(values, prefix, num_digits): """Transforms a values=['a', 'b', 'c'], prefix='myval', num_digits=4 into a dict { 'myval0000': 'a', 'myval0001': 'b', 'myval0002': 'c', } so it can be sent as telemetry over MQTT, see https://thingsboard.io/docs/reference/gateway-mqtt-api/#telemetry-upload-api """ return dict( ('{prefix}{index:0>{width}}'.format(prefix=prefix, index=i, width=num_digits), values[i]) for i in range(len(values)) )
def multi_replace(inputstring, replacements): """Apply the replace method multiple times. "inputstring" is self-explanatory, "replacements" is a list of tuples, the fist item of each tuple the substring to be replaced and the second the replacement text. """ for replacement in replacements: inputstring = inputstring.replace(replacement[0], replacement[1]) return inputstring
def find_motif_positions(sequence: str, motif: str): """ Returns the start and end position(s) of a core motif in a sequence Args: sequence: string of nucleotides motif: string of nucleotides representing a motif Returns: startpositions: list of start position(s) of core motif in read endpositions: list of end position(s) of core motif in read """ startpositions = [] for i in range(len(sequence) - len(motif) + 1): # loop over read match = True for j in enumerate(motif): # loop over characters if sequence[i + j[0]] != motif[j[0]]: # compare characters match = False # mismatch break if match: # all chars matched startpositions.append(i) endpositions = [] for k in enumerate(startpositions): endpositions.append(startpositions[k[0]] + len(motif) - 1) return startpositions, endpositions
def convert_seconds(seconds): """ Convert the duration of time in 'seconds' to the equivalent number of hours, minutes, and seconds. """ hours = seconds // 3600 minutes = (seconds - hours * 3600) // 60 remaining_seconds = seconds - hours * 3600 - minutes * 60 return hours, minutes, remaining_seconds
def Rpivot(p, q, Mb): """ Given an augmented matrix Mb, Mb = M|b, this gives the output of the pivot entry [i, j] in or below row p, and in or to the right of column q. """ # n is the number of columns of M, which is one less than that of Mb. m = len(Mb) n = len(Mb[0]) - 1 # Initialize i, j to p, q, and we will not go above or leftwards of p, q. i = p j = q # Iterate through the columns of Mb to find its first nonzero column. for y in range(q, n): if [Mb[x][y] for x in range(p, m)] == [0] * (m - p): j = j + 1 else: break # Iterate through the rows of M from p to n-1. for x in range(p, n): # Adds one to row index i if column i is all zeros from column j # to column n. if Mb[x][j:n] == [0] * (n - j + 1): i = i + 1 else: break return [i, j]
def TransformNextMaintenance(r, undefined=''): """Returns the timestamps of the next scheduled maintenance. All timestamps are assumed to be ISO strings in the same timezone. Args: r: JSON-serializable object. undefined: Returns this value if the resource cannot be formatted. Returns: The timestamps of the next scheduled maintenance or undefined. """ if not r: return undefined next_event = min(r, key=lambda x: x.get('beginTime', None)) if next_event is None: return undefined begin_time = next_event.get('beginTime', None) if begin_time is None: return undefined end_time = next_event.get('endTime', None) if end_time is None: return undefined return '{0}--{1}'.format(begin_time, end_time)
def uppercase(s: str) -> str: """ Convert a string to uppercase. Args: s (str): The string to be converted. Returns: str: The converted uppercase string. Example: >>> uppercase('completely different') == 'COMPLETELY DIFFERENT' True """ return s.upper()
def relu(x): """Rectified linear unit Parameters ---------- x : matrix input matrix Returns ------- y : matrix output matrix """ return x*(x>1e-13);
def partition(arr, left, right): """Funciton to partition list.""" pivot = left i, j = left + 1, right while True: while i <= j and arr[i] < arr[pivot]: i += 1 while j >= i and arr[j] > arr[pivot]: j -= 1 if j < i: break else: temp = arr[j] arr[j] = arr[i] arr[i] = temp temp = arr[pivot] arr[pivot] = arr[j] arr[j] = temp return arr, i, j
def multiply(x, y): """Function to perform multiply""" return x * (-1 * y) # return x * y
def remove_nones(**kwargs): """Return diict copy with nones removed. """ return dict((k, v) for k, v in kwargs.items() if v is not None)
def bisect_left(a, x, hi): """Return the index in the sorted list 'a' of 'x'. If 'x' is not in 'a', return the index where it can be inserted.""" lo = 0 while lo < hi: mid = (lo+hi)//2 if a[mid] < x: lo = mid+1 else: hi = mid return lo
def fib2(n): """ returns list of Fibonacci series up to nth term """ result = [0, 1] i = 2 while i < n: result.append(result[i-1] + result[i-2]) i += 1 return result
def Ida2Olly(sig) -> str: """ Ida2Olly(sig) Convert an IDA sig to an Olly Debugger compatible sig Arg: sig: IDA style sig Return: string """ pattern = [] for entry in sig.split(' '): if entry == '?': pattern.append('??') else: pattern.append(entry) return " ".join(pattern)
def dict_to_list(d, default=0, size=None): """ Converts the given dictionary of type (Map Int a) to [a]. """ if size is None: size = max(d.keys(), default=-1) + 1 result = [default] * size for i, v in d.items(): assert(type(i) == int) result[i] = v return result
def _get_windows(peak_list): """ Given a list of peaks, bin them into windows. """ win_list = [] for t0, t1, hints in peak_list: p_w = (t0, t1) for w in win_list: if p_w[0] <= w[0][1] and p_w[1] >= w[0][0]: w[0] = (min(p_w[0], w[0][0]), max(p_w[1], w[0][1])) w[1].append((t0, t1, hints)) break else: win_list.append([p_w, [(t0, t1, hints)]]) return win_list
def sort_solution(sol): """ Sort a solution to an equation by the variable names. """ return tuple(sorted(sol, key=lambda e: str(e.lhs())))
def drop_prefix_from_str(item: str, prefix: str, divider: str = '') -> str: """Drops 'prefix' from 'item' with 'divider' in between. Args: item (str): item to be modified. prefix (str): prefix to be added to 'item'. divider (str): str to add between 'item' and 'prefix'. Defaults to '', which means no divider will be added. Returns: str: modified str. """ prefix = ''.join([prefix, divider]) if item.startswith(prefix): return item[len(prefix):] else: return item
def isValidCell(point_coor, grid_size) -> bool: """Assess if a given point is within the grid. :param array-like point_coor: Array-like object of size 2 that holds the x and y coordinates of a given point. :param array-like grid_size: Array-like object of size 2 taht holds the number of rows and cols in the grid. :returns: True if the point is within the grid, False otherwise. :rtype: bool """ x, y = point_coor # get the coordinates of the point rows, cols = grid_size # get the rows and cols return (x >= 0) and (x < rows) and (y >= 0) and (y < cols)
def delta_nu(numax): """ Estimates dnu using numax scaling relation. Parameters ---------- numax : float the estimated numax Returns ------- dnu : float the estimated dnu """ return 0.22*(numax**0.797)
def flatten(l: list) -> list: """ 1.2 Flatten a multi dimensional list [[1, 2], [2, 4]], gives : [1, 2, 2, 4] """ flat_list = [] for el in l: if isinstance(el, list): flat_list.extend(flatten(el)) else: flat_list.append(el) return flat_list
def left_justify(words, width): """Given an iterable of words, return a string consisting of the words left-justified in a line of the given width. >>> left_justify(["hello", "world"], 16) 'hello world ' """ return ' '.join(words).ljust(width)
def generate_repr_code(repr, node, fields): """ The CPython implementation is just: ['return self.__class__.__qualname__ + f"(' + ', '.join([f"{f.name}={{self.{f.name}!r}}" for f in fields]) + ')"'], The only notable difference here is self.__class__.__qualname__ -> type(self).__name__ which is because Cython currently supports Python 2. """ if not repr or node.scope.lookup("__repr__"): return "", {}, [] code_lines = ["def __repr__(self):"] strs = [u"%s={self.%s!r}" % (name, name) for name, field in fields.items() if field.repr.value and not field.is_initvar] format_string = u", ".join(strs) code_lines.append(u' name = getattr(type(self), "__qualname__", type(self).__name__)') code_lines.append(u" return f'{name}(%s)'" % format_string) code_lines = u"\n".join(code_lines) return code_lines, {}, []
def is_templated_secret(secret: str) -> bool: """ Filters secrets that are shaped like: {secret}, <secret>, or ${secret}. """ try: if ( (secret[0] == '{' and secret[-1] == '}') or (secret[0] == '<' and secret[-1] == '>') or (secret[0] == '$' and secret[1] == '{' and secret[-1] == '}') ): return True except IndexError: # Any one character secret (that causes this to raise an IndexError) is highly # likely to be a false positive (or if a true positive, INCREDIBLY weak password). return True return False
def _from_little_endian(data, index, n_bytes): """Convert bytes starting from index from little endian to an integer.""" return sum(data[index + j] << 8 * j for j in range(n_bytes))
def nofirst(l): """ Returns a collection without its first element. Examples -------- >>> nofirst([0, 1, 2]) [1, 2] >>> nofirst([]) [] """ return l[1:]