content
stringlengths
42
6.51k
def to_positive_int(int_str): """ Tries to convert `int_str` string to a positive integer number. Args: int_str (string): String representing a positive integer number. Returns: int: Positive integer number. Raises: ValueError: If `int_str` could not be converted to a posi...
def format_vnic_listing(vnics): """Returns a formated list of vnics. Args: vnics (list): A list of vnics objects. Returns: The formated list as string """ import re out = "" i = 1 for v in vnics: # Shorten to 24 chars max, remove linebreaks ...
def _get_filepath_components(filepath): """ Splits filepath to return (path, filename) """ components = filepath.rsplit("/", 1) if len(components) == 1: return (None, components[0]) return (components[0], components[1])
def _trim(string): """Remove one leading and trailing ' or " used in values with whitespace.""" if string[0] in "'\"": return string[1:-1] return string
def lemmatize(parseResult): """ Args: parseResult: Returns: """ res = [] wordIndex = 1 for i in range(len(parseResult['sentences'][0]['tokens'])): tag = [ [ parseResult['sentences'][0]['tokens'][i]['characterOffsetBegin'], ...
def packman_api_name(api_name): """Changes an pipeline kwarg API name to format expected by Packman""" return api_name.replace('-', '/')
def duplicates(items): """Keep the items that show up more than once in a row, drop the rest""" dupes = list( items[_] for _ in range(len(items)) if ( ((_ > 0) and (items[_ - 1] == items[_])) or ((_ < (len(items) - 1)) and (items[_] == items[_ + 1])) ) ...
def l2_dist_sq(p1: tuple, p2: tuple) -> float: """ Compute squared L2 distance between p1 and p2 :param p1: Point 1 in the form (x, y) :param p2: Point 2 in the form (x, y) :return: Squared L2 distance """ assert len(p1) == 2 assert len(p2) == 2 dx = p1[0] - p2[0] dy = p1[1] - p2...
def intdivceil(x, y): """ Returns the exact value of ceil(x // y). No floating point calculations are used. Requires positive integer types. The result is undefined if at least one of the inputs is floating point. """ result = x // y if (x % y): result += 1 return result
def exkurt_fullsky(l): """ Returns the excess kurtosis of the full-sky marginal likelihood for a given l. Args: l (int): The l to return the excess kurtosis for. Returns: float: Excess kurtosis of the full-sky marginal likelihood for this l. """ nu = 2 * l + 1 k = nu / 2. ...
def is_file(filename): """Determine if the string passed in refers to a valid file Parameters ---------- filename: `str` attempt to open the file for reading Returns ------- `bool` indicating a file """ try: open(filename, "r") return True except IOEr...
def _write_key(key, value): """ Write in the proper format the key and the value in a octopus input file """ oct_str = "" keylen = 20 if isinstance(value, int) or isinstance(value, float): oct_str = oct_str + (key.ljust(keylen) + " = " + str(value) + '\n') elif isinstance(value,...
def filter_dict_keys(adict, allow): """Return a similar dict, but just containing the explicitly allowed keys Arguments: adict (dict): Simple python dict data struct allow (list): Explicits allowed keys """ return {k: v for k, v in adict.items() if k in allow}
def sum(a, b): """Returns the sum of a, b""" print("Calculating the sum of %d, %d" % (a, b)) return a + b
def removeStopwords(terms, stopwords): """ This function removes from terms all occurrences of words in the list stopwords. This will be provided for the student. """ return [x for x in terms if x not in stopwords]
def _split_divisible(num, num_ways, divisible_by=8): """Evenly splits num, num_ways so each piece is a multiple of divisible_by.""" assert num % divisible_by == 0 assert num / num_ways >= divisible_by # Note: want to round down, we adjust each split to match the total. base = num // num_ways // divisible_by *...
def avoid_wrapping(value): """ Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces. """ return value.replace(" ", "\xa0")
def flip_coords(xy_list): """ Given a list of coordinate pairs, swap the first and second coordinates and return the resulting list. """ return [(y, x) for (x, y) in xy_list]
def remove_hr_tags(str_obj): """ Remove all <hr> tags in strings """ str_obj = str_obj.replace(r'<hr>','') str_obj = str_obj.replace(r'<hr/>','') return str_obj
def _findUnusedName(peakSelectionModel): """ :rtype: str """ names = ["% 8s" % p.name() for p in peakSelectionModel] if len(names) > 0: names = list(sorted(names)) bigger = names[-1].strip() number = 0 for c in bigger: number = number * 26 + (ord(c) - ord(...
def hexdump(b): """Convert byte array to hex string""" return ' '.join(["{:02X}".format(v) for v in b])
def number_of_numerical_cells(row): """Count cells with int or float types.""" numtypes = [isinstance(c, int) or isinstance(c, float) for c in row] return numtypes.count(True)
def prettify_name(name): """ Prettify pythonic variable name. For example, 'hello_world' will be converted to 'Hello World' :param name: Name to prettify """ return name.replace("_", " ").title()
def replace_repeat_character(text, char_1, target, delimiter, char_2=None): """ Replace two characters by a single one. Replaces them even if separated by space or delimiter. Also merges any adjacent delimiters. If char_2 is not provided then it is assumed that char_1 is repeated """ char_...
def ascendingRange(rangeStart, rangeEnd): """Get start and end into ascending order by switching them if necessary. @param rangeStart: the start of the range @type rangeStart: C{int} @param rangeEnd: the end of the range @type rangeEnd: C{int} @return: range in ascending order @rtype: C{tuple} of length 2 """ i...
def is_user_pages(full_name): """ Return True if the repository is a user pages repository. """ username, repo_name = full_name.split('/', 1) return ( repo_name.startswith(username) and repo_name.endswith(('github.io', 'github.com')) )
def _normalize(rendered): """Return the input string as a list of stripped lines.""" return [line.strip() for line in rendered.splitlines() if line.strip()]
def team_name_to_group_name(team_name): """Return the Keycloak group name corresponding to `team_name`.""" return f"TEAM-{team_name}"
def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Utility function for computing output of convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ from math import floor if type(kernel_size) is not tuple: kernel_size = (kernel_size, kernel_size) h = f...
def to_percent(x): """ To percent with 2 decimal places. :param x: :return: """ return '{:.2%}'.format(x)
def verify_new_patient_info(in_dict): """Verifies post request was made with correct format The input dictionary must have the appropriate data keys and types, or be convertible to correct types, to be added to the patient database. Args: in_dict (dict): input with new patient ID, physicia...
def _pack_16b_int_arg(arg): """Helper function to pack a 16-bit integer argument.""" return ((arg >> 8) & 0xff), (arg & 0xff)
def append_flags_to_args(argsList, flags): """ Append user flags to VSEARCH command line args Arguments: argsList {list} -- args to appen flags onto flags {dict} -- flags with outpins Returns: list -- modified command to be sent to VSEARCH """ for flag in fl...
def switch_player(player): """Switch the player from X to O or vice versa and return the player""" players = {"X": "O", "O": "X"} return players[player]
def binomial_coefficient(n: int, k: int) -> int: """ Returns the binomial coefficient Defined as: factorial(n) // (factorial(n - k) * factorial(k)) :param n: The number of items :param k: The number of selected items :return: The number of ways to select k items from n options """ if k...
def cidr_to_netmask(cidr): """ Convert cidr to netmask Notes: http://www.linuxquestions.org/questions/blog/bittner-195120/cidr-to-netmask-conversion-with-python-convert-short-netmask-to-long-dotted-format-3147/ Args: cidr (int): cidr value Returns: string: netmask (ie 255....
def _ensure_echarts_is_in_the_front(dependencies): """ make sure echarts is the item in the list require(['echarts'....], function(ec) {..}) need it to be first but dependencies is a set so has no sequence :param dependencies: :return: """ if len(dependencies) > 1: dependencies.remo...
def _filename_info(name): """ Compose the filename for an info-file given its name. :param name: String with name of the info-file. :return: String with filename for the info-file. """ return name + '.json'
def read_lines(filename): """return a list containing each line in filename, with newlines removed.""" try: return [line.rstrip('\n') for line in open(filename)] except IOError: return []
def search(search_dict, field): """ Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided. """ fields_found = [] if isinstance(search_dict, dict): for key, value in search_dict.items(): if key == field: fields_fou...
def is_naht(liste): """ Parameters ---------- liste : list Returns ------- bool """ pre = liste[0] for el in liste: if abs(pre - el) > 1: return False pre = el return True
def _isbool(string): """ Checks if a string can be converted into a boolean. Parameters ---------- value : str Returns ------- bool: True/False if the string can/can not be converted into a boolean. """ return string in ("True", "true", "False", "false")
def levenshtein_array(s1, s2): """ Levenstein distance where insertion and deletions cost double as substitutions """ if len(s1) < len(s2): return levenshtein_array(s2, s1) if len(s2) == 0: return len(s1) * 2 previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): ...
def tochr(lst): """Converts every value of a list into a character""" return [chr(i) for i in list(lst)]
def build_flow_dict(G, R): """Build a flow dictionary from a residual network. """ flow_dict = {} for u in G: flow_dict[u] = dict((v, 0) for v in G[u]) flow_dict[u].update((v, attr['flow']) for v, attr in R[u].items() if attr['flow'] > 0) return flow_dict
def is_a_number(x): """ Returns True if x is an int or a float. """ return (type(x) is int) or (type(x) is float)
def to_gauss_smooth_sd(var): """ Sample from distributions :param var: either a dict describing a distribution, or a scalar value :return: standard deviation of gaussian smoothing """ if type(var) == dict: if var['type'] == 'uniform': try: rv = var['sm...
def octagonal(n: int) -> int: """ Octagonal Number Conditions: 1) n >= 0 :param n: non-negative integer :return: nth octagonal number """ if not n >= 0: raise ValueError return 3*n**2 - 2*n
def solution(max_base: int = 10, max_power: int = 22) -> int: """ Returns the count of all n-digit numbers which are nth power >>> solution(10, 22) 49 >>> solution(0, 0) 0 >>> solution(1, 1) 0 >>> solution(-1, -1) 0 """ bases = range(1, max_base) powers =...
def count_str_chars(str_var, strs_to_exclude = None, verbose = 0): """takes an input string and a list of strings and returns the length of the string, discounting the counts for any strings that appear in the list. the function default counts all charaters parameters ---------- str_va...
def apply_pool(pool, func, iters): """Routine to apply pathos multiprocessing. Escapes the overhead of pathos multiprocessing if we are using only one processor by explicitly running in series. Args: pool : pathos ProcessPool class object. func : function to be applied. iters : lis...
def type_is_namedtuple(t) -> bool: """Figuring out if a type is a named tuple is not as trivial as one may expect""" try: return issubclass(t, tuple) and hasattr(t, "_fields") except TypeError: return False
def normalize_snappy(s): """Normalization function that performs SNAPPY normalization (hyphen to underscore).""" return s.replace("-", "_")
def MEAN(strArg, composList, atomDict): """ *Calculator Method* calculates the average of a descriptor across a composition **Arguments** - strArg: the arguments in string form - compos: the composition vector - atomDict: the atomic dictionary **Returns** a float """ ac...
def normalize_to_100(score, out_of) : """ score: numerator out_of: denominator Returns normalized score out of 100 """ return score*100/out_of
def linear_search(arr, x): """return index of i in a list""" for i in range(len(arr)): if arr[i][0] == x[0]: return i return -1
def start_of_chunk(prev_tag, tag, prev_type, type_): """Checks if a chunk started between the previous and current word. Args: prev_tag: previous chunk tag. tag: current chunk tag. prev_type: previous type. type_: current type. Returns: chunk_start: boolean. """...
def token_auth_header(token): """ Create the value for the 'Authorization' HTTP header when using token based auth. :param token: The token to use :type token: str :return: The value for the Authorization header with token auth :rtype: str """ return "Token {token}".format(token=to...
def info_locale_opts(locale): """Example usage with *infostring*:: opts = info_locale_opts('en_US') opts.setdefault('arguments', []) opts['arguments'].extend(['-x', '-r', 'mkvinfo.log']) opts.setdefault('env', {}) opts['env']['MTX_DEBUG'] = 'topic' print infostring(m...
def check_not_mnist_files(path): """Filters some bad files in NotMNIST dataset.""" bad_paths = [ "RGVtb2NyYXRpY2FCb2xkT2xkc3R5bGUgQm9sZC50dGY=.png", "Q3Jvc3NvdmVyIEJvbGRPYmxpcXVlLnR0Zg==.png", ] for bad_path in bad_paths: if bad_path in path: return False return T...
def outline_gcp_project(project_index, project, zone, key_file_path): """Return a summary of a GCP project for logging purpose. Arguments: project_index (int): Project index. project (Resource): GCP Resource object of the project. zone (str): Name of the zone for the project. ke...
def get_keywords_prefix(model): """ Return the correct keyword's file prefix given the model :param model: name of the model :return: keyword's file prefix """ if model == "cyclerank" or model == "cyclerank_pageviews": return "keywords_cyclerank" elif model == "pagerank" or model == ...
def quick_scenarios(fieldname, values, probabilities): """ Quickly build common scenarios, like: [('foo', dict(somefieldname='foo')), ('bar', dict(somefieldname='bar')), ('boo', dict(somefieldname='boo'))] via a call to: quick_scenario('somefieldname', ['foo', 'bar', 'boo']) ...
def extractProteinThemeOfEventPairs(proteins, event_triggers, events, predict=False): """ Extract Protein = themeOf => Event Trigger Relations, Ignoring equivalences for now! Parameters ---------- proteins : dict dict of Protein objects event_triggers : dict dict of EventTrigger ...
def partition(sequence, predicate): """ Partition the sequence into two lists, according to the function provided. Args: sequence: A sequence of elements. predicate: A function of one argument, returning bool. Returns: A tuple of lists, where the first list contains all ...
def length_last_word(s): """ Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. """ s = s.strip() word_length = 0 for c in s: if c == ' ': word_length = 0 else: word_len...
def dict_to_entity(entity_dict: dict): """Convert a dict of str: str entries to a single entity bytes object. """ line_template = '\t"{}" "{}"' entity_lines = b'\n'.join(line_template.format(key, value).encode('ascii') for key, value in entity_dict.items()) return b'{\n' + entity_lines + b'\n}'
def k_to_c(t_k): """Convert Kelvin to Celsius.""" if t_k is None: return None return t_k - 273.15
def format_target(os_name, arch): """ Formats target name for provided OS name and CPU architecture. """ os_name = os_name.lower().replace("win32", "windows").replace("darwin", "macos") extension = ".exe" if os_name == "windows" else "" assert os_name in ["linux", "windows", "macos"] retur...
def parse_directive(directive): """ Parse a directive into a whitelist, blacklist, and substitution map. :param str directive: Directive to parse :return: whitelist, blacklist, substitutions :rype: tuple[list, list, dict] """ whitelist = [] blacklist = [] substitutions = {} fo...
def normalize_whitespace(msg): """Sanitize help message by removing extra white space. This helps keeping clean help messages when passed through a function's docstring. """ if msg is None: return msg return ' '.join(msg.strip().split())
def fnJulianDate(yr, mo, d, h, m, s): """ Implements Algo 14 in Vallado book: JulianDate Date: 05 October 2016 originally in AstroFunctions.py """ JD = 367.0*yr - int((7*(yr+ int((mo+9)/12)))/4.0) + int((275.0*mo)/9.0) + d+ 1721013.5 + ((((s/60.0)+m)/60+h)/24.0); return JD
def transformPrefs(prefs): """ {'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5}, 'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5}} to: {'Lady in the Water':{'Lisa Rose':2.5,'Gene Seymour':3.0}, 'Snakes on a Plane':{'Lisa Rose':3.5,'Gene Seymour':3.5}} ...
def percentile(N, P): """ Find the percentile of a list of values @parameter N - A list of values. N must be sorted. @parameter P - A float value from 0.0 to 1.0 @return - The percentile of the values. """ if len(N)==0: return 0.0 n = int(round(P * len(N) + 0.5)) return N[n-...
def compare_str(str1: str, str2: str) -> bool: """Compare two string and ignore \n at the end of two strings.""" return str1.rstrip() == str2.rstrip()
def add_tuples(t1, t2): """Adds t1 and t2.""" return (t1[0]+t2[0], t1[1]+t2[1])
def round_to_multiple_of(val, divisor, round_up_bias=0.9): """ Asymmetric rounding to make `val` divisible by `divisor`. With default bias, will round up, unless the number is no more than 10% greater than the smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88. """ assert 0.0 < round_up_bias...
def serialize_heading(title, depth): """Generate h1-h6 in markdown.""" hashes = '#' * depth return f'{hashes} {title}'
def lockerNumDigits (lockerNum, digits=3): """Adds leading zeroes to ensure len (lockerNum) == digits. :param str lockerNum: The locker number to ensure has sufficient digits :param int digits: The assigned number of digits for locker numbers to include leading zeroes :except Va...
def get_value_by_key_in_pairs_list(pairs_list, key): """e.g. [('a': 4), ('b': 3)], 'b' -> 3""" for pair in pairs_list: if pair[0] == key: return pair[1] raise ValueError('Attribute not found: {}'.format(key))
def __add_remove(base, delta, adding): """Add or remove delta from base.""" if adding: return base + delta return base - delta
def get_1s_count(number: int) -> int: """ Count the number of set bits in a 32 bit integer using Brian Kernighan's way. Ref - http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan >>> get_1s_count(25) 3 >>> get_1s_count(37) 3 >>> get_1s_count(21) 3 >>> get_1s_...
def fib( n ): """ fib( n ). This method calculate the nth Fibonacci number. Parameters: n(int): the nth Fibonacci number in the Fibonacci sequence Returns: f: nth Fibonacci number. """ if n < 2: return 1 else: f = fib(n-1) + fib(n-2) ...
def _next_regular(target): """ Find the next regular number greater than or equal to target. Regular numbers are composites of the prime factors 2, 3, and 5. Also known as 5-smooth numbers or Hamming numbers, these are the optimal size for inputs to FFTPACK. Target must be a positive integer. ...
def percent_boundary(used_ram, total_ram): """Return a upper and lower bound for percent ram used.""" calc = int((1.0 * used_ram / total_ram) * 100) # return calculated percent +/- 2 to account for rounding errors lower_boundary = calc - 2 upper_boundary = calc + 2 return lower_boundary, upper_b...
def formatsWritersField(writers_list): """ Formats Writers field for Web app template. """ film_writers="" if writers_list != None: for writer in writers_list: if len(writers_list) == 1 or writer == writers_list[-2]: film_writers = writer elif writer != w...
def image_filter(alpha: float = 0.5) -> str: """A css image filter as a constant gradient.""" return f"linear-gradient(to bottom, rgba(44,62,80,{alpha}) 0%, rgba(44,62,80,{alpha}) 100%)"
def factor_n(n): """ Converts input n to the form 2^exp * mult + 1, where mult is the greatest odd divisor of n - 1, and returns mult and exp. """ assert n >= 3 and n % 2 != 0, "n must be an odd integer > 2" mult = n - 1 exp = 0 while mult % 2 == 0: mult //= 2 exp += ...
def element_at(my_list, idx): """ Gets an element in a list at given index And returns it """ list_len = len(my_list) if idx >= list_len or idx < 0: return return (my_list[idx])
def echo(s): """Return the string passed in.""" return "We are echoing: %s" % s
def nth_child_edge_types(max_child_count): """Constructs the edge types for nth-child edges. Args: max_child_count: Maximum number of children that get explicit nth-child edges. Returns: Set of edge type names. """ return {f"CHILD_INDEX_{i}" for i in range(max_child_count)}
def find_min_and_its_index(largest_pairs): """Linear search for the minimum word-count pair.""" current_min_index, current_min = 0, largest_pairs[0][1] for i in range(1, len(largest_pairs)): next_count = largest_pairs[i][1] if next_count < current_min: current_min = next_count ...
def coordinates(x, y, dx, dy, nb_consecutive=5): """Coordinates of consecutive intersections from (x,y) directed by (dx,dy).""" return [(x + i * dx, y + i * dy) for i in range(nb_consecutive)]
def decode_report_item_id(report_id): """Provided with a DOM report item id return the report_item id in the database""" return int(report_id.replace("reportItem", "").split("-")[1])
def xgcd(b, n): """ Return g, x0, y0 such that x0*b + y0*n = g and g is the gcd of (b,n)""" x0, x1, y0, y1 = 1, 0, 0, 1 while n != 0: q, b, n = b // n, n, b % n x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return b, x0, y0
def wants_all_toppings(ketchup, mustard, onion): """Return whether the customer wants "the works" (all 3 toppings) """ return ketchup and mustard and onion
def between(a, b, x): """Check if x is in the somewhere between a and b. Parameters: ----------- a: float, interval start b: float, interval end x: float, value to test for Returns: -------- True if x is between a and b, False otherwise """ if a < b: return x >= a a...
def swap_element(list1, list2, index): """ Swaps element between list1 and list2 at given index Parameters: list1 -- First list list2 -- Second list index -- Index the swap operation will be applied Returns: list1 -- First list with swapped element list2 -- Second list with...
def safe_join(separator, values): """Safely join a list of values. :param separator: The separator to use for the string. :type separator: str :param values: A list or iterable of values. :rtype: str """ _values = [str(i) for i in values] return separator.join(_values)
def slug(text): """Transform text into an slug for use as a tag id or an anchor href. Spaces are replaced with hyphens, and the result is lower-cased. :param str text: Text to transform to a slug. :return: :py:obj:`text` with spaces replaced by hyphens, and the result lower-cased. :r...