content
stringlengths
42
6.51k
def unique_elements(array): """Return unique elements of an array.""" unique = [] for x in array: if x not in unique: unique.append(x) return unique
def _get_ace_translation(value, *args): """ This will take the ace name and return the total number accosciated to all the ace accessmasks and flags Below you will find all the names accosiated to the numbers: """ ret = 0 ace_dict = {'ReadData': 1, 'CreateFiles': 2, 'AppendData': 4, 'ReadEx...
def is_valid_error_cls(cls): """ Check whether the supplied object is valid VK API error exception class. :param cls: Class object to be checked :rtype: bool """ valid_name = cls.__name__.endswith('Error') valid_attrs = hasattr(cls, 'error_code') return valid_name and valid_attrs
def lr_poly(base_lr, iter, max_iter, power): """ Args: base_lr: initial learning rate iter: current iteration max_iter: maximum number of iterations power: power value for polynomial decay Returns: the updated learning rate with polynomial decay """ return base_lr...
def total_t(arr): """ Returns the total of nodes with value "TRUE" in a given array """ count = 0 for x in arr: if x == True: count += 1 return count
def s_one_one(topics): """ This function performs s_one_one segmentation on a list of topics. s_one_one segmentation is defined as: s_one_one = {(W', W*) | W' = {w_i}; W* = {w_j}; w_i, w_j belongs to W; i != j} Example: >>> topics = [np.array([1, 2, 3]), np.array([4, 5, 6])] >>> s_one_p...
def should_pursue_references(path): """ Given a file path, returns whether or not we are interested in seeing whether or not the file contains additional references to other files. """ return not ( path.endswith('.wav') or path.endswith('.bsp') or path.endswith('.vtf')...
def none_conv(result): """Just in case of a None result, to prevent script crashing""" if result != None: return result else: new_result = 0.0 return new_result
def get_used_in(id_set, script_id): """ Gets the integrations, scripts and playbooks that used the input script, without test playbooks. :param id_set: updated id_set object. :param script_id: the script id. :return: list of integrations, scripts and playbooks that used the input script """ ...
def make_list_dict(item): """ Initialize a dictionary of keys with empty lists as values. Parameters ---------- item: list List of titles used to initialize a dictionary Returns ------- list_dict: dict Dictionary initialized with objects in `item` list as keys and empty...
def send_to_right_side(targets, values): """Send the given target values to the right of all other values. Example: targets = ["b", "x","c"] values = ["a", "b", "c", "x", "y", "z"] send_to_right_side(targets, values) # -> ["a", "y", "z", "b", "x", "c"] Args: targets: Values to sen...
def safe_add(direction, direction_delta, check_constraints=False): """Check resulting vector values and add if not violates constraints. Constraints are [-1; 1]. """ x, y, z = direction new_x = x + direction_delta['x'] new_y = y + direction_delta['y'] new_z = z + direction_delta['z'] if...
def timeStamp(list_time): """ Format time stam into `00h00m00s` into the dictionary :param list_time: float list of time stamp in second :return format_time: dictionary of format time """ format_time = dict() i = 0 for time in list_time: m, s = divmod(time, 60) h, m = div...
def _hgvs_to_zbc(i): """Convert hgvs (1 based, missing zero) """ if i >= 1: i -= 1 return i
def one(nodes, or_none=False): """ Assert that there is exactly one node in the give list, and return it. """ if not nodes and or_none: return None assert len( nodes) == 1, 'Expected 1 result. Received %d results.' % (len(nodes)) return nodes[0]
def get_sum(a, b): """ Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b. :param a: :param b: :return: """ if a > b: a, b = b, a retur...
def get_fraction_unique(molecular_graphs): """ Returns the fraction (`float`) of unique graphs in `molecular_graphs` (`list` of `MolecularGraph`s) by comparing their canonical SMILES strings. """ smiles_list = [] for molecular_graph in molecular_graphs: smiles = molecular_graph.get_smiles(...
def copy_files(in_files, out_files): """ Create a function to copy a file that can be modified by a following node without changing the original file """ import shutil import sys if len(in_files) != len(out_files): print( "ERROR: Length of input files must be identical to...
def is_rotated_list(list_a, list_b): """ Check if `list_b` is a rotated version of `list_a`. To do this, concat `list_a` with `list_a`, then check if `list_b` is a sublist of it. Args: list_a (list): The "primary" list. list_b (list): The list to check if is rotated. ...
def combine_data(data: dict) -> dict: """ Clean all data """ keys = data.keys() for number in keys: tempt = {} loudness, tempo, mode, time_signature, key = [], [], [], [], [] for i in data[number]["sections"]: loudness.append(i["loudness"]) tempo.append(i["t...
def array_to_string(array, delimiter=" ", format="{}", precision=None): """ Converts a numeric array into the string format in mujoco. Examples: [0, 1, 2] => "0 1 2" """ if precision is not None and format == "{}": return delimiter.join([format.format(round(x, precision)) for x in a...
def mk_int(s): """ Function to change a string to int or 0 if None. :param s: String to change to int. :return: Either returns the int of the string or 0 for None. """ try: s = s.strip() return int(s) if s else 0 except: return s
def clean_for_geocode(orig_str): """ Remove punctuation and stopwords at the end of the string only, repeatedly. :param orig_str: original string :return: clean string, ready to be geocoded """ stopwords = ['in', 'the', 'upon', 'of', 'at', 'within', 'to', 'along', 'near'] prev_len = l...
def complement_base(base, material ='DNA'): """Returns the Watson-Crick complement of a base.""" if base == 'A' or base == 'a': if material == 'DNA': return 'T' elif material == 'RNA': return 'U' elif base == 'T' or base == 't' or base == 'U' or base == 'u': r...
def _split_varpath(cont, path): """Return a tuple of compname,component,varname given a path name of the form 'compname.varname'. If the name is of the form 'varname', then compname will be None and comp is cont. """ try: compname, varname = path.split('.', 1) except ValueError: ...
def effir(interest_rate, compounds): """ """ return (1 + interest_rate / compounds) ** compounds - 1
def convertRowIntoIndexValuePairs(row): """ Converts [x, y, z, ...] into [(0, x), (1, y), (2, z)] for use in the classifiers in their "where" statements """ return [ (index, value) for index, value in enumerate(row)]
def make_url(type: str) -> str: """Will compose a url based on the given type.""" return f"/{type}/add"
def odeFun(t,y,**kwargs): """ Contains system of differential equations. Arguments: t : current time variable value y : current state variable values (order matters) **kwargs : constant parameter values, interpolanting functions, etc. Returns: Dictionary c...
def isNearBrightStar(nearStarPeak, mainPeak): """ Is the main star near another bright star? """ return (0.2 * mainPeak < nearStarPeak)
def mapping(row): """ @param row : The row which is generated as a result of the select query done The new values are returned which are are generarated for each row . """ return row["id"]
def call_until(fun, expr): """Keep calling function for timeout secs and exit if eval() expression is True. """ ret = fun() assert eval(expr) return ret
def humanize_time(seconds): """Convert time in seconds to (better) human readable format. :param seconds: seconds :type seconds: float :return: Human readable time in h:m:s:ms :rtype: str """ ms = seconds % int(seconds) * 1000 mins, seconds = divmod(int(seconds), 60) hours, mins...
def is_valid_gatech_username(username: str) -> bool: """ Rough validator for GT usernames :param username: the username to check :return: whether this is a valid username """ if not username.isalnum(): return False if not username[0].isalpha(): return False if not userna...
def check_shell(cmd, shell=None): """ Determine whether a command appears to involve shell process(es). The shell argument can be used to override the result of the check. :param str cmd: Command to investigate. :param bool shell: override the result of the check with this value. :return bool: ...
def get_overlap( tabix, chrom, start, end, priority=["exon", "gene", "transcript", "cds"], no_hit="intergenic", fix_chr=True, ): """ args: tabix (pysam.libctabix.TabixFile) - open TabixFile chrom (str) start (int) end (int) priority (Optional[l...
def is_constructed(val): """Check if a tag represents a "constructed" value, i.e. another TLV""" return val & 0b00100000 == 0b00100000
def number_of_words(string): """Return the number of words in a string. :param string: The string to check """ return len(string.split())
def validate(config): """ Validate the beacon configuration """ # Configuration for service beacon should be a list of dicts if not isinstance(config, list): return False, "Configuration for service beacon must be a list." else: _config = {} list(map(_config.update, confi...
def patch_transform(diff_opcodes, a_transformed, b_raw, transform, verify=False): """ Minimally patch the list a_transformed == [transform(ai) for ai in a_raw] into the list b_transformed == [transform(bi)...
def _is_singleton(input_value, param_info): """ Returns True if the given input value is a singleton of that parameter. E.g., if it's a single string or number for a text parameter, or a list of strings/numbers if the parameter allows multiples, or it's a dict if the parameter is a group param. Tha...
def sum_that_match_next(sequence): """Return the sum of numbers that match the next digit.""" total = 0 for idx, val in enumerate(sequence): if int(val) == int(sequence[(idx + 1) % len(sequence)]): total += int(val) return total
def find_diff_of_lists_and_sets(stat1, stat2): """ Finds the difference between two stats. If there is no difference, returns "unchanged". Removes duplicates and returns [unique values of stat1, shared values, unique values of stat2]. :param stat1: the first statistical input :type stat1: Unio...
def do_something(x): """ Do something so we have something to test. >>> do_something(3) 16 >>> do_something(7) 24 """ return (x+5)*2
def _merge_by_type(usage_types, missing_values, unusual_changes_by_type): """Merge the contents of dicts `missing_values` and `unusual_changes_by_type`. The result will have the following form: { <UsageType>: { 'unusual_changes': [ (datetime.date, datetime.date, float, fl...
def parse_lats_lons(val): """Takes a 'lats' or 'lons' value and returns two floats representing the southern/western coordinate and the northern/eastern coordinate. Example input: '60 S 80 N' Example output: (-60.0, 80.0) Parameters ---------- val (str): String representing 'lats' ...
def get_board_copy(board): """Duplicates the board list & returns it duplicate.""" BoardCopy = [] board_length = len(board) for i in range(board_length): BoardCopy.append(board[i]) return BoardCopy
def _has_file(mod): """ :param mod: Module object. Can be any of the multiple types used to represent a module, we just check for a __file__ attribute. :type mod: ``Any`` :return: If given module has a not None __file__ attribute. :rtype: ``bool`` """ return hasattr(mod, "__file__") ...
def exc_repr(exc): """Construct representation of given exception appropriate for printed output. """ exc_repr = '' if exc.__class__.__module__ != 'builtins': exc_repr += f'{exc.__class__.__module__}.' exc_repr += exc.__class__.__name__ if exc.args: exc_repr += ': ' + ', ...
def validate_password(password: str): """ Validate the user password >>> validate_password("short") Traceback (most recent call last): ... raise ValueError("password must have at least 8 characters") ValueError: password must have at least 8 characters >>> validate_password("This is a g...
def _get_column_lables(line): """ Extract the following column lables from pilercr "SUMMARY BY POSITION" table: "Position", "Length", "Copies", "Repeat", "Spacer", "Strand", "Consensus". """ lables = line.split() lables_to_remove = ["Array", "Sequence", "#", "+"] lables = [lable fo...
def challenge_request(name): """Create ACME "challengeRequest message. :param str name: Domain name :returns: ACME "challengeRequest" message. :rtype: dict """ return { "type": "challengeRequest", "identifier": name, }
def commands(user_input): """funtion used to evaluate user's commands""" if user_input == "/help": print("The program performs simple mathematic operations based on user input") return False elif user_input == "/exit": print("Bye!") return True else: prin...
def replace_printable(s, printables, wild=" "): """ If the character in s is not in printables, replaces by wild. """ new_s = "" for i in s: new_s += i if i in printables else wild return new_s
def Get_state_as_str(n_qubits, qubit_state_int): """ converts qubit state int into binary form. Args: n_qubits (int): Number of qubits qubit_state_int (int): qubit state as int (NOT BINARY!) Returns: string of qubit state in binary! state = |000> + |001> + |010> + |011> + |...
def encode(plaintext, key): """Encodes plaintext Encode the message by shifting each character by the offset of a character in the key. """ ciphertext = "" i, j = 0, 0 # key, plaintext indices # strip all non-alpha characters from key key2 = "" for x in key: key2 += x if x.isalpha...
def fix_interactive(code: str) -> str: """Strip out >>> and output (lines without >>>)""" lines = code.split("\n") good_lines = [] # interactive = sum(1 for line in lines if ">>>" in line) for line in lines: if line.startswith("... "): good_lines.append(line.strip()[4:]) ...
def reference_values(): """Reference values for fit statistics test. Produced using sherpa stats module in dev/sherpa/stats/compare_wstat.py """ return dict( wstat=[ 1.19504844, 0.625311794002, 4.25810886127, 0.0603765381044, 11.728500...
def second_to_day(seconds): """ :param seconds: (int) Time in seconds starting at 0 as start of data collection. :return: (int) Time in days starting at 0 as start of data collection """ return int(seconds) / 86400
def magND(v): """Returns magnitude of an nD vector""" return sum(vv**2 for vv in v) ** 0.5
def _get_partition_from_id(partitions, user_partition_id): """ Look for a user partition with a matching id in the provided list of partitions. Returns: A UserPartition, or None if not found. """ for partition in partitions: if partition.id == user_partition_id: return p...
def calc_diff(time1, time2): """Returns the difference between two time objects or returns None.""" try: return time1 - time2 except TypeError: return None
def bruteforce_range(sequence, target): """ Again not my proudest achievement, it's obviously not optimized enough... But at least I have my second gold star and can go to sleep :) """ n = len(sequence) for start in range(n): for length in range(1, n-start): if target == sum(...
def u4(vector): """ A utility function that is a constant. :param vector: The input payoff vector. :return: A constant utility k. """ k = 2 return k
def query_result_to_cluster_token_pairs(query_result): """Given a query result structure, returns a sequence of (cluster, token) pairs from the result""" cluster_token_pairs = ((c, t) for c, e in query_result['clusters'].items() for t in e['tokens']) cluster_token_pairs_sorted = sorted(cluster_token_pairs, ...
def is_route_dfs(graph, node1, node2): """Determine if there is a route between two nodes.""" def dfs(current_node, visited_nodes): for child_node in graph[current_node]: if child_node not in visited_nodes: if child_node == node2: return True ...
def factorial(num): """Another recursive function""" if num == 0 or num == 1: return 1 return num * factorial(num - 1)
def detectTextTwgoCancelled(frame): """Return an empty string if there is no cancelled message in this text TWGO frame. Otherwise return string with cancellation details. Args: frame (dict): Contains a text TWGO frame. Returns: (str): '' if there is no cancellation associated ...
def getPitch(cmdf, tau_min, tau_max, harmo_th=0.1): """ Return fundamental period of a frame based on CMND function. :param cmdf: Cumulative Mean Normalized Difference function :param tau_min: minimum period for speech :param tau_max: maximum period for speech :param harmo_th: harmonicity thres...
def has_rna_tracks(case_obj): """Returns True if one of more individuals of the case contain RNA-seq data Args: case_obj(dict) Returns True or False (bool) """ # Display junctions track if available for any of the individuals for ind in case_obj.get("individuals", []): #...
def get_id_str(objects, delimiter='_'): """ Get a string of sorted ids, separated by a delimiter. Args: objects (Model): An iterable of model instances. Keyword Args: delimiter (str): The string the ids will be joined on. Returns: str: The joined and sorted...
def splitall(string, splitcharlist): """Splits the supplied string at all of the characters given in the second argument list :param string: the string to break up :type string: string :param splitcharlist: a list of characters to break on :type splitcharlist: a list of character...
def default_popup_element(title=None, operation=None, format=None): """Helper function for quickly adding a default popup element based on the style. A style helper is required. Args: title (str, optional): Title for the given value. By default, it's the name of the value. operation (str, o...
def dict_pop_nested(d, key): """Get a (potentially nested) key from a dict-like.""" if '.' in key: key, rest = key.split('.', 1) if key not in d: raise KeyError(key) return dict_pop_nested(d[key], rest) else: if key not in d: raise KeyError(key) ...
def bin_search(find, lst): """ >>> bin_search(0, [0, 1]) 0 >>> bin_search(1, [0, 1]) 1 >>> bin_search(2, [0, 1]) -1 >>> bin_search(0, [0, 1, 2]) 0 >>> bin_search(1, [0, 1, 2]) 1 >>> bin_search(2, [0, 1, 2]) 2 >>> bin_search(3, [0, 1, 3, 5]) 2 >>> b...
def needleman_wunsch(a,b,p=0.97): """Needleman-Wunsch and Smith-Waterman""" z=[] for i,r in enumerate(a): z.append([]) for j,c in enumerate(b): if r==c: z[-1].append(z[i-1][j-1]+1 if i*j>0 else 1) else: z[-1].append(p*max(z[i-1][j] if i>0 else 0,z[i][j-1] if j>0 else 0)) ...
def try_add_value_case_insensitive(d, key_name, new_value): """ Look in a dictionary for a key with the given key_name, without concern for case. If the key is found, return the associated value. Otherwise, set the value to that provided. """ for name, value in d.items(): if name.lower()...
def formatter(format_string, kwargs): """ Default formatter used to format strings. Instead of `"{key}".format(**kwargs)` use `formatter("{key}", kwargs)` which ensures that no errors are generated when an user uses braces e.g. {}. Bear in mind that formatter consumes kwargs which in turns replaces ...
def strip_prefices(columns, prefices): """Filters leaderboard columns to get the system column names. Args: columns(iterable): Iterable of leaderboard column names. prefices(list): List of prefices to strip. You can choose one of ['channel_', 'parameter_', 'property_'] Returns:...
def parse_response(resp): """Parse requests response. `resp` will have the following format: {'base': 'stations', 'clouds': {'all': 20}, 'cod': 200, 'coord': {'lat': 46.05, 'lon': 14.51}, 'dt': 1495803600, 'id': 3196359, 'main': {'humidity': 37, ...
def to_byte_string(value, count=2, signed=False, byteorder='little'): """Take bytes and return string of integers. Example: to_byte_string(123456, count=4) = '64 226 1 0' """ byte_value = value.to_bytes(count, byteorder=byteorder, signed=signed) return ' '.join([str(x) for x in byte_value])
def lol_tuples(head, ind, values, dummies): """ List of list of tuple keys Parameters ---------- head : tuple The known tuple so far ind : Iterable An iterable of indices not yet covered values : dict Known values for non-dummy indices dummies : dict Ranges ...
def sigmoid_derivative(x): """sigmoid_derivative the derivative of sigma(x) d sig(x)/ dx! """ return x * (1.0 - x)
def is_palindrome_iterative(text): """is_palindrome_iterative return True if input text is a palindrome, and false if not""" # Start at either end of the word, work towards middle left_index = 0 right_index = len(text)-1 # Ensure middle hasn't been surpased while left_index <= right_index: ...
def append_write(filename="", text=""): """ Write a new file or append info if exists Args: filename: string containing the name or "" if not given. text: content of the file Return: number of chars written """ with open(filename, 'a', encoding="utf-8") a...
def excape_u(byte_str): """ Replace '\\u' with '$' folowed by capital letters. """ if b'\\u' in byte_str: index = byte_str.find(b'\\u') left = byte_str[:index] right = byte_str[index + 6:] digit = byte_str[index + 2: index + 6] return left + b'$' + digit.upper() +...
def in_clause_subs(number): """ Returns a string with n question marks to be used as substitutions placeholders in sql queries. """ return ','.join(['?'] * number)
def electron_binding_energy(charge_number): """Return the electron binding energy for a given number of protons (unit is MeV). Expression is taken from [Lunney D., Pearson J. M., Thibault C., 2003, Rev. Mod. Phys.,75, 1021].""" return 1.44381e-5 * charge_number ** 2.39\ + 1.55468e-12 * char...
def sourcemorerecent(sourcefile, targetfile): """ Returns True if sourcefile is more recent than targetfile """ from os.path import isfile, getmtime if isfile(targetfile): time_source = getmtime(sourcefile) time_target = getmtime(targetfile) return time_source > time_target else: retu...
def search_all_places_for_place_name(place_array, place_name, state): """Searches a place with a specified name and state in a given array.""" all_places = [] for place in place_array: if place.place_name == place_name and place.state == state: all_places.append(place) return all_...
def check_uniqueness_in_rows(board: list) -> bool: """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check...
def check_weights(nodes_with_a_weight): """ Ensure that the sum of the values is 1 :param nodes_with_a_weight: a list of Node objects with a weight attribute """ weights = [n['weight'] for n in nodes_with_a_weight] if abs(sum(weights) - 1.) > 1E-12: raise ValueError('The weights do not ...
def _alien_domain(environ, space_name): """ Detect if a space_name is in an alien domain. Alien means not in the server_host subdomain or _the_ main domain. """ # Some other things will eventually happen here, which # is why environ is being passed in. if space_name == 'frontpage': ...
def _get_result(args): """Calculates a full result code for use in generating predictions""" stage, app_type, result_code, attending, waitlisted, deferred = args if result_code == "denied": return "Denied" elif result_code in ["accepted", "cond. accept", "summer admit"]: if attendi...
def parse_file(filename): """Read a recipe file and return the data as a dict{name, body}. Return None on failure. """ try: recipe_dict = {} with open(filename, "r") as file: contents = file.read() recipes = contents.split("\n\n\n") for recipe in rec...
def class_in_path(class_name, path_str): """ Checks if the class of interest is in the tree path Note that the path is supposed to have the nodes separated by "."-symbol. The main issue this function addresses is ambiguous cases, e.g. SL:PATH vs SL:PATH_AVOID Args: class_name: str, e.g...
def multi_lane_to_dict(lane): """Convert a list of lane entries into a dictionary indexed by library ID """ return dict( ((x['library_id'],x) for x in lane) )
def local_repo_name(group, repo_name, pull_id): """ combine name to avoid name conflit """ return "{}_{}_{}".format(group, repo_name, pull_id)
def get_whois_key(text): """Method that parses a line of text extracting a key value that appears just before a ':'""" is_key = "" if text[-1] == ":": # Check if the last character in text is a ':' # if so, this matches the format of a key value is_key = text[:-1] else: i...
def normalize_bbox(bbox): """Normalizes bounding box: sets minimal coords for first point and maximal for second point. Returns new bounding box. :type bbox: list :param bbox: bounding box :rtype: list :return: new bounding box """ x0, y0, x1, y1 = bbox return [min(x0, x1), min(y0, y1), max(x0, x1),...