content
stringlengths
42
6.51k
def polygon (points, extrude=0): """ Function translate return openscad polygon command @param points: points of the polygon """ if extrude > 0: extrude = "linear_extrude(height={})".format(extrude) else: extrude = "" return "{} polygon(points={});".format(extrude, points)
def create_equation_from_terms(terms): """ Create a string equation (right hand side) from a list of terms. >>> create_equation_from_terms(['x','y']) 'x+y' >>> create_equation_from_terms(['-x', 'y', '-z']) '-x+y-z' :param terms: list :return: str """ if len(terms) == 0: ...
def extract_objective(objective_field): """Extract the objective field id from the model structure """ if isinstance(objective_field, list): return objective_field[0] return objective_field
def findAllOfStyle( cls, forms ) : """ Find all the occurences of a guven style class from a list of style classes. """ formsFound = [] for form in forms : if( isinstance( form, cls ) ) : formsFound.append( form ) return( formsFound )
def list_all_items_inside(_list, *items): """ is ALL of these items in a list? """ return all([x in _list for x in items])
def deriv1(x, y, i, n): """ Alternative way to smooth the derivative of a noisy signal using least square fit. In this method the slope in position 'i' is calculated by least square fit of 'n' points before and after position. Required Parameters ---------- x : array of x axis y : a...
def one(iterable): """Return the single element in iterable. Raise an error if there isn't exactly one element. """ item = None iterator = iter(iterable) try: item = next(iterator) except StopIteration: raise ValueError('Iterable is empty, must contain one item') try: next(iterator) except StopIteration...
def binary_search_by_recursion(sorted_collection, item, left, right): """Pure implementation of binary search algorithm in Python by recursion Be careful collection must be ascending sorted, otherwise result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_coll...
def parse_imag(data): """returns real and imaginary components""" real = [n.real for n in data] imag = [n.imag for n in data] return real, imag
def ravel(nlabel_list): """ only up to 2D for now. """ if not isinstance(nlabel_list, list): return nlabel_list raveled = [] for maybe_list in nlabel_list: if isinstance(maybe_list, list): for item in maybe_list: raveled.append(item) else: ...
def check_for_real_numbers(value): """check if inputed value is a real number""" val = value if value[0] == '-': val = value[1:len(value)] if val.find("."): if (val.replace(".", "1", 1)).isnumeric() is False: return False else: if val.isnumeric(): retu...
def stability_selection_to_threshold(stability_selection, n_boots): """Converts user inputted stability selection to an array of thresholds. These thresholds correspond to the number of bootstraps that a feature must appear in to guarantee placement in the selection profile. Parameters --------...
def evaluate(x,y): """ Evaluates Rosenbrock function. @ In, x, float, value @ In, y, float, value @ Out, evaluate, value at x, y """ return (1- x)**2 + 100*(y-x**2)**2
def make_iterable(a): """ Check if a is iterable and if not, make it a one element tuple """ try: iter(a) return a except TypeError: return (a, )
def has_pattern(guesses, pattern): """Return True if `guesses` match `pattern`.""" result = len(guesses) >= len(pattern) if result: for guess, check in zip(guesses, pattern): result = result and guess.has(**check) if not result: break return result
def format_element(eseq): """Format a sequence element using FASTA format (split in lines of 80 chr). Args: eseq (string): element sequence. Return: string: lines of 80 chr """ k = 80 eseq = [eseq[i:min(i + k, len(eseq))]for i in range(0, len(eseq), k)] return("\n".join(eseq))
def score_seating(seating, preferences): """Score seating using preferences.""" score = 0 table_size = len(seating) for index, name in enumerate(seating): for seat_index in ((index - 1) % table_size, (index + 1) % table_size): seating_by = seating[seat_inde...
def run_length_encode(s): """ Return run-length-encoding of string s, e.g.:: 'CCC-BB-A' --> (('C', 3), ('-', 1), ('B', 2), ('-', 1), ('A', 1)) """ out = [] last = None n = 0 for c in s: if c == last: n += 1 else: if last is not None: ...
def safeissubclass(cls, cls_or_tuple): """Like issubclass, but if `cls` is not a class, swallow the `TypeError` and return `False`.""" try: return issubclass(cls, cls_or_tuple) except TypeError: # "issubclass() arg 1 must be a class" pass return False
def split_section(input_file, section_suffix, test_function): """ Split a pipfile or a lockfile section out by section name and test function :param dict input_file: A dictionary containing either a pipfile or lockfile :param str section_suffix: A string of the name of the section :para...
def to_bytes(value): """ returns 8-byte big-endian byte order of provided value """ return value.to_bytes(8, byteorder='big', signed=False)
def remove_key(d, key): """ Remove an entry from a dictionary . """ r = d.copy() del r[key] return r
def is_gzipped(file_location): """ Determines whether or not the passed file appears to be in GZIP format. ARGUMENTS file_location (str): the location of the file to check RETURNS gzipped (bool): whether or not the file appears to be in GZIP format """ GZIP = ".gz" if fil...
def ssh_url_to_https_url(url: str) -> str: """Convert git ssh url to https url :param url: ssh url to be converted :return: Returns git https url as string """ if ".git" in url[-4:]: return url.replace(":", "/", 1).replace("git@", "https://") return url.replace(":", "/", 1).replace("g...
def read_record(file_path, default=None): """ Reads the first line of a file and returns it. """ try: f = open(file_path, 'r') try: return f.readline().strip() finally: f.close() except IOError: return default
def cost_memory_removed(size12, size1, size2, k12, k1, k2): """The default heuristic cost, corresponding to the total reduction in memory of performing a contraction. """ return size12 - size1 - size2
def str_to_latex(string): """do replacements in ``string`` such that it most likely compiles with latex """ #return string.replace('\\', r'\textbackslash{}').replace('_', '\\_').replace(r'^', r'\^\,').replace(r'%', r'\%').replace(r'~', r'\ensuremath{\sim}').replace(r'#', r'\#') return string.replace('\\', r...
def linear_approximation_complex(x, x1, y1, x2, y2): """Linear approximation for complex arguments""" return complex((y1.real - y2.real) / (x1 - x2) * x + (y2.real * x1 - x2 * y1.real) / (x1 - x2), (y1.imag - y2.imag) / (x1 - x2) * x + (y2.imag * x1 - x2 * y1.imag) / (x1 - x2))
def cleanup_authorizer(authorize): """Given a dictionary of a comment authorizer record, return a new dictionary for output as JSON.""" auth_data = authorize auth_data["id"] = str(auth_data["_id"]) auth_data["authorizer"] = str(auth_data["authorizer"]) auth_data["authorized"] = str(auth_data["...
def d(value): """ Discretizes variables that are > 0, sets them to zero if < 1 Args: alue(float): value to be discretized Returns (float): discretized value """ if value < 1: return 0 else: return value
def get_class_name(obj) -> str: """ Get an arbitrary objects name. :param obj: any object :return: name of the class of the given object """ return obj.__class__.__name__
def adjust_timestamp_from_js_to_python(jsTimestamp): """ javascript and python produce slightly different POSIX timestamps. This converts the javascript timestamps to python. args: jsTimestamp: this should come from the client. It will probably be the output of Date.now() retur...
def _tag_depth(path, depth=None): """Add depth tag to path.""" # All paths must start at the root if not path or path[0] != '/': raise ValueError("Path must start with /!") if depth is None: depth = path.count('/') return "{}{}".format(depth, path).encode('utf-8')
def serialize_func(fun, args): """ Serializes callable object with arguments :param fun: callable object :param args: arguments :return: dictionary with 'module', 'fun' and 'args' """ return { 'module': fun.__module__, 'fun': fun.__name__, 'args': args }
def TokenFromUrl(url): """Extracts the AuthSub token from the URL. Returns the raw token value. Args: url: str The URL or the query portion of the URL string (after the ?) of the current page which contains the AuthSub token as a URL parameter. """ if url.find('?') > -1: query_params = url.s...
def msg_to_array(msg): """ convert string to lowercased items in list """ return [word.strip().lower() for word in msg.strip().split()]
def fixme_pattern(word): """ It is essential to have same pattern between build.py and mmd2doc.py, so keeping pattern construction here """ # **OPEN**: blah # OPEN[John Doe]: blah blah # **OPEN[John Doe]:** blah blah # <mark>OPEN[John Doe]:</mark> blah blah # <mark>OPEN[John Doe]</ma...
def check_col(board, num_rows, num_cols): """check if any 4 are connected vertically(in 1 column) returns bool""" won = False for row in range(num_rows - 3): for col in range(num_cols): start = board[row][col] if start == " ": continue won ...
def getValue(dictionary, key, value): """ Returns the value for the key in the dictionary or the default. :param dict dictionary: :param object key: :param object value: :return object: """ if not key in dictionary.keys(): return value else: return dictionary[key]
def check_managability(user, note, action): """ Determine if user can edit or delete this note. This note can be edited or deleted if at least one of the following criteria is met: - user is an admin - user is the author of the note - user is member of a group in groups AND note is p...
def to_list(value): """ Create an array from any kind of object """ if value is None: return [] initial_list = [x.strip() for x in value.translate(None, '!@#$[]{}\'"').split(',')] return [x for x in initial_list if x]
def to_csv_str(s: str): """Escapes a string that is supposed to be written to a csv file""" return s.replace('\n', '\\n')
def extract_z(lst): """ Extract z coordinate from list with x, y, z coordinates :param lst: list with [[x, y, z], ..., [x, y, z]] :return: list with z coordinates [x, ..., x] """ return [item[2] for item in lst]
def crunchHomopolymers(motifList): """ Take as input a list of target motifs, collapse poly-nucleotide tracks, return list of collapsed motifs. """ # List to catch all collapsed motifs. crunchList = list() # For each motif for motif in motifList: # Create empty list to catch not repe...
def binarize(threshold=0.5): """ binarize the tensor with a fixed threshold, values above the threshold will be set to one, values below the threshold to zero """ dict_binarize = {'name': 'binarize', 'kwargs': {'threshold': threshold} } return dict_binari...
def q_to_nu(q): """Convert mass ratio (>= 1) to symmetric mass ratio.""" return q / (1. + q)**2.
def mag2counts(mag, band): """ Converts AB magnitudes to GALEX counts per second. See: http://asd.gsfc.nasa.gov/archive/galex/FAQ/counts_background.html :param mag: The AB magnitude to convert. :type mag: float :param band: The band to use, either 'FUV' or 'NUV'. :type band: str ...
def get_slice(seq, start=0, stop=None, step=1): """Get a slice of a sequence with variable step. Specify start,stop,step.""" if stop == None: stop = len(seq) item = lambda i: seq[i] return list(map(item,range(start,stop,step)))
def minmax(data): """ Return a pair (min, max) of list arg """ lo = 0 hi = 0 for i in data: if i > hi: hi = i if i < lo: lo = i return lo, hi
def parse_version(version): """convert version to int""" if version is None: raise ValueError("sbe:messageSchema/@version is required") return int(version)
def _inject_args(sig, types): """ A function to inject arguments manually into a method signature before it's been parsed. If using keyword arguments use 'kw=type' instead in the types array. sig the string signature types a list of types to be inserted Returns the altered signature. """ i...
def addStationRiverID(station, riverIDs): """Adds river ID to station dictionary.""" stationID = station["id"] riverID = riverIDs.get(stationID) station["riverId"] = riverID return station
def rotate_list(l): """ Rotate a list of lists :param l: list of lists to rotate :return: """ return list(map(list, zip(*l)))
def format_discord_str(discord_id: int, type_chars: str) -> str: """Formats an ID into a Discord's representation of a channel / role / user mention.""" return f"<{type_chars}{discord_id}>"
def calculate_amortization_amount(principal: float, interest_rate: float, period: int) -> float: """ Calculates Amortization Amount per period :param principal: Principal amount :param interest_rate: Interest rate per period :param period: Total number of period :return: Amortization amount per...
def reverse_string(s): """ Reverses order or characters in string s. """ return s[::-1]
def beta_expval(alpha, beta): """ Expected value of beta distribution. """ return 1.0 * alpha / (alpha + beta)
def _sort_and_merge_sub_arrays(left_array, right_array): """This method assumes elements in `left_array` and `right_array` are already sorted. Parameters ---------- left_array: list[int] right_array: list[int] Returns ------- list: merged and sorted list """ left_array_le...
def listprepender(lista, field='user'): """ Prepend a first element to all elements in lista lista = ['A', 'B', 'C'] field = ['X'] returns -> [['X','A'], ['X', 'B'], ['X,'C']] """ out = [] for s in lista: s.insert(0, field) out.append(s) return out
def model_as_json(bot_entries): """ Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB @param bot_entries (list) list of sub-lists @returns json_list (list) list of modeled dictionaries ...
def str_lower(value: str) -> str: """Converts a string to all lower case. Parameters ---------- value : str The string to turn to lower case. Returns ------- str The lower case string. """ return value.lower()
def _check_variable_names(names): """ checks variable names :param names: list of names for each feature in a dataset. :return: """ assert isinstance(names, list), '`names` must be a list' assert all([isinstance(n, str) for n in names]), '`names` must be a list of strings' assert len(nam...
def secs_to_human(seconds): """Convert a number of seconds to a human readable string, eg "8 days" """ assert isinstance(seconds, int) or isinstance(seconds, float) return "%d days ago" % int(seconds / 86400)
def generate_product_id(smooth, constant=None, initial_product_id='0000'): """ Parameters ---------- smooth: int constant: None or not None initial_product_id: str Returns ------- str new 4 chars product id. - 1st char: 'Z' if smooth >= 1, or 'C' if constant is not...
def _get_compute_id(local_ips, id_to_node_ips): """ Compute the instance ID of the local machine. Expectation is that our local IPs intersect with one (only) of the remote nodes' sets of IPs. :param set local_ips: The local machine's IPs. :param id_to_node_ips: Mapping from instance IDs to set...
def hello(msg="World"): """Function that prints a message. :param msg: message to say :type msg: string :returns: string :raises: something .. note:: You can note something here. .. warning:: You can warn about something here. >>> hello() Hello World! >>> hello(...
def get_gimbal_data(rotate_order): """ Get detail information about the gimbal data based on the current rotate order @param rotate_order: (str) The current rotate order @return: dict of gimbal data """ return {"bend": rotate_order[0], "roll": rotate_order[1], "twist": rotate_order[2]}
def check_strands(hsp_objs, fwd_strand): """Return True if hsps in the list are not all on the same strand. """ hsps_on_different_strands = False for hsp in hsp_objs: x = True if hsp.hit_frame < 0: x = False if x != fwd_strand: hsps_on_different_strands = ...
def range_sub(amin, amax, bmin, bmax): """A - B""" if amin == bmin and amax == bmax: return None if bmax < amin or bmin > amax: return 1 if amin < bmin: if amax > bmax: return [(amin, bmin), (bmax, amax)] else: return [(amin, bmin)] else: ...
def get_value(it): """ Simplest function for explicit outing of range :param it: parsing result :return: """ return it[0] if len(it) > 0 else ''
def plaintext2toc(plaintext: str) -> list: """ :param plaintext: plaintext :return: table of content -> DOCUMENT.get_toc() """ toc = [] contents = plaintext.split('\n') for content in contents: if len(content) != 0: c = content.split('-->') t = [len(...
def make_command_summary_string(command_summaries): """Construct subcommand summaries :param command_summaries: Commands and their summaries :type command_summaries: list of (str, str) :returns: The subcommand summaries :rtype: str """ doc = '' for command, summary in command_summaries...
def different_ways_memoization(n): """Memoization implementation of different ways, O(n) time, O(n) max stack frames, O(n) pre-allocated space""" d = [0] * (n + 1) d[0] = 1 def different_ways_memoization_helper(k): if k < 0: return 0 if d[k] == 0: d[k] = differen...
def parse_maddr_str(maddr_str): """ The following line parses a row like: {/ip6/::/tcp/37374,/ip4/151.252.13.181/tcp/37374} into ['/ip6/::/tcp/37374', '/ip4/151.252.13.181/tcp/37374'] """ return maddr_str.replace("{", "").replace("}", "").split(",")
def xround(value: float, rounding: float = 0.) -> float: """ Extended rounding function, argument `rounding` defines the rounding limit: ======= ====================================== 0 remove fraction 0.1 round next to x.1, x.2, ... x.0 0.25 round next to x.25, x.50, x.75 or x.00 ...
def _lwp3_uuid(short: int) -> str: """Get a 128-bit UUID from a ``short`` UUID. Args: short: The 16-bit UUID. Returns: The 128-bit UUID as a string. """ return f"0000{short:04x}-1212-efde-1623-785feabcd123"
def to_float(i): """Convert to a float.""" if isinstance(i, list): return [to_float(j) for j in i] if isinstance(i, tuple): return tuple(to_float(j) for j in i) return float(i)
def reverseDict(myDict): """Makes a new dictionary, but swaps keys with values""" keys = myDict.keys() values = myDict.values() retDict = dict() for k in keys: retDict[myDict[k]] = k return retDict
def is_integer(num): """ Returns True if the num argument is an integer, and False if it is not. """ try: num = float(num) except ValueError: return False return num.is_integer()
def mean(ls): """ Takes a list and returns the mean. """ return float(sum(ls))/len(ls)
def le_power_of_2(num): """ Gets a power of two less than or equal to num. Works for up to 64-bit numbers. """ num |= (num >> 1) num |= (num >> 2) num |= (num >> 4) num |= (num >> 8) num |= (num >> 16) num |= (num >> 32) return num - (num >> 1)
def _tls_version_check(version, min): """Returns if version >= min, or False if version == None""" if version is None: return False return version >= min
def setWordsProdosy(words, phons): """set word prosody according to phons break""" prosodys = ['#', '*', '$', '%'] new_words = [] for i in range(len(words)): cur_prosody = '' if phons[i][-1] in prosodys: cur_prosody = phons[i][-1] new_words.append(words[i] + cur_proso...
def macro_link(*args) -> str: """Creates a clickable hyperlink. Note: Since this is a pretty new feature for terminals, its support is limited. """ *uri_parts, label = args uri = ":".join(uri_parts) return f"\x1b]8;;{uri}\x1b\\{label}\x1b]8;;\x1b\\"
def remove_null_fields(data): """Remove all keys with 'None' values""" for k, v in data.items(): if isinstance(v, dict): remove_null_fields(v) if isinstance(v, list): for element in v: remove_null_fields(element) if not data[k]: del dat...
def sort_stack(stack_object: list) -> list: """ Sorts stack. :param stack_object: stack object, iterable object :return: sorted stack, iterable object """ tmp_stack = [] while stack_object: # complexity check print(f'stack 1') element = stack_object.pop(-1) w...
def _write_text(file, text): """ Write to file in utf-8 encoding.""" with open(file, mode='w', encoding='utf-8') as f: return f.write(text)
def formatNumber(number): """Ensures that number is at least length 4 by adding extra 0s to the front. """ temp = str(number) while len(temp) < 4: temp = '0' + temp return temp
def is_unique(s: str) -> bool: """ >>> is_unique('ABCDE') True """ """ >>> is_unique('programmer') False """ arr = [False for _ in range(128)] #creating hashtable with False input for character in s: #iterate throughout the string char_value = ord(charact...
def parse_number(number): """Parse the number.""" try: return int(number) except (TypeError, ValueError) as e: return {"zero": 0, "one": 1, "first": 0}.get(number, number)
def fib_memoized(n): """Find the n-th fibonacci number, recursively, but using memoization.""" if n < 1: return 0 fibs = [0, 1] + (n - 2) * [-1] def fib_inner(n): if fibs[n] == -1: fibs[n] = fib_inner(n - 1) + fib_inner(n - 2) return fibs[n] # note the n - 1, b...
def ratio(value): """Returns single-digit ratio""" try: value = float(value) except (ValueError, TypeError, UnicodeEncodeError): return '' return '{0:0.1f}'.format(value)
def csvlist(value: str, index: int) -> str: """Returns a single value from a comma separated list of values""" return str(value).split(',')[index]
def calculate_jaccard(loads): """Compute the jaccard across all loads Must pass in just a list of load_sets without additional metadata """ union_all = set() intersection_all = loads[0] for load in loads: union_all = union_all.union(load) intersection_all = intersection_all.int...
def percentile_from_dict(D, P): """ Find the percentile of a list of values @parameter N - A dictionary, {observation: frequency} @parameter P - An integer between 0 and 100 @return - The percentile of the values. """ assert 0 < P <= 100, "Percentile must be in range (0, 100)" N = sum(...
def rename_fields_from_feature_collection(feature_collection): """This function renames feature collection keys to leave it according to STAC 9.0 and it is returned""" if 'meta' in feature_collection: # rename 'meta' key to 'context' feature_collection['context'] = feature_collection.pop('meta'...
def _preprocess_dn(original_dn): """ Reverse the DN and replace slashes with commas """ # remove leading slash dn = original_dn[1:] dn = dn.split('/') dn = dn[::-1] dn = ", ".join(dn) return dn
def V0_rel_diff(v0w, b0w, b1w, v0f, b0f, b1f, config_string, prefact, weight_b0, weight_b1): """ Returns the relative difference in the volumes. THE SIGNATURE OF THIS FUNCTION HAS BEEN CHOSEN TO MATCH THE ONE OF ALL THE OTHER FUNCTIONS RETURNING A QUANTITY THAT IS USEFUL FOR COMPARISON, THIS SIMPLIFIES ...
def add_next (res_comb): """ Generates all the possible permutations by calling itself""" l = [] for item in res_comb [0]: if len (res_comb) > 1: new = add_next (res_comb [1:]) for item2 in new: l.append (item + item2) else: l.append (item)...
def subclasstree(cls): """Return dictionary whose first key is the class and whose value is a dict mapping each of its subclasses to their subclass trees recursively. """ classtree = {cls: {}} for subclass in type.__subclasses__(cls): # long version allows type classtree[cls].update(sub...