content
stringlengths
42
6.51k
def verify_required_properties(deep_security_event): """ Verify if the specified Deep Security event contains the required properties to be convert to an Amazon Finding Format finding """ result = False required_properties = [ 'HostOwnerID', 'HostInstanceID', 'TenantID', 'EventID', 'EventType', 'Log...
def get_region(regions, cluster): """ Gets the region name from the cluster ID Args: regions (dictionary): dictionary of regions where shortname is the key to the long name value. cluster (str): the OCI ID of the cluster in question. Returns a string of the region long name. """ re...
def _format_write_list(write_list): """Format a BaseI2CBus.wr_rd() write_list arg for logging. Args: write_list: list of output byte values [0~255], or None for no write Returns: str """ if write_list is None: return str(None) return '[%s]' % (', '.join('0x%02X' % (value,) for value in write_l...
def line_goes_through_border(pos1, pos2, dest1, dest2, border, lower, upper): """ Test if the line from (pos1, pos2) to (dest1, dest2) goes through the border between lower and upper. """ try: m = (border - pos1) / (dest1 - pos1) except ZeroDivisionError: return False wall_closer...
def fib(n): """Fibonacci example function Args: n (int): integer Returns: int: n-th Fibonacci number """ assert n > 0 a, b = 1, 1 for _ in range(n-1): a, b = b, a+b return a
def distance(coord_a, coord_b): """ Calcuate the distance between 2 coordinates. Arguments: coord_a (array): coordinate of point a coord_b (array): coordinate of point b Return: dist (float) """ assert len(coord_a) == len(coord_b) dim = len(coord_a) sum_square_d...
def is_empty_string(s): """ Tells if a string is empty. @param s string @return boolean """ if s is None: return True return len(s) == 0
def smart_str_conversion(value): """Convert to Title Case only if UPPER CASE.""" if value.isupper(): return value.title() return value
def get_arguments(args): """ Recieves sys.argv and generates and error if the number of arguments is invalid Parameters: arg (list of strings) Returns: filename (string) and topic (string) """ filename = '' topic = '' if len(args) != 3: # Check for the right number of...
def compare_dict_keys(dict_a, dict_b, compare_keys): """Compare two dictionaries with the specified keys""" return all(dict_a[k] == dict_b[k] for k in dict_a if k in compare_keys)
def _parse_date_string(dateString, isInterval=False): # {{{ """ Given a string containing a date, returns a tuple defining a date of the form (year, month, day, hour, minute, second) appropriate for constructing a datetime or timedelta Parameters ---------- dateString : string A da...
def parse_url(url): """Parse URL's query string and return as a dictionary.""" # Split the url into a GET param list. q_params = url.split('?')[-1].split('&') collection = {} for item in q_params: """Value is a=1, we need to split one more time in order to get the key, value pairs o...
def int_to_bitstring(x: int) -> str: """ Function to convert an integer to AT LEAST a 32-bit binary string. For integer less than 32 bits, it will pad the integer with extra bits of 0s until it is of size 32bit. If the integer is greater than 32-bits, then return the binary representation with the minimum ...
def determine_root_gpu_device(gpus): """ :param gpus: non empty list of ints representing which gpus to use :return: designated root GPU device """ if gpus is None: return None assert isinstance(gpus, list), "gpus should be a list" assert len(gpus) > 0, "gpus should be a non empty l...
def __check_args_type(args): """Check if it is a tuple-like object.""" if args is None or args == (): return None elif isinstance(args, int) or isinstance(args, str) or isinstance(args, list): # manage the case of 1 element in tuple (example: args=(4)) return (args, ) elif not is...
def subtract(value, arg): """ Substract 2 numbers """ if value or arg: return int(value or 0) - int(arg or 0) return ''
def autocomplete_if_release_report(actions, objects, field_name='user'): """ Returns value of the first item in the list objects of the field_name if release_report is actions. Args: actions: Transition action list objects: Django models objects field_name: String of name R...
def degree(coeffs): """highest power among monomials with non-zero coefficient; zero polynomial has degree -1""" deg = len(coeffs) - 1 for c in reversed(coeffs): if c != 0: break deg -= 1 return deg
def cos_series(x): """Returns cos(x) for x in reange -pi/2 .. pi/2""" # https://en.wikipedia.org/wiki/Trigonometric_functions#Power_series_expansion C=[1.,0.5,0.08333333333333333,0.03333333333333333,0.017857142857142856,0.011111111111111111,0.007575757575757576,0.005494505494505495,0.004166666666666667,0.00...
def pop_from_key_value_set(kvset, *keys): """ Pops the values of ``keys`` from ``kvset`` and returns them as a tuple. If a key is not found in ``kvset``, ``None`` is used instead. >>> kvset = [('a',0), ('b',1), ('c',2)] >>> pop_from_key_value_set(kvset, 'a', 'foo', 'c') (0, None, 2) >>> kvs...
def process_question(question): """Process the question to make it canonical.""" return question.strip(" ").strip("?").lower() + "?"
def pprint(g): """ Pretty print a tree of goals """ if callable(g) and hasattr(g, '__name__'): return g.__name__ if isinstance(g, type): return g.__name__ if isinstance(g, tuple): return "(" + ', '.join(map(pprint, g)) + ")" return str(g)
def calCons1(op, op1): """ calculate the unary instruction """ if op == "!": temp = int(op1) temp = not temp return str(temp) if op == "-": temp = int(op1) temp = -temp return str(temp)
def quadraric_distortion_scale(distortion_coefficient, r_squared): """Calculates a quadratic distortion factor given squared radii. The distortion factor is 1.0 + `distortion_coefficient` * `r_squared`. When `distortion_coefficient` is negative (barrel distortion), the distorted radius is only monotonically in...
def isalpha(text): """ Checks if all characters in ``text`` are alphabetic and there is at least one character. Alphabetic characters are those characters defined in the Unicode character database as a "Letter". Note that this is different from the "Alphabetic" property defined in the Unicod...
def missing_digits(n): """Given a number a that is in sorted, increasing order, return the number of missing digits in n. A missing digit is a number between the first and last digit of a that is not in n. >>> missing_digits(1248) # 3, 5, 6, 7 4 >>> missing_digits(1122) # No missing numbers ...
def l_min(s, m): """ Minimum allowed value of l for a given s, m. The formula is l_min = max(\|m\|,\|s\|). Parameters ---------- s: int Spin-weight of interest m: int Magnetic quantum number Returns ------- int l_min """ return max(abs(s), abs(m))
def standard_event_metrics_to_list(standard_event_results): """ Converting standard event metric results to a list (position of each item is fixed) Argument: standard_event_results (dictionary): as provided by the 4th item in the results of eval_events function Returns: list: Item order: 1...
def remove_all_white_space(string): """Remove all spaces, newlines and tabs.""" return string.replace('\n', '').replace('\t', '').replace(' ', '')
def IsLeadingSpace(s): # type: (str) -> bool """Determines if the token before ''' etc. can be stripped. Similar to qsn_native.IsWhitespace() """ for ch in s: if ch not in ' \t': return False return True
def ip_address_to_string(ip_list, inverted=False): """Returns a IP address string. """ fn = lambda x:x if inverted: fn = reversed return '.'.join(['%d' % b for b in fn(ip_list)])
def fld2str(fld_v): """converts field value into string""" if type(fld_v) == type(1.1): fld_v = '%s' % fld_v if '.' in fld_v: fld_v = fld_v.rstrip('0') fld_v = fld_v.rstrip('.') else: fld_v = '%s' % fld_v if fld_v.startswith('SYS_C'): fld_v = 'SYS_Cxxx' return fld_v
def volume_type_delete(volume_type_id, **kwargs): """ delete the specified volume type """ url = "/types/{volume_type_id}".format(volume_type_id=volume_type_id) return url, {}
def check_function_equality(func1, func2): """Checks if two functions are same.""" return func1.__code__.co_code == func2.__code__.co_code
def transpose_lists(lsts): """Transpose a list of lists.""" return [list(i) for i in zip(*lsts)]
def comb(n: int, k: int) -> int: """Defines `C(n, k)` as the number of ways to pick `k` items among `n` """ if k > n: raise ValueError result = 1 for i in range(n - k + 1, n + 1): result *= i for i in range(2, k + 1): result /= i return int(result)
def aec2 (val=None): """ Set or get auto exposure control 2""" global _aec2 if val is not None: _aec2 = val return _aec2
def flatten_dict(d): """function to flatten a dictionary into a single layer Parameters ---------- d : dict multilayered dictionary Returns ------- dict flattened dictionary """ out = {} def flatten(x, name="", sep="|"): if type(x) is dict: ...
def url_strip_appendix(url): """ removes trailing stuff behind a url definition """ lst = url.split('/') return lst[0] + '//' + lst[2]
def _op_name(tensor_name): """Extract the Op name from a Tensor name. The Op name is everything before a colon, if present, not including any ^ prefix denoting a control dependency. Args: tensor_name: the full name of a Tensor in the graph. Returns: The name of the Op of which the given Tensor is an...
def vector_mean(*args): """ Computes the mean (average) of a list of vectors. The function computes the arithmetic mean of a list of vectors, which are also organized as a list of integers or floating point numbers. .. code-block:: python # Import geomdl.utilities module from geomdl i...
def _sorted_facet_counts(solr_counts, field): """ Convert the raw solr facet data (counts, ranges, etc.) from a flat array into a two-dimensional list sorted by the number of hits. The result will look something like this: (('field1', count1), ('field2', count2), ...) """ raw = solr_counts.get(...
def _union_all(iterables): """Return a set representing the union of all the contents of an iterable of iterables. """ out = set() for iterable in iterables: out.update(iterable) return out
def alternatingCharacters(s1): """ Args: s1 (str): first string Returns: int: how many elements need to be deleted""" del_count = 0 # check every pair of elements in a loop for i in range(len(s1) - 1): if s1[i] == s1[i + 1]: del_count += 1 return del_coun...
def frequency(total: float, percentage: float, value: float, invert: bool = False) -> float: """Return frequency of a given value . Freq = v*t/p v-> value t-> total p-> percentage Args: total (float): total value percentage (float): percentage value between 0 and 1 val...
def split_message(message, embedded=False, language: str=""): """ Splits a message into more messages of size less than 2000 characters. This is to bypass the Discord 2000 character limit. Parameters ---------- message : str A long message to split up. embedded : bool Wheth...
def mat_diff(mat_a, mat_b): """ Function that subtracts two matrices: mat_a and mat_b. The subtraction can be carried out if the two matrices have same dimension, i.e. same number of rows and columns. The elements of the resulting matrix, mat_c, are c_ij = a_ij - b_ij :param mat_a: list of list...
def _fact(n: int) -> int: """n!""" if n <= 1: return 1 return n * _fact(n - 1)
def find_first_greater(key, numbers): """ vstup: 'key' hodnota hledaneho cisla, 'numbers' serazene pole cisel vystup: index prvniho vyskytu prvku vetsiho nez hodnota 'key', -1, pokud tam zadny takovy prvek neni casova slozitost: O(log n), kde 'n' je pocet prvku pole 'numbers' """ low...
def should_exclude(dirname, excludes): """Returns true if the directory should be excluded when walking the source tree""" if excludes: if dirname in excludes: return True return False
def color_map_rgb(color_values): """Map numbers to RGBA colors with three polars. -1 maps to red. 0 maps to white. 1 maps to blue. Use linear interpolation in between. The alpha value is always 1. Argument: color_values -- A list of numbers normalized between -1 and 1. Return value...
def hex16_to_u64le(data): """! @brief Build 64-bit register value from little-endian 16-digit hexadecimal string""" return int(data[0:16], 16)
def get_coalition_leads_sql_string_for_state(coalition_id,state_id): """ :type party_id: integer """ str = """ select lr.candidate_id, c.fullname as winning_candidate, lr.constituency_id, cons.name as constituency, lr.party_id, lr.max_votes, (lr.max_vo...
def parse_dbotu_parameters(summary_obj, amplicon_type): """ Parses summary file for dbOTU options. Parameters ---------- summary_obj SummaryParser object amplicon_type '16S' or 'ITS' Returns ------- dist max sequence dissimilarity (default = 0.1) ab...
def command_validator(keystroke): """Change default keymappings. Keybindings from more common `ASCII control codes`_ are remapped to emacs-type keybindings accepted by curses `Textbox objects`_. .. _ASCII control codes: https://www.cs.tut.fi/~jkorpela/chars/c0.html .. _Textbox objects: ses.html#te...
def _invert(x, limits): """inverts a value x on a scale from limits[0] to limits[1]""" return limits[1] - (x - limits[0])
def course_info_as_list(course_info, with_section): """ Given a dictionary as returned by `parse_course_code`, return a list that can be used on the frontend as a sort key (`with_section` true) or mutual exclusion key (`with_section` false). If the `with_section` argument to this function is true, ...
def uniq_tokens_in_nested_col(col_series): """ Given a column in a dataframe containing lists of tokens, return unique tokens. Can also receive a list of lists, pd.Series of lists, np.array of lists. """ return set([el for sublist in col_series for el in sublist])
def getLowestPayment2(balance, annualInterestRate): """ Input balance - the outstanding balance on the credit card annualInterestRate - annual interest rate as a decimal Return the remaining balance at the end of the year, rounded to 2 decimals """ low = round((balance + (balance * an...
def DGS3620(v): """ DGS-3620-series :param v: :return: """ return v["platform"].startswith("DGS-3620")
def dump_list(l): """ returns strings of list """ try: return '[%s]' % ', '.join(map(str, l)) except TypeError: return str(l)
def numCompletedSteps(stepsDict): """ Takes the stepsDict, walk through counting up the number of steps that are complete. """ c = 0 for s in stepsDict: if stepsDict[s].complete: c += 1 return c
def is_file_ignored(file_name): """ filetype to be ignored during precommit validation """ ignored_file_name_ends = [ '.eot', '-min.js', '.min.js', '.pyc', '.svg', '.ttf', '.woff', ] for file_name_end in ignored_file_name_ends: ...
def totalLinks(n): """Gives the number of possible links for a linkograph of size n.""" # The number of possible links is just the triangle number for # n-1. return int(n*(n-1)/2)
def get_next_code(code): """ Generate the next code from the code that precedes it. """ return code * 252533 % 33554393
def sum(x, y): """ Sum x and y >>> sum(11, 11) 22 >>> sum(10, 20) 30 """ assert isinstance(x, (int, float)), "The x value must be an int or float" assert isinstance(y, (int, float)), "The y value must be an int or float" return x + y
def pwd(raw_value, unit=None): """Pulse Width Modulator (PWM) output. The register is a 16-bit word as usual, but the module does not use the 5 LSBs. So, 10-bit resolution on the PWM value (MSB is for sign and is fixed). 0-100% duty cycle maps to 0 to 32736 decimal value in the register. ``PWD = 1...
def extract_features(document): """Extract features from a document and returns them in a Bag Of Words model dict. """ return {word: True for word in document}
def md_heading(level, heading): """ Returns the markdown heading at the level specified """ return "{} {}\n".format("#"*int(level), heading)
def _get_resource_id(scardecname, res_type, tag=None): """ Helper function to create consistent resource ids. """ res_id = "smi:local/scardec/%s/%s" % (scardecname, res_type) if tag is not None: res_id += "#" + tag return res_id
def nucleotides_counter(dna): """ Counts DNA nucleotides in a given dna. Args: dna (str): DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T'). Returns: str: four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C...
def match_resource(resource, bid, cid): """Helper that returns True if the specified bucket id and collection id match the given resource. """ resource_name, matchdict = resource resource_bucket = matchdict['id'] if resource_name == 'bucket' else matchdict['bucket_id'] resource_collection = matc...
def list_to_string(lst: list = []) -> str: """Join list with commas. Args: lst (list): List to join. Returns: str: Joined list. """ return ", ".join(lst)
def jets_to_mjj(jets): """ Convert jets to Mjj. """ mjj = [] for k in range(len(jets)): E = jets[k][0].e + jets[k][1].e px = jets[k][0].px + jets[k][1].px py = jets[k][0].py + jets[k][1].py pz = jets[k][0].pz + jets[k][1].pz mjj += [(E ** 2 - px ** 2 - py ** 2...
def expand_nested_lists(query, key): """ Produce flat lists from list and nested lists. Args: query (dict): A single query from the decision tree. key (str): A string denoting the field to be taken from the dict. Returns: list: A 1D list cont...
def lifetime(mass1: float): """ Stellar lifetime function of Maeder & Maynet (1989) extrapolated by Chiappini, Matteucci & Gratton (1997). See also Tornatore (2007) for use case in stellar chemical enrichment. ----- tau: stellar age (one star) [Gyr] mass: stellar mass (one star) [Msun] """ ...
def filesystem_fs(path_str, glob_stuff="*", sep=","): """ fs(path_str, glob_stuff="*", sep=",") Enable access to file system: list files """ from pathlib import Path l = [] for f in Path(path_str).glob(glob_stuff): l.append(f.name) return sep.join(l)
def unpadding(sample): """delete '0' from padding sentence""" sample_new = [] for item in sample: _list = [] _list_tmp = [] for ii in item: _list_tmp.append(ii) if ii != 0: _list = _list + _list_tmp _list_tmp = [] sample...
def expand_call(kargs): """ Snippet 20.10 Passing the job (molecule) to the callback function Expand the arguments of a callback function, kargs['func'] """ func = kargs['func'] del kargs['func'] out = func(**kargs) return out
def stiefel_dimension(dim_n, dim_p): """Return the dimension of a Stiefel manifold St(1, p)^n. in general, dim St(d, p)^m = mdp - .5 * md(d + 1) hence here, dim St(1, p)^n = np - n = n(p - 1) """ return dim_n * (dim_p - 1)
def classify(true_otu, pred_otu): """ Classify a prediction as a true positive (tp), true negative (tn), false positive (fp), or false negataive (fn). """ if true_otu and pred_otu: result = "tp" elif true_otu and not pred_otu: result = "fn" elif not true_otu and pred_otu:...
def Q(a: float, e: float) -> float: """ Q = a * (1 + e) :param a: semi-major axis :type a: float :param e: eccentricity :type e: float :return: apocentric distance :rtype: float """ return a * (1 + e)
def isHttpUrl(url: str) -> bool: """Check is url is http url Args: url: url to be checked Returns: bool: True is url is http or https url """ return isinstance(url, str) and ( url.startswith("http://") or url.startswith("https://") )
def insert_whitespace(seq: str) -> str: """ Return the sequence of characters with whitespace after each char >>> insert_whitespace("RKDES") 'R K D E S' """ return " ".join(list(seq))
def seqfilter(seq): """doctring.""" return "".join([b for b in seq if b in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"])
def sign(x): """Returns sign of x""" if x==0: return 0 return x/abs(x)
def does_task_have_task_runs(task, task_runs): """ Figure out if at least one task run exists for a given task Faster than get_task_runs() """ task_id = task['id'] for tr in task_runs: if task_id == tr['task_id']: return True else: return False
def parse_cell_value(val): """Parse value from table cell. >>>parse_cell_value("5.4") (5.4, None) >>>parse_cell_value("5 432") (5432.0, None) >>>parse_cell_value("--") (None, "Saknas") :param val (str): cell content :returns (tuple): value and status as tuple """ missing_...
def _get_num_contracts(contracts_list, param_name): """ Return the number of simple/default contracts. Simple contracts are the ones which raise a RuntimeError with message 'Argument `*[argument_name]*` is not valid' """ msg = "Argument `*[argument_name]*` is not valid" return sum( ...
def sublist(l1, l2): """Naive but adequate sublist testing.""" for i in range(len(l1)): if l1[i] == l2[0]: for j in range(len(l2)): try: if l1[i + j] != l2[j]: break except IndexError: break ...
def euler_step(t, y, h, f): """ Numerical integration using the Euler method. Given the initial value problem y'(t) = f(t, y(t)), y(t_0) = y_0 one step of size h is y_{n+1} = y_n + h * f(t_n, y_n). """ tp = t + h yp = y + h * f(t, y) evals = 1 return tp, yp, evals
def fragment_sequences(sequence, qualities, splitchar): """Works like split() on strings, except it does this on a sequence and the corresponding list with quality values. Returns a tuple for each fragment, each sublist has the fragment sequence as first and the fragment qualities as second elemnt""" ...
def case(casenum): """ Creates a test case consisting of two polylines Parameters ---------- casenum : int Number between 0 and count -1. Returns ------- Two polylines, or the count if casenum == -1 """ cases = [] # input lines from Hangouet 19...
def kv_encode(dict_object): """Encodes a dictionary object to a string with the kv encoding format. For example, given this input: { foo: 'bar', baz: 'qux', zap: 'zazzle' } The function will return this string: foo=bar&baz=qux&zap=zazzle """ encoded_text = ''...
def wind_power_law(comp_orig, height_obs=3., height_interp=10., correction=False): """simple power law wind adjustment default - 3m observations, 10m interpolated height""" if correction: wind_cor = comp_orig * (height_interp / height_obs)**(0.143) else: wind_cor = comp_orig ...
def generate_vnd_json(attributes, object_type, object_id=None): """ Generate Vendor API Json format. Optionally include `object_id` for PUT/PATCH operations """ data = { 'data': { 'type': object_type, 'attributes': attributes } } if object_id is not None...
def find_components(value): """ Extract the three values which have been combined to form the given output. """ r1 = value >> 20 # 11 most significant bits r2 = (2**10 - 1) & (value >> 10) # 10 middle bits r3 = (2**10 - 1) & value # 10 least significant bits return...
def _get_connect_string(backend, user, passwd, database): """Establish connection Try to get a connection with a very specific set of values, if we get these then we'll run the tests, otherwise they are skipped """ if backend == "postgres": backend = "postgresql+psycopg2" elif backend =...
def flagger(value): """ Conversion routine for flags. Accepts ints or comma-separated strings. :param str value: The value to convert. :returns: A value of an appropriate type. """ try: # Convert as an integer return int(value) except ValueError: # Convert as ...
def move_id_behind(element_id, reference_id, idstr_list): """Moves element_id behind reference_id in the list""" if element_id == reference_id: return idstr_list idstr_list.remove(str(element_id)) reference_index = idstr_list.index(str(reference_id)) idstr_list.insert(reference_index + 1, st...