content
stringlengths
42
6.51k
def _dict(value): """ A dictionary """ return isinstance(value, dict)
def filter_Graph(G,filter_set): """ This allows us to apply a set of filters encoded as closures/first-order functions that take a graph as input and return a graph as output. """ graph = G.copy() for f in filter_set: graph = f(graph) return graph
def calculate1dios(s1, s2): """ Calculate intersection over smallest """ res = 0 i_b = max((s1[0], s2[0])) # intersection begin i_e = min((s1[1], s2[1])) # intersection end if i_b < i_e: smallest = min((s1[1] - s1[0], s2[1] - s2[0])) res = (i_e - i_b) / smallest return res
def make_aggregate(docs, aggregations): """ Given `docs` and `aggregations` return a single document with the aggregations applied. """ new_doc = dict(docs[0]) for keyname, aggregation_function in aggregations: new_doc[keyname] = aggregation_function(docs) return new_doc
def leap_year(year, calendar='standard'): """Determine if year is a leap year""" leap = False if ((calendar in ['standard', 'gregorian', 'proleptic_gregorian', 'julian']) and (year % 4 == 0)): leap = True if ((calendar == 'proleptic_gregorian') and (year % 100 == 0) and (year % 400 != 0)): leap = False elif ((calendar in ['standard', 'gregorian']) and (year % 100 == 0) and (year % 400 != 0) and (year < 1583)): leap = False return leap
def str_to_seconds(tstring): """ Convert time strings to seconds. Strings can be of the form: <int> (ninutes) <int>m (minutes) <int>h (hours) <int>d (days) <int>y (years) Args: tstring (str): An integer followed by an (optional) 'm', 'h', 'd', 'y'. Returns int: The number of seconds represented by the input string. If the string is unadorned and represents a negative number, -1 is returned. Raises: ValueError: If the value cannot be converted to seconds. """ if tstring.endswith('m'): secs = 60 * int(tstring.replace('m', '')) elif tstring.endswith('h'): secs = 60 * 60 * int(tstring.replace('h', '')) elif tstring.endswith('d'): secs = 24 * 60 * 60 * int(tstring.replace('d', '')) elif tstring.endswith('y'): secs = 365 * 24 * 60 * 60 * int(tstring.replace('y', '')) else: secs = 60 * int(tstring) if secs < 0: secs = -1 return secs
def parse_mac_address(mac_address): """ This function parses raw SNMP MAC address into pretty hexadecimal format. Positional Argument: - mac_address -- SNMP raw MAC address string Returns: - mac_address -- string hexadecimal MAC address """ mac_address = ['{:02x}'.format(int(ord(val))) for val in mac_address] for i in range(2, 6, 3): mac_address.insert(i, '.') mac_address = ''.join(mac_address) return mac_address if mac_address != '..' else "None"
def trap_exception(e, f, default=None): """ Call f(), trapping e, default to default (which might be callable) """ try: # pragma: no cover return f() except e: # pragma: no cover if callable(default): return default(e) else: return default
def BLACK(obj): """Format an object into string of black color in console. Args: obj: the object to be formatted. Returns: None """ return '\x1b[1;30m' + str(obj) + '\x1b[0m'
def shutdown(application): """Invoke to shutdown the InfluxDB collector, writing any pending measurements to InfluxDB before stopping. :param tornado.web.Application application: the application to install the collector into. :rtype: tornado.concurrent.TracebackFuture or None """ collector = getattr(application, 'influxdb', None) if collector: return collector.shutdown()
def escape_regex(p, white=''): # type: (str, str) -> str """Escape string for use within a regular expression.""" # what's up with re.escape? that code must be neglected or something return ''.join(c if c.isalnum() or c in white else ('\\000' if c == '\000' else '\\' + c) for c in p)
def generate_list(name): """ Make sure parameters xmltodict generates is a list. :param name: The dict/list that xmltodict gives :return: Guaranteed a list :rtype: list """ if not name: return [] elif isinstance(name, list): return name else: return [name]
def move_up(loc): """increments the location for upward movement. """ return (loc[0], loc[1] + 1)
def is_number(s): """ Test whether a given string can be parsed as a float """ try: float(s) return True except ValueError: return False
def diviseur(n): """ premier diviseur premier de n """ i = 2 while i * i <= n: q, r = divmod(n, i) if r == 0: return i i += 1 return n
def first(seq): """Returns the first item in the sequence. Returns None if the sequence is empty.""" return next(iter(seq), None)
def _format_host_port_alias(host, port, alias): """Format a host, port, and alias so it can be used for comparison or display.""" if alias: return f"{alias}@{host}:{port}" return f"{host}:{port}"
def predicted_rb_number(modelA, modelB): """ Prediction of RB number based on estimated (A) and target (B) models """ #TEMPORARILY disabled b/c RB analysis is broken #from ..extras.rb import theory as _rbtheory return -1.0
def fizz_buzz_three( start, end ): """ Returns the fizzbuzz string for a given range using an inner function and a list comprehension. """ def int_to_fizzbuzz(i): """ Output the 'fizzbuzz' string for a single number. """ entry = '' if i%3 == 0: # if i divided by 3 has no remainder entry += "fizz" if i%5 == 0: # if i divided by 5 has no remainder entry += "buzz" if i%3 != 0 and i%5 != 0: # i is not divisible by 3 or 5 without remainder entry = i return entry return [int_to_fizzbuzz(i) for i in range(start, end+1)]
def dd_poly_f(x, c): """Derivative of d_poly_f""" ddf_x = 0 for i in range(2, len(c)): ddf_x += pow(x, i - 2) * c[i] * i * (i - 1) return ddf_x
def onCircle_elements(nelx,nely): """ return a list of the element centroid located on the border of a circle of radius nelx """ list = [] for x in range(nelx): for y in range(nely): if abs(((x-(nelx-1)/2.0)**2+(y-(nely-1)/2.0)**2)**.5 - (nelx-1)/2.0) < .5 : list.append((x,y)) return list
def html_table(list_of_lists): """ Overridden list class which takes a 2-dimensional list of the form [[1,2,3],[4,5,6]], and renders an HTML Table in IPython Notebook. Taken from: http://calebmadrigal.com/display-list-as-table-in-ipython-notebook/ """ html = ["<table>"] for row in list_of_lists: html.append("<tr>") for col in row: html.append("<td>{0}</td>".format(col)) html.append("</tr>") html.append("</table>") return ''.join(html)
def threeSum(nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) < 2: return [] nums.sort() triplets = [] for i in range(len(nums) -2): if i > 0 and nums[i] == nums[i-1]: continue target = -nums[i] small = i +1 big = len(nums) - 1 while small < big: tsum = nums[small] + nums[big] if tsum == target: triplets.append([nums[i], nums[small], nums[big]]) # -4,-1,-1,0,1,2 while small < big and nums[small] == nums[small+1]: small +=1 while small < big and nums[big] == nums[big-1]: big -=1 small +=1 big -=1 elif tsum < target: small +=1 else: big -=1 return triplets
def list_partial_circuits(circuit): """ List the partial sub-circuits of `circuit`. The "parital circuits" are defined as the slices `circuit[0:n]` for `0 <= n <= len(circuit)`. Parameters ---------- circuit : tuple of operation labels or Circuit The circuit to act upon. Returns ------- list of Circuit objects. The parial circuits. """ ret = [] for l in range(len(circuit) + 1): ret.append(tuple(circuit[0:l])) return ret
def getUriName(uri): """Return local name, i.e. last segment of URI.""" return uri.strip("/").split("/")[-1]
def add_zero(number, size): """add_zero.""" out = str(number) for i in range(size - len(out)): out = "0" + out return out
def parselog(loglines, fields): """ Parse a subset of a zeek logfile's contents. Each line's fields are put into a hash with the retrieved field names as the key. Each of those hashed entries are appended to a list of hashed entries. That list is returned to the caller. """ zeekcomm = [] # Hashed communications. fcnt = len(fields) # Number of fields in output. # # Build the list of hashed entries. # for ln in loglines: entry = {} # # Remove comment lines and strip off any leading and # trailing whitespace. # ln = ln.strip() if(ln == ''): continue if(ln.startswith('#') == True): continue # # Split the line into its constituent atoms. # atoms = ln.split("\t") # # Put the atoms into a hash, keyed off the field. # for ind in range(fcnt): entry[fields[ind]] = atoms[ind] # # Add the new entry hash to our big list of entry hashes. # zeekcomm.append(entry) return(zeekcomm)
def filter_loan_to_value(loan_to_value_ratio, bank_list): """Filters the bank list by the maximum loan to value ratio. Args: loan_to_value_ratio (float): The applicant's loan to value ratio. bank_list (list of lists): The available bank loans. Returns: A list of qualifying bank loans. """ # create an empty list loan_to_value_approval_list = [] # go throught all the banks to find which banks meet the loan to home value ratio requirements for bank in bank_list: # select the bank if the user's loan to home value ratio meets the bank's maximum loan to home value ratio requirement if loan_to_value_ratio <= float(bank[2]): loan_to_value_approval_list.append(bank) # return the list of qualifying banks return loan_to_value_approval_list
def _find_all_subclasses(cls): """ Recursively find all subclasses """ subclasses = set(cls.__subclasses__()) for sub in cls.__subclasses__(): subclasses = subclasses | _find_all_subclasses(sub) return subclasses
def api_get_manageable_snapshots(*args, **kwargs): """Replacement for cinder.volume.api.API.get_manageable_snapshots.""" snap_id = 'ffffffff-0000-ffff-0000-ffffffffffff' snaps = [ {'reference': {'source-name': 'snapshot-%s' % snap_id}, 'size': 4, 'extra_info': 'qos_setting:high', 'safe_to_manage': False, 'reason_not_safe': 'snapshot in use', 'cinder_id': snap_id, 'source_reference': {'source-name': 'volume-00000000-ffff-0000-ffff-000000'}}, {'reference': {'source-name': 'mysnap'}, 'size': 5, 'extra_info': 'qos_setting:low', 'safe_to_manage': True, 'reason_not_safe': None, 'cinder_id': None, 'source_reference': {'source-name': 'myvol'}}] return snaps
def filepath_exist_cmd(path): """Checks if filepath exists.""" return " ".join(["test", "-e", path])
def fibonacci(n: int) -> int: """ The Fibonacci sequence is a list of numbers where the subsequent number is the sum of the previous two. :param n: The number of items requested for the Fibonacci sequence. :return: The Fibonacci number at position n """ if n <= 0: raise ValueError("The number must be greater than zero.") exit(code=1) if n == 1: return 0 elif n == 2: return 1 else: return fibonacci(n-1) + fibonacci(n - 2)
def getFibonacciIterative(n: int) -> int: """ Calculate the fibonacci number at position n iteratively """ a = 0 b = 1 for i in range(n): a, b = b, a + b return a
def table_drop(name: str) -> str: """Return command to drop a table from a PostgreSQL database. :param str name: name of table to drop :returns: command to remove table from database :rtype: str """ return 'DROP TABLE if EXISTS {name} CASCADE;'.format(name=name)
def getLetterGrade(score): """ Method to return the letter grade schollar of a student. :param score: A integer with the final grade schollar of a student. :return: return the final letter grade schollar. """ if score >= 90: finalScore = 'A' elif score >= 80: finalScore = 'B' elif score >= 70: finalScore = 'C' elif score >= 60: finalScore = 'D' else: finalScore = 'F' return finalScore
def get_unspecified_default_args(user_args, user_kwargs, all_param_names, all_default_values): """ Determine which default values are used in a call, given args and kwargs that are passed in. :param user_args: list of arguments passed in by the user :param user_kwargs: dictionary of kwargs passed in by the user :param all_param_names: names of all of the parameters of the function :param all_default_values: values of all default parameters :return: a dictionary mapping arguments not specified by the user -> default value """ num_args_without_default_value = len(all_param_names) - len(all_default_values) # all_default_values correspond to the last len(all_default_values) elements of the arguments default_param_names = all_param_names[num_args_without_default_value:] default_args = dict(zip(default_param_names, all_default_values)) # The set of keyword arguments that should not be logged with default values user_specified_arg_names = set(user_kwargs.keys()) num_user_args = len(user_args) # This checks if the user passed values for arguments with default values if num_user_args > num_args_without_default_value: num_default_args_passed_as_positional = num_user_args - num_args_without_default_value # Adding the set of positional arguments that should not be logged with default values names_to_exclude = default_param_names[:num_default_args_passed_as_positional] user_specified_arg_names.update(names_to_exclude) return { name: value for name, value in default_args.items() if name not in user_specified_arg_names }
def tamper(payload, **kwargs): """ Escapes a char encoded payload Tested against: * This is just a proof of concept but used for SQL injection against MySQL 5.7.25 via a GraphQL query Notes: * Useful when passing a char unicode encoded payload as part of the GraphQL query as a string via a JSON context >>> tamper('\u0022') '\\u0022' """ retVal = payload if payload: retVal = retVal.replace("\\", "\\\\") return retVal
def change_possible(part): """Check if there is anything to permute""" if ':' not in part or (part.count(':') == 1 and ('http:' in part or 'https:' in part)): return False else: return True
def version_tuple_to_str(version, sep='.'): """Join the version components using '.' and return the string.""" return sep.join([str(x) for x in version])
def fix_msg(msg, name): """Return msg with name inserted in square brackets""" b1 = msg.index('[')+1 b2 = msg.index(']') return msg[:b1] + name + msg[b2:]
def get_dotted(data, path): """access nested dict by dotted helper""" parts = path.split('.') if len(parts) == 1: return data.get(parts[0]) if (parts[0] in data) and isinstance(data[parts[0]], dict): return get_dotted(data[parts[0]], '.'.join(parts[1:])) return None
def icv(p): """Returns interval-class vector of pcset.""" l = [] c = 1 n = len(p) while c < n: for x in p: for y in range(c, n): k = (x-p[y])%12 if k > 6: k = 12 - k l.append(k) c += 1 return [l.count(z) for z in range(1, 7)]
def quadratic(mu, c, i0=1.0): """ Calculates the intensity of a given cell in the stellar surface using a quadratic limb-darkening law. Parameters ---------- mu (``float`` or ``numpy.ndarray``): Cosine of the angle between a line normal to the stellar surface and the line of sight. c (``array-like``): Limb-darkening coefficients in the order c1, c2. i0 (``float``, optional): Intensity without limb-darkening. Default is 1.0. Returns ------- i_mu (``float`` or ``numpy.ndarray``): Intensity with limb-darkening. The format is the same as the input ``mu``. """ c1, c2 = c attenuation = 1 - c1 * (1 - mu) - c2 * (1 - mu) ** 2 i_mu = i0 * attenuation return i_mu
def power(base, exp): """ Write a program to find x to power y using recursion :param base: :param exp: :return: """ if exp == 0: return 1 if exp != 0: return base * power(base, exp - 1)
def __get_pivots(diameter, x, y): """ Get the x-intercepts and y-intercepts of the circle and return a list of pivots which the coin lies on. """ pivots = [] radius = diameter / 2 sqval = radius**2 - y**2 if sqval > 0: # no imaginary numbers! sqrt = sqval**(0.5) pivots.append((x + sqrt, 0)) pivots.append((x - sqrt, 0)) elif sqval == 0: # tangent pivots.append((x, 0)) sqval = radius**2 - x**2 if sqval > 0: sqrt = sqval**(0.5) pivots.append((0, y + sqrt)) pivots.append((0, y - sqrt)) elif sqval == 0: pivots.append((0, y)) return pivots
def get_args_tuple(args, kwargs, arg_names, kwargs_defaults): """Generates a cache key from the passed in arguments.""" args_list = list(args) args_len = len(args) all_args_len = len(arg_names) try: while args_len < all_args_len: arg_name = arg_names[args_len] if arg_name in kwargs_defaults: args_list.append(kwargs.get(arg_name, kwargs_defaults[arg_name])) else: args_list.append(kwargs[arg_name]) args_len += 1 except KeyError as e: raise TypeError("Missing argument %r" % (e.args[0],)) return tuple(args_list)
def cpu_profile(func, repetitions=1): """Profile the function `func`. """ import cProfile import pstats profile = cProfile.Profile() profile.enable() success = True for _ in range(repetitions): success = func() if not success: break profile.disable() # after your program ends stats = pstats.Stats(profile) stats.strip_dirs() stats.sort_stats('time').print_stats(80) return success
def time_handling(year1, year1_model, year2, year2_model): """ This function is responsible for finding the correct files for the needed timespan: year1 - the start year in files year1_model - the needed start year of data year2 - the last year in files year2_model - the needed last year of data WARNINGS: we reduce our analysis only to years """ # model interval < data interval / file # model requirements completely within data stretch if year1 <= int(year1_model) and year2 >= int(year2_model): return True,True # model interval > data interval / file # data stretch completely within model requirements elif year1 >= int(year1_model) and year2 <= int(year2_model): return True,False # left/right overlaps and complete misses elif year1 <= int(year1_model) and year2 <= int(year2_model): # data is entirely before model if year2 <= int(year1_model): return False,False # data overlaps to the left elif year2 >= int(year1_model): return True,False elif year1 >= int(year1_model) and year2 >= int(year2_model): # data is entirely after model if year1 >= int(year2_model): return False,False # data overlaps to the right elif year1 <= int(year2_model): return True,False
def get_key_and_value_by_key_match(key_value_map, key_to_try, default_key="any"): """ This method looks for a key in a dictionary. If it is not found, an approximate key is selected by checking if the keys match with the end of the wanted key_to_try. The method is intended for use where the key is a relative file path! :param key_value_map: :param key_to_try: :param default_key: :return: """ retrieved_value = None if key_to_try in key_value_map: retrieved_value = key_value_map[key_to_try] return retrieved_value if default_key is not None: retrieved_value = key_value_map.get(default_key, None) if len(key_value_map) == 1 and default_key in key_value_map: retrieved_value = key_value_map[default_key] else: for key in key_value_map.keys(): key_clean = key.strip().strip("\"") key_clean = key_clean.replace("___dot___", ".") if key_clean == "any": continue if key_to_try.endswith(key_clean): retrieved_value = key_value_map[key] break if retrieved_value is None: raise ValueError( "key_value_map %s was not matched with a value! Even for the default key %s" % (key_to_try, default_key)) return retrieved_value
def seqhasattr( z, attr ): """like hasattr, but on sequences checks all their elements.""" if hasattr( z, '__iter__') and not hasattr( z, '__cdms_internals__'): return all([ seqhasattr( w, attr ) for w in z ]) else: return hasattr( z, attr )
def _int_to_rgba(omero_val): """ Helper function returning the color as an Integer in RGBA encoding """ if omero_val < 0: omero_val = omero_val + (2**32) r = omero_val >> 24 g = omero_val - (r << 24) >> 16 b = omero_val - (r << 24) - (g << 16) >> 8 a = omero_val - (r << 24) - (g << 16) - (b << 8) a = a / 256.0 return (r, g, b, a)
def _clean_identifier(arg): """ Our class property names have an appended underscore when they clash with Python names. This will strip off any trailing underscores, ready for serialisation. :type arg: str :rtype: str >>> _clean_identifier('id_') 'id' >>> _clean_identifier('id') 'id' """ return arg[:-1] if arg.endswith('_') else arg
def html_escape(text: str) -> str: """ Return the text with all HTML characters escaped. """ for character, html_code in [('&', '&amp;'), ('"', '&quot;'), ("'", '&#39;'), (">", '&gt;'), ("<", '&lt;')]: text = text.replace(character, html_code) return text
def char_count( text, ignore_spaces=True): """ Function to return total character counts in a text, pass the following parameter `ignore_spaces = False` to ignore whitespaces """ if ignore_spaces: text = text.replace(" ", "") return len(text)
def is_completions_display_value(x): """Enumerated values of ``$COMPLETIONS_DISPLAY``""" return x in {"none", "single", "multi"}
def _axes_to_sum(child, parent): """Find the indexes of axes that should be summed in `child` to get `parent`""" return tuple(child.index(i) for i in child if i not in parent)
def get_human_ccy_mask(ccy): """Function that convert exchange to human-readable format""" # {"ccy":"USD","base_ccy":"UAH","buy":"24.70000","sale":"25.05000"} return "{} / {} : {} / {}".format(ccy["ccy"], ccy["base_ccy"], ccy["buy"], ccy["sale"])
def gf_degree(f): """Returns leading degree of f. """ return len(f)-1
def kv(d): """ Pretty Print the dictionary. """ return '(' + ','.join(['%s: %s'%(k, d[k]) for k in sorted(d.keys()) if k[0] != "_"]) + ')'
def seek_for_mark(x, y, marks, w, h): """ Seek for a mark existence in a WxH neighbourhood around (x,y) coordinate """ for mark in marks: x_range = range(x - int(w/2), x + int(w/2)+1) y_range = range(y - int(h/2), y + int(h/2)+1) for yy in y_range: for xx in x_range: if mark.intCenterX_r == xx and mark.intCenterY_r == yy: return 1 return 0
def set_equal(one, two): """Converts inputs to sets, tests for equality.""" return set(one) == set(two)
def isFileGzip(fileName): """ Inputs a file name and returns a boolean of if the input file is gzipped """ if fileName[-3:] == ".gz": return True else: return False
def get_apps_hr(app_detail): """ Prepare human readable json for command 'risksense-get-apps' command. :param app_detail: response from host command. :return: None """ return { 'ID': app_detail.get('id', ''), 'Address': app_detail.get('uri', ''), 'Name': app_detail.get('name', ''), 'Network': app_detail.get('network', {}).get('name', ''), 'Groups': len(app_detail.get('groups', [])), 'URLs': app_detail.get('urlCount', 0), 'Total Findings': app_detail.get('findingsDistribution', {}).get('total', {}).get('value', 0), 'Critical Findings': app_detail.get('findingsDistribution', {}).get('critical', {}).get('value', 0), 'High Findings': app_detail.get('findingsDistribution', {}).get('high', {}).get('value', 0), 'Medium Findings': app_detail.get('findingsDistribution', {}).get('medium', {}).get('value', 0), 'Low Findings': app_detail.get('findingsDistribution', {}).get('low', {}).get('value', 0), 'Info Findings': app_detail.get('findingsDistribution', {}).get('info', {}).get('value', 0), 'Tags': len(app_detail.get('tags', [])), 'Notes': len(app_detail.get('notes', [])) }
def getLowerUpperSab(temp): """ gets moderator S(a,b) data bounding library strings from a temperature """ baselib = 'gre7' # endf7 graphite if temp < 600.: raise Exception('temp not implemented. ask gavin') temps = [600.,700.,800.,1000.,1200.,1600.,2000.] libnames =['12t','16t','18t','20t','22t','24t','26t'] for j, (templib, lib) in enumerate(zip(temps, libnames)): if templib == temp: return baselib+'.'+lib,'' elif templib <= temp: return baselib+'.'+lib+' ',baselib+'.'+libnames[j+1]+'' else: raise Exception("Temperature {} not implemented.".format(temp))
def sort_dict_name_by_number(part): """this is the sort function used for sorting the names within a group""" count = 0 for character in part['NAME']: if character.isdigit(): count += 1 if count == 0: return 0 else: return int(''.join(character for character in part['NAME'] if character.isdigit()))
def makeaxisdivs(start, finish, divs, rounded=-1): """ Creates an axis, or vector, from 'start' to 'finish' with 'divs' divisions. :type start: float :param start: First value of the axis. :type finish: float :param finish: Last value of the axis. :type divs: int :param divs: Number of divisions :type rounded: int :param rounded: Number of decimals to consider. If -1 then no rounding is performed. :returns: Axis with the set parameters. :rtype: list[float] """ step = (finish-start)/(divs-1) if rounded >= 0: axis = [round(start+step*i,rounded) for i in range(divs)] else: axis = [start+step*i for i in range(divs)] return axis
def measure_memory_deterministic(shots, hex_counts=True): """Measure test circuits reference memory.""" targets = [] if hex_counts: # Measure |00> state targets.append(shots * ['0x0']) # Measure |01> state targets.append(shots * ['0x1']) # Measure |10> state targets.append(shots * ['0x2']) # Measure |11> state targets.append(shots * ['0x3']) else: # Measure |00> state targets.append(shots * ['00']) # Measure |01> state targets.append(shots * ['01']) # Measure |10> state targets.append(shots * ['10']) # Measure |11> state targets.append(shots * ['11']) return targets
def _read_formula(Line): """ Helper function for output2acceptingstates(..) """ formula = str(Line.split(":")[1].strip()) return formula # minimization is very expensive if formula in ["FALSE","TRUE"]: return formula formula = PyBoolNet.BooleanLogic.minimize_espresso(formula) if formula == "0": return "FALSE" if formula == "1": return "TRUE" return formula
def get_snapshots_list(response, is_aurora): """ Simplifies list of snapshots by retaining snapshot name and creation time only :param response: dict Output from describe_db_snapshots or describe_db_cluster_snapshots :param is_aurora: bool True if output if from describe_db_cluster_snapshots, False otherwise :return: Dict with snapshot id as key and snapshot creation time as value """ snapshots = {} response_list_key = "DBClusterSnapshots" if is_aurora else "DBSnapshots" identifier_list_key = "DBClusterSnapshotIdentifier" if is_aurora else "DBSnapshotIdentifier" for snapshot in response[response_list_key]: if snapshot["Status"] != "available": continue snapshots[snapshot[identifier_list_key]] = snapshot["SnapshotCreateTime"] return snapshots
def get_protocol(protocol): """Return the protocol (tcp or udp).""" if str(protocol).lower() == 'tcp': return 'tcp' if str(protocol).lower() == 'http': return 'tcp' if str(protocol).lower() == 'udp': return 'udp' else: return None
def _check_trip_stack_has_tripleg(temp_trip_stack): """ Check if a trip has at least 1 tripleg. Parameters ---------- temp_trip_stack : list list of dictionary like elements (either pandas series or python dictionary). Contains all elements that will be aggregated into a trip Returns ------- has_tripleg: Bool """ has_tripleg = False for row in temp_trip_stack: if row["type"] == "tripleg": has_tripleg = True break return has_tripleg
def tertiary_spherical(rho, phi): """Zernike tertiary spherical.""" return 70 * rho**8 - 140 * rho**6 + 90 * rho**4 - 20 * rho**2 + 1
def create_idea(idea_str): """ Given a string, returns a dictionary entry. Arguments: idea_str: A string, representing the idea the user has. Returns: idea_dict: {"text": idea_str} """ return {"text": idea_str}
def bytetohex(bytearray): """ Returns hexadecimal string representation of byte array Copied from StackOverflow https://stackoverflow.com/questions/19210414/byte-array-to-hex-string """ return ''.join('{:02x}'.format(x) for x in bytearray)
def pretty_size_print(num_bytes): """ Output number of bytes in a human readable format Parameters ---------- num_bytes: int number of bytes to convert returns ------- output: str string representation of the size with appropriate unit scale """ if num_bytes is None: return KiB = 1024 MiB = KiB * KiB GiB = KiB * MiB TiB = KiB * GiB PiB = KiB * TiB EiB = KiB * PiB ZiB = KiB * EiB YiB = KiB * ZiB if num_bytes > YiB: output = '%.3g YB' % (num_bytes / YiB) elif num_bytes > ZiB: output = '%.3g ZB' % (num_bytes / ZiB) elif num_bytes > EiB: output = '%.3g EB' % (num_bytes / EiB) elif num_bytes > PiB: output = '%.3g PB' % (num_bytes / PiB) elif num_bytes > TiB: output = '%.3g TB' % (num_bytes / TiB) elif num_bytes > GiB: output = '%.3g GB' % (num_bytes / GiB) elif num_bytes > MiB: output = '%.3g MB' % (num_bytes / MiB) elif num_bytes > KiB: output = '%.3g KB' % (num_bytes / KiB) else: output = '%.3g Bytes' % (num_bytes) return output
def middle(l): """ Return a new list containing all but first and last element of a given list. """ new_l = l[:] del new_l[::len(new_l)-1] return new_l
def find_between(s: str, before: str, after: str): """Searches string S and finds the first substring found between the BEFORE and AFTER substrings, if they are found. Returns the indexes of the start and end of the found substring, such that s[start:end] would be the substring. (first character, last character + 1) If not found, (0,0) is returned. example: >>> find_between("hayneedlestack", "hay", "stack") (3, 9) >>> find_between("hello world", "hay", "stack") (0, 0) """ start = s.find(before) + len(before) if start < 0: return 0, 0 end = s[start:].find(after) if end < 0: return 0, 0 return start, start + end
def _has_project(link: str) -> bool: """HELPER: check if the link in oracc, and has a project :param link: an oracc project link :type link: str :return: true if the link is in oracc with project, false otherwise :rtype: bool """ return ("oracc.org" in link.lower() or "oracc.museum.upenn.edu" in link.lower()) and ( "projectlist" not in link.lower())
def bubble_sort(unsorted_list): """Iterate through an unsorted list and swap elements accordingly.""" # make a copy of the list unsorted_copy = unsorted_list[:] for index in range(len(unsorted_list) - 1): if unsorted_copy[index] > unsorted_copy[index + 1]: a, b = unsorted_copy[index], unsorted_copy[index + 1] unsorted_copy[index + 1], unsorted_copy[index] = a, b return bubble_sort(unsorted_copy) return unsorted_copy
def build_word_list(in_file): """Processes a list of words stored in file, placing them in a list of lists where the outer list index is the number of characters in each word of the corresponding inner list file -> str set list """ word_list = list() for word in in_file: word = word.strip() # word list hasn't gotten here yet if len(word_list) <= len(word): # extend the list for n in range(len(word_list), len(word) + 1): word_list.insert(n, set()) # insert into appropriate sublist word_list[len(word)].add(word) return word_list
def get_overlap(a, b): """ Computes the amount of overlap between two intervals. Returns 0 if there is no overlap. The function treats the start and ends of each interval as inclusive, meaning that if a = b = [10, 20], the overlap reported would be 11, not 10. Args: a: First interval, formattted as a list b: Second interval, formatted as a list """ overlap = max(0, min(a[1], b[1]) - max(a[0], b[0]) + 1) return overlap
def is_pow_two(val: int) -> bool: """ Test if input integer is power of two by summing the bits in its binary expansion and testing for 1. :param val: Input value :type val: int :return: Indicate whether x is a power-of-two. :rtype: bool """ return val > 0 and not (val & (val - 1))
def _normalize_function_name(function): """ Given a C++ function name, convert it to a nicely formatted Python function name. For example "SetPositions" becomes "set_positions". """ name = function[0].lower() for i,l in enumerate(function[1:]): if l.isupper(): name += '_' name += l.lower() return name
def transpose(m): """ >>> transpose([[1, 2, 3], [4, 5, 6]]) [[1, 4], [2, 5], [3, 6]] """ return [list(i) for i in zip(*m)]
def format_size(num): """http://stackoverflow.com/a/1094933 """ for x in ['bytes', 'KB', 'MB', 'GB']: if num < 1024.0 and num > -1024.0: return "%3.1f%s" % (num, x) num /= 1024.0 return "%3.1f%s" % (num, 'TB')
def parsePos(text): """ parse a string of format chr:start-end:strand and return a 4-tuple Strand defaults to + and end defaults to start+23 """ if text!=None and len(text)!=0 and text!="?": fields = text.split(":") if len(fields)==2: chrom, posRange = fields strand = "+" else: chrom, posRange, strand = fields posRange = posRange.replace(",","") if "-" in posRange: start, end = posRange.split("-") start, end = int(start), int(end) else: # if the end position is not specified (as by default done by UCSC outlinks), use start+23 start = int(posRange) end = start+23 else: chrom, start, end, strand = "", 0, 0, "+" return chrom, start, end, strand
def flipcoords(xcoord, ycoord, axis): """ Flip the coordinates over a specific axis, to a different quadrant :type xcoord: integer :param xcoord: The x coordinate to flip :type ycoord: integer :param ycoord: The y coordinate to flip :type axis: string :param axis: The axis to flip across. Could be 'x' or 'y' >>> flipcoords(-5, 5, "y") (5, 5) >>> flipcoords(5, 5, "y") (-5, 5) >>> flipcoords(0, -5, "y") (0, -5) >>> flipcoords(-5, -5, "x") (-5, 5) >>> flipcoords(5, 5, "x") (5, -5) >>> flipcoords(0, -5, "x") (0, 5) >>> flipcoords(-5, 0, "x") (-5, 0) >>> flipcoords(5, 5, "foo") Traceback (most recent call last): ... ValueError: Invalid axis. Neither x nor y was specified. """ axis = axis.lower() if axis == 'y': if xcoord == 0: return xcoord, ycoord return -xcoord, ycoord elif axis == 'x': if ycoord == 0: return xcoord, ycoord return xcoord, -ycoord raise ValueError("Invalid axis. Neither x nor y was specified.")
def toSigned32(n): """https://stackoverflow.com/a/37095855""" n = n & 0xffffffff return (n ^ 0x80000000) - 0x80000000
def gss(f, a, b, c, tau=1e-3): """ Python recursive version of Golden Section Search algorithm tau is the tolerance for the minimal value of function f b is any number between the interval a and c """ goldenRatio = (1 + 5 ** 0.5) / 2 if c - b > b - a: x = b + (2 - goldenRatio) * (c - b) else: x = b - (2 - goldenRatio) * (b - a) if abs(c - a) < tau * (abs(b) + abs(x)): return (c + a) / 2 if f(x) < f(b): if c - b > b - a: return gss(f, b, x, c, tau) return gss(f, a, x, b, tau) else: if c - b > b - a: return gss(f, a, b, x, tau) return gss(f, x, b, c, tau)
def is_numeric(s): """test if a string is numeric""" for c in s: if c in "1234567890-.": return True else: return False
def get_title(event: dict): """Returns the title for the event.""" context = event.get("context", {}) if ( event["event_source"] == "server" and isinstance(context, dict) and context.get("path", {}) == event["event_type"] ): return "ServerEventModel" # The title of browser event `seq_goto` should be `SeqGotoBrowserEventModel`. title = f"{event['event_type']}.{event['event_source']}.event.model" return "".join(x.capitalize() for x in title.replace("_", ".").split("."))
def m3sectoCFM(Vm3sec): """ Convertie le debit volumique en m3/sec vers CFM Conversion: 1 m3/sec = 2 118.88 [CFM] :param Vm3sec: Debit volumique [m3/sec] :return VCFM: Debit volumique [CFM] """ VCFM = Vm3sec * 2118.8799727597 return VCFM
def generate_role_with_colon_format(content, defined_role, generated_role): """Generate role data with input as Compute:ComputeA In Compute:ComputeA, the defined role 'Compute' can be added to roles_data.yaml by changing the name to 'ComputeA'. This allows duplicating the defined roles so that hardware specific nodes can be targeted with specific roles. :param content defined role file's content :param defined_role defined role's name :param generated_role role's name to generate from defined role :exception ValueError if generated role name is of invalid format """ # "Compute:Compute" is invalid format if generated_role == defined_role: msg = ("Generated role name cannot be same as existing role name ({}) " "with colon format".format(defined_role)) raise ValueError(msg) # "Compute:A" is invalid format if not generated_role.startswith(defined_role): msg = ("Generated role name ({}) name should start with existing role " "name ({})".format(generated_role, defined_role)) raise ValueError(msg) name_line = "name:%s" % defined_role name_line_match = False processed = [] for line in content.split('\n'): stripped_line = line.replace(' ', '') # Only 'name' need to be replaced in the existing role if name_line in stripped_line: line = line.replace(defined_role, generated_role) name_line_match = True processed.append(line) if not name_line_match: raise ValueError(" error") return '\n'.join(processed)
def parse_known_rooms(rooms): """ Parse a known rooms string (token:room@conf.host:nick [...]) to a Python dictionary Keys are tokens, values are nested dicts of room JIDs and associated user nicks :param: rooms string :return: dict """ known_rooms = {} for pairs in rooms.split(' '): valid_token, valid_room, nick = pairs.split(':') known_rooms[valid_token] = {'room': valid_room, 'nick': nick} return known_rooms
def adj_dict_to_lists(xs, ys, d): """Convert a dictionary of x -> y to a list of lists, where each x corresponds to a list of indices of y.""" M = [] for x, y_list in d.items(): M.append( [ list(ys).index(y) for y in y_list ] ) return M
def isfloat(x): """ determine if a string can be converted to float """ try: a = float(x) except ValueError: return False except TypeError: return False else: return True
def format_args(args, kwargs, arg_names, ignore=set()): """Format args Args: args (tuple): kwargs (dict): arg_names (List[str]): Returns: str: """ def items(): for i, name in enumerate(arg_names): if name in ignore: continue if i < len(args): yield name, args[i] elif name in kwargs: yield name, kwargs[name] d = ', '.join(('{}: {}'.format(*m) for m in items())) return '{' + d + '}'
def requestParser(requestStr): """ accept request string, return dictionary returning None indicates parsing error """ requestStr = requestStr.strip() #According to the RFC, the body starts after a \r\n\r\n sequence headerBodySplit = requestStr.split("\r\n\r\n".encode(), 1) reqlineAndHeaders = headerBodySplit[0].decode('utf-8') requestBody = '' #since the body maybe absent sometimes, this avoids an IndexError if(len(headerBodySplit)>1): requestBody = headerBodySplit[1] headerFields = reqlineAndHeaders.strip().split('\r\n') #RFC : Request-Line = Method SP Request-URI SP HTTP-Version CRLF requestFields = headerFields[0].split(" ") requestHeaders = headerFields[1:] requestLine = dict() requestLine['method'] = requestFields[0] #Request-URI = "*" | absoluteURI | abs_path | authority try: requestLine['requestUri'] = requestFields[1] requestLine['httpVersion'] = requestFields[2] headersDict = dict() for i in requestHeaders: keyValSplit = i.split(':', 1) key = keyValSplit[0] val = keyValSplit[1] #lower used since according to RFC, header keys are case insensitive #Some values maybe case sensitive or otherwise, depending on key, THAT CASE NOT HANDLED headersDict[key.strip().lower()] = val.strip() requestHeaders = headersDict #At this point requestLine(dictionary), requestHeaders(dictionary) and requestBody(string) constitute the entire message #uncomment line below if debugging to compare with original requestStr #print(requestStr) parsedRequest = { 'requestLine': requestLine, 'requestHeaders': requestHeaders, 'requestBody': requestBody } return parsedRequest except IndexError: return None
def mcd(nums): """MCD: step good for different blocksizes""" res = min(nums) while res > 0: ok = 0 for n in nums: if n % res != 0: break else: ok += 1 if ok == len(nums): break res -= 1 return res if res > 0 else 1
def get_hq_start_end(seq, is_hq_f): """ ..doctest: >>> def f(c): return c.isupper() >>> get_hq_start_end('', f) (0, 0) >>> get_hq_start_end('GC', f) (0, 2) >>> get_hq_start_end('aGCc', f) (1, 3) """ start, end = 0, 0 i = 0 while i < len(seq): if is_hq_f(seq[i]): start = i break i += 1 i = len(seq) - 1 while i >= 0: if is_hq_f(seq[i]): end = i + 1 break i -= 1 return (start, end)