content
stringlengths
42
6.51k
def sbox(block): """Bitsliced implementation of the s-box""" a = (block[0] & block[1]) ^ block[2] c = (block[1] | block[2]) ^ block[3] d = (a & block[3]) ^ block[0] b = (c & block[0]) ^ block[1] return [a,b,c,d]
def textmark(string, mark=""): """ Excerpt of content >>> textmark('<p>Hello</p><!----><p>World</p>') '<p>Hello</p>' >>> textmark('<p>Hello</p><!--ex--><p>World</p>', 'ex') '<p>Hello</p>' >>> textmark('<p>Hello</p><!----><p>World</p><!--test-->', 'test') '<p>Hello</p><!----><p>World</p>' """ mark = "<!--{0}-->".format(mark) if mark in string: index = string.index(mark) return string[0:index] return ""
def lr_schedule(epoch): """ schedule a dynamic learning rate :param epoch: :return: """ lr = 0.001 if (epoch > 75): lr = 0.0005 elif (epoch > 100): lr = 0.0003 return lr
def get_full_asetup(cmd, atlas_setup): """ Extract the full asetup command from the payload execution command. (Easier that generating it again). We need to remove this command for stand-alone containers. Alternatively: do not include it in the first place (but this seems to trigger the need for further changes). atlas_setup is "source $AtlasSetup/scripts/asetup.sh", which is extracted in a previous step. The function typically returns: "source $AtlasSetup/scripts/asetup.sh 21.0,Athena,2020-05-19T2148,notest --makeflags='$MAKEFLAGS';". :param cmd: payload execution command (string). :param atlas_setup: extracted atlas setup (string). :return: full atlas setup (string). """ pos = cmd.find(atlas_setup) cmd = cmd[pos:] # remove everything before 'source $AtlasSetup/..' pos = cmd.find(';') cmd = cmd[:pos + 1] # remove everything after the first ;, but include the trailing ; return cmd
def is_integer(s): """ Using exceptions for this feels... wrong...""" try: int(s) return True except ValueError: return False
def cloudtrail_snapshot_or_ami_made_public(rec): """ author: spiper description: Alert on AWS API calls that make EBS snapshots, RDS snapshots, or AMIs public. playbook: (a) identify the AWS account in the log (b) identify what resource(s) are impacted by the API call (c) determine if the intent is valid, malicious or accidental """ # For each resouce walk through through the request parameters to check # if this is adding permissions for 'all' # Check AMIs if rec['eventName'] == 'ModifyImageAttribute': # For AMIs params = rec.get('requestParameters', {}) if params.get('attributeType', '') == 'launchPermission': if 'add' in params.get('launchPermission', {}): items = params['launchPermission']['add'].get('items', []) for item in items: if item.get('group', '') == 'all': return True # Check EBS snapshots if rec['eventName'] == 'ModifySnapshotAttribute': params = rec.get('requestParameters', {}) if params.get('attributeType', '') == 'CREATE_VOLUME_PERMISSION': if 'add' in params.get('createVolumePermission', {}): items = params['createVolumePermission']['add'].get('items', []) for item in items: if item.get('group', '') == 'all': return True # Check RDS snapshots if rec['eventName'] == 'ModifyDBClusterSnapshotAttribute': params = rec.get('requestParameters', {}) if 'all' in params.get('valuesToAdd', []): return True return False
def diff(first, second): """Takes the set diff of two lists""" second = set(second) return [item for item in first if item not in second]
def densenet_params(model_name): """ Map densenet_pytorch model name to parameter coefficients. """ params_dict = { # Coefficients: growth_rate, num_init_features, res "densenet121": (32, 64, 224), "densenet161": (48, 96, 224), "densenet169": (32, 64, 224), "densenet201": (32, 64, 224), } return params_dict[model_name]
def ewma(p_mean, val, alpha=0.8): """computes exponentially weighted moving mean""" return p_mean + (alpha * (val - p_mean))
def get_type_hint(q_list: list): """ Uses the first word of the question to return the likely response format of the question's answer. Args: ----- q_list: a list of strings containing the questions Returns: -------- A list of strings containing whether the questions are extraction or classification """ hints = [] for q in q_list: first_word = q.split(" ")[0].lower() if first_word in [ "what's", "which", "what", "when", "where", "how", "on", "who", "in", "per", "the", "at", "could", "aside", "during", "how's", "pertaining", ]: hints.append("extraction") elif first_word in [ "does", "are", "is", "am", "can", "do", "did", "was", "were", "should", "has", "have", "will", "while", "after", ]: hints.append("classification") else: raise Exception( "Did not expect Q: ", q ) # NOTE: if you add a new question with a new start word, add it here return hints
def fix_date(date): """ fix date value from user input Args: date: date value - user input Returns: an array with fixed date value or original date """ if date: if date.count(":") == 2: return [ date, "{0} 23:59:59".format( date.rsplit()[0] ) ] elif date.count("|") == 1 and date.count(":") == 4: return date.rsplit("|") elif date.count("|") == 1 and date.count(":") == 0: return [ "{0} 00:00:00".format( date.rsplit("|")[0] ), "{0} 23:59:59".format( date.rsplit("|")[1] ) ] else: return "{0} 00:00:00|{0} 23:59:59".format(date).rsplit("|") return date
def GetFlakeIssue(flake): """Returns the associated flake issue to a flake. Tries to use the flake's issue's merge_destination, and falls back to the issue itself if it doesn't merge into any other ones. Args: flake: A Flake Model entity. Returns: A FlakeIssue entity if it exists, otherwise None. This entity should be the final merging destination issue. """ if not flake: return None return flake.GetIssue(up_to_date=True)
def count_to_palindrome(arr: list) -> int: """ Time Complexity: O(n) """ i, j = 0, len(arr) - 1 total: int = 0 while i < j: if arr[i] == arr[j]: i += 1 j -= 1 continue elif arr[i] < arr[j]: i += 1 arr[i] += arr[i - 1] else: j -= 1 arr[j] += arr[j + 1] total += 1 return total
def kinetic_energy(vehicle_mass, v): """ Calculates the rotational energy stored in a tire :param vehicle_mass: The tire moment of inertia :param v: The velocity of the vehicle (m/s) :return: The energy in Joules stored as rotational kinetic energy """ return vehicle_mass * (v ** 2) / 2
def subplot_index(nrow, ncol, k, kmin=1): """Return the i, j index for the k-th subplot.""" i = 1 + (k - kmin) // ncol j = 1 + (k - kmin) % ncol if i > nrow: raise ValueError('k = %d exceeds number of rows' % k) return i, j
def increment(x): """adds 1 to x""" return(x+1)
def compile_references(d): """get the references from the Excel sheet for each year in the decade. return them in a list.""" refs = [] for e, date in enumerate(d["dates"]): if d["references"][e] not in refs: refs.append(d["references"][e]) return refs
def create_put_request(item): """Create a PutRequest object.""" return {'PutRequest': {'Item': item}}
def cdp_version_decode( cdp_version ): """ Decode a CDP version string of the form 'xx.yy.zz' into xx -> cdprelease, yy --> cdpversion and zz -> cdpsubversion. Strings of the form 'xx.yy' or 'xx' are also decoded (with the missing version numbers returned as None). If an empty or invalid string is provided, all three version numbers are returned as None. :Parameters: cdp_version: str CDP version string, of the form 'xx.yy.zz', 'xx.yy' or 'xx'. :Returns: xxyyzz: tuple of 3 str (xx, yy, zz) """ # Reject a null version code, a non-string or an empty string. if cdp_version is None or \ not isinstance(cdp_version, str) or \ len(cdp_version) < 1: return (None, None, None) # Split the version code into words separated by '.'. version = cdp_version.split('.') nwords = len(version) cdprelease = version[0] if nwords > 1: cdpversion = version[1] if nwords > 2: cdpsubversion = version[2] else: cdpsubversion = None else: cdpversion = None cdpsubversion = None return (cdprelease, cdpversion, cdpsubversion)
def find_center_point(corners): """ use points that are on the diagonal to calculate the center points corners - array of 4 [x,y] arrays. corner[0] = [x0,y0] corner[0][0] = x0 corner[0][1] = y0 """ center_x = (corners[0][0] + corners[2][0])//2 center_y = (corners[0][1] + corners[2][1])//2 return center_x, center_y
def check(result, response): """ Returns a string of correct, incorrect, or invalid after comparing the conversion result and response of the student rounded to the ones place. """ try: if result is None: return "invalid" elif response is not None: return "correct" if int(response) == int(result) else "incorrect" return result except ValueError: return "incorrect"
def get_trials_per_job_mpi(njobs, ntrials): """ split for mpi """ return int(round(float(ntrials)/njobs))
def apply_to_list(op, inputs): """Apply operator `op` to list `inputs` via binary tree """ n = len(inputs) if n == 1: return inputs[0] m0 = apply_to_list(op, inputs[: n // 2]) m1 = apply_to_list(op, inputs[n // 2 :]) return op(m0, m1)
def hello(name,origin): """ This is the first hello world for python function/modules """ return "helo " + str.strip(str(name)) +" van "+ str.strip(str(origin))
def is_numeric(string): """ Determine whether the string is a number. :param string: String to test. :return: True if the string is a number. False otherwise. """ try: float(string) return True except ValueError: return False pass
def human_readable(value): """ Returns the number in a human readable format; for example 1048576 = "1Mi". """ value = float(value) index = -1 suffixes = 'KMGTPEZY' while value >= 1024 and index + 1 < len(suffixes): index += 1 value = round(value / 1024) if index == -1: return '{:d}'.format(value) return '{:d}{}i'.format(round(value), suffixes[index])
def weighted_match_score(vector1, vector2): """Calculate matching score that considers both the relative intensities of the matching peaks (i.e. is is 100 vs 98, or 100 vs 2?) and also the number of matches versus the total number of peaks in each vector """ vector1_weighted_pairwise_match = 0 vector2_weighted_pairwise_match = 0 for i in range(len(vector1)): if vector1[i] > 0 and vector2[i] > 0: weighting_factor = vector1[i]/vector2[i] if weighting_factor > 1: weighting_factor = 1/weighting_factor vector1_weighted_pairwise_match += vector1[i] * weighting_factor vector2_weighted_pairwise_match += vector2[i] * weighting_factor if sum(vector1) > 0: vector1_score = vector1_weighted_pairwise_match/sum(vector1) else: vector1_score = 0 if sum(vector2) > 0: vector2_score = vector2_weighted_pairwise_match/sum(vector2) else: vector2_score = 0 if vector1_score < vector2_score: return vector1_score else: return vector2_score
def linear_mapping(_from, _to, x): """ Lets use a simple linear function that maps the ends of one scale onto ends of another. Obviously, we need that f(left_min) -> right_min and f(left_max) -> right_max, and points in between are mapped proportionally. """ return _to[0] + (x - _from[0]) / (_from[1] - _from[0]) * (_to[1] - _to[0])
def string_to_int(s): """Convert a string of bytes into an integer, as per X9.62.""" result = 0 for c in s: if not isinstance(c, int): c = ord(c) result = 256 * result + c return result
def endswith(value, arg): """Usage, {% if value|endswith:"arg" %}""" return value.endswith(arg)
def cidr_to_netmask(cidr): """ :param cidr: :return: """ cidr = int(cidr) mask_addr = (0xffffffff >> (32 - cidr)) << (32 - cidr) return (str((0xff000000 & mask_addr) >> 24) + '.' + str((0x00ff0000 & mask_addr) >> 16) + '.' + str((0x0000ff00 & mask_addr) >> 8) + '.' + str((0x000000ff & mask_addr)))
def sum_multiples_three_five(number): """ number: random integer return: the sum of all multipliers of 3 and 5 below number """ multipliers = [] n = 0 while n < number: if n % 3 == 0 or n % 5 == 0: multipliers.append(n) n += 1 return sum(multipliers)
def translate(value, from_min, from_max, to_min, to_max): """ Translates the value passed as a parameter into a corresponding value in the right range. """ # Figure out how 'wide' each range is left_span = from_max - from_min right_span = to_max - to_min # Convert the left range into a 0-1 range (float) value_scaled = float(value - from_min) / float(left_span) # Convert the 0-1 range into a value in the right range. return to_min + (value_scaled * right_span)
def is_wd_id(var): """ Checks whether a variable is a Wikidata id """ if var[0] == "Q" and var.split("Q")[1].isnumeric(): # check if it's a QID return True if var[0] == "P" and var.split("P")[1].isnumeric(): # check if it's a PID return True return False
def LCS(X,Y): """ Return length of longest common subsequence of X and Y. Used to measure how much has changed in student ordering when an optimization is done. Algorithm straight from CLRS (Chapter 13--Dynamic Programming) """ m = len(X) n = len(Y) C = [[0 for j in range(n+1)] for i in range(m+1)] for i in range(1, m+1): for j in range(1, n+1): if X[i-1]==Y[j-1]: C[i][j] = C[i-1][j-1] + 1 elif C[i-1][j] > C[i][j-1]: C[i][j] = C[i-1][j] else: C[i][j] = C[i][j-1] return C[m][n]
def has_changes(statements): """ See if a list of SQL statements has any lines that are not just comments """ for stmt in statements: if not stmt.startswith('--') and not stmt.startswith('\n\n--'): return True return False
def Power_Calc(Vcell, i): """ Calculate power. :param Vcell: Vcell Voltage [V] :type Vcell : float :param i: cell load current [A] :type i : float :return: cell power [W] as float """ try: result = Vcell * i return result except TypeError: print( "[Error] Power Calculation Error (Vcell:%s, i:%s)" % (str(Vcell), str(i)))
def safeForKids(haveKids, kidFriendly): """Determines if the user is travelling with kids or not, as if the country is kid friendly, anyone can go, but if it is no kid friendly, then only people travelling without kids can go there Parameters: haveKids: The user's input as to if they have kids or not kidFriendly: the .csv info on if the country if kid friendly Return: bool: Uses boolean (bool) to set the user input to true or false to compare with the .csv file""" isSafeForKids = True if(haveKids and not kidFriendly): isSafeForKids = False return isSafeForKids
def valid_name_request(count): """A method for validating a request to get unique names. Parameters ---------- filename : str The filename to read. """ if 0 < count <= 1000: return True
def parse_pos_line(cell_line): """ Parse single line in the cell block. Return element, coorindates and a dictionary of tags """ import re cell_line = cell_line.strip() s = re.split(r"[\s]+", cell_line, maxsplit=4) if len(s) < 4: raise ValueError("Cannot understand line: {}".format(cell_line)) if len(s) == 5: tags = s[-1] else: tags = "" elem = s[0].capitalize() coor = list(map(float, s[1:4])) return elem, coor, tags
def get_base_layout(figures): """Generate a layout with the union of multiple figures' layouts. Parameters ---------- figures : list List of Plotly figures to get base layout from. """ if not isinstance(figures, list): raise TypeError("Invalid figures '{0}'. " "It should be list." .format(figures)) layout = {} for figure in figures: if not figure['layout']: raise Exception("Figure does not have 'layout'.") for key, value in figure['layout'].items(): layout[key] = value return layout
def _union_1d(first, second, size): """Computes if slice first and second overlap for the size of the dimension""" first_min, first_max, _ = first.indices(size) second_min, second_max, _ = second.indices(size) if first_max >= second_min and second_max >= first_min: return slice(min(first_min, second_min), max(first_max, second_max)) else: return None
def check_request_params(data, params): """ Checks that a JSON request contains the proper parameters. Parameters ---------- data : json The JSON request params: list The parameters that should appear in the JSON request Returns ------- str A message detailing validation errors, if any """ msg = "" if type(data) is not dict: msg = "JSON request data is in invalid format" return msg for p in params: if p not in data: msg = "The following field is required: " + p return msg return msg
def contains_alpha(string): """ Return True if the input 'string' contains any alphabet """ return any([c.isalpha() for c in string])
def memoized_fibonacci(n): """Returns the nth fibonacci number Time complexity: O(n) Parameters ---------- n : int the nth fibonacci position Returns ------- int the nth fibonacci number ------- >>> memoized_fibonacci(0) 0 >>> memoized_fibonacci(1) 1 >>> memoized_fibonacci(3) 2 """ cache = {} def fib(m): if m < 0: raise ValueError("Value cannot be negative") if m in cache: return cache[m] if m == 1: return 1 if m == 0: return 0 cache[m] = fib(m - 1) + fib(m - 2) return cache[m] return fib(n)
def signed_area(coords): """Return the signed area enclosed by a ring using the linear time algorithm at http://www.cgafaq.info/wiki/Polygon_Area. A value >= 0 indicates a counter-clockwise oriented ring.""" try: xs, ys = tuple(map(list, zip(*coords))) except ValueError: # Attempt to handle a z-dimension xs, ys, _ = tuple(map(list, zip(*coords))) xs.append(xs[1]) ys.append(ys[1]) return sum(xs[i] * (ys[i + 1] - ys[i - 1]) for i in range(1, len(coords))) / 2.
def get_altitude(pressure: float, sea_level_hPa: float = 1013.25) -> float: """ the conversion uses the formula: h = (T0 / L0) * ((p / P0)**(-(R* * L0) / (g0 * M)) - 1) where: h = height above sea level T0 = standard temperature at sea level = 288.15 L0 = standard temperatur elapse rate = -0.0065 p = measured pressure P0 = static pressure = 1013.25 g0 = gravitational acceleration = 9.80665 M = mloecular mass of earth's air = 0.0289644 R* = universal gas constant = 8.31432 Given the constants, this works out to: h = 44330.8 * (1 - (p / P0)**0.190263) Arguments: pressure {float} -- current pressure sea_level_hPa {float} -- The current hPa at sea level. Returns: [type] -- [description] """ return 44330.8 * (1 - pow(pressure / sea_level_hPa, 0.190263))
def ident_values_changed(func_args, ident): """Check for changes to state or attributes on ident vars.""" var_name = func_args.get("var_name", None) if var_name is None: return False value = func_args["value"] old_value = func_args["old_value"] for check_var in ident: var_pieces = check_var.split(".") if len(var_pieces) == 2 and check_var == var_name: if value != old_value: return True elif len(var_pieces) == 3 and f"{var_pieces[0]}.{var_pieces[1]}" == var_name: if getattr(value, var_pieces[2], None) != getattr(old_value, var_pieces[2], None): return True return False
def _interpolate(val, vmin, vmax): """Interpolate a color component between to values as provided by matplotlib colormaps """ interp = (val - vmin[0]) / (vmax[0] - vmin[0]) return (1 - interp) * vmin[1] + interp * vmax[2]
def to_lower_case(name): """Returns a lower-case under-score separated format of the supplied name, which is supposed to be camel-case: >>> ToScriptName("AbcABC01ABCAbc") "abc_abc01abc_abc" """ script_name = "" for i in range(len(name)): if i > 0 and (name[i-1:i].islower() or name[i-1:i].isdigit() or (i+1 < len(name) and name[i+1:i+2].islower())) and name[i:i+1].isupper(): script_name += "_" script_name += name[i:i+1].lower() return script_name
def default_none(value, default): """ Returns |value| if it is not None, otherwise returns |default|. """ return value if value != None else default
def unconvert_rounded_offset(y): """ >>> from undervolt import convert_offset, unconvert_offset >>> domain = [ 1024 - x for x in range(0, 2048) ] >>> all( x == unconvert_rounded_offset(convert_rounded_offset(x)) for x in domain ) True """ x = y >> 21 return x if x <= 1024 else - (2048 - x)
def hours_to_minutes(time): """ input: 'HH:MM', output: same time in minutes """ time = time.split(':') return int(time[0])*60 + int(time[1])
def update_final_dict_to_have_no_mappings(final_dict): """ This function removes all mappings from the dictionary and only element values are retained """ for element in final_dict: if final_dict[element] is not None and final_dict[element] is not False and "=" in final_dict[element]: temp_list = final_dict[element].split("=") if temp_list[0] in final_dict: temp_var = temp_list[1] for i in range(2, len(temp_list)): temp_var = temp_var + "=" + temp_list[i] final_dict[element] = temp_var return final_dict
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message, response_card): """Builds the response to elicit slot clarification""" return { 'sessionAttributes': session_attributes, 'dialogAction': { 'type': 'ElicitSlot', 'intentName': intent_name, 'slots': slots, 'slotToElicit': slot_to_elicit, 'message': message, 'responseCard': response_card } }
def counting_sheep(sheeps) -> int: """This function count True in list.""" count = 0 for sheep in sheeps: if sheep: count += 1 return count
def _get_string(dictionary, key, del_if_bad=True): """ Get a string from a dictionary by key. If the key is not in the dictionary or does not refer to a string: - Return None - Optionally delete the key (del_if_bad) """ if key in dictionary: value = dictionary[key] if isinstance(value, str): return value else: if del_if_bad: del dictionary[key] return None else: return None
def answer(word): """ initialize an answer space. :param word: string :return: string """ ans = '' for i in range(len(word)): ans += '-' return ans
def get_subindex(string, ch): """ Finds all indexes of the specified character in the string. """ return [c for (c, i) in enumerate(string) if i == ch]
def remove_underscores(s): """ :param s: :return: """ return s.replace('_', ' ')
def common_characters(w1, w2): """ Parameters: ---------- w1: str w2: str Returns: -------- int: Number of characters common between two strings """ ws1 = set(w1) ws2 = set(w2) return len(ws1.intersection(ws2))
def null_distance_results(string1, string2, max_distance): """Determines the proper return value of an edit distance function when one or both strings are null. """ if string1 is None: if string2 is None: return 0 else: return len(string2) if len(string2) <= max_distance else -1 return len(string1) if len(string1) <= max_distance else -1
def _fixiternum(s): """ Fix the string by adding a zero in front if double digit number, and two zeros if single digit number. """ if len(s) == 2: s = '0' + s elif len(s) == 1: s = '00' + s return s
def encode(content: int) -> bytearray: """Encode an integer into a SDNV :param content: Integer to encode :return: Bytearray containing the encoded value """ if content < 0 or type(content) != int: raise ValueError("Invalid content") flag = 0 ret_array = bytearray() while True: new_bits = content & 0x7F content >>= 7 ret_array.append(new_bits + flag) if flag == 0: flag = 0x80 if content == 0: break ret_array.reverse() return ret_array
def format_value(value): """ Formats a value for output. Arguments: value (?): The value to format. Returns: If the value is a list, returns a comma-separated string of the items in the list. If the value is a dictionary, returns a comma-separated string-representation of the key-value-pairs. Else returns the value, cast to a string. """ if isinstance(value, list): return ', '.join(map(str, value)) elif isinstance(value, dict): return ', '.join(['{0}: {1}'.format(k, v) for k, v in value.items()]) return str(value)
def create_attribute_names(attribute_names): """Create attribute names Args: attribute_names (str): Attribute names Returns: str: Expression attribute names """ expression_attribute_names = {} for attribute_name in attribute_names: expression_attribute_names[f"#{attribute_name}"] = attribute_name return expression_attribute_names
def extract_confidence(result): # pragma: no cover """Extracts the confidence from a parsing result.""" return result.get('intent', {}).get('confidence')
def standardize_old_hpo_objects(hpo_objects, old_hpo_objects): """ In the case where an HPO exists in a 'newer' iteration of an analytics report but not in the 'older' analytics report, this function places a copy of the 'new' HPO object into the old HPO objects list. This placement is to ensure that both lists can be used to evaluate 'new' and 'old' data quality issues in a parallel fashion. Both of the HPO objects will have the same associated DataQualityMetric objects. The fact that the 'first_reported' attributes of said DQM objects will be identical is handled later on in the cross_reference_old_metrics function. Parameters ---------- hpo_objects (lst): list of HPO objects from the current/updated analytics report. old_hpo_objects (lst): list of HPO objects from the previous/reference analytics report. Returns ------- hpo_objects (lst): list of HPO objects and their associated data quality metrics from the 'new' analytics report. old_hpo_objects (lst): list of the HPO objects that were in the previous analytics report. now also contains any HPOs that were introduced in the latest data quality metrics report. new_hpo_ids (lst): list of the 'new' HPO IDs that were added in the most recent iteration of the script. eventually used to ensure that we do not 'look' for the added HPO in the old panels. """ number_new_hpos = len(hpo_objects) new_hpo_ids = [] idx = 0 while idx < number_new_hpos - 1: for hpo, old_hpo, idx in \ zip(hpo_objects, old_hpo_objects, range(number_new_hpos)): # discrepancy found - need to create an 'old' HPO # this will just be a 'copy' of the 'new' HPO if hpo.name != old_hpo.name: copy_of_hpo_object = hpo old_hpo_objects.insert(idx, copy_of_hpo_object) new_hpo_ids.append(hpo.name) idx = 0 # restart the loop # now we have two parallel lists. any 'novel' HPOs # have a counterpart in the 'old HPO list' with identical DQMs. return hpo_objects, old_hpo_objects, new_hpo_ids
def cubic_cutoff(r_cut: float, ri: float, ci: float): """A cubic cutoff that goes to zero smoothly at the cutoff boundary. Args: r_cut (float): Cutoff value (in angstrom). ri (float): Interatomic distance. ci (float): Cartesian coordinate divided by the distance. Returns: (float, float): Cutoff value and its derivative. """ rdiff = r_cut - ri fi = rdiff * rdiff * rdiff fdi = 3 * rdiff * rdiff * ci return fi, fdi
def compute_perfect_tree(total): """ Determine # of ways complete tree would be constructed from 2^k - 1 values. This is a really subtle problem to solve. One hopes for a recursive solution, because it is binary trees, and the surprisingly simple equation results from the fact that it is a complete tree. It comes down to the number of ways you can independently interleave the sequential values from two subsequences. The total of the subsequences is (total - 1), because you leave out the subtree root. Each of the (total // 2) half sequences are then interleaved. To properly count the number of possibilities, you need to multiply by the ways you can create subtrees of half the side (one for the left and one for the right). https://stackoverflow.com/questions/17119116/how-many-ways-can-you-insert-a-series-of-values-into-a-bst-to-form-a-specific-tr """ import math if total == 1: return 1 half = total // 2 return (math.factorial(total-1) / (math.factorial(half) * math.factorial(half))) * compute_perfect_tree(half) * compute_perfect_tree(half)
def int_from_code(code): """ :type code: list :rtype: int """ num = 0 for i, v in enumerate(reversed(code), 1): num *= i num += v return num
def all_none(*args): """Shorthand function for ``all(x is None for x in args)``. Returns True if all `*args` are None, otherwise False.""" return all(x is None for x in args)
def adder_function_json(args): """Dummy function to execute returning a dict.""" loc, scale = args return {'result': loc + scale}
def get_task(task_id, tasks_object): """ Find the matching task.json for a given task_run.json 's task_id :param task_id: task_run.json['task_id'] :type task_id: int :param tasks_object: tasks from json.load(open('task.json')) :type tasks_object: list :return: a JSON task object from task.json :rtype: dict """ task = None for t in tasks_object: if t['id'] == task_id: task = t break return task
def isspace(char): """ Indicates if the char is a space, tabulation or new line """ if char == " " or char == "\t" or char == "\n" or char == "\r": return True return False
def set_led_ring(amount: float): """Return count and color based on credit float amount the ring LED has 8 elements and are set based on credit amounts: credits LEDs lit Color =============== =================== =========================== 0 - 0.24 8 red (#FF0000) 0.25 - 0.49 2 white (#F0F0F0) 0.50 - 0.74 4 white (#F0F0F0) 0.75 - 0.99 6 white (#F0F0F0) 1.00 - 1.99 1 darkest green (#006600) 2.00 - 2.99 2 dark green (#009900) 3.00 - 3.99 3 green (#00E600) 4.00 - 4.99 4 bright green(#00FF00) 5.00 - 5.99 5 bright green(#00FF00) 6.00 - 6.99 6 bright green(#00FF00) 7.00 - 7.99 7 bright green(#00FF00) 8.00 > 8 bright green(#00FF00) """ # Green colors for 1, 2, 3, and greater color_scale = ["#006600", "#009900", "#00E600", "#00FF00"] # Cast to float, most likely Decimal coming in amount = float(amount) if amount == 0.0: # No credits all lit up red count = 8 color = "#FF0000" elif amount < 1.00: # 0.01 - 0.99 - 2 per .25, white count = int(amount / 0.25) * 2 color = "#F0F0F0" else: # At least 1.00 or more, set count to 1-8 per 1.00 count = int(amount / 1.00) if amount < 8.00 else 8 if count < 4: color = color_scale[count - 1] else: color = color_scale[3] return count, color
def mangle_struct_typename(s): """Strip leading underscores and make uppercase.""" return s.lstrip("_").upper()
def regroup_pre_validation_checks(workflow_config_dict): """ Checks if provided configuration is correct for regroup validation. Returns valid regroup filename if found, error list otherwise """ if (workflow_config_dict["run_reference_alignment"] != "yes"): return '', [] # return default output if "regroup_output" in workflow_config_dict: if workflow_config_dict["regroup_output"] == "yes": regroup_file = workflow_config_dict["regroup_file"] if regroup_file != '': return regroup_file, [] else: return '',\ ["Error: Invalid workflow configuration. " + " regroup_output is set to yes, but no reroup " + " file name is specified. Please specify the file" + " name or set regroup_output to no."] return '', []
def count_set_bits(n: int) -> int: """ Count bits == 1 """ count = 0 while (n): count += n & 1 n >>= 1 return count
def undotify(dotdict): """ Expand a dictionary containing keys in "dot notation". This support both standard dict or OrderedDict, or any dict subclass. For example:: .. code-block:: python3 dotdict = { 'key1.key2.key3': 'string1', 'key1.key2.key4': 1000, 'key4.key5': 'string2', } expanded = undotify(dotdict) Will produce: .. code-block:: python3 { 'key1': { 'key2': { 'key3': 'string1', 'key4': 1000, }, }, 'key4': { 'key5': 'string2', }, } :param dict dotdict: Original dictionary containing string keys in dot notation. :return: The expanded dictionary. Same datatype of the input. :rtype: dict """ assert isinstance(dotdict, dict), 'Invalid dictionary' dtype = type(dotdict) result = dtype() for key, value in dotdict.items(): path = key.split('.') assert path, 'Invalid dot-notation path' node = result for part in path[:-1]: node = node.setdefault(part, dtype()) assert isinstance(node, dtype), 'Incompatible paths to {}'.format( key, ) node[path[-1]] = value return result
def getFrequencyDict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list returns: a dictionary """ freq = {} for x in sequence: freq[x] = freq.get(x, 0) + 1 return freq
def to_unicode(text, encoding='utf-8', errors='strict'): """Force text to unicode""" if isinstance(text, bytes): return text.decode(encoding, errors) return text
def str2bool(option): """Convert a string value to boolean @param option: yes, true, 1, no, false, 0 @type option: String @rtype: Boolean """ option = option.lower() if option in ("yes", "true", "1"): return True elif option in ("no", "false", "0"): return False else: raise ValueError("invalid boolean value: %r" % option)
def selection_sort(my_list): """Define the selection sort algorithm.""" if len(my_list) < 2: return my_list for index in range(0, len(my_list)-1, +1): index_of_min = index for location in range(index, len(my_list)): if my_list[location] < my_list[index_of_min]: index_of_min = location temp = my_list[index] my_list[index] = my_list[index_of_min] my_list[index_of_min] = temp return my_list
def conv2d_size_out(size, kernel_size, stride): """ common use case: cur_layer_img_w = conv2d_size_out(cur_layer_img_w, kernel_size, stride) cur_layer_img_h = conv2d_size_out(cur_layer_img_h, kernel_size, stride) to understand the shape for dense layer's input """ return (size - (kernel_size - 1) - 1) // stride + 1
def _nearest(pivot, items): """Returns nearest point """ return min(items, key=lambda x: abs(x - pivot))
def cmdEcho(args, flags, context): """ Echo arguments to output """ # NOTE: args must be a list of Strings or literals msg = ' '.join(map(lambda x: str(x), args)) return msg
def get_neighbors(y, x, H, W): """ Return indices of valid neighbors of (y, x). Return indices of all the valid neighbors of (y, x) in an array of shape (H, W). An index (i, j) of a valid neighbor should satisfy the following: 1. i >= 0 and i < H 2. j >= 0 and j < W 3. (i, j) != (y, x) Args: y, x: location of the pixel. H, W: size of the image. Returns: neighbors: list of indices of neighboring pixels [(i, j)]. """ neighbors = [] for i in (y - 1, y, y + 1): for j in (x - 1, x, x + 1): if 0 <= i < H and 0 <= j < W: if i == y and j == x: continue neighbors.append((i, j)) return neighbors
def dec2hex(number): """return a decimal number into its hexadecimal form""" return hex(number)[2:]
def add_binary(a, b): """ Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string. :param a: an integer value. :param b: an integer value. :return: the binary value of the sum of a and b. """ return bin(a + b)[2:]
def factorial (n): """Factorial, computed recursively. What is the base case? How can you express n! recursively, in terms of itself? Params: n (int): n >= 1 Returns: n! """ if n == 1: return 1 else: return n*factorial(n-1) return n
def add3(a, b, c=2): """exec a + b + c = ?""" print('exec add3') ret = a + b + c print('add3: %s + %s + %s = %s' % (a, b, c, ret)) return ret
def unscratch_win(x, ndx, n, scr=-1): """ :param x: Vector of info (e.g. win price) for starters only :param ndx: Indexes of starters :param n: Original number of runners :param scr: :return: """ p = [scr for _ in range(n)] for ndx,xi in zip(ndx,x): p[ndx] = xi return p
def get_num_classes(dataset: str): """Return the number of classes in the dataset. """ if dataset == "imagenet": return 1000 elif dataset == "cifar10": return 10 elif dataset == "mnist": return 10
def format_time(time_to_go): """Return minutes and seconds string for given time in seconds. :arg time_to_go: Number of seconds to go. :returns: string representation of how much time to go. """ if time_to_go < 60: return '%ds' % time_to_go return '%dm %ds' % (time_to_go / 60, time_to_go % 60)
def shorter_name(key): """Return a shorter name for an id. Does this by only taking the last part of the URI, after the last / and the last #. Also replaces - and . with _. Parameters ---------- key: str Some URI Returns ------- key_short: str A shortened, but more ambiguous, identifier """ key_short = key for sep in ['#', '/']: ind = key_short.rfind(sep) if ind is not None: key_short = key_short[ind+1:] else: key_short = key_short return key_short.replace('-', '_').replace('.', '_')
def get_product_variants(variants, sku): """Returns a list of variants for a product.""" product_variants = [ variant for variant in variants if variant["Product SKU"] == sku and variant["Variant Enabled"] == "Y" ] product_variants.sort(key=lambda variant: variant["Variant Sort"]) return product_variants
def is_whitespace(c: str) -> bool: """Return True if c is a whitespace, False otherwise.""" return c == " " or c == "\t" or c == "\n"
def _indented_repr(o): """Returns repr(o), with any lines beyond the first one indented +2.""" return repr(o).replace("\n", "\n ")
def validate_ruletype(ruletype): """ Validate RuleType for ResolverRule. Property: ResolverRule.RuleType """ VALID_RULETYPES = ("SYSTEM", "FORWARD") if ruletype not in VALID_RULETYPES: raise ValueError("Rule type must be one of: %s" % ", ".join(VALID_RULETYPES)) return ruletype