content
stringlengths
42
6.51k
def string_to_glob(string): """Create case-insensetive search pattern from the string. For example: '.otf' => '.[oO][tT][fF]' """ return ''.join( '[{}{}]'.format(c.lower(), c.upper()) if c.isalpha() else c for c in string)
def _get_unit(sentence,index) : """Get the unit based on an index """ for unit in sentence : if unit[0] == index : return unit return None
def vis_options_merge(original, target): """Merge the target dict with the original dict, without modifying the input dicts. :param original: the original dict. :param target: the target dict that takes precedence when there are type conflicts or value conflicts. :return: a new dict containing referenc...
def cents_to_midi_bend(cents): """Cents to MIDI pitch bend value. :param cents: Cents :type cents: float :rtype: int **Reference** http://www.elvenminstrel.com/music/tuning/reference/pitchbends.shtml **Eamples** >>> cents_to_midi_bend(1.96) 80 >>> cents_to_midi_bend(47.41) ...
def _validrgb(r, g, b): """_validrgb(int, int, int) validate three ints as valid rgb values """ if type(r) == int and r > -1 and r < 256 and \ type(g) == int and g > -1 and g < 256 and \ type(b) == int and b > -1 and b < 256: return True else: return False
def resolve_task_field(task, field): """ Get task field from root or 'data' sub-dict """ if field.startswith('data.'): result = task['data'].get(field[5:], None) else: result = task.get(field, None) return result
def grompp_npt(job): """Run GROMACS grompp for the npt step.""" npt_mdp_path = "npt.mdp" msg = f"gmx grompp -f {npt_mdp_path} -o npt.tpr -c em.gro -p init.top --maxwarn 1" return msg
def buy(portfolio, ticker, ticker_price, amount): """Buys stocks for the bot's portfolio""" price = ticker_price * amount # ($) if portfolio['Cash'] > price: portfolio[ticker] += amount portfolio['Cash'] -= price return portfolio else: return portfolio
def validate_host(host): """ Checks the hostname four chunks separated by 3 dots each a valid integer(0 - 255) """ bits = host.split('.') try: if len(bits) != 4: raise ValueError for bit in bits: num = int(bit) if num > 255 or num < 0: ...
def _vimdiff(filepath, local_file_path, remote_file_path): """ Tried for a ludicrous amount of time to get it to open vimdiff automagically. Instead we settled on just letting user know what command they should run. """ command = "vimdiff -f -d -c 'wincmd J' {merged} {local} {remote}".format( ...
def SplitString(value): """simple method that puts in spaces every 10 characters""" string_length = len(value) chunks = int(string_length / 10) string_list = list(value) lstring = "" if chunks > 1: lstring = "\\markup { \n\r \column { " for i in range(int(chunks)): l...
def factorial(num): """Calculates the factorial of a number. Use pre-test repetition to write a function that computes the factorial of a number. A factorial of a number is the product of all the positive integers less than it. For example 4 factorial is 4 x 3 x 2 x 1 = 24 Args: num: ...
def digits(n, string=False): """Get the digits of a number as a list of numbers `string` if True, return a list of strings """ if string: list_of_digits = [digit for digit in str(n)] else: list_of_digits = [int(digit) for digit in str(n)] return list_of_digits
def filter(f, s): """Filter a sequence to only contain values allowed by filter. >>> def is_even(x): ... return x % 2 == 0 >>> def divisible_by5(x): ... return x % 5 == 0 >>> filter(is_even, [1,2,3,4]) [2, 4] >>> filter(divisible_by5, [1, 4, 9, 16, 25, 100]) [25, 100] ""...
def CreatePriceTableRow(header, description, final_url, price_in_micros, currency_code, price_unit, final_mobile_url=None): """Helper function to generate a single row of a price table. Args: header: A str containing the header text of this row. description: A str description of thi...
def standard_slices(problem_size, num_agents, overlap=0): """Create standard slices for a problem. We assume that the problem size is exactly divisible by the number of agents; hence all agents have exactly the same subproblem size. Parameters ---------- problem_size : int problem size...
def correct_sentence(text: str) -> str: """ returns a corrected sentence which starts with a capital letter and ends with a dot. """ if text[0].islower() == True: text = text[0].upper() + text[1:] if text[-1] != ".": text = text + "." return text
def type_nested(iterable, tp): """ Finds if array is of type tp (homogenous). Args: iterable (list): a list tp (type): type of iterable Returns: bool: If all are of same type. """ if iterable == []: return False return all(isinstance(item, tp) for item in iterable...
def persistence_diagram(f): """ compute PD being given a function f as a list of values (can typically be a time series) - f: a list (or a 1D numpy array) of POSITIVE values """ barcodes = [] n_points = len(f) sorted_f = sorted([(y,i) for i,y in enumerate(f)]) tmp = [[-1,0,0]]*n...
def build_request_dict_basic(tag, text): """Builds a dictionary matches the json structure of a Dialogflow request.""" request_mapping = {"fulfillmentInfo": {}} request_mapping["fulfillmentInfo"]["tag"] = tag request_mapping["text"] = text return request_mapping
def bash_array(lst): """Converts python array [a, b, c] to bash array (a b c)""" contents = ' '.join(str(x) for x in lst) return '({:s})'.format(contents)
def sanitize_column_list(input_column_list): """Remove empty elements (Nones, '') from input columns list""" sanitized_column_list = [input for input in input_column_list if input] return sanitized_column_list
def _create_id(data_set_id, record_id): """ The record_ids are not necessarily globally unique, because they're user provided and are only guaranteed to be unique within a collection. So that we have a unique primary key we're joining them with a colon. >>> _create_id('foo', 'bar') 'foo:bar' ...
def usb_bandwidth(nbytes: int, sec: float) -> str: """ :param nbytes: Total number of bytes (including headers and padding) transmitted over USB channel. :param sec: Total plot duration in seconds. """ bwidth = nbytes / sec for unit in ["B", "kB", "MB", "GB"]: if bwidth < 10 ** 3...
def gcdex(a, b): """Returns x, y, g such that g = x*a + y*b = gcd(a, b). Examples ======== >>> from ndindex._crt import gcdex >>> gcdex(2, 3) (-1, 1, 1) >>> gcdex(10, 12) (-1, 1, 2) >>> x, y, g = gcdex(100, 2004) >>> x, y, g (-20, 1, 4) >>> x*100 + y*2004 4 ""...
def get_first_val(key_tuple, dict_obj): """Return the first value mapped by a key in the given tuple. Parameters ---------- key_tuple : tuple The keys to use for extraction, in order. dict_obj : dict The dict to extract from. Returns ------- value : object The e...
def simplified_target(target): """ Returns two values based on contents of target string Args: target (str): string value of target_arrays variable in vars_file.yml Returns: str, str: Simplied values of alias found in target_arrays variable """ if '_prod_' in target: retur...
def policy_v2_0(probability=0.7, magnitude=5): """ Randomly select three transformations from all transformations""" policy = { # color augment 0: [[('Mixup', probability, magnitude)], [('Vignetting', probability, magnitude)], [('Gaussian_noise', probability, magnitude)], [('Saturati...
def get_bucket_key(uri): """Return bucket name and key from given S3 URI""" if uri.startswith("s3://"): uri = uri[5:] components = uri.split("/") bucket = components[0] key = "" if len(components) > 1: key = "/".join(components[1:]) return bucket, key
def positive_coin_types_to_string(coin_dict): """ Converts only the coin elements that are greater than 0 into a string. Arguments: coin_dict (dict): A dictionary consisting of all 4 coin types. Returns: (string): The resulting string. """ plat = "" gold = "" silver = "...
def smaller_root(a, b, c): """ Returns the smaller root of a quadratic equation with the given coefficients. """ dis = (b **2) - (4 * a * c) if dis < 0: return "Error: No real solutions" else: s = (-b - (dis ** 0.5)) / (2 * a) return s
def generate_key_value_pair(key, choices): """ Given a key from a list of choices, generate a key value pair :param key: A key from a list of choices, eg "in_review" :param choices: A list of tuples, matching the key with a display version of it :return: A key value pair of the key and its value, eg...
def _get_standard_imports(declaration: str) -> str: """Get group if imports from standard library. Currently only includes type annotations. """ type_imports = ", ".join( [ annotation for annotation in ("Any", "List", "Union") if annotation in declaration ...
def generate_parameter_defs(parameters): """ Generates verilog parameter definitions for the IOB cell model. """ verilog = [] for feature, parameter in sorted(parameters): verilog.append("parameter [0:0] {} = 1'b0;".format(parameter)) return "\n".join(verilog)
def traverse_list_fwd(head): """Prints all elements from head to tail in forward direction""" if head is None: return -1 curr = head arr = [] while curr.next != head: arr.append(curr.data) curr = curr.next arr.append(curr.data) return ' '.join(map(str, arr))
def sum_of_digits(number): """ What comes in: An integer. What goes out: The sum of the digits in the given integer. Side effects: None. Example: If the integer is 83135, this function returns (8 + 3 + 1 + 3 + 5), which is 20. """ # -------------------------------------------...
def get_cache_control(max_age): """Return a Cache-Control header for `max_age`.""" return "public, max-age={:d}".format(max_age)
def checkNone(obj): """Check if obj is None""" if obj is None: return True else: return False
def get_pairs(word): """Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
def indentLevel(line, spacesPerTab=4): """Counts the indent levels on the front. It is assumed that one tab equals 4 spaces. """ x = 0 nextTab = 4 for ch in line: if ch == ' ': x = x + 1 elif ch == '\t': x = nextTab nextTab = x +...
def factorize(n): """return factors of n where n > 0""" # basically just try each number from 1 to itself. if remainer == 0, then return it factors = [] for i in range(1, n + 1): if n % i == 0: factors.append(i) return factors
def g_test(w): """An easier function to debug the raw numerical output of.""" return w[0] ** 2 + w[1] ** 2
def ensure_final_value(packageName, arsc, value): """Ensure incoming value is always the value, not the resid androguard will sometimes return the Android "resId" aka Resource ID instead of the actual value. This checks whether the value is actually a resId, then performs the Android Resource look...
def tail(f, window=20): """ Taken from http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail Returns the last `window` lines of file `f` as a list. """ if window == 0: return [] BUFSIZ = 1024 f.seek(0, 2) bytes = f.tell() size = wind...
def is_websocket(headers): """ Determine whether a given set of headers is asking for WebSockets. """ return ("Upgrade" in headers.get("Connection", "") and headers.get("Upgrade").lower() == "websocket")
def byteListToU16leList(byteData): """Convert a byte array into a halfword array""" data = [] for i in range(0, len(byteData), 2): data.append(byteData[i] | (byteData[i + 1] << 8)) return data
def halo(colors): """ Set the four bottom/side LEDs to colors corresponding to the color spectrum on the outermost of the top 11 LEDs. """ used_leds = len(colors) # add additional RGB-Color-lists to the colors-list to fill up the top LEDs with emptiness colors += [[0, 0, 0]] * (11 - used_le...
def striptype(v): """Strips type information from repr of type(v) Args: v (Any): the value Returns: str """ if v is None: return 'Any' return str(type(v)).replace('<class ', '').replace('>', '').replace("'", '')
def contains_tokens(pattern): """Test if pattern is a list of subpatterns.""" return type(pattern) is list and len(pattern) > 0
def proximal(theta, marginal, a, b): """Compute proximal operator of MTW penalty (b * Lasso + a * KL(.|marginal))""" z = theta - a - b delta = (z ** 2 + 4 * a * marginal) ** 0.5 theta = (z + delta) / 2 return theta
def ceil_div(a: int, b: int) -> int: """ Return ceil(a / b). """ return a // b + (a % b > 0)
def _search(name, obj): """Breadth-first search for name in the JSON response and return value.""" q = [] q.append(obj) while q: obj = q.pop(0) if hasattr(obj, '__iter__'): isdict = isinstance(obj, dict) if isdict and name in obj: return obj[name] ...
def verb(dirty): """ Given a 'dirty' string (lowercased, with trailing whitespaces), strips it and returns it uppercased. """ return dirty.strip().upper()
def not_raises(UnexpectedException, target, *args, **kwargs): """raise AssertionError, if target code raises the given unexpected exception""" try: result = target(*args, **kwargs) except UnexpectedException as e: raise AssertionError("Call to %s raised %s: %s" % (target.__name__, e.__class_...
def topics_to_calldata(topics, bytes_per_topic=3): """Converts a list of topics to calldata. Args: topics (bytes[]): List of topics. bytes_per_topic (int): Byte length of each topic. Returns: bytes: Topics combined into a single string. """ return b''.join(topic.to_bytes(b...
def truncate_string(string: str, max_length: int = 2048, replace_value: str = '...') -> str: """Shortens string to a specified length.""" if len(string) > max_length: return string[:max_length - len(replace_value)] + replace_value return string
def first(seq, predicate, default=None): """ Return the first item in sequence that satisfies the callable, predicate, or returns the default if not found. :param seq: iterable sequence of objects :param predicate: callable that accepts one item from the sequence :param default: v...
def get_label_dict(task:str): """Returns the label dict for the task Args: task: one of 'a' , 'b' """ assert isinstance(task,str) task == task.lower() if task == 'a': task_a_label_dict = {'NAG':0, 'CAG':1, 'OAG':2} return task_a_label_dict elif task == 'b': ...
def get_frequencies(column): """ The purpose of this function is to get the count for how many times a value appeaars in a given column. Attributes: - column(list): a list of values in a column which will be checked for values and frequencies. Returns: - values, counts(tuple of lists): a tup...
def break_up_ipv4_address_space(num_threads=8): """ >>> break_up_ipv4_address_space() == \ [('0.0.0.0', '31.255.255.255'), ('32.0.0.0', '63.255.255.255'),\ ('64.0.0.0', '95.255.255.255'), ('96.0.0.0', '127.255.255.255'),\ ('128.0.0.0', '159.255.255.255'), ('160.0.0.0', '191.255.255.255'),\ (...
def compare_values(values0, values1): """Compares all the values of a single registry key.""" values0 = {v[0]: v[1:] for v in values0} values1 = {v[0]: v[1:] for v in values1} created = [(k, v[0], v[1]) for k, v in values1.items() if k not in values0] deleted = [(k, v[0], v[1]) for k, v in values0....
def split_string(string, char_split="-"): """ Split char based on char_split Parameters ---------- string : string string to be split char_split : string characters used for the spliting Returns ------- string splited : list a list with all splited members ...
def from_internal(message): """returns True if this message was sent by an internal user, else False""" return message.get("from_internal", False)
def sort_data(data, index=None): """ Function to sorted by name :param data: list(list(), list()) :param index: int :return: ordered list """ if not index: return sorted(data, key=lambda x: x[0]) else: return sorted(data, key=lambda x: x[index], reverse=True)
def build_composite_expr(query_values, entity_name, date): """Builds a composite expression with ANDs in OR to be used as MAG query. Args: query_values (:obj:`list` of :obj:`str`): Phrases to query MAG with. entity_name (str): MAG attribute that will be used in query. date (:obj:`tuple` ...
def custom(n): """ Returns true if the field name is not in the person, address, contact, donation.""" nDown = n.lower() return "person." not in nDown and "address." not in nDown and "contact." not in nDown and "donation." not in nDown
def parse_group_images(data): """ Returns a list of group images. @parameter{data,dict} """ images_group = [] for group in data['images_group']: for image in group['images']: images_group.append(image) return images_group
def pointobb2bbox(pointobb): """convert pointobb to bbox Args: pointobb (list): [x1, y1, x2, y2, x3, y3, x4, y4] Returns: list: [xmin, ymin, xmax, ymax] """ xmin = min(pointobb[0::2]) ymin = min(pointobb[1::2]) xmax = max(pointobb[0::2]) ymax = max(pointobb[1::2]) b...
def hoya(lmbda, A0, A1, A2, A3, A4, A5): """ Estimate refractive index of glass with wavelength. Using the Hoya equation. Input: lmbda : wavelength A(1-5) : A coefficients of glass Returns: n : Fitted refractive index """ n_squ = A0 + A1*lmbda**2 + A2*lmbda**-2 + A3*lmbda*...
def sort_batch_contributions(contributions): """Returns the list of contributions sorted by creation date (old -> young) and score (high -> low). """ by_creation = sorted(contributions, key=lambda x: x["created"]) by_score = sorted(by_creation, key=lambda x: x["score"], reverse=True) return by_...
def convert_args_to_list(args): """Convert all iterable pairs of inputs into a list of list""" list_of_pairs = [] if len(args) == 0: return [] if any(isinstance(arg, (list, tuple)) for arg in args): # Domain([[1, 4]]) # Domain([(1, 4)]) # Domain([(1, 4), (5, 8)]) ...
def split_escaped(string, split_char=' ', escape_char='\\'): """ Splits escaped string :param string: String to split :param split_char: Character to split on. Defaults to single space :param escape_char: Character to escape with. Defaults to \ """ ret = [] current = '' skip = False ...
def gate_error_to_irb_decay(irb_error: float, rb_decay: float, dim: int): """ For convenience, inversion of Eq. 4 of [IRB]_. See :func:`irb_decay_to_error`. :param irb_error: error of the interleaved gate. :param rb_decay: Observed decay parameter in standard rb experiment. :param dim: Dimensi...
def toggle_endianness(values): """Toggle endianness of values :param values: list of bytes, ints ... :return: values with other endianness (little -> big, big -> little) """ return list(reversed(values))
def _get_volume_property(key, node_name, container_requirements): """Returns a property from the relationship definition of a requirement """ requirements = [ required["volume"] for required in container_requirements if "volume" in required ] for required in requirements: ...
def case_insensitive(string): """ :param string: str, a character. :return: lst, a lower character lst. """ new_string = '' for ch in string: if ch.islower(): new_string += ch else: new_string += ch.lower() return new_string
def format_error_string(stacktrace_str): """Return a formatted exception.""" # return '["e", "{}"]'.format(stacktrace_str.replace('"', '""')) return ("e", stacktrace_str)
def _EscapePosixShellArgument(arg): """Escapes a shell command line argument so that it is interpreted literally. Args: arg: The shell argument to escape. Returns: The escaped string. """ return "'%s'" % arg.replace("'", "'\\''")
def sb_sort_fn_list(fn_list): """ sort the file name list to xml, edi, png :param fn_list: list of files to sort :type fn_list: list :returns: sorted list ordered by xml, edi, png, zip files """ fn_list_sort = [None, None, None] index_dict = {"xml": 0, "edi": 1, "png": 2} for ext...
def save_list(test, filename="../database/r1h.vrtl", exp=True): """ Saves the dictionary containing the commands information into a special file (.vrtl) to be imported in a second time. """ languages = [] for i in test.keys(): languages.append(i) if not exp: with open("config...
def unique_layers(layers): """return layers with unique blobSum""" seen_sums = [] un_layers = [] for layer in layers: blobSum = layer["blobSum"] if blobSum in seen_sums: continue seen_sums.append(blobSum) un_layers.append(layer) return un_layers
def to_camel(snake): """time_skill -> TimeSkill""" return snake.title().replace("_", "")
def del_target_name(prefix='', rconn=None): """Return True on success, False on failure""" if rconn is None: return False try: rconn.delete(prefix+'target_name') except: return False return True
def get_input_path_parameters(path): """"Get the input parameters from the path url.""" path_params = [] params = path.split('/') for param in params: if len(param) > 0 and param[0] == '{' and param[len(param) - 1] \ == '}': path_params.append(param[1:-1]) return ...
def oridam_generate_patterns(word_in, cm, ed=1, level=0, pos=0, candidates=None): """ ed = 1 by default, pos - internal variable for algorithm """ alternates = cm.get(word_in[pos], []) if not candidates: candidates = [] assert ed <= len( word_in ), "edit distance has to be comparable...
def interpret_abbreviation(user_input): """ Get shortcut and returns the real value ------- Returns str The option of the user as a complete string """ if user_input == "r": user_input = "rock" if user_input == "s": user_input = "scissors" if user_input == "p":...
def FibonacciSearch(arr, x, n): """ Inputs => arr - A sorted array in which we're going to search for the key x - The number to be searched for n - Size of the array ======================================================================= Output => Single integer The index of the key ...
def merge_label_equivalent(input_dict): """ A function return output dict after merge all label equivalent @param: - input_dict (a collection label key with another key set value before merge) @return: - output dict after merge all label equivalent """ output...
def linear_rank(A, k): """return the number of elements less than or equal to k in O(n) time""" n = len(A) i = 0 while i < n and k > A[i]: i += 1 return i
def get_dataset_filename(ds_dict): """Figure out the downloaded filename for a dataset entry if a `file_name` key is present, use this, otherwise, use the last component of the `url` Returns the filename Examples -------- >>> ds_dict = {'url': 'http://example.com/path/to/file.txt'} >>...
def PortToTag(switch, port): """Returns the tag for a port.""" return 'switches.%s.%d' % (switch, port)
def _ConvertPercentToAbsolute(total_value, percent): """Given total value and a 100-based percentage, returns the actual value.""" return percent / 100 * total_value
def nonZeroMean(arr): """Takes the mean of an array not counting None or 0 values.""" total = 0 count = 0 for x in arr: if x is not None and x != 0: total, count = total + x, count + 1 count = 1 if count == 0 else count return round(total / count, 2)
def deb_kernel_package(name, kernel_version, arch): """ Check if kernel version match. Args: name (str): package name. kernel_version (str): Kernel version to install. arch (str): Architecture. Returns: str: Package name. """ package = "%s-%s" % (name, kernel_ve...
def _parse_ports(port_str): """ Cleans port data from docker ps. Unit tested: test__parse_ports :param port_str: The string of ports from the docker ps output. :type port_str: str :returns: The ports broken into a list. :rtype: list """ port_str = port_str.strip() if port_str ==...
def cumulativeCountChildren(counts, folder, depth): """ Cumulative counts per folderID and returns the total counters for the number of files and folders within the folderID """ childrenFolders = folder.get('childrenFolders', []) childrenFiles = folder.get('childrenFiles', []) folderID = fol...
def get_file_type(filename): """ Return the extension (if any) of the ``filename`` in lower case. """ return filename[filename.rfind('.')+1:].lower()
def inverse_filter_dict(dictionary, keys): """Filter a dictionary by any keys not given. Args: dictionary (dict): Dictionary. keys (iterable): Iterable containing data type(s) for valid dict key. Return: dict: Filtered dictionary. """ return {key: val for key, val in dictio...
def median_of_3( array: list, first_index: int, middle_index: int, last_index: int ) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> median_of_3(array, 0, 0 + ((len(array) - 0) // 2) + 1, len(array) - 1) 12 """ if (array[first_index] > array[middle_inde...
def fizz(until_n): """Return the list of numbers starting from 1 up to `until_n` replacing multiples of 7 by the word "Fizz" eg fizz(20) should return: [1, 2, 3, 4, 6, "Fizz", 8, 9 10, 11, 12, 13, "Fizz", 15, 16, 17, 18, 19, 20] """ result = [] n = 1 while n <= until_n: ...