content
stringlengths
42
6.51k
def summarize(f): """Return the function's doc summary.""" return (f.__doc__ or "").split("\n", 1)[0].strip()
def _params_to_ints(querystring): """Convert a list of string iD to a list of integers""" return [int(str_id) for str_id in querystring.split(",")]
def get_netmask_bits(netmask): """ Count the number of bits in the netmask """ rv = 0 stop = False for chunk in netmask.split('.'): byte = int(chunk) for bit in reversed(range(8)): if byte & 2**bit: if stop: raise RuntimeError("One bit afte...
def toggle(collection, item): """ Toggles an item in a set. """ if item is None: return collection if item in collection: return collection - {item} else: return collection | {item}
def count_digits(number: int) -> int: """ >>> count_digits(-123) 3 >>> count_digits(-1) 1 >>> count_digits(0) 1 >>> count_digits(123) 3 >>> count_digits(123456) 6 """ number = abs(number) count = 0 while True: number = number // 10 count = coun...
def time_to_decimal(time): """ Get the decimal part of a date. Parameters ---------- time : array a time with hms format split by ':' Returns ------- decimal_time : string the decimal part of a date. Examples -------- >>> time = [20, 17, 40.088] >>> tim...
def extract_content(entity): """ Given an entity, attempt to find "content" (encoded bytes) and "content-type" (Mime type of file). """ content = None content_type = None for key in entity.keys(): if "content" in key.split(":"): content = entity[key] if "content-typ...
def count(count: int, noun: str) -> str: """Count a given noun, pluralizing if necessary.""" return f"{count} {noun}{'s' if count != 1 else ''}"
def generate_normalized_name(name_tuple): """ Generates a normalized name (without whitespaces and lowercase) """ name_arr = list(name_tuple) name_arr.sort() name_str = ''.join(name_arr) return name_str.lower()
def strip_cstring(data: bytes) -> str: """Strip strings to the first null, and convert to ascii. The CmdSeq files appear to often have junk data in the unused sections after the null byte, where C code doesn't touch. """ if b'\0' in data: return data[:data.index(b'\0')].decode('ascii') ...
def Qconjugate(q): """ Qconjugate """ return (q[0], -q[1], -q[2], -q[3])
def location_check(csv_name): """ Function creates path for giving csv file (based on csv file name) :param csv_name: csv file name :return: path where to save giving file """ csv_name = str(csv_name) tournament_type = csv_name[-13:-11] tournament_gender = csv_name[-7] team_individu...
def s_curve(CurrTime, Amp, RiseTime, StartTime=0.0): """ Function to generate an s-curve command Arguments: CurrTime : The current timestep or an array of times Amp : The magnitude of the s-curve (or final setpoint) RiseTime : The rise time of the curve StartTime : The time that the...
def densityWater(temperature): """ Calculates the density of water from an interpolation by Cheng (see viscosity docstring for reference). Args: temperature (float): in Celsius in the range [0, 100] Returns: :class:`float` Density of water in kg/m^3 """ rho = 1000 * (1 - abs((t...
def _convert_yaml_to_bool(_yaml_bool_value): """This function converts the 'yes' and 'no' YAML values to traditional Boolean values. .. versionchanged:: 2.5.2 A conversion is now only attempted if the value is not already in Boolean format. """ if type(_yaml_bool_value) != bool: true_val...
def sort_items_by_count(items): """ Takes a dictionary of items, and returns a list of items sorted by count. :param items: A dictionary in {choice: count} format. :return: A list of (choice, count) tuples sorted by count descending. """ return sorted([(item, items[item]) for item in items], ...
def fix_count(count): """Adds commas to a number representing a count""" return '{:,}'.format(int(count))
def strictNamespaceMappingEnvarParse(envar=None): """Custom format STRICT_NAMESPACE_MAPPING env variable parsing. Note: STRICT_NAMESPACE_MAPPING value example: 'frontend.develop.example.com:develop,frontend.staging.example.com:staging' No spaces or special chars. """ if envar: ...
def parse_gb_allele_freqs_col(_bytes): """ Parse 'alleleFreqs' column of table snp146 in UCSC genome browser """ if _bytes == b'': return [] else: # "0.2,0.8,".split(',') = ['0.2', '0.8', ''] # Remove the last empty string freq_str = _bytes.decode("utf-8").split(',')[...
def recup_min_line (matrix): """Recuperation des min par ligne""" line_min_elt = [] for y_elt in matrix: min_line = y_elt[0] for x_elt in y_elt: if min_line > x_elt: min_line = x_elt line_min_elt.append(min_line) return line_min_elt
def readtime(wordcount: int, words_per_minute=300): """Given a number of words, estimate the time it would take to read them. :return: The time in minutes if it's more than 1, otherwise 1.""" return max(1, round(wordcount / 300))
def isSubhist(hist1, hist2): """ Checks if hist1 is a subset of hist2 Input: hist1, hist2 -- dictionary histograms Output: Boolean """ for letter in hist1: if letter not in hist2 or hist1[letter] > hist2[letter]: return False return True
def world_to_pixel(geoMatrix, x, y): """ Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate the pixel location of a geospatial coordinate """ ulX = geoMatrix[0] ulY = geoMatrix[3] xDist = geoMatrix[1] yDist = geoMatrix[5] rtnX = geoMatrix[2] rtnY = geoMatrix[4] pixel...
def levenshtein_distance(first,second): """ Return the levenshtein distance between two strings. http://rosettacode.org/wiki/Levenshtein_distance#Python """ if len(first) > len(second): first, second = second, first distances = range(len(first)+1) for index2, char2 in enumerate(second): new_distances = [i...
def get_prefix(url): """ @Description: get the prefix of a url to form the sub-level url --------- @Param: url:str ------- @Returns: a substr end where '/' last time appears ------- """ return url[0:url.rfind("/") + 1]
def fragment_3(N): """Fragment-3 for exercise.""" ct = 0 for _ in range(0,N,2): for _ in range(0,N,2): ct += 1 return ct
def create_mask(indexes): """ Convert index to hex mask. """ val = 0 for index in indexes: val |= 1 << int(index) return hex(val).rstrip("L")
def _fix_quoted_whitespace(line): """Replace spaces and tabs which appear inside quotes in `line` with underscores, and return it. """ i = 0 while i < len(line): char = line[i] i += 1 if char != '"': continue quote = char while i < len(line): ...
def drop_substring_from_str(item: str, substring: str) -> str: """Drops 'substring' from 'item'. Args: item (str): item to be modified. substring (str): substring to be added to 'item'. Returns: str: modified str. """ if substring in item: return item.replace(s...
def complete(prog_comp, obs_comp): """ Observation completion weighting factor. - 1.0 if observation not completed - 0.0 if observation or program are completed Parameters ---------- prog_comp : float fraction of program completed. obs_comp : float fraction of o...
def get_tag_list(task, tagging_schema): """ Set up the tag list """ task = task.lower() tagging_schema = tagging_schema.lower() if task == 'absa': if tagging_schema == 'ot': return ['O', 'T-POS', 'T-NEG', 'T-NEU'] elif tagging_schema == 'bio': return ['O', 'B-POS'...
def compute_protien_mass(protien_string): """ test case >>> compute_protien_mass('SKADYEK') 821.392 """ p={'A':'71.03711','C':'103.00919','D':'115.02694','E':'129.04259','F':'147.06841','G':'57.02146','H':'137.05891','I':'113.08406','K':'128.09496','L':'113.08406','M':'131.04049','N':'11...
def pprint_size(value): """Pretty-print size (with rounding)""" for postfix, limit in [("G", 1e9), ("M", 1e6), ("K", 1e3), ("", 1)]: if value >= limit: return "{}{}".format(int(value/limit), postfix)
def get_alt_support_by_color(is_in_support): """ ***NOT USED YET*** :param is_in_support: :return: """ if is_in_support == 254.0: return 1 elif is_in_support == 152.0: return 0
def ifexists(total_pages, page_no): """ This function checks whether the given page number is in the specified range of total pages. :param total_pages: :param page_no: :return: True or False """ if page_no <= total_pages: return False return True
def catch_parameter(opt): """Change the captured parameters names""" switch = {'-h':'help', '-i':'imp', '-l':'lstm_act', '-d':'dense_act', '-n':'norm_method', '-f':'folder', '-m':'model_file', '-t':'model_type', '-a':'activity', '-e':'file_name', '-b':'n_size', '-c':'l_...
def get_skip_initial_samples_min(post_proc_args): """ Function iterates over a list of arguments of the form ["plot_all_individual_cdfs", "visualise_traceworkload", "skipmins_3"] searches for "skipmins_3" and returns 3 in this case. This parameter indicates how many minutes to skip from the ycsb results...
def dict2coord(d): """dictionary as 'key1=value1, key2=value2, ...' string""" return ', '.join('{0}={1:.2f}'.format(*x) for x in d.items())
def literal(x): """Make literal""" if isinstance(x, str): if x and x[0] == x[-1] and x[0] in '"\'`': # already literal quoted return x # literal quote return f'"{x}"' if isinstance(x, list): # apply to children return [literal(x_) for x_ in x] ...
def option_not_exist_msg(option_name, existing_options): """ Someone is referencing an option that is not available in the current package options """ result = ["'options.%s' doesn't exist" % option_name] result.append("Possible options are %s" % existing_options or "none") return "\n".join(resu...
def provided_args(attrs): """Extract the provided arguments from a class's attrs. Arguments: attrs (:py:class:`dict`) :The attributes of a class. Returns: :py:class:`set`: The provided arguments. """ return attrs.get('PROVIDED', set())
def _is_field_in_transition_actions(actions, field_name): """ Returns True if there is field with given name in one of actions. """ for action in actions: if field_name in getattr(action, 'form_fields', {}): return True return False
def _filter_nonvalid_data(json_data): """ Remove channels that are disabled or that do not declare their policies. """ # Filter to channels having both peers exposing their policies json_data['edges'] = list(filter(lambda x: x['node1_policy'] and x['node2_policy'], json_data['edges'])) # Filter...
def truthiness(s): """If input string resembles something truthy then return True, else False.""" return s.lower() in ('true', 'yes', 'on', 't', '1')
def above_threshold (student_scores, threshold): """Determine how many of the provided student scores were 'the best' based on the provided threshold. :param student_scores: list of integer scores :param threshold : integer :return: list of integer scores that are at or above the "best" threshold. ...
def parse_requirements_fname(dep_name): """Parse requirements file path from dependency declaration (-r<filepath>). >>> parse_requirements_fname('pep8') >>> parse_requirements_fname('-rrequirements.txt') 'requirements.txt' :param dep_name: Name of the dependency :return: Requirements file path...
def get_objects(predictions: list, img_width: int, img_height: int): """Return objects with formatting and extra info.""" objects = [] decimal_places = 3 for pred in predictions: if isinstance(pred, str): # this is image class not object detection so no objects return objects ...
def td(obj): """Create a table entry from string or object with html representation.""" if hasattr(obj, '_repr_html_'): return f'<td style="text-align:left;">{obj._repr_html_()}</td>' elif hasattr(obj, '_repr_image_svg_xml'): return f'<td style="text-align:left;">{obj._repr_image_svg_xml()}<...
def isASNTable(inputFilelist): """Return TRUE if inputFilelist is a fits ASN file.""" if ("_asn" or "_asc") in inputFilelist: return True return False
def shape_to_stride(shape): """Return the stride. Parameters ---------- shape : tuple(int) The shape tuple """ ndim = len(shape) stride = [1] * ndim for i in range(ndim-1, 0, -1): stride[i-1] = stride[i] * shape[i] return tuple(stride)
def lwrap(list_, w=None): """docstring for lwrap""" result = [] o = w or '"' for elem in list_: result.append(o + elem + o) return result
def size_converter(_bytes: int) -> str: """ Converts bytes to KB, MB & GB Returns: formated str """ KB = _bytes / float(1 << 10) MB = _bytes / float(1 << 20) GB = _bytes / float(1 << 30) if GB > 1: return f"{round(GB, 2):,} GB" elif MB > 1: return f"{round(MB, 2)...
def levenshtein(string1, string2, swap=0, substitution=2, insertion=1, deletion=3): """ This is levenshtein distance calculation utility taken from https://github.com/git/git/blob/master/levenshtein.c @param string1: @param string2: @param swap: @param substitution: @param insertion: ...
def all_suffixes(li): """ Returns all suffixes of a list. Args: li: list from which to compute all suffixes Returns: list of all suffixes """ return [tuple(li[len(li) - i - 1:]) for i in range(len(li))]
def gcd_rec(num1: int, num2: int) -> int: """ Return the greatest common divisor of two numbers. Parameters ---------- num1 : int num2 : int Raises ------ TypeError if num1 or num2 is not integer. Returns ------- int """ def _gcd(dividend: int, diviso...
def dms2dd(d, m, s): """ Convert degrees minutes seconds to decimanl degrees :param d: degrees :param m: minutes :param s: seconds :return: decimal """ return d+((m+(s/60.0))/60.0)
def is_success(code): """ Returns the expected response codes for HTTP GET requests :param code: HTTP response codes :type code: int """ if (200 <= code < 300) or code in [404, 500]: return True return False
def same_shape(shape1, shape2): """ Checks if two shapes are the same Parameters ---------- shape1 : tuple First shape shape2 : tuple Second shape Returns ------- flag : bool True if both shapes are the same (same length and dimensions) """ if len(shap...
def get_tidy_invocation(f, clang_tidy_binary, checks, build_path, quiet, config): """Gets a command line for clang-tidy.""" start = [clang_tidy_binary] # Show warnings in all in-project headers by default. start.append('-header-filter=src/') if checks: start.append('-...
def inv_mod_p(x, p): """ Compute an inverse for x modulo p, assuming that x is not divisible by p. """ if x % p == 0: raise ZeroDivisionError("Impossible inverse") return pow(x, p-2, p)
def is_function(x): """ Checks if the provided expression x is a function term. i.e., a tuple where the first element is callable. """ return isinstance(x, tuple) and len(x) > 0 and callable(x[0])
def r(a): """ Make a slice from a string like start:stop:step (default 0:-1:1). """ a = a.split(":") if len(a) == 1: i = int(a[0]) return slice(i,i+1,1) x = a[0] and int(a[0]) or 0 y = a[1] and int(a[1]) or None s = len(a) == 3 and int(a[2]) or 1 return slice(x, y, s)
def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 >>> x = -13 >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 180339.9 po...
def is_child(parent, child, locations): """ Determines if child is child of parent Args: parent: parent_id child: child_id locations: all locations in dict Returns: is_child(Boolean): True if child is child of parent """ parent = int(parent) child = int(child...
def get_position(row_index, col_index, board_size): """(int, int, int) -> int Return the str_index of the cell in the game board of size board_size within the row, row_index, and the column, col_index >>>get_position(1, 1, 2) 0 >>>get_position(3, 2, 3) 7 """ return (row_index - 1) * b...
def gaussian(x, mean, var): """Given the mean and variance of a 1-d gaussian, return the y value for a given `x` value. .. math:: \\frac{1}{\\sigma\\sqrt{2\\pi}}e^{-\\frac{1}{2}(\\frac{x-\\mu}{\\sigma})^2} """ from math import sqrt, exp, pi denom = sqrt(2*pi*var) num = exp(-((x-mean)**2)/(2*var...
def get2(item, key, if_none=None, strict=True): """ similar to dict.get functionality but None value will return then if_none value :param item: dictionary to search :param key: the dictionary key :param if_none: the value to return if None is passed in :param strict: if False an empty ...
def peptide_mods(peptide): """Looks for modification symbols in peptides. Returns list of mod symbols. THIS NEEDS TO BE CHANGED TO HANDLE NEW COMET MODS """ # see if there are bounding residues temp = peptide.split('.') if len(temp) > 1: peptide = temp[1] # c...
def _format_description(description): """Clean the description of a node for display in Graphviz""" return description.replace('\'', '').encode('unicode_escape').decode()
def step_t(w1, w2, t0, width, t): """ Step function that goes from w1 to w2 at time t0 as a function of t. """ return w1 + (w2 - w1) * (t > t0)
def sort_dict_keys_by_value(d): """ Sort the keys in the dictionary by their value and return as a list This function uses `sorted`, so the values should be able to be sorted appropriately by that builtin function. """ ret = sorted(d, key=d.get) return ret
def fix_brace_o(a, b): """Move any `{`s between the contents of line `a` and line `b` to the start of line `b`. :param a: A line of Lean code, ending with `\n' :param b: A line of Lean code, ending with `\n' :returns: A tuple `(anew, bnew, fix)`, where `anew` and `bnew` are `a` and `b` with co...
def max_number_len(n): """Find max power of 10 which can be less or equals than sum of its digits power.""" power_of_9 = 9**n k = 1 while k*power_of_9 >= 10 ** k: k += 1 return k
def common_prefix(strings): """ Given a list of strings, return the common prefix between all these strings. """ ref = strings[0] prefix = '' for size in range(len(ref)): test_prefix = ref[:size+1] for string in strings[1:]: if not string.startswith(test_prefix): ...
def s2b(s): """ Converts a string to boolean value """ s = s.lower() return s == 'true' or s == 'yes' or s == 'y' or s == '1'
def fix_greengenes_missing_data(taxa_list): """ Writes taxa levels as separate list items, passes levelAbbreviation__ for missing data""" blank_taxa_terms = ['k__', 'p__', 'c__', 'o__', 'f__', 'g__', 's__'] missing_terms = 7 - len(taxa_list) if missing_terms != 0: taxa_list.extend(blank_taxa_ter...
def _getResultArray(rows, columns): """ Returns a pre-initialized results array with values <tt>-1</tt>. """ results = {} for row in rows: results[row] = {} for column in columns: results[row][column] = -1 return results
def index(sequence, condition): """ Returns index of the first item in a sequence that satisfies specified condition. Args: sequence: iterable Sequence of items to go through. condition: callable Condition to test. Returns: int ...
def compute_transition_table(init, target, iterations): """Compute a list of values for a smooth transition between 2 numbers. Args: init (int): initial value target (int): target value iterations (int): number of in-between values to create Returns: list: the...
def arithmetic_mean(samples): """Computes the arithmetic mean of a set of samples. """ return float(sum(samples)) / float(len(samples))
def remove_keys_filter(row,keys): """ Remove given keys from the row """ for key in keys: row.pop(key,None) return row
def create_silence(length): """Create a piece of silence.""" data = bytearray(length) i = 0 while i < length: data[i] = 128 i += 1 return data
def _clean_accounting_column(x: str) -> float: """ Perform the logic for the `cleaning_style == "accounting"` attribute. This is a private function, not intended to be used outside of `currency_column_to_numeric``. It is intended to be used in a pandas `apply` method. :returns: An object with...
def aqi(concentration): """Convert PM 2.5 concentration to AQI.""" if concentration <= 12.: return round(4.1667 * concentration) elif concentration <= 35.4: return round(2.1030 * (concentration - 12.1) + 51.) elif concentration <= 55.4: return round(2.4623 * (concentration - 35.5...
def write_internals_visible_to(actions, name, others): """Write a .cs file containing InternalsVisibleTo attributes. Letting Bazel see which assemblies we are going to have InternalsVisibleTo allows for more robust caching of compiles. Args: actions: An actions module, usually from ctx.actions. ...
def yes_no_none(value): """Convert Yes/No/None to True/False/None""" if not value: return None # Yes = True, anything else false return value.lower() == 'yes'
def _attrprint(d, delimiter=', '): """Print a dictionary of attributes in the DOT format""" return delimiter.join(('"%s"="%s"' % item) for item in sorted(d.items()))
def reduce(fea): # pragma: no cover """restore some formula""" rules = [ ('a r c s i n', 'arcsin'), ('a r c c o s', 'arccos'), ('a r c t a n', 'arctan'), ('s i n h', 'sinh'), ('c o s h', 'cosh'), ('t a n h', 'tanh'), ('s i n', 'sin'), ('c o s', 'c...
def freq_id_to_stream_id(f_id): """ Convert a frequency ID to a stream ID. """ pre_encode = (0, (f_id % 16), (f_id // 16), (f_id // 256)) stream_id = ( (pre_encode[0] & 0xF) + ((pre_encode[1] & 0xF) << 4) + ((pre_encode[2] & 0xF) << 8) + ((pre_encode[3] & 0xF) << 12) ) ...
def inherits_from(obj, a_class): """return inherits""" return issubclass(type(obj), a_class) and type(obj) != a_class
def labels_to_onehot(labels, classes): """ Convert a list of labels (integers) into one-hot format. Parameters ---------- labels : list A list of integer labels, counting from 0. classes : int Number of class integers. Returns ------- list List of one-hot lists...
def clean_ensembl_id(identifier): """ Formats an ensembl gene identifier to drop the version number. E.g., ENSG00000002822.15 -> ENSG00000002822 Args: identifier (str) Returns: identifier (str) """ return identifier.split('.')[0].upper()
def longest_prefix(names): """Find the longest common prefix of the repository names.""" return next( names[0][:n] for n in range(min(len(s) for s in names), 0, -1) if len({s[:n] for s in names}) == 1 )
def both_positive(a, b): """Returns True if both a and b are positive. >>> both_positive(-1, 1) False >>> both_positive(1, 1) True """ return a > 0 and b > 0
def _sort_resources(resources): """ Sorts a stack's resources by LogicalResourceId Parameters ---------- resources : list Resources to sort Returns ------- list List of resources, sorted """ if resources is None: return [] return sorted(resources, ke...
def pad(s, n): """Pad a string with spaces on both sides until long enough""" while len(s) < n: if len(s) < n: s = s + " " if len(s) < n: s = " " + s return s
def create_margin(x): """Creates a margin with the specified ratio to the width or height.""" return dict(l=x, r=x, b=x, t=x)
def thread(x, *fns): """Threads `x` left-to-right through the `fns`, returning the final result. thread x :: a -> a thread x, *fns :: a_0, *(a_i -> a_i+1) -> a_n""" for f in fns: x = f(x) return x
def _captchasolutiontokey(captcha, solution): """Turn the CAPTCHA and its solution into a key. >>> captcha = 'KSK@hBQM_njuE_XBMb_? with 10 plus 32 = ?' >>> solution = '42' >>> _captchasolutiontokey(captcha, solution) b'KSK@hBQM_njuE_XBMb_42' """ secret = captcha.split("?")[0] key = ...
def collatz_rec(p, nr_steps): """Recursive Collatz Step Calculation""" nr_steps += 1 if (p <= 1): return nr_steps if p % 2 == 0: return collatz_rec(int(p/2), nr_steps) else: return collatz_rec(int(3*p + 1), nr_steps)