content
stringlengths
42
6.51k
def remove_ncrna_if_possible(rna_types, _): """ ncRNA is always consitent with everything else, so ignore it if possible. """ if 'ncRNA' in rna_types and len(rna_types) > 1: rna_types.discard('ncRNA') return rna_types return rna_types
def get_commit_msg(msg=None): """Define a message for the commit. Args: msg (str): user-defined message. If no msg is provided, the user will be given the choice between a default commit message and a user-defined message. """ if msg: return msg else: ...
def _detect_nonce_too_low_parity(message): """source: https://github.com/paritytech/parity/blob/1cd93e4cebeeb7b14e02b4e82bc0d4f73ed713d9/rpc/src/v1/helpers/errors.rs#L314 """ return message.startswith("Transaction nonce is too low")
def escape_assertion(s): """escapes the dots in the assertion, because the expression evaluation doesn't support such variable names.""" s = s.replace("r.", "r_") s = s.replace("p.", "p_") return s
def GenerateTab(depth): """Generate tabs to represent branching to children. Args: depth: int the depth the tree has reached. Returns: string inserted in front of the root unit. """ tab_list = [] if depth > 0: tab_list.append(' ') tab_list.append('| ' * depth) tab_list.append('+--') re...
def _permute(vector, permutation): """Permute vector according to given ordering of indices. Args: vector: 1-D array-like object permutation: any permutation of indices 0...len(vector) Returns: permuted vector Examples: _permute([4, 5, 6], [0, 2, 1]) == [4, 6, 5] """...
def get_number_of_possible_clauses(num_literals): """Gets number of possible clauses for num_literals. We select two literals from num_literals. Each clause has 4 pairs of negativities (True, True), (False, False), (True, False), (False, True). Args: num_literals: Positive integer, the number of literals ...
def read_path(source, path, separator='/'): """Read a value from a dict supporting a deep path as a key. :param source: a dict to read data from :param path: a key or path to a key (path is delimited by `separator`) :keyword separator: the separator used in the path (ex. Could be "." for a json...
def heuristic(current, target): """calculating the estimated distance between the current node and the targeted node -> Manhattan Distance""" result = (abs(target[0] - current[0]) + abs(target[1] - current[1])) # print(result) return result
def fixed_xor(hex1, hex2): """ Calculates hex1 XOR hex2 """ hex1_ = int(hex1, base=16) hex2_ = int(hex2, base=16) xor_ = hex1_ ^ hex2_ return hex(xor_)[2:]
def parse_word_expression(expr): """ Parses a word expression such as "thermoelectric - PbTe + LiFePO4" into positive and negative words :param expr: a string expression, with " +" and " -" strings separating the words in the expression. :return: Returns a tuple of lists (positive, negative) """ ...
def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to rankine and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_rankine(0) 491.67 >>> reaumur_to_rankine(20.0) 536.67 >>> reaumur_to...
def buddy_strings(s, goal): """ :type s: str :type goal: str :rtype: bool """ if len(s) != len(goal): return False unmatch = {} match={} for i in range(0, len(s)): if s[i]!= goal[i]: unmatch[s[i]] = i else: match[s[i]] = 1 if s[i] not in match else match[s[i]] + 1 if l...
def pairs_do_overlap(algns1, algns2, allowed_offset=5): """ Forward read: Reverse read: -----------------------> <------------------------ algns1 algns2 5----------3_5----------3 3----------5_3----------5 algn1_chim5 algn1_ch...
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 translation...
def _match_all(s, keywords): """ True if all strings in keywords are contained in s, False otherwise. Case-insensitive. :param s: string :param keywords: a tuple containing keywords that should all be included :return: True if all strings in keywords are contained in s, False otherwise """ ...
def get_missing_keys(first_list, second_list): """ Finds all keys in the first list that are not present in the second list :param first_list: list of unicode strings :param second_list: list of unicode strings :return: list of unicode strings """ missing = [] for key in first_list: ...
def lorenzian(x, p): """ Generalized lorenzian function. Parameters ---------- x: numpy.ndarray non-zero frequencies p: iterable p[0] = peak centeral frequency p[1] = FWHM of the peak (gamma) p[2] = peak value at x=x0 p[3] = power coefficient [n] R...
def decimate(inobj): """ Convert numbers and numeric strings in native JSON-like objects to Decimal instances. """ from decimal import Decimal from collections.abc import Mapping, MutableSequence if isinstance(inobj, Mapping): outobj = dict(inobj) for k, v in inobj.items(): ...
def substitute_word(text): """ word subsitution to make it consistent """ words = text.split(" ") preprocessed = [] for w in words: substitution = "" if w == "mister": substitution = "mr" elif w == "missus": substitution = "mrs" else: ...
def translate_backend_state_name(state: str): """ Translate state-machine state from backend into actual state name. :param state: new state given from the backend :return: translated state for state_machine """ switcher = { 'installation': 'waitingForOvershoot', 'blinking': 'bli...
def merge_columns(column_specs, kwargs): """ Merge required columns with given columns """ for spec in column_specs: column = column_specs[spec] try: if column not in kwargs: kwargs[column] = column except TypeError: if not any(item in kwar...
def radix_sort(array): """Radix sort data structure function.""" if len(array) <= 1: return array buckets = {'0': [], '1': [], '2': [], '3': [], '4': [], '5': [], '6': [], '7': [], '8': [], '9': []} for i in range(len(str(max(array)))): for x in range(len(array)): if not isin...
def cleanse_helper(d): """Recursively, destructively elide passwords from hierarchy of dict/list's.""" if type(d) is list: for x in d: cleanse_helper(x) elif type(d) is dict: for k, v in d.items(): if "assword" in k: d[k] = '<...ELIDED...>' ...
def __check_epsilon_productions(cnf_variables, cnf_productions, cfg_productions): """ Check whether all reachable epsilon productions from Context Free Grammar are present in Chomsky Normal Form productions. """ cfg_epsilon_productions = set( filter( lambda prod: prod.head in cn...
def shift_list(seq, shift=1): """ https://stackoverflow.com/a/29498813 """ return seq[-shift:] + seq[:-shift]
def parse_result(res): """ Returns total energy/throughput. """ ret = 0.0 for line in filter(lambda s: s != "", res.split("\n")): # parse key,value ln = [x.strip() for x in line.split(":")] if len(ln) > 1: k, v = ln if k == "Performance per MAC energy"...
def _coerce_type(val): """Coerce the supplied ``val`` (typically a string) into an int or float if possible, otherwise as a string. """ try: val = int(val) except ValueError: try: val = float(val) except ValueError: val = str(val) return val
def format_args(args, kwargs): """ makes a nice string representation of all the arguments """ allargs = [] for item in args: allargs.append('%s' % str(item)) for key, item in kwargs.items(): allargs.append('%s=%s' % (key, str(item))) formattedArgs = ', '.join(allargs) ...
def normalize_path(filepath): """Assume .mst extension if missing""" filepath = filepath.strip() if '.' not in filepath: return filepath + ".mst" else: return filepath
def res_contacts(contacts): """ Convert atomic contacts into unique residue contacts. The interaction type is removed as well as any third or fourth atoms that are part of the interaction (e.g. water-bridges). Finally, the order of the residues within an interaction is such that the first is lexicograph...
def EmailAndIdentityBindingToResourceName(email, identity_binding): """Turns an email and identity binding id into a key resource name.""" return 'projects/-/serviceAccounts/{0}/identityBindings/{1}'.format( email, identity_binding)
def _merge(arr, temp, left, mid, right): """ Helper function for calculating inversions.This method is for internal use only. Merges two sorted arrays and calculates the inversion count. """ i = left j = mid k = left inv_count = 0 while i < mid and j <= right: if arr[i] <...
def calc_t_lineseg_lineseg(x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float): """ Caclulate the Bezier parameter for line 1 (x/y 1,2) Deprecated - replaced by calc_t_u_lineseg_lineseg above """ n = (x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4) d = (...
def id_field_creation(invoice_id, batch_number, sequence_number): """ Returns a field for matching between Fiserv and Smartfolio It is defined as a concatenation of the Credit Card number and the invoice ID :return: str """ ## Old ID included sequence number but this was changing over time...
def lines_that_start_with(string, fp): """Helper function to lines in a FORC data file that start with a given string Inputs: string: string to compare lines to fp: file identifier Outputs: line: string corresponding to data line that meets the above conditions """ return ...
def jib(foot, height): """ jib(foot,height) -> area of given jib sail. >>> jib(12,40) 240.0 """ return (foot*height)/2
def compact(text, **kw): """ Compact whitespace in a string and format any keyword arguments into the string. :param text: The text to compact (a string). :param kw: Any keyword arguments to apply using :func:`str.format()`. :returns: The compacted, formatted string. The whitespace compaction ...
def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i
def get_data_metdata_from_revision_record(revision_record): """ Retrieves the data block from revision Revision Record Parameters: topic_arn (string): The topic you want to publish to. message (string): The message you want to send. """ revision_data = None revision_metadata = No...
def check_if_gz(file_name): """Return a boolean Check if filename ends with gz extension """ return file_name.endswith('.gz')
def generate_db_url(user, password, host, db_name, protocol = "mysql+pymysql"): """ Utility function for generating database URL This function generates a database URL with the mysql and pymysql protocol for use with pandas.read_sql() Parameters ---------- user : str The username for the...
def _check_boolean(input, name): """Exception raising if input is not a boolean Checks whether input is not ``None`` and if not checks that the input is a boolean. Parameters ---------- input: any The input parameter to be checked name: str The name of the variable for prin...
def mapped_to_chromosome(chrom): """ Returns true if mapped to, eg, chr1 or X; false if mapped to other contig, eg GL*, MT*, hs*, M* """ if chrom[0:2] in ["GL", "MT", "hs"] or chrom[0:1] == "M": return False return True
def convert_green2conv_processed(py, nproc, cmts_directory, green_directory, conv_directory, waveform_length, taper_tmin_tmaxs, periods, sampling_rate): """ conv and process the green function. """ script = f"ibrun -n {nproc} {py} -m seisflow.scripts.source_inversion.mpi_convert_green2sync --cmts_direct...
def encodeXMLName(name): """ Encodes an XML (namespace, localname) pair into an ASCII string. If namespace is None, returns localname encoded as UTF-8. Otherwise, returns {namespace}localname encoded as UTF-8. """ namespace, name = name if namespace is None: return name.encode("utf-8") r...
def binom(n, k): """ Returns binomial coefficient (n choose k). """ # http://blog.plover.com/math/choose.html if k > n: return 0 if k == 0: return 1 result = 1 for denom in range(1, k + 1): result *= n result /= denom n -= 1 return result
def filter_by_date(data, date_field, compare_date): """ Date field and compare date should be unix timestamps with mills """ return [record for record in data if record[date_field] >= compare_date]
def settings_name(value): """Makes a capitalized name from an option flag.""" return value.lstrip('-').replace('-', '_').upper()
def carry_around_add(a, b): """ Helper function for checksum calculation. :param a: operand :param b: operand :return addition result """ c = a + b return (c & 0xffff) + (c >> 16)
def get_button_id_from_name(button_name): """ Convert a button name to the its id """ parts = button_name.lower().split(' - ') task = parts[0] suffix = '' if len(parts) > 1: resource_type = parts[1] suffix = '-' + parts[1][0] return task + '-btn' + suffix
def active(request, pattern): """ Returns 'active' if the give pattern is in the current URL. """ try: if (request.path == '/' == pattern) or (pattern != '/' and request.path.startswith(pattern)): return 'active' except: # pragma: no cover pass return ''
def merge_result(res): """ Merges all items in `res` into a list. This command is used when sending a command to multiple nodes and they result from each node should be merged into a single list. """ if not isinstance(res, dict): raise ValueError("Value should be of dict type") re...
def ComputeDistanceMatrix(n): """ Compute the ground distance with power p of an n*n image """ C = {} for i in range(n): for j in range(n): C[i,j] = {} for v in range(n): for w in range(n): C[i,j][v,w] = abs(i - v) + abs(j - w) ret...
def get_chunk_ranges(ds_dim, chunk_size): """ Create list of chunk slices [(s_i, e_i), ...] Parameters ---------- ds_len : int Length of dataset axis to chunk chunk_size : int Size of chunks Returns ------- chunks : list List of chunk start and end positions...
def index_from_address(level, address): """Computes TLR Index from Address vector. Returns the TLR index of a point with certain address vector in a graph of SG at some fixed level. For point F_{w1} F_{w2} ... F_{wm} q_{k} (0<=wi<=2, 0<=k<=2), we can represent it in two ways: 1. ...
def ymd2jd(year, month, day): """ Converts a year, month, and day to a Julian Date. This function uses an algorithm from the book "Practical Astronomy with your Calculator" by Peter Duffet-Smith (Page 7) Parameters ---------- year : int A Gregorian year month : int A Gre...
def product_level(item): """Check for S2 product type. This information will change the relative path to images. Parameters: item (str): full path to S2 products location Return: exit status (bool) Raise ValueError for Unrecognized product types """ if "MSIL2A" in item: return ...
def compact(lst): """Return a copy of lst with non-true elements removed. >>> compact([0, 1, 2, '', [], False, (), None, 'All done']) [1, 2, 'All done'] """ return_list = [] for item in lst: if item: return_list.append(item) return return_list
def get_catalog_record_access_type(cr): """Get the type of access_type of a catalog record. Args: cr (dict): A catalog record as dict. Returns: str: Returns the Access type of the dataset. If not found then ''. """ return cr.get('research_dataset', {}).get('access_rights', {}).get...
def set_to_list(obj): """ Helper function to convert a set to a list. """ if isinstance(obj, set): return list(obj) raise TypeError
def endofanswer(answer): """Return True if answer is complete in terms of GCS. @param answer : Answer to check as string. @return : True if last character is "\n" with no preceeding space. """ return ' ' != answer[-2:-1] and '\n' == answer[-1:]
def get_key_in_nested_dict(nested_dict, target_key): """ Traverses the passed dict to find and return the value of target_key in the dict. :param nested_dict: dictionary to search in :param target_key: key you are looking for :return: values of key """ for key in nested_dict: if key ...
def filter_options_on_prefix(options, prefix, delimiter='-'): """ splits an options dict based on key prefixes >>> filter_options_on_prefix({'foo-bar-1': 'ok'}, 'foo') {'bar-1': 'ok'} >>> """ return dict((key.split(delimiter, 1)[1], value) for key, value in options.items() ...
def build_simc_file(talent_string, covenant_string, profile_name): """Returns output file name based on talent and covenant strings""" if covenant_string: if talent_string: return f"profiles/{talent_string}/{covenant_string}/{profile_name}.simc" return f"profiles/{covenant_string}/{p...
def vector_to_action(vector): """ vector: tuple return action (int) """ #LEFT if vector ==(-1, 0): return 0 #RIGHT if vector ==( 1, 0): return 1 #UP if vector ==( 0, 1) : return 2 #DOWN if vector ==( 0, -1) : return 3 return None
def JoinDisjointDicts(dict_a, dict_b): """Joins dictionaries with no conflicting keys. Enforces the constraint that the two key sets must be disjoint, and then merges the two dictionaries in a new dictionary that is returned to the caller. @type dict_a: dict @param dict_a: the first dictionary @type dic...
def Truncate(text, length): """ Returns text truncated to length, with "..." appended if truncation was necessary. """ if len(text) > length: return text[:length] + '...' else: return text[:length]
def components_to_hosts(components): """Convert a list of Component namedtuples to a list of their hosts :param components: a list of Component namedtuples :returns: list of the hosts associated with each Component """ hosts = [] for component in components: hosts.append(component.host) ...
def isiter(val): """Return True is val is iterable.""" try: iter(val) except TypeError: return False else: return True
def filter_date(date): """Return x-axis labels based on dates list.""" if date[-2:] != "01": return "" return date[:7]
def return_common_items(xs, ys): """ merge sorted lists xs and ys. Return only those items that are present in both lists. """ result = [] xi = 0 while True: if xi >= len(xs): # If xs list is finished, return result # We're done. if xs[xi] in ys: ...
def is_bias_before_norm(norm_type='instance'): """When using BatchNorm, the preceding Conv layer does not use bias, but it does if using InstanceNorm. """ if norm_type == 'instance': return True elif norm_type == 'batch': return False else: raise NotImplementedError(f"Nor...
def delist(list_obj): """ Returns a copy of `list_obj` with all empty lists and tuples removed. Parameters ---------- list_obj : list A list object that requires its empty list/tuple elements to be removed. Returns ------- delisted_copy : list Copy of `list_obj`...
def text2railfence(text, key = 3): """ Returns the encrypted text after encrypting the text with the given key Parameters: text (str): The text that needs to be encrypted in the Railfence cipher key (int): The Key that should be used to encrypt the text Returns: encrypted (str): The encrypted text "...
def get_name(s_file): """Return sample name from file path.""" return s_file.split('/')[-1].replace('.gz', '').replace('.bed', "").replace('.xl', "")
def hello(name): """Generate a friendly greeting. Greeting is an important part of culture. This function takes a name and generates a friendly greeting for it. Parameters ---------- name : str A name. Returns ------- str A greeting. """ return 'Hello {na...
def allnamesequal(name: list) -> bool: """ Verify all names are equal. Parameters ---------- name : list of strings all the names Returns ------- all : bool True if all the names are equal, False otherwise """ return all(n == name[0] for n in name[1:])
def backpointer_cell_to_string(cell): """Makes a string of a cell of a backpointer chart""" s="[" for (k,rhs) in cell: s+="(%i, %s)"%(k,",".join(rhs)) s+="]" return s
def _parse_float(s): """Parse a floating point with implicit dot and exponential notation. >>> _parse_float(' 12345-3') 0.00012345 >>> _parse_float('+12345-3') 0.00012345 >>> _parse_float('-12345-3') -0.00012345 """ return float(s[0] + '.' + s[1:6] + 'e' + s[6:8])
def GetCommandOutput(data): """ remove the first and last line,return the raw output data: str return data_output *** Notice *** This function works in low efficiency, it should be replace in the future. """ str_linesep='\r\n' data_list=str(data).split(str_linesep) if l...
def is_store_song_id(item_id): """Validate if ID is in the format of a Google Music store song ID.""" return len(item_id) == 27 and item_id.startswith('T')
def find_class_match(name, sub_vals): """ find the Define-XML CT term based on the class name for the dataset :param name: string; name of the class associated with a dataset in the Library :param sub_vals: dictionary of Define-XML class terms (submission values) to look-up by name :return: string; ...
def create_mapping(dico): """ Create a mapping (item to ID / ID to item) from a dictionary. Items are ordered by decreasing frequency. """ sorted_items = sorted(dico.items(), key=lambda x: (-x[1], x[0])) id_to_item = {i: v[0] for i, v in enumerate(sorted_items)} item_to_id = {v: k for k, v i...
def _find_AP_and_RL_diameter(major_axis, minor_axis, orientation, dim): """ This script checks the orientation of the and assigns the major/minor axis to the appropriate dimension, right- left (RL) or antero-posterior (AP). It also multiplies by the pixel size in mm. :param major_axis: major ellipse axi...
def n_th_order_difference(array, order): #Calculate nth order difference of given input """ :param array: :param order: :return: """ length_of_input = len(array) # Check whether given order can be calculated or not if order >= length_of_input: # Right hand side is 'm', thus order can be 'm-...
def get_interval_unit(interval: int) -> str: """Get interval unit. :param interval: :return: """ return "seconds" if interval > 1 else "seconds"
def dict_union(a, b): """ Return the union of two dictionaries without editing either. If a key exists in both dictionaries, the second value is used. """ if not a: return b if b else {} if not b: return a ret = a.copy() ret.update(b) return ret
def get_file_type(path): """ Get file type for path. """ if path.endswith('.jp2'): return 'jp2' if path.endswith('.tif'): return 'tiff' if '/alto/' in path: if path.endswith('.xml'): return 'alto' return None if '/casemets/' in path: if path.endswi...
def hit_list(hits, sink_ips, sink_port): """ Convert a list of hit indices or ranges into a list of [ip, port]. :param hits: list of sink indices or pairs [range_start, range_end] of ranges of indices. :param sink_ips: list of sink ips. :param sink_port: port used by the sinks. :return list ...
def _next_k_combination(x): """ Find the next k-combination, as described by an integer in binary representation with the k set bits, by "Gosper's hack". Copy-paste from en.wikipedia.org/wiki/Combinatorial_number_system Parameters ---------- x : int Integer with k set bits. Re...
def replace_segment(seq, start, end, replacement): """Return the sequence with ``seq[start:end]`` replaced by ``replacement``.""" return seq[:start] + replacement + seq[end:]
def guitarset_instrument_to_program(instrument: str) -> int: """GuitarSet is all guitar, return the first MIDI guitar program.""" if instrument == 'Clean Guitar': return 24 else: raise ValueError('Unknown GuitarSet instrument: %s' % instrument)
def GCDBest(a, b): """ Runtime: O(log(a*b)) """ if not b: return a _a = a % b return GCDBest(b, _a)
def clean_font_name(font_name): """Given a font name from PDFMiner's XML, return the font name with the "AAAAAA+" prefix removed (if present). """ # For some reason font names have "AAAAAA+" or similar prepended, e.g. AAAAAA+Arial-BoldMT. # I've googled around but can't figure out the significance o...
def _human_bytes(size): """Return the given bytes as a human friendly KB, MB, GB, or TB string""" power = 2**10 n = 0 power_of_n = {0: 'B', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'} while size > power: size /= power n += 1 value = "{:.2f} {}".format(size, power_of_n[n]) return val...
def reformat_element_symbol(element_string): """ Reformat the string so the first letter is uppercase and all subsequent letters lowercase. Parameters ---------- element_string : str Inputted element symbol Returns ------- str Returned reformatted element symbol ...
def memory_one_estimate(data_dict): """Estimates the memory one strategy probabilities from the observed data.""" estimates = dict() for context in data_dict.keys(): C_count = data_dict[context][0] D_count = data_dict[context][1] try: estimates[context] = float(C_coun...
def lower_bound(arr, value): """ find the index of the first element in arr >= value. """ low = 0 high = len(arr) - 1 found = len(arr) while(low <= high): mid = (low + high) // 2 if arr[mid] < value: low = mid + 1 else: found = mid ...
def dashed(word): """ This function will turn the character of random word into dash :param word: str, random word given by the program that have to be guessed by the user :return: ans(called as old_ans in the program), str, dashed word """ ans = '' for ch in word: if ch.isalpha(): ...