content
stringlengths
42
6.51k
def graph2groups(G): """Returns lists of each element in each connected component in G as dictionary. DFS recursive algorithm. Adapted from: stackoverflow.com/questions/21078445/find-connected-components-in-a-graph """ def dfs(node1): nonlocal visited nonlocal groups no...
def translate_tokens(tokens, d): """ Produce set of translated tokens, returns number of tokens that were translated. All possible translations of a token are added. """ n_translated = 0 translated = set() for w in tokens: if w not in d: continue translated.update(d[w]) ...
def key(i): """ Helper method to generate a meaningful key. """ return 'key{}'.format(i)
def ref(obj): """Extracts $ref of object.""" try: return obj['$ref'] except (KeyError, TypeError): return None
def find_direct_containing(rules, param): """ return list of all rules that directly contain param """ return_list = [] for rule in rules: if param in rules[rule]: return_list.append(rule) return return_list
def valid_coloring(G): """Returns True if G's coloring is valid Parameters: G: a networkx graph with Graph Nodes Return: valid: True if valid coloring (boolean) """ valid = False if G is not None: valid = True for node in G.nodes(): for neighbor in G....
def any_endswith(items, suffix): """Return True if any item in list ends with the given suffix """ return any([item.endswith(suffix) for item in items])
def get_search(names, verb = 'show'): """ Returns an NLP search query to retrieve neurons given a list of neurons. # Arguments names (list): List of neurons to retrieve. verb (str): Verb to use. Defaults to 'show'. Can be 'show', 'add', 'keep' or 'remove'. # Returns str: NLP query s...
def get_file_path(vhost_path): """Get file path from augeas_vhost_path. Takes in Augeas path and returns the file name :param str vhost_path: Augeas virtual host path :returns: filename of vhost :rtype: str """ # Strip off /files avail_fp = vhost_path[6:] # This can be optimized....
def strip_some_punct(s): """ Return a string stripped from some leading and trailing punctuations. """ if s: s = s.strip(''','"}{-_:;&@!''') s = s.lstrip('.>)]\\/') s = s.rstrip('<([\\/') return s
def b(s, name=""): """Return wapitified bigram output features""" return "b:%s=%s" % (name, s)
def conv(value, fromLow=0, fromHigh=0, toLow=0, toHigh=0, func=None): """Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc. Does not constrain values to within the range, because out-of-range...
def is_bool(value): """Return True if `value` is a boolean.""" return bool(value) == value
def place_genes(genes, limit=0): """ Handle the collision between genes by placing overlapping genes on different levels :param genes: Sorted list of genes (gene: [start, end, strand, name]) :return: List of lists (of genes) """ levels = [[]] # For each gene within the same region ...
def _make_message(message_provided, message_otherwise): """If message was provided, use it; otherwise, use the alternative one. Args: message_provided: message to use if provided message_otherwise: message to use if the first one was not provided Returns: First message that evaluat...
def parse_slots(content): """Parse the list of slots. Cleans up spaces between items. Parameters ---------- content: :class:`str` A string containing comma separated values. Returns ------- :class:`str`: The slots string. """ slots = content.split(",") retu...
def ctd_sbe52mp_tempwat(t0): """ Description: OOI Level 1 Water Temperature data product, which is calculated using data from the Sea-Bird Electronics conductivity, temperature and depth (CTD) family of instruments. This data product is derived from SBE 52MP instruments and app...
def decode_url(raw): """ Decode a URL into a unicode string. Expected to be UTF-8. :param raw: Raw URL string. :type raw: string (non-unicode) :returns: Decode URL. :rtype: unicode string """ return raw.decode('utf-8')
def discrete_ternary_search(func, lo, hi): """ Find the first maximum of unimodal function func() within [lo, hi] """ while lo <= hi: lo_third = lo + (hi - lo) // 3 hi_third = lo + (hi - lo) // 3 + (1 if 0 < hi - lo < 3 else (hi - lo) // 3) if func(lo_third) < func(hi_third): ...
def last_n_average_threshold(threshold, n, utilization): """ The averaging CPU utilization threshold algorithm. :param threshold: The threshold on the CPU utilization. :type threshold: float,>=0 :param n: The number of last CPU utilization values to average. :type n: int,>0 :param utilizati...
def startChart(path, chartPath, arguments): """Starts a new instance of a chart. The chart must be set to "Callable" execution mode. Args: path (str): The path to the chart, for example: "ChartFolder/ChartName". chartPath (str): The path to the chart, for example "C...
def _incs_list_to_string(incs): """ Convert incs list to string ['thirdparty', 'include'] -> -I thirdparty -I include """ return ' '.join(['-I ' + path for path in incs])
def notes_view(notes, list_name): """ View for notes :param notes: :param list_name: :return: """ if notes: view = "*Your notes of {}*:\n\n{}" modified_notes = ["*{}.* {}".format(index + 1, value) for index, value in enumerate(notes)] return view.format(list_name, "\n...
def to_bool(val): """ Convert "boolean" strings (e.g., from env. vars.) to real booleans. Values mapping to :code:`True`: - :code:`True` - :code:`"true"` / :code:`"t"` - :code:`"yes"` / :code:`"y"` - :code:`"on"` - :code:`"1"` - :code:`1` Values mapping to :code:`False`: ...
def ternary_search(left, right, key, arr): """ Find the given value (key) in an array sorted in ascending order. Returns the index of the value if found, and -1 otherwise. If the index is not in the range left..right (ie. left <= index < right) returns -1. """ while right >= left: mid1 ...
def problem_1_1(s: str, use_dict: bool = False, use_deque: bool = False) -> bool: """ Q: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? A: If I were to implement a solution efficiently I would utilize a dict to structure my ...
def insertInOrder(personDic,sortedList): """Used in calculateDebts(). Explanation there""" returnList = sortedList for i in range(len(sortedList)): if (personDic['credit'] >= returnList[i][0]): returnList.insert(i,(personDic['credit'],personDic)) return returnList #In gen...
def _ToPretty(text, indent, linelength): """Makes huge text lines pretty, or at least printable.""" tl = linelength - indent output = '' for i in range(0, len(text), tl): if output: output += '\n' output += ' ' * indent + text[i:i+tl] return output
def is_sentence(value): """ Determine if the given string is a sentence. """ if len(value) > 0 and value[0] == "S": return True else: return False
def __parse_version_from_service_name(service_name): """ Parse the actual service name and version from a service name in the "services" list of a scenario. Scenario services may include their specific version. If no version is specified, 'latest' is the default. :param service_name: The name of the ser...
def human_to_zero(value): """ Many of our parsers use 1-based indices as arguments, and convert to 0-based indices for internal usage (eg, "column 1 = index 0 in this list of fields") """ if value is None: return value else: return value - 1
def get_fetch_content_endpoint(domain, entity_type, guid): """Get remote fetch content endpoint. See: https://diaspora.github.io/diaspora_federation/federation/fetching.html """ return "https://%s/fetch/%s/%s" % (domain, entity_type, guid)
def convex_hull(points): """Computes the convex hull of a set of 2D points. Input: an iterable sequence of (x, y) pairs representing the points. Output: a list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically smallest coordinates. Imple...
def unpack_wsd_training_instance(context): """ context is a list of tokens from semcor or the WSD evaluation datasets. each token is a dict with keys 'token', 'senses', etc. Some of the tokens are multi-word expressions. Returns: tokenized_text: a list of tokenized text where multi-word exp...
def is_config_exist(cmp_cfg, test_cfg): """is configuration exist?""" if not cmp_cfg or not test_cfg: return False return bool(test_cfg in cmp_cfg)
def Qcopy(q): """ Qcopy """ return (q[0], q[1], q[2], q[3])
def rws(t): """Remove white spaces, tabs, and new lines from a string""" for c in ['\t', '\n', ' ']: t = t.replace(c,'') return t
def location_to_string(locationID): """ helper to calculate port and bus number from locationID """ loc = ['{}-'.format(locationID >> 24)] while locationID & 0xf00000: if len(loc) > 1: loc.append('.') loc.append('{}'.format((locationID >> 20) & 0xf)) locationID <<...
def bool_str(v): """Convert a boolean to a string.""" return "Yes" if v else "No"
def diff_sets(desired, current): """ Diff two state dictionaries by key :param desired: the desired state :param current: the current state :type desired: dict :type current: dict :return: returns a tuple that contains lists of added, removed and \ changed elements from the desired ...
def euler(y, f, t, h): """Euler integrator. Returns new y at t+h. """ return y + h * f(t, y)
def pointsInRect(array, rect): """Determine which points are inside a bounding rectangle. Args: array: A sequence of 2D tuples. rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. Returns: A list containing the points inside the rectangle. ...
def add(old, new): """Adds the new value to the old value Args: old: old value to extend new: new value Returns: extended old value """ if old is None: return new if new is None: return old return old + new
def req2(s): """ Passwords may not contain the letters i, o, or l, as these letters can be mistaken for other characters and are therefore confusing. """ return "i" not in s and "o" not in s and "l" not in s
def find_all(searchin, substr): """returns a list of locations where substr occurs in searchin locations are not allowed to overlap""" location = 0 locations = [] while location != -1: location = searchin.find(substr, location) if location != -1: locations.append(location...
def public_key(g, a, p): """g is the base, a is the private key, p is the modulus""" return pow(g, a, p)
def build_style_name(width='', weight='', custom='', is_italic=False): """Build style name from width, weight, and custom style strings and whether the style is italic. """ return ' '.join( s for s in (custom, width, weight, 'Italic' if is_italic else '') if s ) or 'Regular'
def get_full_text(t): """Handle RTs and extended tweets to always display all the available text""" if t.get('retweeted_status'): rt_status = t['retweeted_status'] if rt_status.get('extended_tweet'): elem = rt_status['extended_tweet'] else: elem = rt_status ...
def _make_state_key(game_id: str) -> str: """Make the redis key for the game state.""" return 'ttt:{}.state'.format(game_id)
def find_lcm(num_1, num_2): """Find the LCM of two numbers.""" max_num = num_1 if num_1 > num_2 else num_2 lcm = max_num while True: if ((lcm % num_1 == 0) and (lcm % num_2 == 0)): break lcm += max_num return lcm
def expanded_form(num): """ Expands an integer into ones, tens, hundreds, etc... :param num: an integer value. :return: a string of the integer in expanded form. """ result = [] divider = 10 while divider < num: temp = num % divider if temp != 0: result.insert...
def format_commas(number: int): """ Takes int, adds commas between 1000s. eg. converts 10000 to 10,000 """ return "{:,}".format(number)
def get_protein_short(prot): """Get short protein identifier to work with xiFDR.""" return (";".join([i.split("|")[0] for i in prot.replace("sp|", "").split(";")]))
def correlate_objects(objects, attr): """Correlate several objects under one dict. If you have several objects each with a 'name' attribute, this puts them in a dict keyed by name. :: >>> class Flintstone(DumbObject): ... pass ... >>> fred = Flintstone(name="Fred", ...
def build_lineage(taxid_list, mapping): """Given a list of taxIDs, generate a NCBI LineageEx-like list.""" temp_list = [] for taxid in taxid_list: temp_dict = {} if taxid == "": pass else: temp_dict["TaxId"] = taxid if taxid in mapping.keys(): ...
def sim_to_rgba(similarity, edge_color): """Convert similarity to RGBA. Parameters ---------- similarity : float Similarity between two answers. edge_color : tuple When the graph is plotted, this is the RGB color of the edge i.e (0, 0, 1). Returns ------- tuple ...
def micro_amount_to_num(micro_amount): """ Converts micro-amount into its number. Args: micro_amount (int) Returns: a float: micro_amount divided by 1M """ return float(micro_amount) / (10 ** 6)
def percent_initiated_interactions(records, user): """ The percentage of calls initiated by the user. """ if len(records) == 0: return 0 initiated = sum(1 for r in records if r.direction == 'out') return initiated / len(records)
def get_dimension(cone): """ `cone` holds the dimensions of the individual cones. Calculate and return the sum of all the cone dimensions. For PSD-cones consider the vector-length of the upper-triangle. """ dim = 0 for k in cone: if k == "f" or k == "l": dim += cone[k] ...
def get_index(values, target_value): """Returns the index of a value in a list, or -1 if not found. >>> get_index([5, 6, 7], 8) -1 >>> get_index([5, 6, 7], 7) 2 >>> get_index([5, 6, 7], 6) 1 >>> get_index([5, 6, 7], 5) 0 """ found_index = -1 index = 0 for element in values: if element ==...
def reverse_lex(ustring): """ Strings must be in unicode to reverse the string strings are returned in unicode and may not able able to be converted to a regular string Args: ustring: String to reverse """ newstr = "" for ii in ustring: ordinance = ord(ii) new_byte = 255 - ordinance ...
def get_max_parsimony_n_alleles(n, ploidy): """Get the expected number of true alleles in the connected component given that n alleles have been observed. The returned value can be seen as the parsimonious solution: if ploidy is higher than the number of observed alleles, there must be at least as many...
def transform_int_to(value: int, base: int): """ transform int :param value: int like 999 :param base: int like 90 :return: string like "b9" """ if base < 2 or base > 90: return None base_str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$%^&*()-_=+|;:,<.>/?...
def bbox_equals(src_bbox, dst_bbox, x_delta=None, y_delta=None): """ Compares two bbox and checks if they are equal, or nearly equal. :param x_delta: how precise the comparison should be. should be reasonable small, like a tenth of a pixel. defaults to 1/1.000.000th ...
def cartes(seq0, seq1, modus='pair'): """ Return the Cartesian product of two sequences >>> from sympy.utilities.iterables import cartes >>> cartes([1,2], [3,4]) [[1, 3], [1, 4], [2, 3], [2, 4]] """ if modus == 'pair': return [[item0, item1] for item0 in seq0 for item1 in seq1] ...
def egcd(a, b): """ This function performs an extended GCD according to euclid's algorithm. It finds a pair (s, t) such that a*s + b*t == gcd """ s0, s1, t0, t1 = 1, 0, 0, 1 while b > 0: q, r = divmod(a, b) a, b = b, r s0, s1, t0, t1 = s1, s0 - q * s1, t1, t0 - q...
def ntp2ts(ntp: int, rate: int) -> int: """Comvert NTP time into timestamp.""" return int((ntp >> 16) * rate) >> 16
def pick_datatype(counts): """ If the underlying records are ONLY of type `integer`, `number`, or `date-time`, then return that datatype. If the underlying records are of type `integer` and `number` only, return `number`. Otherwise return `string`. """ to_return = 'string' if coun...
def get_boundary_locations(size, sector_size, stride): """Get a list of 1D sector boundary positions. Args: size: length of the full domain. sector_size: length of the sector. stride: how far each sector moves to the right Returns: boundaries: a list of 1D sector boundary pos...
def sed_replacement_escape(path): """ Escape the '/' so "sed s///" can use it for replacement """ return path.replace("/", r"\/")
def is_potentially_prime(a: int, n: int) -> bool: """ is_potentially_prime is used to compute whether or not a number is prime. This function is correct about 50% of the time. Called multiple times with a different a value, this method can nearly assure that a number is prime. Args: a (int)...
def corrSteeringAngle(centerMeasurement, corrFac): """ corrects the steering angel for the left and right image by adding(left img)/substracting(right img) 'corrFac' to the measurement """ leftMeasurement = [x+corrFac for x in centerMeasurement] rightMeasurement = [x-corrFac for x in centerMeasureme...
def layer_name_to_dict(min_zoom: int, max_zoom: int, name: str) -> dict: """Convert layer name to dict for conversion.""" return dict( directory=name + "/{z}/{y}/{x}.png", name=name, min_zoom=min_zoom, max_zoom=max_zoom + 5, max_native_zoom=max_zoom, )
def diff_lists(lists): """Diff the last list with the other lists and return a list of elements that are in the last list but not in the any of the previous lists. Arguments: lists -- The last list (-1) in this list of lists will be diffed with the other lists. Returns: A list of elements that...
def dict_to_sorted_pairs(d): #=============================================================================== """ Convert a dictionary to a list of key/value pairs sorted by key. """ keys = list(d.keys()) keys.sort() results = [] for key in keys: results.append((key, d[key])) ret...
def pandigital_string(first: int = 0, last: int = 9) -> str: """Forms a string containing all of the digits in a range. Args: first: A digit from 0 to 9 representing the start of the range. Must be less than or equal to ``last``. last: A digit from 0 to 9 representing the end of the...
def extract_fields(data, fields_names): """ Return requested data fields using data generated by cve-search' api. Takes as input data, fields requested """ return [{name: item.get(name) for name in fields_names} for item in data]
def get_failed_unittests_from(unittests_output, set_of_tests): """Parse unittests output trying to find the failed tests""" failed_tests = set() for test in set_of_tests: if test in unittests_output: failed_tests.add(test) return failed_tests
def isExecError(executionReport, checkContinue=True): """Returns whether an execution returned an error according to its exit code. checkContinue means that we also return False if the continueOnError flag is True.""" return (executionReport['exitCode'] != 0 and not (checkContinue and execut...
def fact_iter(n): """ 1. number of times around loop is n 2. number of operations inside loop is a constant 3. overall just O(n) >>> fact_iter(5) 120 >>> fact_iter(12) 479001600 >>> fact_iter(10) 3628800 >>> fact_iter(16) 20922789888000 >>> fact_iter(4) 24 ""...
def into_dict(l): """Convert a list into a dict.""" return {l[i]: l[i + 1] for i in range(0, len(l), 2)}
def content_store_url(base_path): """ API URL for a content item """ if not base_path.startswith('/'): base_path = '/' + base_path return 'https://www.gov.uk/api/content' + base_path
def clean_code(content): """Automatically removes code blocks from the code.""" if content.startswith("```") and content.endswith("```"): return "\n".join(content.split("\n")[1:])[:-3] else: return content
def read_bodyplan(file): """Read body plan from csv file. Args: file: path to file containing a bodyplan Returns: A list of L layers representing the model structure with layer keys: "layer", "n", "activation", "lreg", "regval", and "desc" indicating the layer index, inte...
def ipv4_int(ipv4_str): """Returns an integer corresponding to the given ipV4 address.""" parts = ipv4_str.split('.') if len(parts) != 4: raise Exception('Incorrect IPv4 address format: %s' % ipv4_str) addr_int = 0 for part in parts: part_int = 0 try: part_int = ...
def get_var_type_size(ref, alt): """ Calculate the variant type SNV, INS or DEL and length :param ref: String :param alt: String :return: var_type and var_size """ var_size = len(alt) - len(ref) if var_size == 0: var_type = 'SNV' elif var_size > 0: var_type = 'INS' ...
def size_sort(seq1, seq2): """ return longer sequence before shorter one """ if len(seq2) > len(seq1): tmp = seq1 seq1 = seq2 seq2 = tmp return seq1.upper(), seq2.upper()
def canonical_chrom_sorted(in_chroms): """ Sort a list of chromosomes in the order 1..22, X, Y, M/MT :param list in_chroms: Input chromosomes :return: Sorted chromosomes :rtype: list[str] """ if len(in_chroms) == 0: return [] chr_prefix = False mt = False if in_chroms[0]...
def validate_enum(value, valid_values, name=None): """Validates that value is in a list of valid values. Args: value: The value to validate. valid_values: The list of valid values. name: The name of the argument being validated. This is only used to format error messages. Returns: A valid ...
def ajuste(w, x, d, y): """ Define a taxa de aprendizagem e ajusta o valor do w. """ taxa_aprendiz = 0.01 return w + taxa_aprendiz * (d - y) * x
def _validate_strat_level(ts_num, ts_denom, strat_num, strat_denom): """ Check if the stratification level is valid for the time signature Parameters ---------- ts_num : int Time signature numerator ts_denom : int Time signature denominator strat_num : int Stratifica...
def _parse_setup_lines(lines): """Return a list of the setup names""" setups = [] for l in lines: if 'Setup' in l: tsetup = l.split()[1].strip() # Remove any lingering colon if tsetup[-1] == ':': setup = tsetup[:-1] else: ...
def get_superclasses_from_class_definition(class_definition): """Extract a list of all superclass names from a class definition dict.""" # New-style superclasses definition, supporting multiple-inheritance. superclasses = class_definition.get('superClasses', None) if superclasses: return list(s...
def wrap_seq_string(seq_string, n=60): """Wrap nucleotide string (seq_string) so that each line of fasta has length n characters (default n=60) Args: seq_string (str): String of DNA/protein sequence n (int): Maximum number of characters to display per line Returns: (str): String o...
def is_no_cache_key_option(number): """Return ``True`` iff the option number identifies a NoCacheKey option. A :coapsect:`NoCacheKey option<5.4.2>` is one for which the value of the option does not contribute to the key that identifies a matching value in a cache. This is encoded in bits 1 through 5 o...
def fGetSEGBaseIDFromSEGName( SEGName='6_AAD_41_OHV1' ): """ Returns 'Objects.3S_FBG_SEG_INFO.3S_L_'+SEGName+'.In.' In some cases SEGName is manipulated ... siehe auch fGetBaseIDFromResID """ if SEGName == '6_AAD_41_OHV1': x='6_AAD_41_OHN' elif SEGName == '6_O...
def flatten(s, accepted_types=(list, tuple)): """flatten lists and tuples to a single list, ignore empty Parameters ---------- s : Sequence accepted_types : Tuple (acceptable sequence types, default (list,tuple) Return ------ l : Flat sequence Exa...
def is_cidr_notation(netmask) -> bool: """ This function will check if the netmask is in CIDR format. :param netmask: Can be a 255.255.255.255 or CIDR /24 format :return bool: True if mask is in CIDR format """ return "." not in str(netmask)
def doubleCompare(expected, result, max_double_error): """ Compares double values for relative or absolute error. :param expected: expected correct value :param result: test value :param max_double_error: maximal error :return: Is |expected - result| <= max_double_error * max(1, |expected|) ...
def contains_toxicity(perspective_response): """Checking/returning comments with a toxicity value of over 50 percent.""" is_toxic = False if (perspective_response['attributeScores']['TOXICITY']['summaryScore'] ['value'] >= .5): is_toxic = True return is_toxic