content
stringlengths
42
6.51k
def combine_envs(*envs): """Combine zero or more dictionaries containing environment variables. Environment variables later from dictionaries later in the list take priority over those earlier in the list. For variables ending with ``PATH``, we prepend (and add a colon) rather than overwriting. If...
def serialize_json(msg: dict) -> bytes: """ create a compact sorted rendering of a json object since micropython implementation of ujson.dumps does not support sorted keys :param msg: the json object (dict) to serialize :return: the compact sorted rendering """ serialized = "{" for key i...
def check_valid_domain(domain, valid_domains): """Check if the logged-in user comes from a valid domain.""" if domain in valid_domains: return True return False
def get_resource_name(rule): """Returns resourceName from endpoint Args: rule (str): the endpoint path (e.g. '/v1/data') Returns: (str): the resource name Examples: >>> rule = '/v1/data' >>> get_resource_name(rule) 'data' """ url_path_list = [p for p in...
def sqreuclidean_distance(input1: list, input2: list): """ function that calculates the squared euclidean distance for our task :param input1: instance 1 :param input2: instance 2 :return: distance """ distance = 0 for i in range(len(input1)-1): distance += pow(input1[i] - input2...
def join_tag_version(name, version): """ Join the root and version of a tag back together. """ return '{0}-{1}'.format(name, version)
def redirect(url: str, perm: bool = True) -> bytes: """Send a 3x (redirect) response. :param url: The URL to redirect to. :param perm: Whether this is a permanent redirect. :return: Bytes to be sent to the client. """ code = 31 if perm else 30 return f'{code} {url}\r\n'.encode()
def load_line_slope(sa_, sm_): """ Computes the slope of the load line :param sa_: alternating load :param sm_: midrange load :return: """ return sa_ / sm_ * 300;
def bytes_rjust(x: bytes, width: int, fill: bytes) -> bytes: """Given a bytes object, a line width, and a fill byte, right-justifies the bytes object within the line. Compiling bytes.rjust compiles this function. This function is only intended to be executed in this compiled form. Checking the fill len...
def median(x): """Find the median of a sample by sorting the sample and then returning the middle element.""" x = sorted(x) # Sort the sample n = len(x) middle = n // 2 if n % 2 == 0: # If there's an even number of elements, the median is an average of the two middle values return 0...
def truncate_val(val, lower_bound, upper_bound): """Truncate val to be in the range [lower_bound, upper_bound].""" val = max(val, lower_bound) val = min(val, upper_bound) return val
def round_charge(xml): """Round charge fields in a serialized OpenMM system to 2 decimal places""" # Example Particle line: <Particle eps=".4577296" q="-.09709000587463379" sig=".1908"/> xmlsp = xml.split(' q="') for index, chunk in enumerate(xmlsp): # Skip file before first q= if in...
def max_index(numbers): """ Returns the largest number in the given list of numbers :param numbers: list(int) or list (float) or list(str) :return: int or float or str """ max_value = 0 result = 0 for i in numbers: current_value = abs(float(i)) if current_value > max_val...
def _get_int(value): """Encode python int type to bson int32/64.""" if -2147483648 <= value <= 2147483647: return "int" else: return "long"
def is_header(line, name): """only the first 4 chancters are read, but we're going to ensure all the letters are correct""" return line.startswith(name[:4]) and line == name[:len(line)]
def bisect(list_, x, begin=0, end=None): """ Return the insertion point for x to maintain sorted order, in logarithmic time. list_ -- the sorted list of items; we assume ascending order by default x -- the item we search for begin -- the first index of the range we want to search in en...
def _flatten(name): """Convert characters {dot, dash} to underscore. Args: name: string - The string to replace. Returns: string - The replaced string. """ return name.replace(".", "_").replace("-", "_")
def _tf_vpc_config(lambda_config): """Compute VPC configuration from the Lambda config.""" result = {} vpc_config = lambda_config.get('vpc_config', {}) if not vpc_config: return result if 'security_group_ids' in vpc_config: result['vpc_security_group_ids'] = vpc_config['security_gro...
def GetSchemeHostPort(environ): """Reconstructs scheme, host and port from wsgi environment. Args: environ: environment variables dictionary. Returns: reconstructed part of URI: scheme://host:port. """ url = "{}://".format(environ["wsgi.url_scheme"]) if environ.get("HTTP_HOST"): url += environ...
def form_openid_url(url, username): """Fill in username into url.""" return url.replace('<username>', username)
def where_above(list, limit): """ where_above behaves like table.where(column, are.above(limit)). The analogy is completed if you think of a column of a table as a list and return the filtered column instead of the entire table. >>> where_above([1, 2, 3], 2) [3] >>> where_above(range(13), 10) ...
def map_float(data): """ Converts a list's items to floats, returning the modified list. """ return list(map(lambda x: float(x), data))
def convert_yaml_to_tuple(yaml_dictionary): """Converts a yaml dictionary with two keys: `key` and `value` into a two argument tuple of those values.""" return (yaml_dictionary["key"], yaml_dictionary["value"])
def blend_screen(cb: float, cs: float) -> float: """Blend mode 'screen'.""" return cb + cs - (cb * cs)
def obs_is_afternoon(obcode): """Given an observation code (eg 'ob_1a', 'ob12_b') is this an afternoon obs?""" return obcode[-1] == 'b'
def dna_check(possible_dna): """ :param possible_dna: A sequence that may or may not be a plausible DNA (translatable!) sequence :return: True/False """ return set(possible_dna.upper()).issubset({'A', 'C', 'G', 'T', 'N'})
def get_landscape(region): """Takes the region and returns the correct landscape name Args: region (str): a AWS region name, such as 'eu-west-1' Returns: String """ return { 'us-east-1': 'na', 'eu-central-1': 'eu', 'eu-west-1': 'uk' }.get(region, 'eu')
def toint(x): """Convert x to integer without throwing an exception""" try: return int(x) except: return 0
def cartogrid_remap(cartogrid, x1, y1): """ Given an nx*ny grid of (x,y) points used for the cartogram, remap the point (x1,y1) into index coordinates, for example grid[0][0]->[0,0], grid[-1][-1]->[nx,ny] """ x0, y0 = cartogrid[0][0] x2, y2 = cartogrid[-1][-1] dx, dy = (x2 - x0) / len(cartogrid[...
def convert_behavior_adj(adj): """ Convert a COMP behavioral adjustment to work with the Behavioral-Responses package """ behavior = {} if adj: for param, value in adj.items(): behavior[param] = value[0]["value"] return behavior
def shortText(text, limit): """shorten text to limit""" if len(text) > limit + 4 and limit > 4: text = text[:limit] + '...' return text
def version_tuple(ver): """Convert a version string to a tuple containing integers. Parameters ---------- ver : str Version string to convert. Returns ------- ver_tuple : tuple Three-part tuple representing the major, minor, and patch versions. """ s...
def construct_names(gene_ID, transcript_ID, prefix, n_places): """ Create a gene and transcript name using the TALON IDs. The n_places variable indicates how many characters long the numeric part of the name should be. """ gene_ID_str = str(gene_ID).zfill(n_places) gene_name = prefix + "G" ...
def format_field_name_for_checkbox(field): """ Format the name of an option-checkbox using the field name of the option as it exists in the UserOptions tuple for the purpose of having a unique codename in the Mimic backend. :param field: :return: """ return 'cb_{}'.format(field)
def is_valid_num(num): """ Check if x or y falls on board. Parameters ---------- num : str row or column value Returns ------- bool true if its a valid number [0,4] false otherwise """ return -1 < num < 5
def parse_line(line): """ Parse a queue trace line into a dict """ result = {} line = line.split() if len(line) < 5 or line[0][0] == "#": return result result["time"] = float(line[0]) result["from"] = int(line[1]) result["to"] = int(line[2]) result["len_bytes"] = float(line[3...
def chunk_size_or_default(chunk_size): """Use default chunksize if not configured.""" return chunk_size or 5 * 1024 * 1024
def is_word_list_list(obj): """Determines if `obj` is a sequence of sequence of strings. Examples: >>> is_word_list_list([['hello'], ['another'], ['word']]) True >>> is_word_list_list(np.random.rand(10)) False """ try: oset = set() for sent in obj: for word...
def group(items, number_of_groups): """Group items into number of groups Takes a countable items and divides it into the desired number of groups. :param items: :param number_of_groups: :return: """ if not items: return [] groups = list() step = round(len(items) / number_...
def stdDevOfLengths(L): """ L: a list of strings returns: float, the standard deviation of the lengths of the strings, or NaN if L is empty. """ if (len(L) == 0): return float('NaN') sumVals = 0 for s in L: sumVals += len(s) meanVals = sumVals / len(L) sumDevSq...
def generar_cifrador(offset): """Recibe un valor de tipo entero y regresa un diccionario con la llave-valor del cifrador. """ #se declara e instancia una variable de tipo lista que contiene todos los caracteres del alfabeto. letras = [chr(l) for l in range(97, 123)] #se declara e instancia un dicci...
def compare_objects(first, second, cmp_fct): """ Compare two objects, possibly None. :param first: First object. :param second: Second object. :param cmp_fct: A comparison function. :return: The "greatest" object according to `cmp_fct`, None if both values are None. >>> compar...
def refine_city_name(location): """display User-friendly city name""" if location == 'newyork': # does this have to capitalized loc = 'New York' elif location == 'washingtondc': loc = 'Washington D.C.' elif location == 'sanfrancisco': loc = 'San Francisco' else: loc ...
def _merge_lists(a, b, append=False): """ Merge two lists. """ merged = b.copy() if append: temp_list = a temp_list.extend(x for x in b if x not in temp_list) merged = temp_list return merged
def get_ta_status_flag(funding_status): """Generate TA status flag for student entry. This flag is from a "teaching preference request" perspective, not a funding perspective. Arguments: funding_status (str): funding entry for current term Returns: (str) : flag ("" for non-TA, "*"...
def safe_module_name(n): """Returns a module name which should not conflict with any other symbol.""" if n: return "_mod_" + n.replace(".", "_") return n
def flatten_json(data, delimiter): """ Flattens a JSON file. Input: data: A JSON dictionary of hierarchical format. {key1: {key2: value2, key3: value3}, key4: {key5: value5, key6: [value6, value7, value8]}} delimiter: A parameter to separate the keys in or...
def _get_value_for_key(lines, key): """Given list of |lines| with colon separated key value pairs, return the value of |key|.""" for line in lines: parts = line.split(':') if parts[0].strip() == key: return parts[1].strip() return None
def MakeExt( ext ): """Returns a file extension, starting with a dot if the given one does not.""" return ( '' if not ext or ext.startswith( '.' ) else '.' ) + ext
def linux_path(windowsPath): """Convert Windows Path to Linux Path @code print libFile.linux_path(r"c:\myDir\mayaFile.ma") # Result: 'c:/myDir/mayaFile.ma' # @endcode @param windowsPath (string) Folder or file path @return maya compliant file path """ return str(windowsPath.replace...
def ERR_NEEDMOREPARAMS(sender, receipient, message): """ Error Code 461 """ return "ERROR from <" + sender + ">: " + message
def parse_big_number(num): """Parse large numbers into human readable format (e.g., 1K, 1M, 1B). :param num: int or float of number to parse :return: str of parsed number """ if num < 1e3: num = f'{num}' elif num < 1e6: num = f'{num / 1e3:.0f}K' elif num < 1e9: num =...
def _bin_approx_search(lst, tg): """ Find the index of the element in lst which is closest to the number tg """ top = len(lst) - 1 bottom = 0 while top > bottom: curri = (top - bottom)//2 + bottom if lst[curri] < tg: bottom = curri else: top = curr...
def _generate_unique(name, existing_names, prefix="api"): """ Generate a unique name among existing ones by suffixing a number. Can also add an optional prefix. """ if prefix is not None: new_name = prefix + "_" + name else: new_name = name for j in range(1, 1001): if new...
def wort_srm(mcu, vol_gal): """Convert Malt Color Units to SRM. Parameters ---------- mcu : float Malt color units vol_gal : float Wort volume, in gallons. Returns ------- srm : float SRM. """ return 1.49 * (mcu / vol_gal) ** 0.69
def _BuildIntervalList(input_list, predicate): """Find ranges of contiguous list items that pass a given predicate. Args: input_list: An input list of items of any type. predicate: A function that takes a list item and return True if it passes a given test. Returns: A list of (start_pos, end_po...
def perform_abstraction( pattern, abstraction, con_traces, con_timestamps, start=0 ): """ desc the pattern in traces are abstracted Input pattern pattern to be abstracted ...
def square_area(side): """Returns the area of a square""" # You have to code here # REMEMBER: Tests first!!! return pow(side,2)
def check(word: str, compare: str) -> bool: """Marches a word vs a word, returns true or false""" for l1, l2 in zip(word, compare): if l1 == "_": pass elif l1 != l2: return False return True
def all_tag_filter(tags): """Return a filter of the element by all the tags for a json post advance search. :param List of :class:`str` tags: Desired filtering tags :returns: json structure to call the the asking tasks. """ if not isinstance(tags, list): tags = [tags] tag_selector = { ...
def collapse_braces(src_text): """ Removes the contents of all top-level curly brace pairs {}. Args: src_text: The source code to collapse. Returns: The collapsed source code. """ nesting = 0 start_index = 0 collapsed_src_text = '' for index, char in enumerate(src_...
def render_2d(game: dict, xray: bool = False) -> list: """ Create a string representation of the board. Makes a list of lists, representing a 2d matrix, of strings corresponding to the tile values of the game['board']. '.' denotes a bomb, '_' denotes a hidden tile, ' ' denotes an empty reveal...
def get_bollinger_bands(rm, rstd): """Return upper and lower Bollinger Bands.""" upper_band = rm + 2 * rstd lower_band = rm - 2 * rstd return upper_band, lower_band
def insert_at_nth_column_of_matrix(column_vector, M, column_num): """ Inserts a new column into an existing matrix :param column_vector: The column vector to insert IF a value is passed in, a column is created with all elements equal to the value :param M: The matrix to i...
def remove_escaped_characters(text): """ Remove all escaped characters Args: text (string): the content that will have the escaped characters removed Returns: string: text without escaped characters """ if (text is None): return return text.replace("\r\n", " ")
def clean_join(separator, iterable): """ Filters out iterable to only join non empty items. """ return separator.join(filter(None, iterable))
def to_port(port_str): """ Tries to convert `port_str` string to an integer port number. Args: port_str (string): String representing integer port number in range from 1 to 65535. Returns: int: Integer port number. Raises: ValueError: If `port_str` ...
def rollbar_ignore_handler(payload): """Filter out certain errors rom Rollbar logs.""" error_class_name = ( payload["data"] .get("body", {}) .get("trace", {}) .get("exception", {}) .get("class", "") ) # We ignore ServerErrorResponse, because that error will be re...
def get_number_of_decimal(tick_size): """ Get price decimal number of a contract from its tick size. """ str_price_tick_ = str(tick_size) decimal_pos_ = str_price_tick_.find('.') if decimal_pos_ == -1 or str_price_tick_[decimal_pos_ + 1:] == '0': return 0 else: return len(str...
def julia_quadratic(zx, zy, cx, cy, threshold): """Calculates whether the number z[0] = zx + i*zy with a constant c = x + i*y belongs to the Julia set. In order to belong, the sequence z[i + 1] = z[i]**2 + c, must not diverge after 'threshold' number of steps. The sequence diverges if the absolute value...
def conv_repoids_to_list(repo_ids): """ Convert repo ids seperated by "\n" to list. """ if not repo_ids: return [] repoid_list = [] for repo_id in repo_ids.split("\n"): if repo_id == '': continue repoid_list.append(repo_id) return repoid_list
def mk_key(combined_name): """Make a key from the author's name.""" try: [first_name, last_name] = combined_name.split() except ValueError as errormsg: print(errormsg, '\n', combined_name) # ! is a low value in the ASCII table # This filters the author names that need to be f...
def removeDuplicateChars(a_string): """assumes a-string is a string returns a string, a_string with any duplicate characters removed """ duplicateless_string = "" char_set = set() for char in a_string: if char not in char_set: char_set.add(char) duplicateless_stri...
def max(cube1,cube2): """Return max value between two cubes """ return (cube1 > cube2)*cube1 + (cube1 <= cube2) * cube2
def str_fill(i, n): """Returns i as a string with at least n digits. i: int n: int length returns: string """ return str(i).zfill(n)
def init(i): """ Input: {} Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ return {'return': 0}
def is_targeting_windows(pkg_vars): """Returns true if 'platform' in pkg_vars indicates Windows.""" return pkg_vars['platform'].startswith('windows-')
def lowercase_keys(input_dict): """ Take input and if a dictionary, return version with keys all lowercase and cast to str """ if not isinstance(input_dict, dict): return input_dict safe = dict() for key, value in input_dict.items(): safe[str(key).lower()] = value return safe
def with_previous_s2(sequence): """Provide each sequence item with item before it Comments: Solution using the zip function Solution fails all bonuses """ items = [] for curr, prev in zip(sequence, [None] + list(sequence)): items.append((curr, prev)) return items
def alignments(value, multiple_of): """align an address with a section alignment""" if value <= multiple_of: return multiple_of c = 1 while value > multiple_of * c: c += 1 return multiple_of * c
def split_byte_into_nibbles(value): """Split byte int into 2 nibbles (4 bits).""" first = value >> 4 second = value & 0x0F return first, second
def string_or_bool(value): """ Ritorna True o False in caso venga passata la stringa 'true' o 'false' (o 't' o 'f') altrimenti ritorna una stringa. :param value: Stringa da analizzare. :type value: str """ if value.lower() in ['t', 'true']: value = True elif value.lower() in ['f...
def has_file_allowed_extension(filename, extensions): """Checks if a file is an allowed extension. Args: filename (string): path to a file Returns: bool: True if the filename ends with a known image extension """ filename_lower = filename.lower() return any(filename_lower.endswit...
def prod_n(lst): """ Alternative to tf.stacking and prod, since tf.stacking can be slow """ prod = lst[0] for p in lst[1:]: prod *= p return prod
def build_speechlet_response(title, output, reprompt_text=None, should_end_session=False): """ Build JSON structure for Alexa response. """ return { 'outputSpeech': { 'type': 'PlainText', 'text': output }, 'card': { 'type': 'Simple', ...
def move_along_the_axis(lead_list, index=0): """ move along the axis :param lead_list: :param index: point for orientation of the origin :return: new lead list """ tmp = 0 for (x, y), i in zip(lead_list, range(len(lead_list))): if x < index: tmp = i x0, y0 = ...
def _trim_zero_to_3_digits_or_less(trim: bool, exponent: int, ticker: str) -> str: """Returns a string representation of the number zero, limited to 3 digits This function exists to reduce the cognitive complexity of pretty_ether """ if trim: zero = "0" else: if exponent == -1: ...
def tokens_to_idxes(tokens_l): """ create a vocab, convert the texts into indexes using this vocab return the vocab and the indexes to avoid having to store the vocab, we'll just scan all words, then sort them... """ words = set() for tokens in tokens_l: for token in tokens: ...
def is_seq_valid(seq_pattern: str, probable_seq: str): """ seq_pattern: The input from the user (E.g., 1,2,?1,10,15--30) probable_seq: A sequence of integers to check if the sequence is applied for the pattern return: True if the probable sequence is fit on the pattern input """ x = seq_pattern....
def reverse_axis(x_data): """ Reverse axis Axis = -Axis """ if x_data[:1] == '-': x_data = x_data[1:] else: x_data = '-'+x_data return x_data
def iobes_iob(tags): """ IOBES -> IOB """ new_tags = [] for i, tag in enumerate(tags): if tag.split('-')[0] == 'B': new_tags.append(tag) elif tag.split('-')[0] == 'I': new_tags.append(tag) elif tag.split('-')[0] == 'S': new_tags.append(tag.replace(...
def get_dictionary_values_ordered(dict_list, key_name): """Generate a list, with values from 'key_name' found in each dictionary in the list of dictionaries 'dict_list'. The order of the values in the returned list match the order they are retrieved from 'dict_list' dict_list - a list of di...
def workflow(func=None, system_wide=False, **kwargs): """This decorator should only be used to decorate system wide workflows. It is not required for regular workflows. """ if func: func.workflow_system_wide = system_wide return func else: return lambda fn: workflow(fn, sy...
def shared_data_volume_driver(sdv, sdvkey): # type: (dict, str) -> str """Get shared data volume driver :param dict sdv: shared_data_volume configuration object :param str sdvkey: key to sdv :rtype: str :return: volume driver """ return sdv[sdvkey]['volume_driver']
def _buildSpectrumFromQIisotopes(mz, isotopeDistribution, delta=1.0033550000000009): """ Build a mass spectrum from a QI mz value, and isotopic distribution pattern. :param float mz: m/z of the lightest isotope :param str isotopeDistribution: Hyphenated list of isotopic abundances ordered by 1Da intervals :param ...
def parse_multi_target_selection_strings(key_strings): """given an arg string list, parse out into a dict assumes a format of: key=indices:key=indices::param=val,param=val this is for smart indexing into tensor dicts (mostly label sets). Returns: list of tuples, where tuple is (list of tuple...
def get_all_options(args_string): """ Read all of the hyperparameter options from the arguments string. """ # Get all the list strings first. char_ix = 0 list_start = -1 list_strings = [] # Read the dictionaries which contain the options. for char_ix, curr_char in enumerate(args_string): if curr_char == "{...
def safe_divide(nm, dm): """ To avoid dividing by zero :param nm: Nominator :param dm: Dominator :return: Float """ if dm == 0: return 0. else: return nm / float(dm)
def _set_default_picv(subcategory_id: int) -> float: """Set the default piCV value. :param subcategory_id: the subcategory ID of the capacitor with missing defaults. :return: _pi_cv :rtype: float """ if subcategory_id in {14, 15}: return 1.3 elif subcategory_id > 15: return ...
def topic_filename(topic: str) -> str: """ Returns the filename that should be used for the topic (without extension). """ # Remove commas and replace spaces with '-'. return topic.replace(",", "").replace(" ", "-")