code
stringlengths
15
1.19k
docstring
stringlengths
13
400
def n_char(record, char="", digit=False): if digit or char != "": if digit: n = len([k for k in record if k.isdigit()]) else: n = len([k for k in record if k == char]) else: raise ValueError("Please select a character") return n
This function get the number of characters of certain kind from a string
def title_format(name): person_names = [k.title() if len(k) > 3 else k for k in name.split(" ")] return " ".join(person_names)
This customized title function transform names in title format while keeping prepositions like "de" and "das" in lowercase
def _sdss_info_to_urlpath_(baseurl, basename, bands=None): return baseurl + "/" + basename + ".fits.bz2"
band name inside the sdss url. *bands is not used.
def hamming_distance(seq1, seq2): dist = sum([char1 != char2 for char1, char2 in zip(seq1, seq2)]) return dist
Calculate the Hamming distance between two sequences of the same length. The Hamming distance corresponds to the number of characters that differ between these two sequences.
def write_fastq(reads, fastq_file): try: with open(fastq_file, "w") as f: for read in reads: f.write(read.name + "\n") f.write(read.seq + "\n") f.write(read.desc + "\n") f.write(read.bqs + "\n") except IOError as e: prin...
Write list of reads of FASTQ file.
def read_list(filename): with open(filename, "r") as file_: all_lines = file_.read().splitlines() return all_lines
Read a given file into a list, where each line becomes another element. Intended for simple lists of words / strings to be read in, such as vendor-supplied index sequences to be quantified.
def find_file_name(directory, file_name): counter = 1 original_file_name, extension = os.path.splitext(file_name) file_name = f"{original_file_name}_{counter}{extension}" while os.path.exists(os.path.join(directory, file_name)): counter += 1 file_name = f"{original_file_name}_{counter}{e...
Find a file name which doesn't exist yet.
def parse_allowed_people(datafile): try: with open(datafile) as people_data: people = {} csv_reader = csv.reader(people_data) next(csv_reader) for row in csv_reader: name = row[0] birthday = row[1] people[name] =...
Read celebrities' name and birthday from csv file given its path
def print_birthdays(people): print( """Welcome to the birthday dictionary. We know the birthdays of these people:""" ) for name in people.keys(): print(people[name])
print names of people in birthdays dictionary The birthdays dictionary contains names as keys and birthdays as values. When the function is invoked, it returns the names of the people in the dictionary built in the program
def return_birthday(name, people, verbosity): if verbosity: print("Started looking for {}'s birthday".format(name)) if name in list(people.keys()): return people[name] else: return False
print the birthday of a celebrity The birthdays dictionary contains names as keys and birthdays as values. When this function is invoked, it returns the birthday of the person received as a parameter if the value exists in the dictionary, False otherwise.
def compute_n_hashings(string, n): for i in range(n): string = hashlib.sha256(string.encode("utf-8")).hexdigest() return string
Iterate n times the hashing funciton given a string value (password)
def extract_object(dictionary, key_sequence): ret = dictionary for k in key_sequence: ret = ret[k] return ret
Extract the object inside the dictionary at a specific path
def insert_into_dictionary(dictionary, key_sequence, value): parent = dictionary for key in key_sequence[:-1]: parent = parent.setdefault(key, {}) parent[key_sequence[-1]] = value
Insert value into dictionary at path specified by key_sequence. If the sequence of keys does not exist, it will be made
def check_valid_key_name(name): if not isinstance(name, str): return False bad_chars = ["*", ".", "&&&&"] if any(k in name for k in bad_chars): return False return True
Ensure the key name provided is legal
def check_valid_key_name_ext(name): if isinstance(name, int): return True if not isinstance(name, str): return False bad_chars = ["*", ".", "&&&&"] if any(k in name for k in bad_chars): return False return True
Ensure the key / index name provided is legal
def vec(X): X_flat = X.flatten() return X_flat
Vectorizes the given matrix by stacking rows from left to right
def lin_poly_solve(L, M): x0, x1, x2 = M.parent().gens() a0 = L.coefficient(x0) a1 = L.coefficient(x1) a2 = L.coefficient(x2) b0 = M.coefficient(x0) b1 = M.coefficient(x1) b2 = M.coefficient(x2) return [a1 * b2 - a2 * b1, -a0 * b2 + a2 * b0, a0 * b1 - a1 * b0]
Return the point defined as the intersection of two lines (given as degree-one polynomials in some field).
def linear_reduction(L): cycles = [] x0, x1, x2 = L[0][1].parent().gens() for [mi, Fi, Li] in L: a = Li.monomial_coefficient(x1) b = Li.monomial_coefficient(x2) if a == 0: cycles.append([mi, Fi(x0, x1, 0), Li]) else: cycles.append([mi, Fi(x0, -b / a * ...
L is a list of elements [m, Fi, Li], where mi is accumulated multiplicity Fi is a poly in three variables Li is a linear form in two variables Return: Linear reduction of each Fi*Li.
def right_distribute(K, L): return [ [mi * ri, Fi.change_ring(K), Li] for [mi, Fi, Gi] in L for (Li, ri) in Gi.change_ring(K).factor() ]
K is an embedding into a big enough field. Factor every G_i over a big enough field and apply cycle distribution. Note that every polynomial in the ouput has base field the big field.
def package_in_pip_output(package, output): return ( re.search("^{}\s".format(package), output, re.IGNORECASE | re.MULTILINE) is not None )
Determine if a package is found in the output of packages installed by pip
def tarfile_content_name(installer, file_name): name = os.path.basename(installer) name = name[: len(".tar.gz") * -1] return os.path.join(name, file_name)
Construct a path into a tar file to be able to extract a single file
def version_no_valid(version): try: x = [int(v) for v in version.split(".")] return 2 <= len(x) <= 3 except Exception: return False
Determine if string version is valid for getting specific PyPi package version
def overwrite_checksum(file, checkoff, checksum): file.seek(checkoff) file.write(struct.pack(">H", checksum))
Seek to current checksum and overwrite it
def xor_flag(key1, key2, data): new_data = bytearray() for i in range(0, len(data), 2): tid = struct.unpack(">H", data[i : i + 2])[0] new_data += struct.pack(">H", tid ^ key1 ^ key2) return new_data
XOR flag with key1 and key2
def GetBaseDir(server_name): basedir = "/var/www/html/%s/proj/pred" % (server_name) if os.path.exists(basedir): return basedir else: sys.stderr.write('unrecognized server name "%s"\n' % (server_name)) return ""
Get basedir of the server given server name
def scale_to_255(image_array): a_min = min(image_array.min(), 0) a_max = image_array.max() image_array = (image_array - a_min) / (a_max - a_min) * 255 return image_array
Default normalizing functor to scale image to [0, 255]
def dump_func_name(func): def echo_func(*func_args, **func_kwargs): logging.debug("### Start func: {}".format(func.__name__)) return func(*func_args, **func_kwargs) return echo_func
This decorator prints out function name when it is called
def _get_valid_length(line_scan): sum_length = 0 acc = 0 last_x = 0 for current_x in sorted(line_scan): if acc > 0: sum_length += current_x - last_x acc += line_scan[current_x] last_x = current_x return sum_length
Helper function for calculating valid length in one line_scan.
def maybe_make_new_dir(new_directory): logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s") if not os.path.exists(new_directory): os.makedirs(new_directory) logging.debug("Making new directory {}".format(new_directory))
Make directory if it does not already exist
def remove_leading_char_a(filepath): file_dir = os.path.dirname(filepath) basename = os.path.basename(filepath)[1:] new_filepath = os.path.join(file_dir, basename) return new_filepath
Remove the leading character `a` in the image file name to match original nih dataset
def filter_list(input_list, key_fn=(lambda x: x), filter_keys=None): if filter_keys is None: filtered_input_list = input_list else: input_dict = {key_fn(x): x for x in input_list} keys = set(input_dict.keys()) & set(filter_keys) keys = sorted(list(keys)) filtered_input_li...
Filter a list with a list of keys
def install(cls, pkgs): pass
pkgs ise set of packages, if the package is str it will go trough mapping rules, in case of binary they are explicit
def scia_orbit_range(string): res = [int(str) for str in string.split(",")] if len(res) > 2: msg = "%r is not a orbit number or range" % string raise argparse.ArgumentTypeError(msg) if len(res) == 2 and res[0] > res[1]: res.sort() return res
Generate list from comma separated string
def lv0_consts(key=None): consts = {} consts["mph_size"] = 1247 consts["num_aux_bcp"] = 16 consts["num_aux_pmtc_frame"] = 5 consts["num_pmd_packets"] = 200 consts["channel_pixels"] = 1024 if key is None: return consts if key in consts: return consts[key] raise KeyErro...
defines consts used while reading Sciamachy level 0 data
def _orient3dfast(plane, pd): pa, pb, pc = plane adx = pa[0] - pd[0] bdx = pb[0] - pd[0] cdx = pc[0] - pd[0] ady = pa[1] - pd[1] bdy = pb[1] - pd[1] cdy = pc[1] - pd[1] adz = pa[2] - pd[2] bdz = pb[2] - pd[2] cdz = pc[2] - pd[2] return ( adx * (bdy * cdz - bdz * cdy) ...
Performs a fast 3D orientation test. Parameters (3,3) float, three points in space that define a plane pd: (3,) float, a single point Returns float, if greater than zero then pd is above the plane through the given three points, if less than zero then pd is below the given plane, and if equal to zero then pd is ...
def render_notebook(file_name, out_name, nbconvert="jupyter"): out_name = os.path.abspath(out_name) file_name = os.path.abspath(file_name) command = [ nbconvert, "nbconvert", "--execute", "--to", "html", file_name, "--output", out_name, ] ...
Render an IPython notebook to an HTML file.
def key2freq(n): return 440 * 2 ** ((n - 49) / 12)
Gives the frequency for a given piano key.
def lowercase_ext(filename): if "." in filename: main, ext = os.path.splitext(filename) return main + ext.lower() return filename
This is a helper used by UploadSet.save to provide lowercase extensions for all processed files, to compare with configured extensions in the same case. : 0.1.4 Filenames without extensions are no longer lowercased, only the extension is returned in lowercase, if an extension exists.
def file_path(relative_path): try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath("") return os.path.join(base_path, relative_path)
Get absolute path to resource, works for dev and for PyInstaller
def scramble(text): perms = ["".join(p) for p in itertools.permutations(text)] return perms
Returns list of lists of all permutations of text
def index_to_coordinates(string, index): if index < 0: index = index % len(string) sp = string[: index + 1].splitlines(keepends=True) return len(sp), len(sp[-1])
Returns the corresponding tuple (line, column) of the character at the given index of the given string.
def line_at_index(string, index): if index < 0: index = index % len(string) start = string.rfind("\n", 0, index) + 1 end = string.find("\n", index) suffix = "\\n" if end >= 0 else "\\0" if end < 0: end = len(string) return f"{string[start:end]}{suffix}"
Returns the line at the given index of the given string.
def format_text(text, max_length=50, suffix="..."): text = text if len(text) <= max_length else f"{text[:max_length]}{suffix}" return text.replace("\t", "\\t").replace("\n", "\\n")
Replaces tabulations and ends of line.
def bound_json(args): object = {arg["key"]: f"@@{arg['key']}@@" for arg in args} return json.dumps(object).replace('"@@', "").replace('@@"', "")
Allows to create a Json binding to the given arguments, without quotes
def evaluate_env(env, value): old_env = os.environ try: os.environ = env return os.path.expandvars(value) finally: os.environ = old_env
Evaluates the given string with the appropriate environment variables' value.
def os_pathsep(value): if os.name != "nt": return ":" if ":" in value else ";" else: return ";"
Returns the appropriate path separator based the given value and the host OS.
def populate_registry(): from . import base, PEP0257, docblock, google, sphinx, numpy
Import the list of built in parsers and adds them to the registry.
def map_nodes(line): key_values = line.split(":") values = [] if key_values[1].strip() != "": values = [int(node) for node in key_values[1].strip().split(" ")] return values
Map line into graph node key = value as array
def pair_bitmap(items): mul = 1 for item in items: mul *= (2 * item) + 1 return mul % 999917
Hash function for calculation for pairs
def _from_rgb(rgb): if type(rgb) is tuple: pass else: rgb = tuple(rgb) return "#%02x%02x%02x" % rgb
translates an rgb tuple of int to a tkinter friendly color code
def filter_by(cls): return cls.schema().get("properties", {}).keys()
List of fields you can filter model by. By default, all fields are returned.
def move_to(browser, href): browser.get(href)
move to absolute url, not by clicking some elements
def lazy(func, *args, **kwargs): def wrapper(*args, **kwargs): def body(): return func(*args, **kwargs) return body return wrapper
every function decorated with `lazy` should be applied twice to get cons. It's because they get to be wrapped in a hidden function named `body` to defer the immediate application of the function.
def convert_to_bytes(integer, bytes_size): result = bytearray() src = bin(integer).lstrip("0b").zfill(bytes_size * 8) for i in range(0, len(src), 8): _int = int(src[i : i + 8], 2) result.append(_int) return bytes(result)
returns bytes that is converted from given integer
def decrypt(cls, ordinals, key): assert len(ordinals) == len(key) return [None if k is None else b ^ k for b, k in zip(ordinals, key)]
Decrypt ordinals with given key using xor. Decrypt to None if key is none.
def printable_str_from_ordinals(cls, ordinals): return "".join( ( cls.NONE_CHAR if o is None else chr(o) if chr(o) in cls.PRINTABLE_CHARS else cls.FALLBACK_CHAR ) for o in ordinals )
Convert ordinals to string. Unprintable characters are replaced with FALLBACK_CHAR.
def parse_io(inp, out): inp = [i.strip() for i in inp.splitlines() if i.strip()] out = [o.strip() for o in out.splitlines() if o.strip()] return inp, out
io means input/output for testcases; It splitlines them and strip the elements
def merge(it_X, it_Y): C = list(it_X) + list(it_Y) C.sort() return C
assume it_X and it_Y are in ascending order
def add(cls, tree, node): assert not tree.find(node.val) return cls.__add(cls, tree, node)
return new tree with node added
def min_index_nodup_1(arr): n = len(arr) i, j = 0, n - 1 if arr[i] < arr[j]: return 0 assert arr[i] > arr[j] while j - i > 1: k = i + j >> 1 if arr[i] < arr[k]: i = k elif arr[k] < arr[j]: j = k return j
@param arr: unique elements @return min index of the smallest value in arr Time Complexity O(lgn)
def min_index_nodup_2(arr): n = len(arr) i, j = 0, n - 1 if arr[i] < arr[j]: return 0 assert arr[i] > arr[j] while i < j: k = i + j >> 1 if arr[i] < arr[k]: i = k + 1 else: j = k return i
@param arr: unique elements @return min index of the smallest value in arr Time Complexity O(lgn)
def dict_from_packet(bytes): names = ["type", "code", "checksum", "id", "sequence"] struct_format = "!BBHHH" data = bytes[20:28] unpacked_data = struct.unpack(struct_format, data) return dict(zip(names, unpacked_data))
Returns dict of the ICMP header fields from an ICMP packet
def init(cls): pass
Method called during the `gitrack init` phase after the common options are bootstrapped. This method should gather all the configuration from user in interactive manner and process it. The result is to be returned as a dict.
def _folder_has_git(check_dir): for child in check_dir.iterdir(): if child.is_dir() and child.name == ".git": return True return False
Check if directory contains Git metadata folder
def stop(ctx, cancel, description): if ctx.obj["config"].store["running"]: if cancel: ctx.obj["provider"].cancel() else: ctx.obj["provider"].stop(description)
Stops the time tracking with message if provided.
def hooks(): pass
Internal group of commands for handling Git's hooks
def run_command(command, std_output=False): command = shlex.split(command) if std_output: return_data = subprocess.run(command, stderr=sys.stderr, stdout=sys.stdout) else: return_data = subprocess.run( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) return r...
run command using subprocess and return exit code
def socket_mem_from_vars(ansible_vars): numa_nodes = ansible_vars["numa_nodes"] socket_mem = [] for node in sorted(numa_nodes.keys()): socket_mem.append(numa_nodes[node]["dpdk_socket_mem"]) return socket_mem
Return list of DPDK socket memory values defined in Ansible variables
def pinned_cores_from_vars(ansible_vars): numa_nodes = ansible_vars["numa_nodes"] total_num_cores = 0 for node in sorted(numa_nodes.keys()): num_cores = numa_nodes[node]["no_physical_cores_pinned"] total_num_cores += num_cores return total_num_cores
Get requested number of pinned CPU cores for PMD from Ansible Role run and return integer
def pmd_core_numbers_from_mask(pmd_core_mask): pmd_cores = [] binary_mask = bin(int(pmd_core_mask, 16))[2:] for i, val in enumerate(binary_mask[::-1]): if val == "1": pmd_cores.append(i) return pmd_cores
Convert CPU hex mask to a list of CPU core IDs in a list
def ansible_vars(host): hostname = host.check_output("hostname -s") return host.ansible( "include_vars", "file=/tmp/sst_bf_role_vars_{host}.yaml " "name=test_run".format(host=hostname), )["ansible_facts"]["test_run"]
Put variables from Ansible Role run which are in a file into a dictionary
def check_key_value(partial_match, full_match, line, was_found): error = False if line.startswith(partial_match): if line == full_match and not was_found: was_found = True else: error = True return (was_found, error)
Search argument 'line' and ensure it is a full match with argument 'full_match', else report error. Return tuple
def core_numbers_from_mask(core_mask): cores = [] if not isinstance(core_mask, int): core_mask = int(core_mask, 16) binary_mask = bin(core_mask)[2:] for i, val in enumerate(binary_mask[::-1]): if val == "1": cores.append(i) return cores
Generate a list of CPU IDs from CPU mask argument 'core_mask' and return a list of CPU IDs
def filter_cores(cores_to_remove, cores): for core_id in cores_to_remove: cores.remove(core_id)
Remove CPU IDs in list argument 'cores_to_remove' from CPU IDs list in argument 'cores'
def compare_dict(d1, d2, ignore_underscores=True): for k, v in d1.items(): if ignore_underscores and k.startswith("_"): continue if v != d2[k]: return k return None
Returns None if they're the same, else returns the first key that differs.
def min2(a, b): if a and not b: return a elif b and not a: return b else: return min(a, b)
Wrapper around the min build-in that is robust to None.
def max2(a, b): if a and not b: return a elif b and not a: return b else: return max(a, b)
Wrapper around the max built-in that is robust to None.
def isint(f, tol=0.00000001): return abs(float(f) - int(f)) <= 0.00000001
Takes in a float F, and checks that it's within TOL of floor(f).
def xlrd_float_to_str(x): try: y = int(x) return str(y) except (ValueError, TypeError): return x
When importing a cell with a float in it, XLRD (or perhaps Excel) represents it as a float, e.g. a cell with 1000 will appear as 1000.0. This is annoying if you want to keep everything as strings. This function checks whether X can be cast down to an int, and if so, then to a string.
def remove_underscore(s): return s[1:] if s.startswith("_") else s
Get rid of underscore from S if it starts with one.
def add_underscore(s): return s if s.startswith("_") else "_%s" % s
Makes sure S begins with an underscore.
def reverse_dict(d): vals = d.values() assert len(vals) == len(set(vals)) d2 = {} for k, v in d.items(): d2[v] = k return d2
Returns a dictionary with values as keys and vice versa. Will fail if the values aren't unique or aren't hashable.
def as_str_or_hash(s): try: s = str(s) except UnicodeEncodeError: s = str(hash(s)) return s
Tries to convert S to a STR. If it doesn't work, just return the hash.
def timedelta_float(td, units="days"): if units == "days": return td.days + td.seconds / 86400.0 elif units == "seconds": return td.days * 86400.0 + td.seconds else: raise Exception("Unknown units %s" % units)
Returns a float of timedelta TD in UNITS (either 'days' or 'seconds'). Can be negative for things in the past. timedelta returns the number of days and the number of seconds, but you have to combine them to get a float timedelta.
def days_in_minutes(days): return days * 60 * 24
Returns int minutes for float DAYS.
def as_ids(lst, sort=True): ids = [] for x in lst: if isinstance(x, dict): ids.append(x["id"]) else: ids.append(x.id) if sort: ids = sorted(ids) return ids
Returns the IDs for all the objects in the list/QuerySet, to make it easier to compare lists of objects and lists of dictionaries. I wanted this as a standalone function to make it terser to call.
def normed_areas(dataframe): phases = dataframe["GMM_label"].unique() areas = [] for phase in phases: phase_rows = dataframe[dataframe["GMM_label"] == phase] total_area = phase_rows["area"].sum() areas.append(total_area) normed_areas = areas / max(areas) return normed_areas
Takes in morphology descriptors dataframe and calculates a normalized area covered by each of the present phases
def relative_areas(dataframe): phases = dataframe["GMM_label"].unique() areas = [] total_area = 0 for phase in phases: phase_rows = dataframe[dataframe["GMM_label"] == phase] phase_area = phase_rows["area"].sum() areas.append(phase_area) total_area += phase_area relat...
Takes in morphology descriptors dataframe and calculates a normalized relative ratios of the areas covered by each of the present phases
def continuedFraction(x): a = [] a.append(int(x)) x -= a[-1] while x != 0 and len(a) < 30: a.append(int(1 / x)) x = (1 / x) - a[-1] return a
calc continuedFraction approximate generate a continuedFraction list
def rationalContinuedFraction(x, y): if x < y: x, y = y, x k = x / y p, q, m, n = 0, 1, 1, 0 while x != 0 and y != 0: k = x / y p, q = q, p + q * k m, n = n, m + n * k x, y = y, x % y
calc rational fraction's continued fraction approximate
def Eratoshenes(n): composite = set() prime = [] for i in range(2, n + 1): if i not in composite: prime.append(i) j = 2 while j * i <= n: composite.add(i * j) j += 1 return prime
this function need many memory use Eratoshenes to generate prime list
def mrsm(b, n, m): a = 1 b %= m i = map(int, bin(n)[2:][::-1]) for k in i: a = (a * b**k) % m b = (b * b) % m return a
Modular repeat square remainder algorithm return b^n % m
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("task", choices=["seg", "det", "drivable"]) parser.add_argument("gt", help="path to ground truth") parser.add_argument("result", help="path to results to be evaluated") args = parser.parse_args() return args
Use argparse to get command line arguments.
def is_section(config, line): if config.index(line) + 1 == len(config): return False if re.match(r"^ ", line): return False else: if re.match(r"^ ", config[config.index(line) + 1]): return True else: return False
def ines if this line - is section's name.
def findcouchapp(p): while not os.path.isfile(os.path.join(p, ".couchapprc")): oldp, p = p, os.path.dirname(p) if p == oldp: return None return p
Find couchapp top level dir from sub dir
def errexit(errlev=1, mess=""): if mess != "": sys.stderr.write("%s: error: %s\n" % (os.path.split(sys.argv[0])[1], mess)) sys.exit(errlev)
Display an error and exit.
def _get_json_key(key): json_obj = json.loads(key) return json_obj
Return the json serialization for the key.
def _get_pubkey(rsa_key_pair): pub_key = rsa_key_pair.export(private_key=False) return pub_key
Extract the RSA public key from a RSA_keypair.
def configure(subparser): pass
Add additional arguments to the command's subparser.
def group_nodes_by_uuid(graph): uuid_to_nodes = {} for _, node in graph.nodes.items(): node_prop = node.properties if "uuid" in node_prop: uuid = node_prop["uuid"] if uuid not in uuid_to_nodes: uuid_to_nodes[uuid] = set() uuid_to_nodes[uuid].ad...
Creates a dictionary of uuid -> Set of nodes. The set contains all nodes with that uuid. Nodes with no uuid are not included.