content
stringlengths
42
6.51k
def apply_function(function, value): """ The function must be defined in this file and be in the format applyfunct_FUNCNAME where FUNCNAME is the string passed as the parameter 'function'; applyfunct_FUNCNAME will accept only one parameter ('value') and return an appropriate value. """ function_prefix = "applyfunct_" if function is None: return value else: try: return globals()[function_prefix + function](value) except KeyError as e: # Raising an InternalError means that a default value is printed # if no function exists. # Instead, raising a ValueError will always get printed even if # a default value is printed, that is what one wants # raise InternalError( # real_exception=e, message = raise ValueError( "o such function %s. Available functions are: %s." % (function, ", ".join(i[len(function_prefix):] for i in globals() if i.startswith(function_prefix))))
def dicts_are_the_same(a, b): """Compare two dicts, ``a`` and ``b`` and return ``True`` if they contain exactly the same items. Ref: http://stackoverflow.com/a/17095033 """ return not len(set(a.items()) ^ set(b.items()))
def get_segments(tokens, max_seq_length): """Segments: 0 for the first sequence, 1 for the second""" if len(tokens)>max_seq_length: raise IndexError("Token length more than max seq length!") segments = [] current_segment_id = 0 for token in tokens: segments.append(current_segment_id) if token == "[SEP]": current_segment_id = 1 return segments + [0] * (max_seq_length - len(tokens))
def is_string_or_list_of_strings(obj): """Helper function to verify that objects supplied to source_currency and target_currency parameters of __init__ method are either string or list of strings. Parameters ---------- obj : any object object supplied to source_currency and target_currency parameters of __init__ method Returns ------- bool boolean representing whether or not the object satisfies the is a string or list of strings """ # Check if object is string if isinstance(obj, str): return True # Check if object is list elif isinstance(obj, list): # Check if list consists solely of strings if all(isinstance(item, str) for item in obj): return True else: return False else: return False
def mkmdict(seq, *, container=None): """Make multi-dict {key: [val, val]...}.""" if container is None: container = {} for key, val in seq: container.setdefault(key, []).append(val) return container
def generate(applescript): """Generate subprocess run applescript list""" command = ['osascript', '-e', applescript] return command
def trycast(new_type, value, default=None): """ Attempt to cast `value` as `new_type` or `default` if conversion fails """ try: default = new_type(value) finally: return default
def calculate_equipment_cost(equipment): """Calculate cost of equipment.""" cost = 0 for item in equipment: item_name, attributes = item cost += attributes['Cost'] return cost
def bbox_iou(box1, box2): """ Returns the IoU of two bounding boxes """ #Get the coordinates of bounding boxes b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] #get the corrdinates of the intersection rectangle inter_rect_x1 = max(b1_x1, b2_x1) inter_rect_y1 = max(b1_y1, b2_y1) inter_rect_x2 = min(b1_x2, b2_x2) inter_rect_y2 = min(b1_y2, b2_y2) #Intersection area inter_area = max(inter_rect_x2 - inter_rect_x1 + 1, 0)*max(inter_rect_y2 - inter_rect_y1 + 1, 0) #Union Area b1_area = (b1_x2 - b1_x1 + 1)*(b1_y2 - b1_y1 + 1) b2_area = (b2_x2 - b2_x1 + 1)*(b2_y2 - b2_y1 + 1) iou = inter_area / (b1_area + b2_area - inter_area) return iou
def is_image_file(filename): """ Judge whether is an image file. Include png, jpg, jpeg, tif, tiff """ return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg", ".tif", ".tiff"])
def make_mode_name(cond): """ Formats a mode name given a condition set """ name = [] for c in cond.split(","): sig, val = [s.strip() for s in c.strip().split("=")] # If the signal name ends with a digit, replace it with a letter # FIXME: Assuming start from 1 if sig[-1].isdigit(): n = int(sig[-1]) sig = sig[:-1] + "_" + chr(ord('A') + n - 1) # Abbreviate the signal fields = sig.split("_") sig = "".join([f[0] for f in fields]) # Append the value sig += val name.append(sig) return "_".join(name)
def _nbaSeason(x): """Takes in 4-digit year for first half of season and returns API appropriate formatted code Input Values: YYYY Used in: _Draft.Anthro(), _Draft.Agility(), _Draft.NonStationaryShooting(), _Draft.SpotUpShooting(), _Draft.Combine() """ if len(str(x)) == 4: try: return '{0}-{1}'.format(x, str(int(x) % 100 + 1)[-2:].zfill(2)) except ValueError: raise ValueError("Enter the four digit year for the first half of the desired season") else: raise ValueError("Enter the four digit year for the first half of the desired season")
def _float_almost_equal(float1, float2, places=7): """Return True if two numbers are equal up to the specified number of "places" after the decimal point. """ if round(abs(float2 - float1), places) == 0: return True return False
def get_ufa_repo_by_dir(filepath): """ Reads .ufarepo file and returns root repository """ path_list = filepath.split('/') path_list.append('.ufarepo') ufarepo_path = "/".join(path_list) try: with open(ufarepo_path, "r") as f: return f.readline().strip() except FileNotFoundError: return None
def _is_internal_link(link: str) -> bool: """Check if a link is internal. A link is considered internal if it starts with a single slash (not two, as this indicates a link using the same protocol.) """ if len(link) >= 2: return link[0] == '/' and link[1] != '/' else: return link[0] == '/'
def BinToHex(binStr): """ Helper function for converting binary string to hex string Args: binStr (str): binary string Raises: Exception: binStr cannot be packed into hex format Returns: str: hex string """ if len(binStr) % 8 != 0: raise Exception("Length of binary in BinToHex() must be multiple of 8.") h = '%0*X' % ((len(binStr) + 3) // 4, int(binStr, 2)) return h
def name_to_image_size(name: str) -> int: """Returns the expected image size for a given model. If the model is not a recognized efficientnet model, will default to the standard resolution of 224 (for Resnet, etc...). Args: name: Name of the efficientnet model (ex: efficientnet-b0). """ image_sizes = { 'efficientnet-b0': 224, 'efficientnet-b1': 240, 'efficientnet-b2': 260, 'efficientnet-b3': 300, 'efficientnet-b4': 380, 'efficientnet-b5': 456, 'efficientnet-b6': 528, 'efficientnet-b7': 600, 'efficientnet-b8': 672, 'efficientnet-l2': 800, 'efficientnet-l2-475': 475, } return image_sizes.get(name, 224)
def unquote(value): """Removes left most and right most quote for str parsing.""" return value.lstrip('"').rstrip('"')
def most_common(lst, n=3): """Most common elements occurring more then `n` times """ from collections import Counter c = Counter(lst) return [k for (k, v) in c.items() if k and v > n]
def _compat_compare_digest(a, b): """Implementation of hmac.compare_digest for python < 2.7.7. This function uses an approach designed to prevent timing analysis by avoiding content-based short circuiting behaviour, making it appropriate for cryptography. """ if len(a) != len(b): return False # Computes the bitwise difference of all characters in the two strings # before returning whether or not they are equal. difference = 0 for (a_char, b_char) in zip(a, b): difference |= ord(a_char) ^ ord(b_char) return difference == 0
def has_static_registration_perm(user_level, obj, ctnr, action): """ Permissions for static registrations """ return { 'cyder_admin': True, #? 'ctnr_admin': True, #? 'user': True, #? 'guest': action == 'view', }.get(user_level, False)
def get_number_of_networks_with_dhcp(agents): """Get overall number of networks handled by at least one dhcp agent :param: dict with agents and networks handled by thoses agents :return: number of unique networks hosted on dhcp agents """ networks = [] for agent_networks in agents.values(): networks += agent_networks return len(set(networks))
def colorFromProbability(probability): """Calculate a color from probability for viewing purposes.""" rgbList = (255 - (probability() * 6), int(255.0*probability()) * 6.0, 50) return rgbList
def add_normalized_residential_ziploads(loadshape_dict, residenntial_dict, config_data, last_key): """ This fucntion appends residential zip loads to a feeder based on existing triplex loads Inputs loadshape_dict - dictionary containing the full feeder residenntial_dict - dictionary that contains information about residential loads spots last_key - Last object key config_data - dictionary that contains the configurations of the feeder Outputs loadshape_dict - dictionary containing the full feeder last_key - Last object key """ for x in list(residenntial_dict.keys()): tpload_name = residenntial_dict[x]['name'] tpload_parent = residenntial_dict[x].get('parent', 'None') tpphases = residenntial_dict[x]['phases'] tpnom_volt = '120.0' bp = residenntial_dict[x]['load'] * config_data['normalized_loadshape_scalar'] loadshape_dict[last_key] = {'object': 'triplex_load', 'name': '{:s}_loadshape'.format(tpload_name), 'phases': tpphases, 'nominal_voltage': tpnom_volt} if tpload_parent != 'None': loadshape_dict[last_key]['parent'] = tpload_parent else: loadshape_dict[last_key]['parent'] = tpload_name if bp > 0.0: loadshape_dict[last_key]['base_power_12'] = 'norm_feeder_loadshape.value*{:f}'.format(bp) loadshape_dict[last_key]['power_pf_12'] = '{:f}'.format(config_data['r_p_pf']) loadshape_dict[last_key]['current_pf_12'] = '{:f}'.format(config_data['r_i_pf']) loadshape_dict[last_key]['impedance_pf_12'] = '{:f}'.format(config_data['r_z_pf']) loadshape_dict[last_key]['power_fraction_12'] = '{:f}'.format(config_data['r_pfrac']) loadshape_dict[last_key]['current_fraction_12'] = '{:f}'.format(config_data['r_ifrac']) loadshape_dict[last_key]['impedance_fraction_12'] = '{:f}'.format(config_data['r_zfrac']) last_key += last_key return loadshape_dict, last_key
def _attr(obj: object, attr: str) -> object: """Nest `getattr` function.""" n = obj for p in attr.split('.'): n = getattr(n, p, None) if n is None: return None return n
def list_journals(config): """List the journals specified in the configuration file""" sep = "\n" journal_list = sep.join(config['journals']) return journal_list
def bound(x, m, M=None): """ :param x: scalar Either have m as scalar, so bound(x,m,M) which returns m <= x <= M *OR* have m as length 2 vector, bound(x,m, <IGNORED>) returns m[0] <= x <= m[1]. """ if M is None: M = m[1] m = m[0] # bound x between min (m) and Max (M) return min(max(x, m), M)
def parse_is_ssl_from_host(host_name: str) -> bool: """Only controllers without SSL should be on cloud machine""" return host_name.endswith('appd-cx.com') is not True
def buyholdsell(n): """ Param n is a number. Function will decide if the number is worth buying, holding, or selling. """ if (n) in range(1, 30): return "I'm buying" elif (n) in range(30, 71): return "I'm holding" elif (n) in range(70, 101): return "I'm selling" else: return "Your number wasn't in the correct range"
def build_tuple_for_feet_structure(quantity): """ Builds the tuple required to create a FeetAndInches object :param quantity: string containing the feet, inches, and fractional inches :return: tuple containing feet, inches, and calculated fractional inches """ feet = float(quantity[0]) inches = float(quantity[1]) fractional_inches = quantity[2].split('/') return feet, inches, int(fractional_inches[0])/int(fractional_inches[1])
def res_error(code, message): """ Unexpected Error response """ return { "code": code, "message": message }
def numerifyId(string): """ Given a string containing hexadecimal values that make up an id, return a new id that contains all digits and no letters. """ for i in range(0, len(string)): if string[i] < "0" or string[i] > "9": string = string[:i] + "{}".format(ord(string[i]) % 10) + string[i + 1:] return string
def code_msg(msg, code): """ Function that codes a given text with a given Huffman code for each character. :param msg: :param code: :return: coded_msg """ coded_msg = "" for char in msg: coded_msg += code[char] return coded_msg
def format_result(res_arr, qids, pred, labels, scores): """ trans batch results into json format """ for i in range(len(qids)): res="\t".join([str(qids[i]), str(pred[i]), str(labels[i]), " ".join(["%.5f" % s for s in scores[i]])]) res_arr.append(res) return res_arr
def verify_claims(claims): """ Token claims verifier. Author: Lucas Antognoni Arguments: claims (dict): JWT claims dict Response: valid (boolean): True if valid, False o/w. """ if 'org_id' in claims: return False else: return True
def pad_number(number, bits): """Pad integer number to bits after converting to binary.""" return f'{bin(number)[2:]:0>{bits}}'
def rotate(arc, rotation): """Helper for rotation normalisation.""" return (arc + rotation) % 360
def valid_length(repeat, keys): """Check for valid combo of repeat and length of keys.""" return (True if not repeat or repeat == '*' else True if repeat == '+' and len(keys) > 1 else True if repeat == '?' and len(keys) < 2 else False)
def _mid(string, start, end=None): """ Returns a substring delimited by start and end position. """ if end is None: end = len(string) return string[start:start + end]
def add_dict(a, b): """ :param a dict: Dictionary we will merge with b :param b dict: Dictionary that will be merged into a :return a dict: Merged dictionary of a and b """ for key in b: a[key] = a.get(key, 0) + b[key] return a
def say_hello(name: str) -> str: """ Greet someone in English. :param name: Name of the person to greet. :return: The greeting. """ return f"Hello {name}!"
def trim_masic_suffix(container_name): """ Trim any masic suffix i.e swss0 -> swss """ arr = list(container_name) index = len(arr) - 1 while index >= 0: if arr[-1].isdigit(): arr.pop() else: break index = index - 1 return "".join(arr)
def scalinggroup_dialogs(context, request, scaling_group=None, landingpage=False, delete_form=None): """Modal dialogs for Scaling group landing and detail page.""" return dict( scaling_group=scaling_group, landingpage=landingpage, delete_form=delete_form, )
def clamp(value, min_value, max_value): """ Return the value, clamped between min and max. """ return max(min_value, min(value, max_value))
def preplace(schema, reverse_lookup, t): """ Replaces basic types and enums with default values. :param schema: the output of a simplified schema :param reverse_lookup: a support hash that goes from typename to graphql type, useful to navigate the schema in O(1) :param t: type that you need to generate the AST for, since it is recursive it may be anything inside the graph """ if t == 'String': return '@code@' elif t == 'Int': return 1334 elif t == 'Boolean': return 'true' elif t == 'Float': return 0.1334 elif t == 'ID': return 14 elif reverse_lookup[t] == 'enum': return list(schema['enum'][t].keys())[0] elif reverse_lookup[t] == 'scalar': # scalar may be any type, so the AST can be anything as well # since the logic is custom implemented I have no generic way of replacing them # for this reason we return it back as they are return t else: return t
def t_from_td_hr(td, k_mD=10, phi=0.2, mu_cP=1, ct_1atm=1e-5, rw_m=0.1): """ conversion of dimensionless time to dimensional time, result in hours td - dimensionless time k_mD - formation permeability, mD phi - porosity, fractions of units mu_cP - dynamic fluid viscosity, cP ct_1atm - total compressibility, 1/atm rw_m - well radius, m """ return td * phi * mu_cP * ct_1atm * rw_m * rw_m / k_mD / 0.00036
def public_field(obj, f): """ Predicate function that sees if field f in an object is neither callable nor private Useful in filtering functions to print fields in an object :param obj: The object to check :param f: string which is the name of a field in the object :return: bool """ result = False try: no_under = not f.startswith("_") attrib = getattr(obj, f) return no_under and (attrib and not callable(attrib)) except AttributeError: pass except TypeError: pass return result
def length_sort(items, lengths, descending=True): """In order to use pytorch variable length sequence package""" zipped = list(zip(items, lengths, range(len(items)))) zipped.sort(key=lambda x: x[1], reverse=descending) items, lengths, inverse_permutation = zip(*zipped) return list(items), list(lengths), list(inverse_permutation)
def _reconstruct_token(key): """Reconstruct a token from a key in a graph ('SomeName_<token>')""" if len(key) < 34 or key[-33] != "_": return token = key[-32:] try: int(token, 16) except ValueError: return None return token.lower()
def get_indices_by_doc(start, end, offsets, tokens): """ Get sentence index for textbounds """ # iterate over sentences token_start = None token_end = None # flatten offsets offsets = [idx for sent in offsets for idx in sent] tokens = [tok for sent in tokens for tok in sent] for j, (char_start, char_end) in enumerate(offsets): if (start >= char_start) and (start < char_end): token_start = j if (end > char_start) and (end <= char_end): token_end = j + 1 assert token_start is not None assert token_end is not None toks = tokens[token_start:token_end] return (None, token_start, token_end, toks)
def label_gen(index): """Generates label set for individual gaussian index = index of peak location output string format: 'a' + index + "_" + parameter""" # generates unique parameter strings based on index of peak pref = str(int(index)) comb = 'a' + pref + '_' cent = 'center' sig = 'sigma' amp = 'amplitude' fract = 'fraction' # creates final objects for use in model generation center = comb + cent sigma = comb + sig amplitude = comb + amp fraction = comb + fract return center, sigma, amplitude, fraction, comb
def effect(effect_brushtype="stroke", effect_scale=2.5, effect_period=4, **kwargs): """ :param effect_brushtype: The brush type for ripples. options: 'stroke' and 'fill'. :param effect_scale: The maximum zooming scale of ripples in animation. :param effect_period: The duration of animation. :param kwargs: :return: """ _effect = { "brushType": effect_brushtype, "scale": effect_scale, "period":effect_period } return _effect
def image_id_from_path(image_path): """Given a path to an image, return its id. Parameters ---------- image_path : str Path to image, e.g.: coco_train2014/COCO_train2014/000000123456.jpg Returns ------- int Corresponding image id (123456) """ return int(image_path.split("/")[-1][-16:-4])
def is_utf8(data): """ Verify data is valid UTF-8 Args: data (b[]): Byte array Returns: bool: Set to True if valid UTF-8 """ try: data.tostring().decode('utf-8') return True except: return False return True
def get_from_dict_or_default(key, dict, default): """Returns value for `key` in `dict` otherwise returns `default`""" if key in dict: return dict[key] else: return default
def make_divisible(v, divisor, min_value=None): """ Arguments: v: a float. divisor, min_value: integers. Returns: an integer. """ if min_value is None: min_value = divisor new_v = max(min_value, (int(v + divisor / 2) // divisor) * divisor) # make sure that round down does not go down by more than 10% if new_v < 0.9 * v: new_v += divisor # now value is divisible by divisor # (but not necessarily if min_value is not None) return new_v
def clip_rect_to_image(rect, img_width, img_height): """Ensure that the rectangle is within the image boundaries. Explicitly casts all entries to integer. :param rect: list/tuple (l,t,w,h) :param img_width: int :param img_height: int :return: (l, t, w, h) """ l, t, w, h = int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3]) # Right/bottom bounds are exclusive r = max(0, min(img_width, l+w)) b = max(0, min(img_height, t+h)) # Left/top bounds are inclusive l = max(0, l) t = max(0, t) return (l, t, r-l, b-t)
def format_rgds_entries(rgds_entries): """Turn the RG DS dictionary into a list of strings that can be placed into a header object. """ rgds_strings = {} for rg_id in rgds_entries: rgds_string = ("BINDINGKIT={b};SEQUENCINGKIT={s};" "SOFTWAREVERSION={v}" .format(b=rgds_entries[rg_id][0], s=rgds_entries[rg_id][1], v=rgds_entries[rg_id][2])) rgds_strings[rg_id] = rgds_string return rgds_strings
def is_weight(v): """ Check wether a variable is branch length or weight parameter :param v: variable :return: True/False """ return str(v)[0] == 'w'
def _get_scheme(configs): """Returns the scheme to use for the url (either http or https) depending upon whether https is in the configs value. :param configs: OSTemplateRenderer config templating object to inspect for a complete https context. :returns: either 'http' or 'https' depending on whether https is configured within the configs context. """ scheme = 'http' if configs and 'https' in configs.complete_contexts(): scheme = 'https' return scheme
def convert_ints_to_chars(in_ints): """Convert integers to chars. :param in_ints: input integers :return the character array converted""" return [chr(x) for x in in_ints]
def get_marker_obj(plugin, context, resource, limit, marker): """Retrieve a resource marker object. This function is used to invoke plugin._get_<resource>(context, marker) and is used for pagination. :param plugin: The plugin processing the request. :param context: The request context. :param resource: The resource name. :param limit: Indicates if pagination is in effect. :param marker: The id of the marker object. :returns: The marker object associated with the plugin if limit and marker are given. """ if limit and marker: return getattr(plugin, '_get_%s' % resource)(context, marker)
def deep_remove(l, *what): """Removes scalars from all levels of a nested list. Given a list containing a mix of scalars and lists, returns a list of the same structure, but where one or more scalars have been removed. Examples -------- >>> print(deep_remove([[[[0, 1, 2]], [3, 4], [5], [6, 7]]], 0, 5)) [[[[1, 2]], [3, 4], [], [6, 7]]] """ if isinstance(l, list): # Make a shallow copy at this level. l = l[:] for to_remove in what: if to_remove in l: l.remove(to_remove) else: l = list(map(lambda elem: deep_remove(elem, to_remove), l)) return l
def merge_tfds(*terms_d): """ mege_tfds(): is getting a set of term-frequency dictionaries as list of arguments and return a dictionary of common terms with their sum of frequencies of occurred in all dictionaries containing these terms. """ tf_d = dict() tf_l = list() for tr_dict in terms_d: tf_l.extend(tr_dict.items()) for i in range(len(tf_l)): if tf_l[i][0] in tf_d: tf_d[tf_l[i][0]] += tf_l[i][1] else: tf_d[tf_l[i][0]] = tf_l[i][1] return tf_d
def find_largest_palindrome_product(n): """ Finds the largest palindrome product of 2 n-digit numbers :param n: N digit number which specifies the number of digits of a given number :return: Largest Palindrome product of 2 n-digit numbers :rtype: int >>> find_largest_palindrome_product(2) 9009 """ # first find the upper and lower limits for numbers with n digits upper_limit = 0 for _ in range(1, n + 1): upper_limit *= 10 upper_limit += 9 # lower limit is 1 + the upper limit floor division of 10 lower_limit = 1 + upper_limit // 10 # initialize the max product max_product = 0 for x in range(upper_limit, lower_limit - 1, -1): for y in range(x, lower_limit - 1, -1): product = x * y # short circuit early if the product is less than the max_product, no need to continue computation as this # already fails if product < max_product: break number_str = str(product) # check if this is a palindrome and is greater than the max_product currently if number_str == number_str[::-1] and product > max_product: max_product = product return max_product
def jsonpath_to_variable(p): """Converts a JSON path starting with $. into a valid expression variable""" # replace $ with JSON_ and . with _ return p.replace('$', 'JSON_').replace('.', '_')
def addVectors(v1, v2): """assumes v1, and v2 are lists of ints. Returns a list containing the pointwise sum of the elements in v1 and v2. For example, addVectors([4, 5], [1, 2, 3]) returns [5, 7, 3], and addVectors([], []) returns []. Does not modify inputs.""" if len(v1) > len(v2): result = v1 other = v2 else: result = v2 other = v1 for i in range(len(other)): result[i] += other[i] return result
def _get_blocked_revs(props, name, path): """Return the revisions blocked from merging for the given property name and path. """ if name == 'svnmerge-integrated': prop = props.get('svnmerge-blocked', '') else: return "" for line in prop.splitlines(): try: p, revs = line.split(':', 1) if p.strip('/') == path: return revs except Exception: pass return ""
def dict_to_style(style_dict): """ Transform a dict into a string formatted as an HTML style Args: style_dict(dict): A dictionary of style attributes/values Returns: str: An HTML style string """ return "; ".join(["{}: {}".format(k, v) for k, v in style_dict.items()])
def vhdl_slv2num(slv): """ Given a VHDL slv string, returns the number it represents. """ is_hex = slv.startswith('x') return int(slv.lstrip('x').strip('"'), 16 if is_hex else 2)
def build_csv_row(repository: str = '', component: str = '', timestamp: str = '', dep_type: str = '', version: str = '', license_risk: str = '', security_risk: str = '', version_risk: str = '', activity_risk: str = '', operational_risk: str = '', vulnerability_id: str = '', description: str = '', url: str = '', solution: str = ''): """ :param repository: repository name :param component: component/library name :param timestamp: component scan date/time :param dep_type: component dependency type (direct, transitive, exact) :param version: used version :param license_risk :param security_risk :param version_risk :param activity_risk :param operational_risk :param vulnerability_id: the CVE, BDSA id :param description: vulnerability description :param url: vulnerability URL :param solution: update to version :return: a list with parameters """ row = [repository, component, timestamp, dep_type, version, license_risk, security_risk, version_risk, activity_risk, operational_risk, vulnerability_id, description, url, solution] return row
def get_weight_shapes2(num_inputs, layer_sizes, num_outputs, trainable_arr): """ see calc_num_weights2 for relevant of suffix """ weight_shapes = [] input_size = num_inputs for i, layer in enumerate(layer_sizes): if trainable_arr[i]: weight_shapes.append((input_size, layer)) weight_shapes.append((layer,)) input_size = layer if trainable_arr[-1]: weight_shapes.append((input_size, num_outputs)) weight_shapes.append((num_outputs,)) return weight_shapes
def extract_subelements(vector): """ Transform multiple element list into a 1D vector Function 'extract_subelements' return [1,2,3,1] from an oririginal vector like [[1,2,3], [1]] Args: vector (list of list): Original list of list Returns: extracted (list): Return 1D list """ extracted = [] for elem in vector: for value in elem : extracted.append(value) return extracted
def color565(r, g=0, b=0): """Convert red, green and blue values (0-255) into a 16-bit 565 encoding.""" try: r, g, b = r # see if the first var is a tuple/list except TypeError: pass return (r & 0xF8) << 8 | (g & 0xFC) << 3 | b >> 3
def sift_primes(n): """Sieve of eratosthenese. For all integers up to n, sifts out the non-primes and returns list of all primes up to n. """ if n < 2: print('Passed in integer is not large enough to contain primes.') return -1 numbers = [x for x in range(2, n + 1)] # numbers = [True for x in range(2, n + 1)] i = 2 while i < len(numbers) + 2: for j in range(i*2, n + 1, i): # print('j = {}'.format(j)) if j in numbers: numbers.remove(j) i += 1 # Failed attempt """ for i in numbers: for j in numbers: if j % i == 0: numbers.remove(j) """ return numbers
def match_subroutine_end(names): """ """ if len(names) < 3: return "" if names[0]=="END" and names[1]=="SUBROUTINE": return names[2] return ""
def _norm_hsl2rgb(h, s, l): """Convert HSL to RGB colours. This function assumes the input has been sanitised and does no validation on the input parameters. This calculation has been adapted from Wikipedia: https://en.wikipedia.org/wiki/HSL_and_HSV#To_RGB :param h: Hue :param s: Saturation :param l: Lightness :return: A tuple containing R, G, B colours """ C = (1 - abs(2 * l - 1)) * s m = l - C / 2 h_ = h / 60.0 # H' is not necessarily an integer X = C * (1 - abs(h_ % 2 - 1)) r, g, b = 0, 0, 0 if 0 <= h_ <= 1: r, g, b = C, X, 0 elif 1 < h_ <= 2: r, g, b = X, C, 0 elif 2 < h_ <= 3: r, g, b = 0, C, X elif 3 < h_ <= 4: r, g, b = 0, X, C elif 4 <= h_ <= 5: r, g, b = C, 0, X elif 5 < h_ <= 6: r, g, b = X, 0, C return r + m, g + m, b + m
def rad_trans(rad_in, medium, eta): """ Calculates radiation transfer through a semi-transparent medium. One can also use the same function for Johnson-Nyquist PSD (power spectral density) instead of temperature. Parameters ---------- rad_in : scalar or vector brightness temperature (or PSD) of the input Units: K (or W/Hz) medium : scalar brightness temperature (or PSD) of the lossy medium Units: K (or W/Hz) eta : scalar or vector transmission of the lossy medium Units: K (or W/Hz) Returns ------- rad_out : brightness temperature (or PSD) of the output """ rad_out = eta * rad_in + (1 - eta) * medium return rad_out
def response_id(req_data): """ Get the ID for the response from a JSON-RPC request Return None if ID is missing or invalid """ _id = None if isinstance(req_data, dict): _id = req_data.get('id') if type(_id) in (str, int): return _id else: return None
def get_fuel_types(types): """ Input arguments for function = list Returns dictionary with empty values. Input example: get_fuel_types(["95", "95 Premium"]) Output example: {'95': None, '95 Premium': None} """ fuel_types = dict.fromkeys(types) return fuel_types
def oddNumbersUsingFilter(myList: list) -> list: """ Simple filter function for odds numbers using filter and lambda. """ odd = list(filter(lambda x: x % 2 != 0, myList)) return odd
def convert_to_slug(s): """ Very simple filter to slugify a string """ if s is not None: return s.strip().lower().replace('.','').replace(' ','-').replace(',','-').replace('--','-') return None
def relative_distance(A, B): """ Calculates a quantity proportional to 3D distance """ dx, dy, dz = A[0] - B[0], A[1] - B[1], A[2] - B[2] return dx*dx+dy*dy+dz*dz
def r_sigma(row): """Calculates r_sigma. John-Bloch's indicator1: |rp(A) + rs(A) - rp(B) -rs(B)| from Phys. Rev. Lett. 33, 1095 (1974). Input rp(A), rs(A), rp(B), rs(B) They need to be given in this order. """ return abs(row[0] + row[1] - row[2] + row[3])
def calculate_progress(total_count, count, start_progress = 0.0): """Calculates the progress in a way that is guaranteed to be safe from divizion by zero exceptions or any other exceptions. If there is any problem with the calculation or incoming arguments, this function will return 0.0""" default = 0.0 progress = float(start_progress) if not (0.0 <= progress <= 1.0): return default if not (0 <= count <= total_count): return default try: progress += float(count) / float(total_count) except: pass assert type(progress) == float if not (0.0 <= progress <= 1.0): return default return progress
def extract_name_path(file_path: str) -> str: """String formatting to update the prefix of the ERA5 store location to Azure Parameters ---------- file_path : str input file path Returns ------- str azure specific formatted file path """ tgt = "az://cmip6/ERA5/" + file_path.split("/zarr/")[1].replace("/data", "") return tgt
def _valid_scorer(word: str) -> int: """Gives the score of a word assumed to be valid.""" if len(word) == 4: score = 1 else: score = len(word) if len(set(word)) == 7: score += 7 return score
def string2list( in_str ): """ converts comma separated string to the list """ out_list= [] try: for elm in in_str.split(','): if '[' in elm: elm= elm.replace('[', '') if ']' in elm: elm= elm.replace(']', '') out_list.append( elm.strip().encode('utf-8') ) except: pass return out_list
def R(x, alpha , beta, gamma): """Calculates term of the first dimension of the ODE of FitzHugh Nagumo, see function ODE_FHN_network() and ODE_FHN_network_noisy(): R= -alpha* x1**3 + beta *x1**2 - gamma* x1 Parameters ------- x : array of shape (N,) first dimension of state at a single timepoint alpha, beta, gamma : floats parameter of sigle FutzHugh-Nagumo nodes Returns ------- R : array of shape (N,) -alpha* x1**3 + beta *x1**2 - gamma* x1 """ return -alpha* x**3 + beta *x**2 - gamma* x
def get_fps( i_datasets_folder: str, dat: str) -> tuple: """ Parameters ---------- i_datasets_folder : str Path to the folder containing the data/metadata sub-folders dat : str Dataset name Returns ------- tsv_fp : str Path to the .tsv feature table qza_fp : str Path to the .qza feature table meta : str Path to the metadata """ tsv_fp = '%s/data/tab_%s.tsv' % (i_datasets_folder, dat) qza_fp = tsv_fp.replace('.tsv', '.qza') meta_fp = tsv_fp.replace( '%s/data/' % i_datasets_folder, '%s/metadata/' % i_datasets_folder ).replace('tab_', 'meta_') return tsv_fp, qza_fp, meta_fp
def tuple_hasnext(xs): """Whether the tuple is empty or not.""" return len(xs) > 0
def ellipsis(text, length, symbol="..."): """Present a block of text of given length. If the length of available text exceeds the requested length, truncate and intelligently append an ellipsis. """ if len(text) > length: pos = text.rfind(" ", 0, length) if pos < 0: return text[:length].rstrip(".") + symbol else: return text[:pos].rstrip(".") + symbol else: return text
def get_mechanism_file_name(mechanism_name: str) -> str: """Form the CTI file name for a mechanism.""" return f"{mechanism_name}.cti"
def tag_data(data, data_to_tag): """Returns the (data, data_to_tag(data)) pair""" return data, data_to_tag(data)
def iseven(x): """is the number x an even number?""" return x%2 == 0
def get_max(num_list): """Recursively returns the largest number from the list""" if len(num_list) == 1: return num_list[0] else: return max(num_list[0], get_max(num_list[1:]))
def hamming_dist(str1, str2): """ Calculates the hamming distance between 2 strings. :param str1: first string :param str2: second string :return: the distance """ distance = 0 for ch1, ch2 in zip(str1, str2): if ch1 != ch2: distance += 1 return distance
def get_len(in_string, max_len): """Calculate string length, return as a string with trailing 0s. Keyword argument(s): in_string -- input string max_len -- length of returned string """ tmp_str = str(len(in_string)) len_to_return = tmp_str for _ in range(max_len - len(tmp_str)): len_to_return = '0' + len_to_return return len_to_return
def convert_float(string_value): """Converts string to a float (see CONVERTERS). There is a converter function for each column type. :param string_value: The string to convert :raises: ValueError if the string cannot be represented by a float """ return float(string_value.strip())
def process_kwargs(expected_keys, kwargs): """Check for any expected but missing keyword arguments and raise a TypeError else return the keywords arguments repackaged in a dictionary i.e the payload. """ payload = {} for key in expected_keys: value = kwargs.pop(key, False) if not value: raise TypeError("Missing keyword argument: %s" % key) else: payload[key] = value return payload