content
stringlengths
42
6.51k
def _parse_bool(value): """Parse a boolean string "True" or "False". Example:: >>> _parse_bool("True") True >>> _parse_bool("False") False >>> _parse_bool("glorp") Traceback (most recent call last): ValueError: Expected 'True' or 'False' but got 'glorp' ...
def celsius_to_fahrenheit(celsius): """Convert celsius to fahrenheit.""" fahrenheit = 9.0/5.0 * celsius + 32 return fahrenheit
def get_curlyh(beta, alpha, x, xl): """.""" gamma = (1 + alpha*alpha) / beta return beta*xl*xl + 2*alpha*x*xl + gamma*x*x
def handle_err(func, err, fatal, *args, **kwargs): """ Handles functions which may throw errors. """ try: return func(*args, **kwargs) except err as e: if fatal: print(" [-] Fatal error occured: {}".format(e)) exit(1) print(" [-] Error occured: {}".fo...
def is_dna(dna): """ :param dna: str, the strand that user gives(all letters are upper case) :return: bool, is DNA or not """ for base in dna: if base == 'A': pass elif base == 'T': pass elif base == 'G': pass elif base == 'C': ...
def extra_domain_filters(sender, **kwargs): """Return relaydomain filters.""" return ["srvfilter"]
def word_tokenize_mock(sentence): """Mock the function nlth.word_tokenize.""" return sentence.split(" ")
def elementwise_within_bands(true_val, lower_val, upper_val): """Whether ``true_val`` is strictly between ``lower_val`` and ``upper_val``. Parameters ---------- true_val : float True value. lower_val : float Lower bound. upper_val : float Upper bound. Returns --...
def graph6data(str): """Convert graph6 character sequence to 6-bit integers.""" v = [ord(c) - 63 for c in str] if min(v) < 0 or max(v) > 63: return None return v
def fit_text(width, text, center=False): """Fits text to screen size Helper function to fit text within a given width. Used to fix issue with status/title bar text being too long Parameters ---------- width : int width of window in characters text : str input text cente...
def recursive(n: int) -> int: """ Recursive fibonacci. This is a naive approach since it would make computations on every function call. It's not efficient and obtaining fib(50) could hang up the computer. # Base Cases if n == 0: return 0 if n == 1: return 1 """ ...
def remove_whitespace(data): """ Remove whitespace. :param data: string :return: string """ try: data = data\ .replace("\r", "")\ .replace("\t", "")\ .replace("\n", "")\ .replace("\f", "")\ .replace("\v", "")\ .strip...
def _sort_key(item): """ Robust sort key that sorts items with invalid keys last. This is used to make sorting behave the same across Python 2 and 3. """ key = item[0] return not isinstance(key, int), key
def _check_convert_version(tup): """create a PEP 386 pseudo-format conformant string from tuple tup""" ret_val = str(tup[0]) # first is always digit next_sep = "." # separator for next extension, can be "" or "." nr_digits = 0 # nr of adjacent digits in rest, to verify post_dev = False # are we ...
def closed_range(start, stop, step): """Return a `range` that includes the endpoint.""" return range(start, stop + 1, step)
def override_least_significant_bit(integer, bit): """Overrides the last bit of an integer with the given one and returns the result""" # http://stackoverflow.com/questions/6059454/replace-least-significant-bit-with-bitwise-operations integer = (integer & ~1) | bit return integer
def validate_protocol(proto): """ Validating that passed protocol is either http or https """ if "http" not in proto and "https" not in proto: raise ValueError(f"The protocol {proto} is unknown. Can only be either http or https.") return proto
def is_pkg_modular(nvr): """ Returns True if the package is modular, False otherwise. """ return "module+" in nvr
def try_div(x,y, def_value=0): """Divide x/y, and return the default value in case of error (typically if we divide by 0""" try: return x/y except: return def_value
def portfolio_name(fictional: bool) -> str: """returns the proper name (as string) of the portfolio""" return "fictional_crypto_positions.p" if fictional else "actual_crypto_positions.p"
def subvals(x, ivs): """Replace the i-th value of x with v. Args: x: iterable of items. ivs: list of (int, value) pairs. Returns: x modified appropriately. """ x_ = list(x) for i, v in ivs: x_[i] = v return tuple(x_)
def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False """ return len( dna1 ) > len( dna2 )
def number_of_patients(dataset, feature_files, label_files): """ Calculates number of unique patients in the list of given filenames. :param dataset: string. Dataset train/val/test. :param feature_files: list of strings. List of filenames with patient names containing features. :param label_files: ...
def int_from_bytes(bytes_) -> int: """Calculates an integer from provided bytes. """ output = 0 for i in range(0, len(bytes_)): output += bytes_[i] * (2**(8*i)) return output
def _closest_ref_length(references, hyp_len): """ This function finds the reference that is the closest length to the hypothesis. The closest reference length is referred to as *r* variable from the brevity penalty formula in Papineni et. al. (2002) :param references: A list of reference tran...
def _mutagen_fields_to_single_value(metadata): """Replace mutagen metadata field list values in mutagen tags with the first list value.""" return dict((k, v[0]) for k, v in metadata.items() if v)
def not_include(in_list1: list, in_list2: list)->list: """ Return a list of all the element that are not included in the list in_list2 :param in_list1: The source list :param in_list2: The reference list :return: A list which holds the constraint """ if len(in_list1) == 0: return [] ...
def is_same_class(obj, a_class): """ checks an object class and returns if it belongs to Args: obj: object to evaluate a_class: class name Return: booleanType value """ return type(obj) == a_class
def is_same_len_or_none(*args): """ >>> is_same_len_or_none(1, 'aaa') Traceback (most recent call last): ... TypeError: object of type 'int' has no len() >>> is_same_len_or_none([1], ['aaa']) True >>> is_same_len_or_none([1, 'b'], ['aaa', 222]) True >>> is_same_le...
def binary_block_header(byte_count): """returns a binary block header string for a given byte count""" header = '#{:d}{:d}'.format(len(str(byte_count)), byte_count) return header
def join_set(item_list, length): """ Join a set with itself and returns the n-element (length) itemsets Args: -------- item_list: current list of columns length: generate new items of length Returns: -------- return_list: list of items of length-element """ set_len = len(item_list) return_list = [] for i...
def bit_at(b, i): """Returns bit at position i of b (where least_bit is position 0)""" return b & (1 << i)
def centroid(X): """ Calculate the centroid from a vectorset X """ C = sum(X)/len(X) return C
def is_new_tag(image_record: dict, registry: str, repo: str, tag: str): """ Returns false if the provided registry, repo, tag tuple exactly match those fields in one of the image_detail objects in image_record. If no such match is possible, return true. """ # If we are missing an image_details bloc...
def round_up(addr, mem_align): """Keep memory align""" return ((addr + (mem_align - 1)) & (~(mem_align - 1)))
def inverse_time_efficiency(seconds): """ Efficiency strategy for time connected tasks. @param seconds: task duration in seconds @return: Efficiency in interval (0, 1) """ return 1. / (seconds + 1)
def frequencies(words): """ words: list of words Returns a frequency dictionary for input words """ freq_dict = {} for word in words: if word in freq_dict: freq_dict[word] += 1 else: freq_dict[word] = 1 return freq_dict
def generate_label_5_task(c): """Generate label""" if c < 0: return 0 elif (c >= 0 and c < 31): return 1 elif (c >= 31 and c < 91): return 2 elif (c >= 91 and c < 183): return 3 elif (c >= 183 and c < 366): return 4 else: return 5
def main_switch(data): """returns 0 for testing and 1 for operational use.""" main_switch = int(data["main_switch"]) return main_switch
def get_resolutions(ratio): """ Returns recommended resolutions based on current aspect ratio""" ratio = round(ratio, 4) resolutions = {1.7786: ['1366x768'], 1.7778: ['1280x720', '1600x900', '1920x1080', '2560x1440', '3840x2160'], 2.3704: ['1280x720', '1600x900', '1920x...
def decode(string): """Decodes a rle string into normal format""" rle = '' run = 1 loop = False for char in string: if char.isalpha() or char.isspace(): rle += run * char run = 1 loop = False elif char.isdigit(): if loop: ...
def findPrimer(primer, seq): """ Look for a primer sequence. @param primer: A C{str} primer sequence. @param seq: A BioPython C{Bio.Seq} sequence. @return: A C{list} of zero-based offsets into the sequence at which the primer can be found. If no instances are found, return an empty ...
def _added_nodes(steps): """Based on the steps, find node ids that were added.""" added = set() for step in steps: if step['entity_type'] == 'node' and step['action'] == 'add': added.add(step['entity_id']) return list(added)
def compile_truncate_table(qualfied_name): """Delete all data in table and vacuum.""" return 'TRUNCATE %s CASCADE;' % qualfied_name
def convert_to_string(image_path, labels): """convert image_path, lables to string Returns: string """ out_string = '' out_string += image_path for label in labels: for i in label: out_string += ' ' + str(i) out_string += '\n' return out_string
def split_comments(line, comment_char=';'): """ Splits `line` at the first occurence of `comment_char`. Parameters ---------- line: str comment_char: str Returns ------- tuple[str, str] `line` before and after `comment_char`, respectively. If `line` does not contain...
def gravity_points_to_specific_gravity(gravity_points, vol_gal): """Convert gravity points to specific gravity Parameters ---------- gravity_points : float Gravity points. vol_gal : float Wort volume, in gallons. Returns ------- sg : float Specific gravity. ...
def find_matching_close_paren_idx(lst): """Assumes input list starting with '(', finds matching ')' and returns it's index. If not found, returns -1.""" tgtcount = 0 tgtidx = -1 for idx in range(len(lst)): if lst[idx] == ')': tgtcount -= 1 elif lst[idx] == '(': tgtcount += 1 if tgtco...
def npq(fm, fmp): """Calculate NPQ NPQ = (fm - fmp) / fmp :param fm: Fm :param fmp: Fm' :returns: NPQ (float) """ return (fm - fmp) / fmp
def is_subset(dict1, dict2): """Is dict1 subset of dict2.""" for key, value in dict1.items(): if key not in dict2 or value != dict2[key]: return False return True
def unique_formula(*groups,group_labels=[]): """ Docstring for function pyKrev.unique_formula ==================== This function compares n lists of molecular formula and outputs a dictionary containing the unique formula in each list. Use ---- unique_formula(list_1,..,list_n) Returns a ...
def make_signal_header(label, dimension='uV', sample_rate=256, physical_min=-200, physical_max=200, digital_min=-32768, digital_max=32767, transducer='', prefiler=''): """ A convenience function that creates a signal header for a given signal. This can be used ...
def signIn(command): """ Check if command is to Sign In (s | signin). """ return (command.strip().lower() == 's' or command.strip().lower() == 'signin')
def check_inclusion_4(s1: str, s2: str) -> bool: """ optimize method 2 """ len1, len2 = len(s1), len(s2), if len1 > len2: return False diff = [0] * 26 for i in range(len1): diff[ord(s1[i]) - ord('a')] -= 1 diff[ord(s2[i]) - ord('a')] += 1 diff_count = 0 for cn...
def to_bool(data: str) -> bool: """Convert only '1' to True, else False. :param data: Usually part of API response. :type data: str :return: Take a guess. :rtype: bool """ return True if data == "1" else False
def parse_person(person): """ Return name and email from person string. https://guides.cocoapods.org/syntax/podspec.html#authors Author can be in the form: s.author = 'Rohit Potter' or s.author = 'Rohit Potter=>rohit@gmail.com' >>> p = parse_person('Rohit Potter=>rohit@gmai...
def median(a, i, j, k): """ Return median of 3 integers from array a. :param a: Iterable of elements :param i: start element index :param j: end element index :param k: middle element index :return: return median of values at indices i, j and k. """ ai, aj, ak = a[i], a[j], a[k] ...
def obs_dict_to_tensor(obs_dict): """ Convert {None: obs (tensor)} to tensor when original observation space is not Dict or Tuple; else do nothing """ if set(obs_dict.keys()) == {None}: return obs_dict[None] return obs_dict
def quality_to_proba_sanger(quality): """Quality to probability (Sanger)""" return 10**(quality/-10.)
def unescape_specials(s): """ utility method to escape special characters in a string """ return s.replace('%%n', '\n').replace('%%r', '\r').replace('%%t', '\t')
def rotate(vector, angle): """Rotate a vector (x, y) by an angle in radians.""" import math x, y = vector sin, cos = math.sin(angle), math.cos(angle) return ( cos * x - sin * y, sin * x + cos * y, )
def read_file(fpath: str, **kwargs) -> str: """ Read file from file path. Parameters ----------- fpath: str File path. kwargs: optional Other `open` support params. Returns -------- data string of the file. """ with open(fpath, **kwargs) as f: da...
def get_intersection(u, v, node_presence): """ Get the intersection between the presence of u and v. :param u: First Node :param v: Second Node :param node_presence: Node presence :return: Interection """ intersec = [] for ut0, ut1 in zip(node_presence[u][::2], node_presence[u][1::2...
def read_msr_fields(line): """ Function to detect presence of tstat and msr_id fields in a DynaAdjust adj file :param line: Measurement header line :return: True/False switches for presence of tstat and msr_id fields """ t_stat_field = False msr_id_field = False if 'T-stat' in line: ...
def __extract_digits__(string): """ Extracts digits from beginning of string up until first non-diget character Parameters ----------------- string : string Measurement string contain some digits and units Returns ----------------- digits : int ...
def auth_alias_to_official_habitica_name(auth_info_name: str): """ Function that returns habitica official names for the CLI cmd: hopla get_user user-authenticate [alias] """ if auth_info_name in ["e-mail", "mail"]: return "email" return auth_info_name
def check_parity(integer: int) -> int: """Check the bit parity of the input :param integer: :return: -1 for odd numbers of bits, 0 for even number """ parity = 0 while integer: parity = ~parity integer = integer & (integer - 1) return parity
def calRawProfit(initialSharePrice, finalSharePrice, allotment, buyCommission, sellCommission): """Return (Final Share Price - Initial Share Price) * Allotment - Buy Commission - Sell Commission).""" return (finalSharePrice - initialSharePrice) * allotment - buyCommission - sellCommission
def uppercase(string: str) -> str: """ Make the first character of the string uppercase, if the string is non-empty. """ if len(string) == 0: return string else: return string[0].upper() + string[1:]
def hovertext_ip_proto(ip_proto): """ Passed an IP protocol number (decimal, not enumerated) and return it wrapped in extra text to convey context """ return "IP Protocol: " + str(ip_proto) + " (decimal)"
def calculate_score(score: int, threshold: int) -> int: """ Calculates and converts X-Force Exchange score into Demisto score. Args: score (int): the score from X-Force Exchange for certain indicator (1-10). threshold (int): the score threshold configured by the user. Returns: ...
def user_parser(raw, record): """ This is the parser used when a record is parsed because the user specified it. Records that have a built-in parser will not be passed to this method. :param raw: :param record: :return: """ record['description'] = 'User defined event. Double-click to vie...
def cleanup_json(data): """Cleans up the json structure by removing empty "", and empty key value pairs.""" if isinstance(data, str): copy = data.strip() return None if len(copy) == 0 else copy if isinstance(data, dict): copy = {} for key, value in data.items(): ...
def attribute_string(s): """return a python code string for a string variable""" if s is None: return "\"\"" # escape any ' characters #s = s.replace("'", "\\'") return "\"%s\"" % s
def get_initial_states(ctl_str_ids): """ Get list of initial states. ASSUME initial states for ORIFICE/WEIR is 1 (open) and for PUMPS is "OFF" """ initial_states = [] for ctl in ctl_str_ids: ctl_type = ctl.split()[0] if ctl_type == 'ORIFICE' or ctl_type == 'WEIR': ...
def _unify_strand(strand1, strand2): """If strands are equal, return the strand, otherwise return None""" if strand1 != strand2: strand = '.' else: strand = strand1 return strand
def expand_indent(line): """ Return the amount of indentation. Tabs are expanded to the next multiple of 8. >>> expand_indent(' ') 4 >>> expand_indent('\\t') 8 >>> expand_indent(' \\t') 8 >>> expand_indent(' \\t') 8 >>> expand_indent(' \\t') 16 ...
def pairs(array: list) -> int: """ This function returns the count of pairs that have consecutive numbers. """ pairs_from_array = list(zip(array[::2], array[1::2])) count = 0 for i, j in pairs_from_array: if (i - j == 1) or (i - j == -1): count += 1 return count
def roi(image_np, rect): """Returns the cropped ROI, with rect = [l, t, w, h].""" if image_np is None or rect is None or any([r is None for r in rect]): return None l, t, w, h = rect r, b = l+w, t+h img_height, img_width = image_np.shape[0], image_np.shape[1] # Right/bottom bounds are e...
def get_gender_lines_by_scene(gender_to_gender, act_scene_start_end): """ for each scene in play, get the range of lines in female_to_female which belong to that scene. As is in common, the range is defined to be (inclusive, exclusive). For example: if >>> gender_to_gender = [0, 1, 3, 8, 9, 10...
def match_lists(list1, list2): # match list function """to find the number of matching items in each list use sets""" set1 = set(list1) set2 = set(list2) set3 = set1.intersection(set2) # set3 contains all items common to set1 and set2 return set3
def helper(A, k, left, right): """binary search of k in A[left:right], return True if found, False otherwise""" print(f'so far ==> left={left}, right={right}, k={k}, A={A}') #1- base case if left > right: # if empty list there is nothing to search return False #2- solve the subprob...
def fmt_string(value, is_bytes): """Format for bytes string.""" if is_bytes: return value[:-1] + '\xff' if value.endswith('\U0010ffff') else value else: return value
def derivative_pnl(long: list, short: list): # It is assumed that the amount and leverage for both open and close orders are thesame. """ Calculates PnL for a close position :param long: a list containing pairs of open and closed long position orders :param short: a list containing pairs of open and...
def sum_digits(n): """Sum all the digits of n. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 >>> x = sum_digits(123) # make sure that you are using return rather than print >>> x 6 """ total = 0 while n > ...
def getsorteddata(datadict, column): """ get data from dict in column and sort it """ return sorted([item[column] for item in datadict.values()]) # end getsorteddata()
def phasing_to_string(phase_tuple): """ Convert my strange phasing format to a vcf style string """ if phase_tuple==(None,None): return "1/0" elif phase_tuple==(".","."): return "./." else: return str(phase_tuple[0])+"|"+str(phase_tuple[1])
def _get_tfds_task(task): """ A helper function for getting the right task name. Args: task: The huggingface task name. """ if task == "sst-2": return "sst2" elif task == "sts-b": return "stsb" return task
def squared_dist(x1, x2): """Computes squared Euclidean distance between coordinate x1 and coordinate x2""" return sum([(i1 - i2)**2 for i1, i2 in zip(x1, x2)])
def get_available_channels(flist): """ Returns all available channels in the format *type/channel_no* inferred from the first utterance. :param flist: A dictionary with ids as keys and file lists as values :type flist: dict :return: A list of available channels """ if len(flist) == 0: ...
def process_word(word): """ to standardize word to put in list of features :param word: :return: """ # return word.lower() return word
def count_char(tokens, char): """Counts how many times a given character appears in a list of tokens""" return sum(1 for token in tokens if token == char)
def expand_skipgrams_word_list(wlist, qsize, output, sep='~'): """Expands a list of words into a list of skipgrams. It uses `sep` to join words :param wlist: List of words computed by :py:func:`microtc.textmodel.get_word_list`. :type wlist: list :param qsize: (qsize, skip) qsize is the q-gram size and ...
def fake_file(filename, content="mock content"): """ For testing I sometimes want specific file request to return specific content. This is to make creation easier """ return {"filename": filename, "content": content}
def determine_if_name_in_object(name: str, py_object: object) -> bool: """ Determine if a name is in a Python object. :param name: name to search for in py_object :param py_object: Python object """ object_str = str(type(py_object)).lower() if name in object_str: return True els...
def age_start(age, player): """Find when player clicked up to a given age.""" if age in player['ages']: return player['ages'][age]
def MeanAveragePrecision(predictions, retrieval_solution, max_predictions=100): """Computes mean average precision for retrieval prediction. Args: predictions: Dict mapping test image ID to a list of strings corresponding to index image IDs. retrieval_solution: Dict mapping test image ID to list of g...
def safe(string): """Safe string to fit in to the YAML standard (hopefully). Counterpart to :func:`acrylamid.readers.unsafe`.""" if not string: return '""' if len(string) < 2: return string for char in ':%#*?{}[]': if char in string: if '"' in string: ...
def binary2str(b): """ Transfer binary to string :param b: binary content to be transformed to string :return: string """ return b.decode('utf-8')
def get_params(kwargs, valid_params): """ Filter valid_params from kwargs and return as dict """ params = {} for field in valid_params: if field in kwargs: params[field] = kwargs.get(field) return params