content
stringlengths
42
6.51k
def birch_murnaghan(V, E0, B0, B1, V0): """ BirchMurnaghan equation from PRB 70, 224107 """ eta = (V/V0)**(1./3.) return E0 + 9. * B0 * V0 / 16. * (eta**2-1)**2 * (6 + B1*(eta**2-1.) - 4. * eta**2)
def equal(a,b): """ return 1 if True, else 0 """ if(a == b): return 1 else: return 0
def clamp(x, lower, upper=None): """Clamps number within the inclusive lower and upper bounds. Args: x (number): Number to clamp. lower (number, optional): Lower bound. upper (number): Upper bound Returns: number Example: >>> clamp(-10, -5, 5) -5 ...
def _get_base_url(url): """ :param str url: e.g. "http://localhost/some_dir/index.html" :return: e.g. "http://localhost/some_dir/" :rtype: str """ if url.endswith('/'): return url start_idx = url.index('://') + len('://') if '/' not in url[start_idx:]: # Just 'http://domain.com'...
def is_float(string): """ Return whether or not a string is a parseable float. """ try: float(string) return True except ValueError: return False
def as_signed_int32_array(byte_array): """Interprets array of byte values as signed 32 bit ints.""" def int32(a, b, c, d): unsigned = a + (b << 8) + (c << 16) + (d << 24) return unsigned if unsigned < (2**31) else (unsigned - 2**32) return [int32(*byte_array[i:i + 4]) for i in range(0, len(...
def bprop_div(x, y, dz): """Backpropagator for primitive `div`.""" return (dz / y, -dz * x / (y * y))
def remove_from_end(string, text_to_remove): """ Remove a String from the end of a string if it exists Args: string (str): string to edit text_to_remove (str): the text to remove Returns: the string with the text removed """ if string is not None and string.endswith(text_to_rem...
def ucb_sub(mu, std, beta=3.): """Sub function to compute the upper confidence bound acquisition function. Args: mu: n x 1 posterior mean of n query points. std: n x 1 posterior standard deviation of n query points (same order as mu). beta: scaling parameter between mean and standard deviation in...
def boundary_conditions(particle_outer_radius, boundary_temp): """ This function defines the temperature on the outer radius of the particle Inputs -------- -particle_outer_radius: Outer radius of particle -boundary_temp: User input of the temperature at the outer radius [K] Outputs -----...
def modcmp(lib=(), test=()): """Compare import modules.""" if len(lib) > len(test): return False return all(a == b for a, b in zip(lib, test))
def get_options(option): """Get options for a dropdown menu""" if option == 'percentage_match': percent_values = [1, 2, 3, 5, 10, 25, 50] return (['%' + str(x) for x in percent_values])
def ignore_edition(edition_data): """don't load a million editions that have no metadata""" # an isbn, we love to see it if edition_data.get("isbn_13") or edition_data.get("isbn_10"): return False # grudgingly, oclc can stay if edition_data.get("oclc_numbers"): return False # if ...
def _polygon_under_graph(xlist, ylist): """Construct vertex list defining polygon under the (xlist, ylist) line graph. Assumes the xs are in ascending order. Args: xlist: ylist: """ return [(xlist[0], 0.0), *zip(xlist, ylist), (xlist[-1], 0.0)]
def increment(x): """ads one to x""" return(x+1)
def str_list(a_list, keep_decimal=False, separator="-"): """ Convert a list to a single string. """ s_list = [str(item) for item in a_list] s_list = [fitem.split(".")[1] for fitem in s_list] \ if keep_decimal else s_list return '-'.join(s_list)
def linspace(start, stop, num=50, endpoint=True): """linspace from a to b with n entries.""" step = (stop - start) / (num - endpoint) return [start + step*i for i in range(num)]
def actor_key(name, namespace): """ generate the key used to key the actor in memory bases on the actor path and namespace used :param name: name of the actor :type name: str :param namespace: 0-db namespace used by this actor :type namespace: str :return: key used to keep the actor in...
def compute_lambda_tilde(m1, m2 ,l1 , l2): """ Compute Lambda Tilde from masses and tides components -------- m1 = primary mass component [solar masses] m2 = secondary mass component [solar masses] l1 = primary tidal component [dimensionless] l2 = secondary tidal component [d...
def getColorRange(x): """ Determines the range of colors, centered at zero, for normalizing cmap """ vmax=max(x) vmin=min(x) vmax = max([vmax,abs(vmin)]) vmin = -1*vmax return vmax,vmin
def recursive_3(n, memo): """recursively determines if n is a cleanly divisible by 3 """ # Basecase if n == 1: return True elif n in memo: return memo[n] elif n % 3 == 0: memo[n] = n/3 return recursive_3(n/3, memo) else: return False
def str_wrap_double(string): """ Adds double quotes around the input string """ return '"' + string + '"'
def merge(jsons): """ Merge a list of CMS lumi json data Args: jsons (list) : List of CMS lumi json data (dicts with run : list of LS) """ outjson = {} for f in jsons: print("Adding json form "+f+" to merge json") injson = jsons[f] for run in injson: i...
def remove_encoding_indicator(func_string): """ In many functions there is a following "A" or "W" to indicate unicode or ANSI respectively that we want to remove. Make a check that we have a lower case letter """ if (func_string[-1] == "A" or func_string[-1] == "W") and func_string[-2].islower(...
def replace_specified_value(a_list, new_val, old_value): """ Replace all elements of a list that are a certain value with a new value specified in the inputs. Args: a_list: The list being modified new_val: The value to insert into the list old_value: The value of the list to be r...
def get_appearance_points(minutes): """ get points for being on the pitch at all, and more for being on for most of the match. """ app_points = 0. if minutes > 0: app_points = 1 if minutes >= 60: app_points += 1 return app_points
def members(obj): """List all the member variables in an object.""" result = [attr for attr in dir(obj) if not callable(attr) and not attr.startswith("__")] # print result return(result)
def tsv_to_str(obj, comment=None) : """ obj must be a list of list of python objects having a decent str() form """ comment = '' if comment is None else ('# ' + comment.replace('\n', ' ') + '\n') return comment + '\n'.join( '\t'.join( ('' if cell is None else str(cell)).strip().replace('\\', '\\\\').replace('\n...
def manhat_dist(a, b): """Return mahattan ditance between a and b""" return abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2])
def _add_name(mlist, name): """ adding anem to each element from the list""" for i, elem in enumerate(mlist): if isinstance(elem, str): if "." in elem or elem.startswith("_"): pass else: mlist[i] = "{}.{}".format(name, mlist[i]) elif isinst...
def get_response_statements(statement_list): """ Filter out all statements that are not in response to another statement. A statement must exist which lists the closest matching statement in the in_response_to field. Otherwise, the logic adapter may find a closest matching statement that does not ha...
def clean_mention(text): """ Clean up a mention by removing 'a', 'an', 'the' prefixes. """ prefixes = ["the ", "The ", "an ", "An ", "a ", "A "] for prefix in prefixes: if text.startswith(prefix): return text[len(prefix) :] return text
def isHexValue(string): """ Check if a string is a hex value / consists of hex chars only (and - ) Arguments: string - the string to check Return: Boolean - True if the address string only contains hex bytes or - sign """ string = string.replace("\\x","") string = string.replace("0x","") if len(string) > 16...
def reverse(xs): """Reverse a playlist.""" xs.reverse() return xs
def get_paths(file): """ Gets all the paths from a file contaning a list of paths params: file: a path to a file or None """ if file is None: return [] else: ls = [] with open(file) as f: ls.append(f.readline()) return ls
def extract_label(entry, lang): """ Extract the label associated to an entry in a specific language :param entry: :param lang: :return: """ if "labels" in entry: if lang in entry['labels'].keys(): return entry['labels'][lang] return None
def c_term_probability(modified_sequence): """ Returns the probability that C term AA was modified. """ if modified_sequence[-1] == ')': return float(modified_sequence[:-1].split('(')[-1]) else: return 0.0
def _extract_protocol_layers(deserialized_data): """ Removes unnecessary values from packets dictionaries. :param deserialized_data: Deserialized data from tshark. :return: List of filtered packets in dictionary format. """ packets_filtered = [] for packet in deserialized_data: ...
def load_graph_dictionary(g): """ Process a given stream into a nodes and edges dictionary. """ nodes = {} edges = {} for rec in g: if rec: if len(rec) == 4: key = (rec[0], rec[1]) if key in edges: edges[key].append(rec[-1])...
def unique_paths(m: int, n: int) -> int: """ Given a robot located at the top-left corner of a m x n grid that can only move either down or right at any point in time, returns the number of unique paths for the robot to reach the bottom-right corner. Arguments: m (int): Number of rows. ...
def get_resources(data): """Gets resources from the input cloutformation file content.""" return data['Resources']
def comeca_por(x,y): """Recebe duas cadeia de caracteres, sendo a primeira o numero do cartao e a segunda os digitos iniciais (IIN)""" if len(x)<len(y): return False for i in range(len(y)): if y[i]!=x[i]: return False return True
def dicts_equal(dict1, dict2): """ Whether two dicts are identical. """ return dict1.keys() == dict2.keys() and dict1.values() == dict2.values()
def try_except(function,*args): """ Tries a function and catches all exceptions""" try: return function(*args) except BaseException: return None
def make_pretty_name(method): """Makes a pretty name for a function/method.""" meth_pieces = [method.__name__] # If its an instance method attempt to tack on the class name if hasattr(method, '__self__') and method.__self__ is not None: try: meth_pieces.insert(0, method.__self__.__cl...
def merge_split_enhancers(collector): """ :param collector: :return: """ mrg_collect = [] for ghid, splits in collector.items(): if len(splits) == 1: mrg_collect.append(splits[0]) continue c = 1 splits = sorted(splits, key=lambda d: (d['start'], d[...
def binary_to_gray(n): """Convert Binary to Gray codeword and return it.""" n = int(n, 2) # convert to int n ^= (n >> 1) # bin(n) returns n's binary representation with a '0b' prefixed # the slice operation is to remove the prefix return bin(n)[2:]
def _get_ref(word: dict): """HELPER: extracts the reference from the dictionary :param word: the node in the list of the text :type word: dict :return: the reference and the exact part of the file :rtype: str """ try: if "ref" in word: return word["ref"] except TypeE...
def normalize_VR(inputVR, tag): """ Rules : 1- Type1 or Type2 => Type1/Type2 2- See Note => UN 3- Can't be null => UN """ all_vr = ["AE", "AS", "AT", "CS", "DA", "DS", "DT", "FL", "FD", "IS", "LO", "LT", "OB", "OD", "OF", "OW", "PN", "SH", "SL", "SQ", "SS", "ST", ...
def _bbox(pts): """Find the AABB bounding box for a set of points""" x, y = pts[0] ax, ay, bx, by = x, y, x, y for i in range(1, len(pts)): x, y = pts[i] ax = x if x < ax else ax ay = y if y < ay else ay bx = x if x > bx else bx by = y if y > by else by return...
def removeprefix(text: str, prefix: str) -> str: """For python <= 3.8 compatibility. :param text: _description_ :type text: str :param prefix: _description_ :type prefix: str :return: _description_ :rtype: str """ return text[len(prefix) :] if text.startswith(prefix) and len(prefix)...
def count(coll): """ Returns the number of items in the collection. Also works on strings. """ if hasattr(coll, "__len__"): return len(coll) n = 0 for _ in coll: n += 1 return n
def dict_get(params: dict, key: str, default): """ Returns `params[key]` if this exists and is not None, and `default` otherwise. Note that this is not the same as `params.get(key, default)`. Namely, if `params[key]` is equal to None, this would return None, but this method returns `default`. This ...
def mystr(s): """Convert a Unicode string to a basic string.""" try: return str(s) except UnicodeError: s = s.replace('\u201c', '"').replace('\u201d', '"') try: return str(s) except UnicodeError: parts = [] for c in s: try: ...
def _get_harmonic_list(degree_max): """Generate list of all spherical harmonics up to degree_max.""" harmonic_list = [] for degree in range(degree_max + 1): for order in range(-degree, degree + 1): harmonic_list.append((order, degree)) return harmonic_list
def unique_elements_in_list(array): """Returns the unique elements in the input list, preserving the original order. Parameters ---------- array: `List` [`any`] List of elements. Returns ------- unique_array : `List` [`any`] Unique elements in `array`, preserving th...
def convert_title(original_title): """Remove underscores from string""" new_title = original_title.replace("_", " ").title() return new_title
def is_warmer_than_avg(cur_temp,avg_temp,threshold): """ Purpose: Determine if the current temp is warmer than the average temp while being outside the avg_temp/threshold window cur_temp: int avg_temp: int threshold: pos int """ if threshold < 0: raise ValueError("threshold must be a positive int") if c...
def texify_str(s): """Escape a string to not crash LaTeX Parameters ---------- s : str String to escape for use in LaTeX Returns ------- str Formatted string to be used in LaTeX. """ # the following replacements will get added to whenever needed tex_str = s.re...
def buffers_xor(buffer1, buffer2): """buffer1, buffer2: byte-like objects. """ try: return bytes(b1 ^ b2 for b1, b2 in zip(buffer1, buffer2)) except TypeError: print("Function 'buffers_xor' takes byte-like" "objects as an arguments.")
def banner(message): """ Return 80-char width message declaration with = bars on top and bottom. """ bar = '=' * 80 return '%s\n%s\n%s' % (bar, message, bar)
def _split_markdown_post_content(markdown): """Take the first non-empty line of the post as the title.""" lines = markdown.splitlines() title_line = None for i, line in enumerate(lines): if line.strip() != '': title_line = i break if title_line is None: retu...
def join_floats(float_list, places=3, ): """ >>> l = [1.23456789123456, 1, 2, 3, 3.45, 5.6543, 1,3456] >>> join_floats(l) '1.235 1.000 2.000 3.000 3.450 5.654 1.000 3456.000' """ str_floats = " ".join(format(i, "{}.{}f".format(places + 2, places)) for i in float_list) return str_floats
def optimized_bubble_sort(numbers: list) -> list: """ This function implements the Optimized Bubble Sort algorithm. """ # check if the list is empty if len(numbers) == 0: raise ValueError("Empty List") # check if the list contains only numbers for number in numbers: if not is...
def shorten(description, info="anilist.co"): """ Shortens the description :param description: :param info: :return: """ character_description = "" if len(description) > 700: description = description[0:500] + "...." character_description += f"<b>Description</b>: <i>{descr...
def zmw_from_subread(subread): """Given a subread 'movie/zmw/start_end', return 'movie/zmw'""" try: return '/'.join(subread.split('/')[0:2]) except Exception: raise ValueError("Could not convert read %s to zmw" % subread)
def write_router_name_hashtable(var_name, router_names_feature_correspond_list): """ // HashTable -> X router_name (string) to feature_index (size_t). std::map<std::string,int> map_x_router_name_to_index { {"router_name_0", 0}, {"router_name_1", 1}, {"router_name_2", 2} }; """ list_str = [] ...
def urlify(a_str, a_len): """Urlify given string :param a_str: Given string :param a_len: Length of the string """ num_spaces = 0 for c in a_str: if c == " ": num_spaces += 1 total_len = a_len + num_spaces * 2 index = total_len i = a_len - 1 # Take a new li...
def cmd_uninstall(pack): """ Function to generate the command to uinstall a package using pip Parameters -------------- pack: str name of the package to uninstall Returns ----------- cmd: str cmd to apply """ cmd = "pip uninstall {}".format(pack) return cmd
def data_format(account): """format the account data in order to print""" account_name = account['name'] account_descr = account['description'] account_country = account['country'] return f"{account_name}, a {account_descr} from {account_country}"
def _scale_size(size, scale): """ Rescale a size by a ratio. Args: size (tuple[int]): (w, h). scale (float | tuple(float)): Scaling factor. Returns: tuple[int]: scaled size. """ if isinstance(scale, (float, int)): scale = (scale, scale) w, h = size retur...
def rotate_l (sequence) : """Return a copy of sequence that is rotated left by one element >>> rotate_l ([1, 2, 3]) [2, 3, 1] >>> rotate_l ([1]) [1] >>> rotate_l ([]) [] """ return sequence [1:] + sequence [:1]
def _crc_decode(source): """Checksum of crc for the Frame Args: source (bytes): The bytes format of Frame(dictionary) Returns: self: The frame constructed by this method """ # remainder = bytes([source >> 8 & 255]) # remainder += bytes([source & 255]) polynomial = 0x11021...
def hello_user(user): """ this serves as a demo purpose :param user: :return: str """ return "What's up %s!" % user
def get_reader_time_step_values(extensions, reader_description): """Get the XML content for reader time step values the Python path when making a ParaView plugin. """ return '''<DoubleVectorProperty name="TimestepValues" repeatable="1" information_only="1"> <TimeStepsInformationH...
def _remove(node, word, count): """Remove a word from a trie. :arg dict node: Current node. :arg str word: Word to be removed. :arg int count: Multiplicity of `word`, force remove if this is -1. :returns bool: True if the last occurrence of `word` is removed. """ if not word: if ''...
def drange(v0, v1, d): """Returns a discrete range.""" assert v0 < v1, str((v0, v1, d)) return range(int(v0)//d, int(v1+d)//d)
def decode_data(data): """Decode bytes to string """ return data.decode(encoding='utf-8') if isinstance(data, bytes) else data
def bsubstr(astring, pos, nchar): """Awk substr equivalent""" result = 0; l = len(astring); if((pos > 0) & (nchar <= l)): f = pos+nchar-1; if(f <= l): return astring[(pos-1):f]; else: return result;
def ensure_kwarg_not_in(caller, key, forbidden): """Checks a single **key** from keyword arguments against forbidden keys. If **key** is in **forbidden** keys, throws :exc:`TypeError`. :param str caller: name of the caller, :param str key: the key to be examined, :param forbidden: sequ...
def sort_docs_list(lst): """Sort a list of prodigy docs by input hash """ return sorted(lst, key=lambda k: k["_input_hash"])
def remote_nets(networks, topo_id): """ Returns the subnets of all remote ASes the SIG in topo_id is connected to. :param networks dict: Scion elem to subnet/IP map. :param topo_id: A key of a topo dict generated by TopoGenerator. :return: String of comma separated subnets. """ rem_nets = []...
def _nested(submatch, match): """Check whether submatch is nested in match""" ids_submatch = set((key, tok.id) for key, tok in list(submatch.items())) id_match = set((key, tok.id) for key, tok in list(match.items())) return set.issubset(ids_submatch, id_match)
def __convert_strand(strand): """Convert strand (+/-) from XML if present. Default: + """ if strand == "minus": return "-" if strand == "plus" or strand == "none": return "+"
def find_second_highest_key_in_dict(data) -> str: """ Finds the second highest key of a dictionary Note that the key must be in string format Intended to be used to find the last state for session secret key deriving Raises an exception if the dictionary is to short to contain a second highest key ...
def mult(p, a, n): """Multiplication of the provided values""" return p * a * n
def _to_camel_case(s): """Convert a property attribute name to camel case. """ return s[0] + s.title().replace("_", "")[1:]
def build_link_header(links): """ Builds a Link header according to RFC 5988. The format is a dict where the keys are the URI with the value being a dict of link parameters: { '/page=3': { 'rel': 'next', }, '/page=1': { 'rel': '...
def extract_numbers(value, type=str): """Extracts numbers only from a string.""" def extract(vs): for v in vs: if v in "01234567890.": yield v return type("".join(extract(value)))
def evaluate_game(mine, yours): """Determine who won the game based on the two strings mine and yours_lc. Returns three booleans (win, draw, void).""" ### Return with void at True if any input is None try: mine_lc = mine.lower() yours_lc = yours.lower() except AttributeError: ...
def dosta_phase_volt_to_degree(phase_volt): """ Description: Computes the DOCONCS-DEG_L0 data product from DOCONCS-VLT_L0, the analog output of a DOSTA Aanderaa Optode connected to a SBE CTD's 0-5 volt analog data channel. Usage: phase_degree = dosta_phase_volt_to_degree(phase_volt...
def get_line(p1, p2, x): """ Args: p1: point 1 p2: point 2 x: x coordinate Returns: y coordinate with respect to x """ x1, y1 = p1 x2, y2 = p2 y = (x - x1) / (x2 - x1) * (y2 - y1) + y1 return y
def count_valid_bases(seq): """Counts valid bases in sequence. Soft masked bases valid""" valid_bases = ['A', 'T', 'G', 'C'] valid_base_count = 0 for base in seq: if base not in valid_bases: continue else: valid_base_count += 1 continue return vali...
def is_batched(obj) -> bool: """ Returns ------- the `.batched` attribute of the settable/gettable `obj`, `False` if not present. """ return getattr(obj, "batched", False)
def sg_lookup(session, vpc_id, group_name): """Lookup the Id for the VPC Security Group with the given name. Args: session (Session|None) : Boto3 session used to lookup information in AWS If session is None no lookup is performed vpc_id (string) : VPC ID of the ...
def compress_zmem(z_mem, list_index_L2_by_mode, list_absindex_mode): """ This function compresses all of the memory terms into their respective slots for each L_operator. PARAMETERS ---------- 1. z_mem : list a list of all the memory terms in absolute basis 2. list_index_L2_b...
def sort_keywords(keywords): """Sort keywords in the proper order: i.e. glob-arches, arch, prefix-arches.""" def _sort_kwds(kw): parts = tuple(reversed(kw.lstrip('~-').partition('-'))) return parts[0], parts[2] return sorted(keywords, key=_sort_kwds)
def cpus_equal(a, b): """Compares cpu specs for equality. cpu specs can be ints, floats or strings '{:d}m', where 'm' denotes 'milli-', ie. 1/1000th of an integer value. Eg. "50m" is equal to 0.05.""" parse = lambda x: int(x[:-1])/1000. if x.endswith('m') else float(x) return parse(a) == parse(b)
def nic(intcode, n=None, v=None): """ Intcode (ic) interpreter.""" # Grab a copy of intcode since list are mutable. ic = intcode[:] ic[1] = n or ic[1] ic[2] = v or ic[2] for i in range(0, len(ic), 4): opcode = ic[i] if opcode == 99: return ic elif opcode ==...
def parse_url_for_post_data(url): """Split the url between url and data if needed""" url_splitted = url.split("/", 4) data = None if len(url_splitted) > 4: url = "/".join(url_splitted[0:4]) data = url_splitted[4] return url, data