content
stringlengths
42
6.51k
def get_biggest_product(adjacent_digits = 13): """Get the biggest product of n adjacent digits in the following number.""" number = "\ 73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 8586156078911294949545950173795833195285320880551...
def get_mean_as_int_from_mean_plus_or_minus_stderr(input_string): """Convert something like '$37,343 ± $250' to 37343 This also works for medians.""" modified_string = input_string.replace("$","") modified_string = modified_string.replace(",","") values = modified_string.split() return in...
def boolean(string): """ This returns True if the string is "True", False if "False", raises an Error otherwise. This is case insensitive. Args: string (str): A string specifying a boolean Returns: bool: Whether the string is True or False. """ if string.lower() == 'true': ...
def parsepagerecord(record): """Split a division record into interesting parts. :record: json object from the API :returns: object containing the interestingparts """ parsed = { 'title': record['title'], 'date': record['date']['_value'], 'id': record['_about'].split('/')[-1...
def _fmt_path(path): """Format the path for final display. Parameters ---------- path : iterable of str The path to the values that are not equal. Returns ------- fmtd : str The formatted path to put into the error message. """ if not path: return '' ret...
def XOR(bools): """Logical Xor. Result is True if there are an odd number of true items and False if there are an even number of true items. """ # Return false if there are an even number of True results. if len([x for x in bools if x is True]) % 2 == 0: return False return Tr...
def is_property_rel(rel_type): # type: (str) -> bool """Test for string indicating a property relationship Arguments: rel_type {str} -- relationship type Returns: bool -- relationship is a property """ return rel_type.endswith('-properties')
def cut_dict(d, length=100): """Removes dictionary entries according to the given length. This method removes a number of entries, if needed, so that a string representation would fit into the given length. The intention of this method is to optimize truncation of string representation for dictiona...
def get_mckey(scriptnum, fdict, fmt): """Figure out what our memcache key should be.""" vals = [] for key in fdict: # Internal app controls should not be used on the memcache key if not key.startswith("_"): vals.append("%s:%s" % (key, fdict[key])) return ( "/plotting/...
def remove_line_comment(line: str) -> str: """Finds and erases Python style line comments, stripping any leading/trailing whitespace.""" split_pos = line.find("#") if split_pos != -1: clean_line = line[:split_pos] else: clean_line = line return clean_line.strip()
def should_include_file_in_search(file_name, extensions, exclude_dirs): """ Whether or not a filename matches a search criteria according to arguments. Args: file_name (str): A file path to check. extensions (list): A list of file extensions file should match. exclude_dirs (list): A lis...
def total_letters(words: list) -> int: """Counts the total number of letters in all words available Args: words (list): the words list Returns: int: the total number of letters in all words """ total = 0 # iterates through all words and counts all the letters for word in w...
def format_date(date: str) -> str: """ Accepts an EBI json date string and formats it for Nextstrain e.g. 20210100 -> 2021-01-XX """ if date is None: return "?" date = str(date) year = date[:4] month = date[4:6].replace("00", "XX") day = date[6:].replace("00", "XX") return f"{yea...
def imageMetadata(dicomImageMetadata): """ Dictionary with all required metadata to construct a BIDS-Incremental, as well as extra metadata extracted from the test DICOM image. """ meta = {'subject': '01', 'task': 'faces', 'suffix': 'bold', 'datatype': 'func', 'session': '01', 'run': 1} ...
def getHash(s, length): """ Return a hash from string s """ import hashlib _hash = hashlib.md5() _hash.update(s) return _hash.hexdigest()[:length]
def sum_of_exponents(numbers, powers): """ Sums each number raised to the power in the same index powers Ex: sum_of_exponents([2, 3, 4], [1, 2, 3]) = 2^1 + 3^2 + 4^3 = 75 """ return sum(pow(number, power) for (number, power) in zip(numbers, powers))
def get_parent_map(pmx, bones): """ Arranges @bones into a dict of the form { @bone: [ancestors in @bones] } """ boneMap = { -1: [], 0: [] } for bone in sorted(bones): p = bone while p not in boneMap: p = pmx.bones[p].parent_idx if p not in [0,-1]: boneMap[bone] = boneMap[p] + [p] else: ...
def get_factors(n: int) -> list: """Returns the factors of a given integer. """ return [i for i in range(1, n+1) if n % i == 0]
def compute_gain_profile(gain_zero, gain_tilting, freq): """ compute_gain_profile evaluates the gain at the frequencies freq. :param gain_zero: the gain at f=0 in dB. Scalar :param gain_tilting: the gain tilt in dB/THz. Scalar :param freq: the baseband frequencies at which the gain profile ...
def package_url(package): """Return fully-qualified URL to package on PyPI (JSON endpoint).""" return u"http://pypi.python.org/pypi/%s/json" % package
def user_identity_check(user, password): """ Check if user is not null and have exact password as the given ones. For now we just store the plain text password, do not need to hash it. :param user: object that have username and password attribute. :type user: models.UserModel :param password: p...
def get_docker_host_mount_location(cluster_name: str) -> str: """Return host path that Docker mounts attach to.""" docker_mount_prefix = "/tmp/cls_tmp_mount/{cluster_name}" return docker_mount_prefix.format(cluster_name=cluster_name)
def canonicalize_header(key): """Returns the canonicalized header name for the header name provided as an argument. The canonicalized header name according to the HTTP RFC is Kebab-Camel-Case. Keyword arguments: key -- the name of the header """ bits = key.split('-') for idx, b in enumerate...
def echo(session, *args): """Prints a message""" msg = ' '.join(args) if args else '' print(msg) return 0
def odd_or_even(number): """returns even if integer is even, odd if integer is odd""" if type(number) is not int: raise TypeError('Argument must be an integer.') if number % 2 == 0: return 'even' else: return 'odd'
def find_distance(x1, y1, x2, y2): """ finds euclidean distance squared between points """ return (x1-x2)**2 + (y1-y2)**2
def apply_mask(mask, binary): """Apply a bitmask to a binary number""" applied = [] for i, j in zip(mask, binary): if i == 'X': applied.append(j) else: applied.append(i) return ''.join(applied)
def get_right_strip(chonk): """ Compute the right vertical strip of a 2D list. """ return [chonk[_i][-1] for _i in range(len(chonk))]
def f_beta(tp, fn, fp, beta): """Direct implementation of https://en.wikipedia.org/wiki/F1_score#Definition""" return (1 + beta ** 2) * tp / ((1 + beta ** 2) * tp + beta ** 2 * fn + fp)
def query_prefix_transform(query_term): """str -> (str, bool) return (query-term, is-prefix) tuple """ is_prefix = query_term.endswith('*') query_term = query_term[:-1] if is_prefix else query_term return (query_term, is_prefix)
def is_unique_n_lg(string: str) -> bool: """ We sort the string and take each neighbour. If they are equal, return False. """ start = 0 sorted_string = sorted(string) while start + 1 < len(sorted_string): if string[start] == string[start + 1]: return False star...
def validate_blockchain(blockchain): """ Validates the blockchain. """ is_valid = True print("Validating the blockchain...") for i in range(len(blockchain)): if i == 0: continue else: print( f" Comparing block[{i}] ({blockchain[i]})", ...
def gtid_set_cardinality(gtid_set): """Determine the cardinality of the specified GTID set. This function counts the number of elements in the specified GTID set. gtid_set[in] target set of GTIDs to determine the cardinality. Returns the number of elements of the specified GTID set. """ co...
def midiname2num(patch, rev_diva_midi_desc): """ converts param dict {param_name: value,...} to librenderman patch [(param no., value),..] """ return [(rev_diva_midi_desc[k], float(v)) for k,v in patch.items()]
def Arn(key): """Get the Arn attribute of the given template resource""" return { 'Fn::GetAtt': [key, 'Arn']}
def simple_decorated_function(simple_arg, simple_kwargs='special string'): """I should see this simple docstring""" # do stuff return 'computed value'
def _mgSeqIdToTaxonId(seqId): """ Extracts a taxonId from sequence id used in the Amphora or Silva mg databases (ends with '|ncbid:taxonId") @param seqId: sequence id used in mg databases @return: taxonId @rtype: int """ return int(seqId.rsplit('|', 1)[1].rsplit(':', 1)[...
def find_sub_list(sub_list, main_list): """Find starting and ending position of a sublist in a longer list. Args: sub_list (list): sublist main_list (list): main longer list Returns: (int, int): start and end index in the list l. Returns None if sublist is not found in the main lis...
def is_valid_notification_config(config): """ Validate the notifications config structure :param notifications: Dictionary with specific structure. :return: True if input is a valid bucket notifications structure. Raise :exc:`ValueError` otherwise. """ valid_events = ( "s3:Objec...
def parse_tag(tag): """ strips namespace declaration from xml tag string Parameters ---------- tag : str Returns ------- formatted tag """ return tag[tag.find("}") + 1 :]
def to_cuda(*args): """ Move tensors to CUDA. """ return [None if x is None else x.cuda() for x in args]
def is_gregorian (year, month, day): """ """ if year > 1582: return True elif year < 1582 : return False elif month > 10 : return True elif month < 10 : return False else : return (day>=15)
def make_amrcolors(nlevels=4): #------------------------------- """ Make lists of colors useful for distinguishing different patches when plotting AMR results. INPUT:: nlevels: maximum number of AMR levels expected. OUTPUT:: (linecolors, bgcolors) linecolors = list of nlevels c...
def max_lookup_value(dict, key): """lookup in dictionary via key""" if not dict: return None value = max(dict.iteritems(), key=lambda d:d[1][key])[1][key] return value
def determine(userChoice, computerChoice): """ This function takes in two arguments userChoice and computerChoice, then determines and returns that who wins. """ if(userChoice == "Rock" and computerChoice == "Paper"): return "computer" elif(userChoice == "Rock" and computerChoice...
def flatTreeDictToList(root): """flatTreeDictToList(root) This function is used to screen motif informations from old MDseqpos html results. Input is a dict of mtree in MDseqpos.html, output is a flat list. """ result = [] if 'node' not in root.keys(): return [] if not root['node']: return result else: ...
def get_fib(position): """input: nonnegative int representing a position on the fibonacci sequence output: fibonacci number corresponding to given position of the sequence returns -1 for negative inputs recursive function """ if position < 0: return -1 if position == 0 or position ==...
def flatten_dict(nested_dict, sep='/'): """Flattens the nested dictionary. For example, if the dictionary is {'outer1': {'inner1': 1, 'inner2': 2}}. This will return {'/outer1/inner1': 1, '/outer1/inner2': 2}. With sep='/' this will match how flax optim.ParamTreeTraversal flattens the keys, to allow for easy...
def getBounds(lvls_arr: list, n_lvl: float): """ A helper function to calculate the BN interpolation @param lvls_arr: The corruption levels list @param n_lvl: The current level to interpolate @return: Returns the post and previous corruption levels """ lower = lvls_arr[0] upper = lvls_ar...
def is_empty(value): """ Checks if a value is an empty string or None. """ if value is None or value == '': return True return False
def register_class(cls, register): """Add a class to register.""" register[cls.__name__] = cls return register
def verbatim(s, delimiter='|'): """Return the string verbatim. :param s: :param delimiter: :type s: str :type delimiter: str :return: :rtype: str """ return r'\verb' + delimiter + s + delimiter
def set_cutoffs_permissiveEnds(edge_index, n_edges, strand): """ Selects 3' and 5' difference cutoffs depending on the edge index and strand. For internal edges, both cutoffs should be set to zero, but more flexibility is allowed on the 3' and 5' ends. Args: edge_index: index we ...
def extraction(fullDic, subkeys): """Extracts a new dictionary that only contains the provided keys""" subDic = {} for subkey in subkeys: subDic[subkey] = fullDic[subkey] return subDic
def get_experiment_prefix(project_key, test_size, priority_queue=False): """ A convenient prefix to identify an experiment instance. :param project_key: Projects under analysis. :param test_size: Size of the test dataset. :return: The prefix. """ return "_".join(project_key) + "_Test_" + str...
def get_sa_terminal_menu(burl, terminal): """ xxx """ ret = '' if terminal is None: l_sa_terminal_tooltip = 'Launch Terminal' l_sa_terminal = '<i class="fas fa-desktop" style="font-size: x-large;"></i>' l_sa_terminal_menu = '<li class="nav-item d-none d-sm-block">'+\ '<a cla...
def convert_path(path): """Convert to the path the server will accept. Args: path (str): Local file path. e.g.: "D:/work/render/19183793/max/d/Work/c05/112132P-embery.jpg" Returns: str: Path to the server. e.g.: "/D/work/render/191837...
def coprime(a, b): """ coprime :param a: :param b: :return: """ for i in range(2, min(a, b) + 1): if a % i == 0 and b % i == 0: return False return True
def iterative_lcs(var1, var2): """ :param var1: variable :param var2: 2nd variable to compare and finding common sequence :return: return length of longest common subsequence examples: >>> iterative_lcs("abcd", "abxbxbc") 3 >>> iterative_lcs([1, 2, 4, 3], [1, 2, 3, 4]) 3 """ ...
def boolean(value): """Parse the string "true" or "false" as a boolean (case insensitive). Also accepts "1" and "0" as True/False (respectively). If the input is from the request JSON body, the type is already a native python boolean, and will be passed through without further parsing.""" if type(va...
def _get_vals_wo_None(iter_of_vals): """ Returns a list of values without Nones. """ return [x for x in iter_of_vals if x is not None]
def str2bool(val): """ Return True for 'True', False otherwise :type val: str :rtype: bool """ return val.lower() == 'true'
def quantile(x, p=0.50): """Returns the pth percentile value in x. Defaults to 50th percentile.""" # Eg x, 0.10 returns 10th percentile value. pindex = int(p * len(x)) return sorted(x)[pindex]
def calculate_precision_recall_f1score(y_pred, y_true, entity_label=None): """ Calculates precision recall and F1-score metrics. Args: y_pred (list(AnnotatedDocument)): The predictions of an NER model in the form of a list of annotated documents. y_true (list(Annotat...
def S_Generation(PIN, lenMask) -> str: """ """ S = bin(PIN)[2:] n = len(S) k = lenMask//n return S*k + S[:lenMask - n*k]
def build_index(l, key): """Build an O(1) index of a list using key, only works if key is unique """ return dict((d[key], dict(d, index=index)) for index, d in enumerate(l))
def cmp_dicts(dict1, dict2): """ Returns True if dict2 has all the keys and matching values as dict1. List values are converted to tuples before comparing. """ result = True for key, v1 in dict1.items(): result, v2 = key in dict2, dict2.get(key) if result: v1...
def quantity_column_split(string): """ Quantity[100.4, "' Centimeters"^3/"Moles'"] to [100.4, " Centimeters"^3/"Moles"] """ values = string.split("[", 1)[1][:-1].split(",") return(values)
def toBin3(v): """Return a string (little-endian) from a numeric value.""" return '%s%s%s' % (chr(v & 255), chr((v >> 8) & 255), chr((v >> 16) & 255))
def q_mult(a, b): """Multiply two quaternion.""" w = a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3] i = a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2] j = a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1] k = a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0] return [w...
def or_(*xs): """Returns the first truthy value among the arguments, or the final argument if all values are falsy. If no arguments are provided, False is returned. """ final = False for x in xs: if x: return x final = x return final
def to_valid_key(name): """ convert name into a valid key name which contain only alphanumeric and underscores """ import re valid_name = re.sub(r'[^\w\s]', '_', name) return valid_name
def get_stream_digest_data(digest): """ Process deployment digest for stream. """ try: # Process deployment information for stream. latitude = None longitude = None depth = None water_depth = None if digest and digest is not None: latitude = digest...
def capValue(value, max=float('inf'), min=float('-inf')): """Clamp a value to a minimun and/or maximun value.""" if value > max: return max elif value < min: return min else: return value
def _set_quality_risk_icon(risk): """ Function to find the index risk level icon for software quality risk. :param float risk: the Software quality risk factor. :return: _index :rtype: int """ _index = 0 if risk == 1.0: _index = 1 elif risk == 1.1: _index = 2 ...
def get_least_sig_bit(band): """Return the least significant bit in color value""" mask = 0x1 last_bit = band & mask return str(last_bit)
def code_point_of_unicode(unicode_entity, sep="-"): """Converts a given unicode entity to code point. :param unicode_entity: The unicode entity to convert. :type unicode_entity: str :param sep: The separator. The result will be the list of all the converted characters joined with this separator. :t...
def _check_prop_requirements(sort_prop_dct, geo, freqs, sp_ene, locs): """ Check that there is the correct data available for the desired conformer sorting method. """ sort_prop = 'electronic' if 'enthalpy' in sort_prop_dct: if sort_prop_dct['enthalpy'] == 0: sort_prop = 'gro...
def score_of(grade): """Computes numeric score given either a percentage of hybric score object WARNING: currently ignore multipliers and lateness""" if grade['kind'] == 'percentage': return grade['ratio'] elif grade['kind'] == 'hybrid': h = sum(_['ratio'] * _.get('weight',1) for _ in gr...
def rgb_to_hex(r: int, g: int, b: int) -> str: """ Fungsi untuk mengubah tipe value warna RGB ke Hex. Alur proses: * Inisialisasi variabel `result` dengan string kosong * Looping `x` untuk ketiga value dari input * Cek apakah nilai x < 0 * Jika benar, maka nilai x = 0 * Jika...
def find_start_time(disc, positions, time, pos): """What button press time step would match this disc in the open position? """ # Assume time is zero for now return positions - ((disc + pos) % positions)
def harvest_oai_datacite3(xml_content): """Factory for Zenodo Record objects from ``oai_datacite3`` XML Parameters ---------- xml_content : str Content from the Zenodo harvesting URL endpoint for ``oai_datacite3``. Returns ------- records : list Zenodo record objects derive...
def f_to_c(f): """ Convert fahrenheit to celcius """ return (f - 32.0) / 1.8
def bookmark_state(keyword): """Validation for ``bookmark-state``.""" return keyword in ('open', 'closed')
def genUsernamePassword(firstname: str, num: int): """ This function will return a username and password for a given user (username and password are considered as the same) :param firstname: User's first name :param num: User number :return: User name for the user """ username = firstname.lo...
def _fileobj_to_fd(fileobj): """Return a file descriptor from a file object. Parameters: fileobj -- file object or file descriptor Returns: corresponding file descriptor Raises: ValueError if the object is invalid """ if isinstance(fileobj, int): fd = fileobj else: ...
def _allocate_expr_id_instance(name, exprmap): """ Allocate a new free instance of a name Args: name: Existing name exprmap: Map of existing expression names Returns: New id not in exprmap """ ndx = 1 name += "@" nname = name + "1" while nname in exprmap: ...
def find_usable_exits(room, stuff): """ Given a room, and the player's stuff, find a list of exits that they can use right now. That means the exits must not be hidden, and if they require a key, the player has it. RETURNS - a list of exits that are visible (not hidden) and don't require a key! ...
def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = 'red' if val < 0 else 'green' return 'color: %s' % color
def filter_DBsplit_option(opt): """We want -a by default, but if we see --no-a[ll], we will not add -a. """ flags = opt.split() if '-x' not in opt: flags.append('-x70') # daligner belches on any read < kmer length return ' '.join(flags)
def gini(labels): """ Calculate the Gini value of the data set :param labels: Category label for the dataset :return gini_value: The Gini value of the data set """ data_count = {} for label in labels: if data_count.__contains__(label): data_count[label] += 1 else...
def _get_comm_key_send_recv(my_rank, my_gpu_idx, peer_rank, peer_gpu_idx): """Return a key given source and destination ranks for p2p tasks. The p2p key is in the following form: [min_rank]_[gpu_index]:[max_rank]_[gpu_index]. Args: my_rank (int): the rank of the source process. ...
def getElectronState(radicalElectrons, spinMultiplicity): """ Return the electron state corresponding to the given number of radical electrons `radicalElectrons` and spin multiplicity `spinMultiplicity`. Raise a :class:`ValueError` if the electron state cannot be determined. """ electronState = ...
def form_presentation(elastic_apartment): """ Fetch link to apartment presentation and add it to the end of project description """ main_text = getattr(elastic_apartment, "project_description", None) link = getattr(elastic_apartment, "url", None) if main_text or link: return "\n".join(f...
def unicode_to_str(data): """ Unicode to string conversion. """ if not isinstance(data, str): return data.encode('utf-8') return data
def invalid_fg_vsby(s, v): """Checks if visibility is inconsistent with FG""" # NWSI 10-813, 1.2.6 if len(s) == 2 or s.startswith('FZ'): if v > 0.6: return True elif s.startswith('MI'): if v < 0.6: return True return False
def valid_csv(filename): """Validates that a file is actually a CSV""" if filename.rsplit('.', 1)[1] == 'csv': return True else: return False
def find_response_end_token(data): """Find token that indicates the response is over.""" for line in data.splitlines(True): if line.startswith(('OK', 'ACK')) and line.endswith('\n'): return True return False
def process_elem_string(string): """Strips ion denotions from names e.g. "O2+" becomes "O".""" elem = "" for i, c in enumerate(string): try: int(c) break except: elem += c return elem
def _ImageFileForChroot(chroot): """Find the image file that should be associated with |chroot|. This function does not check if the image exists; it simply returns the filename that would be used. Args: chroot: Path to the chroot. Returns: Path to an image file that would be associated with chroot...