content
stringlengths
42
6.51k
def dereference_name(reference): """ Extracts resource name from Deployment Manager reference string. """ # Extracting a name from `$(ref.NAME.property)` value results a string # which starts with `yaml%`. Remove the prefix. return reference.split('.')[1].replace('yaml%', '')
def _get_short_cid(container_id): """returns a shortened container id. Useful for logging, where using a full length container id is not necessary and would just add noise to the log. The shortened container id will contain enough information to uniquely identify the container for most situati...
def _deal_with_limit(template: str, parameters: list) -> list: """ Handle limit patch :param template: Template :return: Results after treatment """ up_template = template.upper() index = up_template.find("LIMIT") if index == -1: return parameters count = template[:index].cou...
def flatten(lst): """Flatten a list of lists into a list.""" return [item for sublist in lst for item in sublist]
def choose(n, k): """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok=1 ktok=1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: retu...
def unique_entries(results): """Prune non-unqiue search results.""" seen = set() clean_results = [] for i in results: if i['code'] not in seen: clean_results.append(i) seen.add(i['code']) return clean_results
def _calc_errors(actual, expected): """Return the absolute and relative errors between two numbers. >>> _calc_errors(100, 75) (25, 0.25) >>> _calc_errors(100, 100) (0, 0.0) Returns the (absolute error, relative error) between the two arguments. """ base = max(abs(actual), abs(expected)...
def strip_vl_extension(filename): """Strip the vega-lite extension (either vl.json or json) from filename""" for ext in ['.vl.json', '.json']: if filename.endswith(ext): return filename[:-len(ext)] else: return filename
def params(bands): """ Returns default EE visualization params for specified three rgb bands or single band. Args: bands: The bands to get visualization params for. Must be one of the following: VV, VV_min, VV_mean, VV_median, VV_max, VV_stdDev, VV_CV, VV_fitted, VV_residuals, ...
def fib(n): """This is documentation string for function. It'll be available by fib.__doc__() Return a list containing the Fibonacci series up to n.""" result = [] a = 1 b = 1 while a < n: result.append(a) tmp_var = b b = a + b a = tmp_var return result
def cell_values(row): """Extract cell values from a table header or row.""" return tuple(cell["value"] for cell in row["cells"])
def get_os(platform): """Queries the system for the operating system.""" if platform == "win32": return "Windows" if platform == "darwin": return "OS X" return "Linux"
def determine_shared_keys_in_dataset(all_keys, raw_dataset): """Determines if there are keys shared by the whole dataset.""" evenKeys = all_keys for item in raw_dataset: # Intersection of two lists. evenKeys = list(set(evenKeys) & set(list(item.keys()))) return evenKeys
def hex_to_rgb(hex): """Format a hex value (#FFFFFF) as RGB (255,255,255). Args: hex: The hex value. Returns: The RGB representation of that hex color value. """ hex = hex.lstrip("#") hlen = len(hex) return tuple( int(hex[i : i + hlen // 3], 16) / 255 for i in range...
def diff_pos(initial, target): """ Return the move required to move from one position to another. Will return the move required to transition from `initial` to `target`. If `initial` equals `target` this is `stop`. Parameters ---------- initial : tuple of (int, int) the starting positi...
def parse_unix_args(valid_args_list,passed_args): """Function creates command line arguments to pass to unix programs Parameters ---------- valid_args_list: list list of valid arguments. Invalid arguments will be ignored passed_args: *dict keyword value argument list to be parsed ...
def get_property(obj, name): """Get named object property Looks first in custom properties, then game properties. Returns a list. """ prop_value = [] try: prop_value.append(obj.properties[name]) except: pass try: # look for game properties prop = obj.getP...
def convStrToNum(s): """Given string s with either 3, 2 or 1 num at the end, converts that num to a int""" try: num = int(s[-3:]) except: try: num = int(s[-2:]) except: num = int(s[-1]) return num
def extract_json_values(obj: dict, key: str) -> list: """ Pull all values of specified key from nested JSON. Args: obj (dict): nested dict key (str): name of key to pull out Returns: list: values for the specified key """ arr = [] def extract(obj, arr, key): ...
def CheckForSize(collection, expected_size, equal_flag, unequal_flag, unexpectedly_empty_flag=None): """Check conditions for collection size. Args: collection: A collection can be a list, set or dictionary. expected_size: The expected size. equal_flag: The value to return if the collec...
def get_recommended_modification(simple_order, impact): """ Generate a recommendation string from an operator and the type of impact :param simple_order: simplified operator :param impact: whether the change has positive or negative impact :return: formatted recommendation string """ bigger_...
def sort_addresses(addrs): """Sort addresses given as argument in place, all addresses must belong to the same pool.""" if not addrs or not addrs[0].pool: return addrs if not addrs[0].pool.addr_range: addrs[0].pool._update() sortablefunc = addrs[0].pool.addr_range.sortable return...
def cipher(text, shift, encrypt=True): """ Conducts the traditional caesar cipher on the string text. Parameters ---------- text: Any python string value shift: Any python integer value encrypt: Default value is left shift, but setting it to False will create a right...
def upper(str): """ Filter that converts string to uppercase """ return str.upper()
def applyPermutation(permutationTable, input): """Apply the permutation specified by the 128-element list 'permutationTable' to the 128-bit bitstring 'input' and return a 128-bit bitstring as the result.""" if len(input) != len(permutationTable): raise ValueError("input size (%d) doesn't match ...
def normalize_weights(weights): """Normalises a list of numerical values (weights) into probabilities. Every weight in the list is assigned a probability proportional to its value divided by the sum of all values. Args: weights (list): A list of numerical values Returns: list: A l...
def world2Pixel(geoMatrix, x, y): """ Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate the pixel location of a geospatial coordinate """ ulX = geoMatrix[0] ulY = geoMatrix[3] xDist = geoMatrix[1] yDist = geoMatrix[5] rtnX = geoMatrix[2] rtnY = geoMatrix[4] pixe...
def assoc_kw(obj, **kwargs): """ __setitem__ all kwargs on the new object, return it. """ # special case None to work like empty dict if obj is None: obj = {} for k, v in kwargs.items(): obj[k] = v return obj
def simplify_code(code, end_of_file): """ @parl.remote_actor has to use this function to simplify the code. To create a remote object, PARL has to import the module that contains the decorated class. It may run some unnecessary code when importing the module, and this is why we use this function to simplify...
def _split_columns(entry, split_list): """ split pre-defined dictionary entries along pre-defined separators args: entry: a bibliography entry split_list: a pre-defined list of columns to separate returns: entry: the split entry """ # function to strip trailing spaces ...
def transpose(matrix): """ IMPORTANT: You should only use list comprehension for this question. Follow the syntax guidelines in the writeup. Takes in a list of lists representation of a matrix and returns its transpose, also as a list of lists. >>> arr1 = transpose([[1,2,3],[4,5,6],[7,8,9]]) ...
def process_json(blobs): """Process JSON objects into a list of dicts""" data_list = [] for item in blobs: input_dict = item[1] try: attributes = input_dict["attributes"] item_dict = {} item_dict["index"] = item[0] for attribute in attributes: ...
def get_line_equation(p1, p2): """ takes 2 points and generating a vector equation of a line. shown as (x, y, z) + t*(x_diff, y_diff, z_diff) :param p1: a tuple of point 1 (x, y, z) :param p2: a tuple of point 2 (x, y, z) :return: a tuple of two tuples, a point tuple and a direction tuple ""...
def char_replacement(list_smiles): """ Replace the double characters into single character in a list of SMILES string. Parameters ---------- list_smiles: list list of SMILES string describing a compound. Returns ------- list list of SMILES with character replacement. ...
def factorial(n): """return n factorial The factorial is defined as n! = n*(n-1)! Note: The recursive factoial implementation will break down if n is too large """ if(n==0): return 1 else: return n*factorial(n-1)
def makeEightBit(a): """makes a binary number 8 bit""" if len(a) == 8: print(str(a)) return str(a) elif len(a) > 8: #print(a[(len(a)-8):]) makeEightBit(a[(len(a)-8):]) else: makeEightBit("0" + a) return ""
def get_frequency_by_index(index: int) -> int: """ -> 0 1 2 3 4 5 6 7 8 ... <- 0 1 -1 2 -2 3 -3 4 -4 ... """ sign: int = -1 if index % 2 == 0 else 1 return ((index + 1) // 2) * sign
def get(key: str, dic, default=None): """Gets key even from not a dictionary.""" try: return dict(dic).get(key, default) except TypeError: return default
def refraction(N, k, l, m, dN, di, Omega): """ Refraction index of internal wave """ K = k**2 + l**2 + m**2 return ((N*(k**2 + l**2)) / (K * Omega)) * (dN/di)
def quantity_label(quantity): """Returns formatted string of parameter label """ labels = { 'accrate': r'$\dot{m}$', 'alpha': r'$\alpha$', 'd_b': r'$d \sqrt{\xi_\mathrm{b}}$', 'dt': r'$\Delta t$', 'fluence': r'$E_\mathrm{b}$', 'length': 'Burst length', ...
def cmap_lifeaquatic(N=None): """ Returns colormap inspired by Wes Andersen's The Life Aquatic Available from https://jiffyclub.github.io/palettable/wesanderson/ """ colors = [ (27, 52, 108), (244, 75, 26), (67, 48, 34), (35, 81, 53), (123, 109, 168), ...
def h_mean(lst): """harmonic mean of a list""" return len(lst)/sum([1/num for num in lst])
def calc_field(phi_k, kx_v, ky_v, kz_v): """ Calculates the Electric field in Fourier space. Parameters ---------- phi_k : numpy.ndarray 3D array of the Potential. kx_v : numpy.ndarray 3D array containing the values of kx. ky_v : numpy.ndarray 3D array containing ...
def get_mean(list_values): """This function return the mean value""" if len(list_values) == 0: raise ZeroDivisionError('Maybe you input a empty file, or there is no float number in spam confidence. ') whole_sum = 0 for i in list_values: whole_sum += i return whole_sum / ...
def get_line_count_string(line_count): """Return string representation for size.""" if line_count == 0: return 'empty' elif line_count == 1: return '1 line' return '%d lines' % line_count
def assert_string(obj): """Make sure it is a string""" try: # isinstance(obj, str) if getattr(obj, 'strip') and getattr(obj, 'split') and getattr(obj, 'rstrip'): return True except: return False
def flatten_dict(d, delim="_"): """Go from {prefix: {key: value}} to {prefix_key: value}.""" flattened = {} for k, v in d.items(): if isinstance(v, dict): for k2, v2 in v.items(): flattened[k + delim + k2] = v2 else: flattened[k] = v return flattened
def _convert_index(index, pos, m=None, is_start=True): """Converts index.""" if index[pos] is not None: return index[pos] n = len(index) rear = pos while rear < n - 1 and index[rear] is None: rear += 1 front = pos while front > 0 and index[front] is None: front -= 1 assert index[front] is no...
def join_row(row, left, middle, right): """Convert a row (list of strings) into a joined string with left and right borders. Supports multi-lines. :param iter row: List of strings representing one row. :param str left: Left border. :param str middle: Column separator. :param str right: Right border...
def distance(pointA, pointB): """ the distance between point A and B :param pointA: point A :param pointB: point B :return: distance """ return ((pointA[0] - pointB[0]) ** 2 + (pointA[1] - pointB[1]) ** 2) ** 0.5
def bin2dec(x): """Convert ``x``, an array of "bits" (MSB first), to it's decimal value.""" bits = [] bits.extend(x) bits.reverse() # MSB multi = 1 value = 0 for b in bits: value += b * multi multi *= 2 return value
def sum_first_n_squares(n: int) -> int: """Finds the sum of the squares of the integers from 1 to n.""" return n * (n + 1) * (2 * n + 1) // 6
def down(dimension, position): """ Return the position on any board with the given dimension immediately below the given position. - None is returned if the generated position is outside the boundaries of a board with the given dimension. ASSUMPTIONS - The gi...
def rho_MC(delta, rhoeq=4.39e-38): """ returns the characteristic density of an axion minicluster in [solar masses/km^3] forming from an overdensity with overdensity parameter delta. rhoeq is the matter density at matter radiation equality in [solar masses/km^3] """ return 140 * (1 + del...
def round_b(x, base=5): """ Rounds a number to base X """ return int(base * round(float(x) / base))
def match_prefixes(text, prefixtree): """Return a list of all matching prefixes, with longest sorted first""" longest_prefix = '' current = prefixtree for char in text: if char in current.children: longest_prefix += char current = current.children[char] else: break prefixes = [] for i in reversed(ra...
def get_col(node, default=-1): """Gets the col_offset of a node, or returns the default""" return getattr(node, "col_offset", default)
def compare_machine_ids( machine_id_a, machine_id_b): """ :param machine_id_a: machine_id :type: dict :param machine_id_a: machine_id :type: dict :return: true if both machine_id match, else False :rtype: boolean """ return machine_id_a['hostname'] == machine_id_b['hostname'] and mac...
def isValid(form): """ Checks the structural and symbol validity of the forumla. Parameters ---------- form : string The formula to be validated. Returns ------- valid : bool Whether the formula is valid or not. Examples -------- >>> isValid("RUR'U'") T...
def print_dict(dict_to_print): """ Formatted print of dictionary """ assert type(dict_to_print) is dict # Init message msg = "" if len(set(dict_to_print)) > 0: # Otherwise crashes for empty dict # Generate template for formatting max_keylength = len(max(dict_to_print.keys...
def repeated_elements(arr)->dict: """ Return the dictionary of the elements with it's count. """ dic={} for i in arr: try: if dic[i]: dic[i]+=1 except: dic[i]=1 return dic
def _validate_float(value): """Validate value is a float.""" try: value = float(value) except ValueError as err: raise ValueError("Could not convert to float") from err return value
def to_binary(value, encoding='utf-8'): """Convert value to binary string, default encoding is utf-8 :param value: Value to be converted :param encoding: Desired encoding """ if not value: return b'' if isinstance(value, bytes): return value if isinstance(value, str): ...
def labels_to_int(labels): """Heuristic to convert label to numeric value. Parses leading numbers in label tags such as 1_worried -> 1. If any conversion fails this function will return None """ label_vals = [] for label in labels: if label == 'positive': label_vals.append(1) ...
def parse_field(field): """ Parse a non-meta key from the response attributes dict. The non-meta keys correspond to (sub-)question titles ((s)qid). If the field name contains no brackets ('[', ']'), a qid without subquestions is meant. Otherwise one or two sqids are within the brackets: two if ...
def get_window(i, k, m, cw): """ Calculate the size of window input: i : the ith backoff stage k : maximum retransmission m : maximum content window grow times cw: initial content window size return:the window of the ith retansmission """ assert (k > m ...
def blend(a, b, perc=.5): """Blend two RGBs, use `perc` % of `a`.""" return [int(a[i] * perc + b[i] * (1 - perc)) for i in range(len(a))]
def capitalize(string): """ Capitalizes only the first letter of a string. Does not change the others. """ newstring = string[0].capitalize() + string[1:] return newstring
def getContour(semitones): """Return semitones in Parson's Code Given a list of integers defining the size and direction of a series of musical intervals in semitones, this function encodes the contour of the melody with Parsons code for musical contour where u=up, d=down, r=repeat. """ contour...
def public_ip_id(subscription_id, resource_group_name, name): """Generate the id for a frontend ip configuration""" return '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/publicIPAddresses/{2}'.format( subscription_id, resource_group_name, name )
def odds(nums): """Odds: Given a list of numbers, write a list comprehension that produces a list of only the odd numbers in that list. >>> odds([1, 2, 3, 4, 5]) [1, 3, 5] >>> odds([2, 4, 6]) [] >>> odds([-2, -4, -7]) [-7] """ lst = [a for a in nums if a%2...
def deserialize_datetime(string): """Deserializes string to datetime. The string should be in iso8601 datetime format. :param string: str. :type string: str :return: datetime. :rtype: datetime """ try: from dateutil.parser import parse return parse(string) except Im...
def user_getbyname(id): """ "/user/{id}": # Must start with forward slash get: summary: "Endpoint to return information about a single user" description: "List information about user of a given id" tags: ["userbyid"] operationId: "get_user_by_id" ...
def make_name(variable, anon="anonymous_variable"): """ If variable has a name, returns that name. Otherwise, returns anon. Parameters ---------- variable : tensor_like WRITEME anon : str, optional WRITEME Returns ------- WRITEME """ if hasattr(variable, 'n...
def flip(pattern): """Flip pattern horizontally.""" return [row[::-1] for row in pattern]
def get_dimension_array(array): """ Get dimension of an array getting the number of rows and the max num of columns. """ if all(isinstance(el, list) for el in array): result = [len(array), len(max([x for x in array], key=len,))] # elif array and isinstance(array, list): else: ...
def jaccard_similarity(x, y): """Calculates the minskowski's distance between the vectors x and y Keyword arguments: x,y -- the vectors between which the distance is to be calculated """ intersection = len(set.intersection(*[set(x), set(y)])) union = len(set.union(*[set(x), set(y)]))...
def _narrow_unichr_workaround(codepoint): """ A replacement for unichr() on narrow builds of Python. This will get us the narrow representation of an astral character, which will be a string of length two, containing two UTF-16 surrogates. """ escaped = b'\\U%08x' % codepoint return escaped....
def s_time_offset_from_secs(secs): """ Return a string with offset from UTC in RFC3339 format, from secs. """ if secs > 0: sign = "+" else: sign = "-" secs = abs(secs) offset_hour = secs // (60 * 60) offset_min = (secs // 60) % 60 return "%s%02d:%02d" % (sign, ...
def _get_target_values(targets: dict, output_name: str): """Pulls out values for a given target""" output_config = {"values": [], "times": []} for t in targets.values(): if t["output_key"] == output_name: output_config = t values = output_config["values"] times = output_config["...
def cn(uc, w, eis, frisch, vphi): """Return optimal c, n as function of u'(c) given parameters""" return uc ** (-eis), (w * uc / vphi) ** frisch
def dayFormat(day: int) -> str: """ Formats a (0-6) weekday number as a full week day name, according to the current locale. For example: dayFormat(0) -> "Sunday". """ days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "...
def is_transitive(r, universe): """ Function to determine if a relation is transitive :param r: a relation on set universe :param universe: a set :return: True if relation is transitive, False otherwise """ for a in universe: for b in universe: if (a, b) in r: ...
def set_bit(value, offset): """Set a bit at offset position :param value: value of integer where set the bit :type value: int :param offset: bit offset (0 is lsb) :type offset: int :returns: value of integer with bit set :rtype: int """ mask = 1 << offset return int(value | mask)
def deep_eq(x, y): """Deeply compares `x` and `y` for equality. :param object x: First object. :param object y: Second object. :returns: :obj:`True` if `x` is equal to `y`, :obj:`False` otherwise \ (:class:`bool`). """ if x is y: return True if isinstance(x, (tuple, list))...
def get_highest_score_index(results_list): """ Given a list of results, returns the index of the hit with the highest score. Simple find the maximum algorithm stuff going on here. """ highest_score = 0.0 highest_index = 0 index = 0 for hit in results_list: if hit.score > hig...
def get_mackowiak_id(object_id, seqname, start, end, strand): """ This function creates a "Mackowiak"-style identifier for, e.g., open reading frames. The form of the identifier is: <object_id>_<seqname>:<start>-<end>:<strand> example: ENSMUST00000033123_7:46175479-46179843:- ...
def first_true_index(x): """ Return index of first true value. """ for index, i in enumerate(x): if i: return index
def trim_string(string1: str, string2: str) -> str: """ Removes any preceding or trailing instances of s2 from s1 :param s1: the string from which preceding or trailing instances of s2 will be removed :param s2: the string that will be removed from the start and end of s1 :return: s1 without any ins...
def x_fmt(x_value, _): """x axis formatter""" if x_value // 10**9 > 0: return '{:.1f}'.format(x_value / 10.**9) if x_value // 10**6 > 0: return '{:.1f}'.format(x_value / 10.**6) if x_value // 10**3 > 0: return '{:.1f}'.format(x_value / 10.**3) return str(x_value)
def vol_pyramid(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Pyramid. Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) :return (1/3) * Bh >>> vol_pyramid(10, 3) 10.0 >>> vol_pyramid(1.5, 3) 1.5 """ return area_of_ba...
def is_valid_port(port): """Validates whether a port is None or now""" return bool(port is not None)
def in_side_select_layer(fsti, layer): """ fst = "FullSingleTokenInfo[]" """ new_side = [] for f in fsti: new_side_obj = {} for k, v in f.items(): if k == 'embeddings' or k == 'contexts': v = f[k][layer] new_side_obj[k] = v new_side....
def relativeBCPOut(anchor, BCPOut): """convert absolute outgoing bcp value to a relative value""" return (BCPOut[0] - anchor[0], BCPOut[1] - anchor[1])
def wrap_type_blink(return_type, type_registry): """Returns True if the type is a blink type that requires wrap_jso but NOT unwrap_jso""" return (return_type == 'Map' or return_type == 'Rectangle')
def _get_sorted_col_indices(select_columns, column_names): """Transforms select_columns argument into sorted column indices.""" names_to_indices = {n: i for i, n in enumerate(column_names)} num_cols = len(column_names) for i, v in enumerate(select_columns): if isinstance(v, int): if v < 0 or v >= num_...
def get_update_stack_input(stack_name, stack_parameters): """Return input for a stack update.""" return { 'StackName': stack_name, 'UsePreviousTemplate': True, 'Parameters': stack_parameters, 'Capabilities': [ 'CAPABILITY_IAM', ...
def all(iterable): """Return True if all elements are set to True. This function does not support predicates explicitely, but this behaviour can be simulated easily using list comprehension. >>> all( [True, True, True] ) True >>> all( [True, False, True] ) False ...
def cdsitem(sizeInGB, mediumType): """ :param sizeInGB: sizeInGB :type string :param mediumType: mediumType :type string ssd, sata, premium_ssd :return: cds """ cds = { 'sizeInGB': sizeInGB, 'mediumType': mediumType } return cds
def get_scaled_size(bytes, suffix="B"): """ Credit to PythonCode for this function.\n > https://www.thepythoncode.com/article/get-hardware-system-information-python\n Scale bytes to its proper format\n e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' (> string) """ factor ...