content
stringlengths
42
6.51k
def validate_bytes(datum, **kwargs): """ Check that the data value is python bytes type Parameters ---------- datum: Any Data being validated kwargs: Any Unused kwargs """ return isinstance(datum, (bytes, bytearray))
def get_choices_map(choices): """ Returns dict where every index and key are mapped to objects: map[index] = map[key] = Choice(...) """ result = {} for choice in choices: result[choice.index] = choice if choice.key: result[choice.key] = choice return result
def andGate(argumentValues): """ Method that evaluates the AND gate @ In, argumentValues, list, list of values @ Out, outcome, float, calculated outcome of the gate """ if 0 in argumentValues: outcome = 0 else: outcome = 1 return outcome
def next_field_pad(pos_prev, offset, width, display): """ Local helper calculates padding required for a given previous position, field offset and field width. pos_prev Position following previous field offset Offset of next field width Width of next field display True if...
def getChunkPartition(chunk_id): """ return partition (if any) for the given chunk id. Parition is encoded in digits after the initial 'c' character. E.g. for: c56-12345678-1234-1234-1234-1234567890ab_6_4, the partition would be 56. For c-12345678-1234-1234-1234-1234567890ab_6_4, the partition ...
def flatten_timeseries(timeseries): """Flatten a timeseries in the style of flatten_port_dicts""" flat = {} for port, store_dict in timeseries.items(): if port == 'time': flat[port] = timeseries[port] continue for variable_name, values in store_dict.items(): ...
def inverseSq_(t, alpha=1, beta=1): """beta/(t+alpha+1)**(0.5)""" return beta / (t + alpha + 1) ** (0.5)
def normalise_unreserved(string): """Return a version of 's' where no unreserved characters are encoded. Unreserved characters are defined in Section 2.3 of RFC 3986. Percent encoded sequences are normalised to upper case. """ result = string.split('%') unreserved = ('ABCDEFGHIJKLMNOPQRSTUVWXY...
def matchIdToNumber(matchId): """ Convert a match's letter identifier to numbers. """ idSum = 0 for letter in matchId: value = ord(letter.upper()) - 64 if value < 1 or value > 26: raise ValueError("Match identifier should only contain letters (got '{}')".for...
def svn_repo(repo): """ """ if repo.startswith('https://svn.code.sf.net/p/') and repo.endswith('/code/'): return repo if repo.startswith('http://svn.uktrainsim.com/svn/'): return repo if repo is 'https://rpg.hamsterrepublic.com/source/wip': return repo # not s...
def add_qualifier_col_diff(player_data_list): """Add qualifier that will determine which rows to take difference from. Args: player_data_list: list with player data Returns: player data list with qualifier """ return [[*year, ''] for year in player_data_list]
def _get_operational_state(resp, entity): """ The member name is either: 'operationState' (NS) 'operational-status' (NSI) '_admin.'operationalState' (other) :param resp: descriptor of the get response :param entity: can be NS, NSI, or other :return: status of the operation """ if...
def checkUnique1(String): """ Time Complexity : O(n) = O(c) = O(1) as we know loop cannot go beyond 128 or 256 """ if len(String)>128: #total ascii characters is 128, can use 256 for extended ascii return False Str_dict = {} for char in String: if char in Str_dict: return False else: Str_dict[char] ...
def pad_insert(list_in: list, item, index: int): """insert an item into list at the specified index, extending the list with zeroes first as needed. Parameters: list_in (list): the list to extend item: the item to insert index (int): the index at which to insert Output: `li...
def choose(population, sample): """ Returns ``population`` choose ``sample``, given by: n! / k!(n-k)!, where n == ``population`` and k == ``sample``. """ if sample > population: return 0 s = max(sample, population - sample) assert s <= population assert population > -1 i...
def calc_intersection(actual_position, calculated_position): """ Calculates the Coordinates of the intersection Area. """ x_actual = actual_position.get("x", None) y_actual = actual_position.get("y", None) w_actual = actual_position.get("width", None) h_actual = actual_position.get("height",...
def chrs(num, width): """width is number of characters the resulting string should contain. Will return 0 if the num is greater than 2**width.""" result = "" while len(result) < width: result = chr(num & 0xff) + result num = num >> 8 return result
def sample_size_z(z, std, max_error): """ Return the sample size required for the specified z-multiplier, standard deviation and maximum error. :param z: z-multiplier :param std: Standard deviation :param max_error: Maximum error :return: Required sample size """ return pow(z, 2.0) * pow...
def compress(lhs_label, rhs_label): """Combine two labels where the rhs replaces the lhs. If the rhs is empty, assume the lhs takes precedent.""" if not rhs_label: return lhs_label label = list(lhs_label) label.extend([None] * len(rhs_label)) label = label[:len(rhs_label)] for idx,...
def pointer_offset(p): """ The offset is something like the top three nybbles of the packed bytes. """ # 4 bytes: a b c d # offset is 0xcab, which is c << 12 # Ex. 0x0700 should return 15h. return ((p & 0xF0) << 4) + (p >> 8) + 0x12
def _new(available_plugin_types, configuration, plugin_type, plugin_configuration_data=None): """Create a new plugin instance. :param available_plugin_types: Iterable :param configuration: Configuration :param plugin_type: str :param plugin_configuration_data: Dict :return: Any :raise: Valu...
def revComp(sequence): """ Input: String of DNA sequences in any case Output: Reverse Complement in upper case """ # Define dictionary, make input string upper case rcDict = {'A':'T', 'T':'A', 'C':'G', 'G':'C', 'N':'N'} seqUp = sequence.upper() rcSeq = '' for letter in seqUp: ...
def piecewise(*args): """implements MathML piecewise function passed as args NB piecewise functions have to be passed through MathMLConditionParser because they may contain and and or statements (which need to be made into and_ and or_ statements) """ result = None for i in range(1, le...
def normalize_whitespace(value: str) -> str: """ Remove unnecessary whitespace from string :param value: String to be processed :return: Normalized string """ return ' '.join(value.split())
def sub_vectors(v1, v2): """ Subtracts v2 to v1 :param v1: vector 1 :param v2: vector 2 :return: v1 - v2 """ return tuple([v1[i] - v2[i] for i in range(0, len(v1))])
def distance_from_modulus(mag, abs_mag): """Given the distance modulus, return the distance to the source, in parsecs. Uses Carroll and Ostlie's formula, .. math:: d = 10^{(m - M + 5)/5}""" return 10.0 ** (mag - abs_mag + 5) / 5
def sol(arr, n): """ We try and go close to the number on the ends by adding the element with its adjacents """ l = 0 r = n-1 res = 0 while l < r: if arr[l] == arr[r]: l+=1 r-=1 elif arr[l] > arr[r]: r-=1 arr[r] += arr...
def generate_project_params(runlevel): """ configs to use in addition to the core config in nest_py.core.nest_config """ config = dict() return config
def _strip_type_mod(ctype: str) -> str: """Convert e.g. numeric(5,3) into numeric for the purpose of checking if we can run comparisons on this type and add it to the range index. """ if "(" in ctype: ctype = ctype[: ctype.index("(")] if "[" in ctype: ctype = ctype[: ctype.index("[")...
def is_within(value, min_, max_): """ Return True if value is within [min_, max_], inclusive. """ if value > max_: return False if value < min_: return False return True
def version2float(s): """Converts a version string to a float suitable for sorting""" # Remove 2nd version: '4.1.1-4.5.5' --> '4.1.1' s = s.split('-')[0] # Max one point: '4.1.1' --> '4.1' s = '.'.join(s.split('.')[:2]) # Remove non numeric characters s = ''.join(c for c in s if c.isdigit() ...
def clean_layer_name(input_name: str, strip_right_of_last_backslash: bool=True, strip_numerics_after_underscores: bool=True): """ There exist cases when layer names need to be concatenated in order to create new, unique layer names. However, the indices added to lay...
def _is_composed(word, is_original, memo): """ :param word: :param is_original: If it is the original word, do not retrieve result from memo table. :param memo: memo table to cache the results of previous recurses :return: True if this word is composed of other words, False otherwise. ""...
def factorial_recursion(n): """ Return the factorial of n using recursion. Parameters ---------- n : an integer of which the factorial is evaluated. Returns ------- result : The factorial of n. """ if n == 1: return 1 return factorial_recursion(n - ...
def spread(spread_factor: int, N: int, n: int) -> float: """Spread the numbers For example, when we have N = 8, n = 0, 1, ..., 7, N, we can have fractions of form n / N with equal distances between them: 0/8, 1/8, 2/8, ..., 7/8, 8/8 Sometimes it's desirable to transform such sequence with finer st...
def tokenize(seq, delim=' ', punctToRemove=None, addStartToken=True, addEndToken=True): """ Tokenize a sequence, converting a string seq into a list of (string) tokens by splitting on the specified delimiter. Optionally add start and end tokens. """ if punctToRemove is not None: for p in punctToRemove: ...
def chainloop(N, X, Y, ops, chainopfunc, chainnormfunc): """ Low-level function called by e.g. chainwithops. """ here = 0 newops = [(op, site) for op, site in ops if op is not None] for op, site in newops: if site < 0: raise IndexError("Invalid site: ", site) oplength...
def drop_axis_ratio(D_eq): """ Axis ratio of drops with respect to their diameter. Parameter: ========== D_eq: float Drop diameter. Return: ======= axratio: float Axis ratio of drop. """ if D_eq < 0.7: axratio = 1.0 # Spherical elif D_eq < 1.5: ...
def conv_32upto64(val, nb): """ converts val (32bits) to 32+n bits (n must be comprised between 0 & 32 bits) :warning: conversion output shall not exceed 32bits (input shall strictly be unsigned 32bits) :warning: nb shall be in range 0-32 (note that using 0 doesn't change val) :param val: 32bit var to c...
def rp(success=False, message=None, payload=None): """ rp (aka, response payload) return standard payload params: success=boolean, message=string|None, payload=dict|None return: dict """ return{ 'success': success, 'message': message, 'payload': payload, ...
def remove_tick(output, content_data): """ Removes Back Ticks which can be used as obfuscation to break strings apart. Args: output: What is to be returned by the profiler content_data: "$v`a`r=`'EXAMPLE'`" Returns: content_data: "$var='EXAMPLE'" modification_...
def choices_as_set(d): """Handy to check if domain is correct""" return set([b for a, b in d])
def calculate_drone_range(speed, loop_time=15): """Calculate the range of drone for each iteration given speed in km/h and loop time in sec.""" drone_range = float(speed) * (float(loop_time) / 3600) * (1 / 2) return drone_range
def CombineDicts(a, b): """Unions two dictionaries of arrays/dictionaries. Unions two dictionaries of arrays/dictionaries by combining the values of keys shared between them. The original dictionaries should not be used again after this call. Args: a: First dict. b: Second dict. Returns: The ...
def CheckTTTVictory(x, y, ttt_board): """ Given the last placement and board, checks if someone has won the on-going tic tac toe game (3x3 board default) :param x, y: coordinates correlating to last placed marker on a 3x3 ttt board :param ttt_board: nested 3x3 list to represent the t...
def geopoint(value,arg=None, autoescape=None): """ Format a geopoint string by replacing comma occurence by dot. This is util when rendering geo value in templates regardless of localization. Geo point should always been rendered with a dot separator but some localizations render with a comma. T...
def sum_of_digits(number): """find the sum of digits in a number.""" _ = 0 while number: _, number = _ + number%10, number // 10 return _
def get_basehour_offset_for_forecast(current_hour): """ 0 -> -1 (-> 23) 1 -> -2 (-> 23) 2 -> 0 (-> 2 ) 3 -> -1 (-> 2 ) 4 -> -2 (-> 2 ) 5 -> 0 (-> 5 ) 6 -> -1 (-> 5 ) 7 -> -2 (-> 5 ) 8 -> 0 (-> 8 ) 9 -> -1 (-> 8 ) 10 -> -2 (-> 8 ) 11 -> 0 (->...
def reconstruct_html_from_attrs(attrs, how_much_to_ignore=0): """ Given an attribute, reconstruct the html for this node. """ result = [] stack = attrs while stack: result.append(stack[0]) stack = stack[2] result.reverse() result = result[how_much_to_ignore:] result.e...
def covers_alphabet(sentence): """This function takes a string and returns if the given string contains all the alphabets""" chars = set(''.join(e for e in sentence.lower() if e.isalpha())) return len(chars) == 26 # return set(s.lower()) >= set("abcdefghijk...")
def return_other_uavs(uavs, uav_index): """return all other zones not assigned to uav to make as a no fly zone""" copy = uavs copy.pop(uav_index) return copy
def is_variable(thing: str) -> bool: """ Identify whether given string is likely to be a variable name by identifying the exceptions. Args: thing: The string to operate on Returns: False if thing is one of ["+", "-", "*", "/"] or if float( thing) does not raise ...
def get_slope(x, y): """Calculate slope by taking first and last values.""" return (y[-1]-y[0])/(x[-1]-x[0])
def primelist(end): """ Returns a list of all primes in the range [0, end] https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes """ is_prime = [1] * (end + 1) is_prime[0] = 0 is_prime[1] = 0 for i in range(int(len(is_prime)**.5 + 1)): if is_prime[i]: index_length = (e...
def bounded_viewport(document_size, viewport_size, viewport_pos): """ Returns a viewport pos inside the document, given a viewport that's potentially outside it. In-bounds, no effect is achieved by bounding: >>> bounded_viewport(500, 200, 250) 250 Any kind of scrolling is impossible if the vie...
def find_factors(x): """ """ factors = [] for i in range(1, x + 1): if x % i == 0: factors.append(i) print(factors) return factors
def calc_mass_function(a_sini, P_orb): """ Function to calculate the mass function """ return ((a_sini**3)/(P_orb**2))* (173.14738217**3 * 365.2422**2)
def NormalizeUserIdToUri(userid): """Normalizes a user-provided user id to a reasonable guess at a URI.""" userid = userid.strip() # If already in a URI form, we're done: if (userid.startswith('http:') or userid.startswith('https:') or userid.startswith('acct:')): return userid if userid.fin...
def dotmv(A, b, check=True): """ Matrix-vector dot product, optimized for small number of components containing large arrays. For large numbers of components use numpy.dot instead. Unlike numpy.dot, broadcasting rules only apply component-wise, so components may be a mix of scalars and numpy arrays ...
def calculate_maestro_acceleration(normalized_limit): """Calculate acceleration limit for the maestro.""" return normalized_limit / 1000 / 0.25 / 80
def format_errors(errors): """Format serializer errors to conform to our messaging format. (ie, sending a list of messages or a single message under 'success', 'info', 'warning', or 'failure'). :param errors: An error dictionary as produced by rest_framework serializers. :returns: A list of messages."""...
def str_range(start, end): """get range with string type""" return [str(i) for i in range(start, end)]
def kind_to_type(kind): """ Converts a SyntaxKind to a type name, checking to see if the kind is Syntax or SyntaxCollection first. A type name is the same as the SyntaxKind name with the suffix "Syntax" added. """ if kind in ["Syntax", "SyntaxCollection"]: return kind if kind.end...
def add(X,varX, Y,varY): """Addition with error propagation""" Z = X + Y varZ = varX + varY return Z, varZ
def to_native_string(string, encoding="ascii"): """Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise. """ if isinstance(string, str): return string ...
def is_list(val: list) -> list: """Assertion for a list type value. Args: val: check value (expect list type) Returns: Same value to input. Raises: Assertion Error: if a value not match a list type. """ assert isinstance(val, list), f"Must be a List type value!: {type(...
def sieve_of_eratosthenes(n): """ function to find and print prime numbers up to the specified number :param n: upper limit for finding all primes less than this value """ primes = [True] * (n + 1) # because p is the smallest prime p = 2 while p * p <= n: # if p is not mark...
def tp_fp_fn(true_set, subm_set): """ Calculate TP, FP and FN when comparing the true set of tuples and the submitted set of tuples by the students. """ true_pos = true_set.intersection(subm_set) fals_pos = subm_set - true_set fals_neg = true_set - subm_set TP = len(true_pos) FP = ...
def _doColorSpaceCallbacks( colorspace, dataTypeHint, callbacks, errorMsg ) : """ Perform the colorspace callbacks expects a string or 'None' to be returned. """ for funcData in callbacks: func = funcData[0] args = funcData[1] kwargs = funcData[2] s = func(colorspace, dataTypeHint, *args, **kw...
def fitting_function(x, a, b): """ My fitting function to be fit to the v_out to sfr surface density data Parameters ---------- x : (vector) the SFR surface density a, b : (int) constants to be fit Returns ------- y : (vector) the outflow velocity """ ...
def fn(r): """ Returns the number of fields based on their radial distance :param r: radial distance :return: number of fields at radial distance """ return 4 * r + 4
def _union_lists(l1, l2): """ Returns the union of two lists as a new list. """ return l1 + [x for x in l2 if x not in l1]
def to_youtube_url(video_identifier: str) -> str: """"Convert video identifier to a youtube url.""" return "https://www.youtube.com/watch?v={:s}".format(video_identifier)
def identifier(cls): """Return the fully-specified identifier of the class cls. @param cls: The class whose identifier is to be specified. """ return cls.__module__ + '.' + cls.__name__
def rightlimit(minpoint, ds, tau): """ Find right limit. Args: minpoint (int): x coordinate of the local minimum ds (list): list of numbers representing derivative of the time-series signal s tau (int): threshold to determine a slope 'too sharp' Returns: minpoint (int): x coo...
def strip_sense_level(rel_sense, level=None): """Strip relation sense to top level.""" if level is not None: rel_sense = ".".join(rel_sense.split(".")[:level]) return rel_sense
def argmin(list_obj): """Returns the index of the min value in the list.""" min = None best_idx = None for idx, val in enumerate(list_obj): if min is None or val < min: min = val best_idx = idx return best_idx
def Btype(var, out=False): """ Like type()function but return the name only name of a var like: int, not <class 'int'> But can print automatically, or return """ if out: print(type(var).__name__) else: return type(var).__name__
def convert(value, to_type, default=None): """ Converts value to to_type, returns default if fails. """ try: return default if value is None else to_type(value) except (ValueError, TypeError): # If value could not be converted return default
def chunk_sentences(sentences, chunk_size): """ For a list of sentences, chunk sentences. Input: - sentences: list of single sentences - chunk_size: n sentences to be in one chunk Returns: - list of chunks, each containing n sentences """ # Create empty target list for chunks ...
def convert_to_tuples(raw_data): """Convert lists to tuples. Takes a list of lists and converts each list to a tuple so that it can be saved to a CSV file. Args: raw_data (list): Lists to be converted. Returns: processed_data (list): Data in tuples. """ processed_data = []...
def propfind_mock(url, request): """Simulate a PROPFIND request.""" content = b""" <d:multistatus xmlns:d="DAV:" xmlns:cs="http://calendarserver.org/ns/"> <d:response> <d:href>/radicale/user@test.com/contacts/</d:href> <d:propstat> <d:prop> <d:sync-token>http://mo...
def maximum_border_length(w): """Maximum string borders by Knuth-Morris-Pratt :param w: string :returns: table f such that f[i] is the longest border length of w[:i + 1] :complexity: linear """ n = len(w) f = [0] * n # init f[0] = 0 k = 0 # current lo...
def generate_hexagonal_board(radius=2): """ Creates a board with hexagonal shape. The board includes all the field within radius from center of the board. Setting radius to 0 generates a board with 1 hexagon. """ def hex_distance(a, b): return int(abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[0] ...
def to_tuple(key): """Convert key to tuple if necessary. """ if isinstance(key, tuple): return key else: return (key,)
def update_two_contribute_score(click_time_one, click_time_two): """ item cf update tow similarity contribution by user :param click_time_one: first click time :param click_time_two: second click time :return: a weight that put time into consider """ delta_time = abs(click_time_one - click_t...
def group_bbox2d_per_label(bboxes): """Group 2D bounding boxes with same label. Args: bboxes (list[BBox2D]): a list of 2D bounding boxes Returns: dict: a dictionary of 2d boundign box group. {label1: [bbox1, bboxes2, ...], label2: [bbox1, ...]} """ bboxes_per_label = {} ...
def align(text, size, char=" "): """ Format text to fit into a predefined amount of space Positive size aligns text to the left Negative size aligns text to the right """ text = str(text).strip() text_len = len(text) if text_len > abs(size): text = f"{text[:size-3]}..." offset = "".join(char * (abs(size)...
def ctestReportDiffImages(testImage, diffImage, validImage, oss=None): """write ctest tags for images of a failed test""" tag = '<DartMeasurementFile name="TestImage" type="image/png"> %s </DartMeasurementFile>\n'%(testImage) tag += '<DartMeasurementFile name="DifferenceImage" type="image/png"> %s </DartMea...
def sum_list_constraint(in_list: list, value: int) -> list: """ Find a sublist of in_list on which the sum of the element is equal to N :param in_list: the source list :param value: the integer value target :return: a sublist """ _shallow_list = [] for element in in_list: if elem...
def parse_ids(ids_string): """ Parse a list of icon object IDs. :param ids_string: extract command output string list of icon object IDs (e.g. `"1-3, 23, 99-123"`) :return: list of icon object IDs as ints (e.g. `[1, 2, 3, 23, 99, 100, ...]`) """ ids = [] for id_string in ids_string.split(', ...
def catch_error(something): """Try catch an exception. __Attributes__ something: Where we will search for Exception. __Returns__ something if not error or "" if error is. """ try: something except IndexError: something = "" print("An Index Error!") ...
def has_duplicated_points(stencil) -> bool: """ Returns True if there is at least one duplicated points in the stencil. Args: stencil (list of int or float): stencil on regular or staggered grid. Returns: bool: True if there is at least one duplicated points in the stencil....
def get_index(x, item): """ return the index of the first occurence of item in x """ for idx, val in enumerate(x): if val == item: return idx return -1
def mrange(start, stop=None, step=1): """ Takes mathematical indices 1,2,3,... and returns a range in the information theoretical format 0,1,2,... """ if stop == None: start, stop = 1, start return list(range(start-1, stop, step))
def linear_normalize(value, min_value, max_value): """Linearly normalizes given value between zero and one so that the given min value will map to zero and the given max value will map to one :param value: the value to be normalized :type value: float :param min_value: the value that will be ma...
def get_bondethernets(yaml): """Return a list of all bondethernets.""" ret = [] if "bondethernets" in yaml: for ifname, _iface in yaml["bondethernets"].items(): ret.append(ifname) return ret
def IsDataByte(num: int) -> bool: """Is a MIDI Data Byte.""" return num >= 0 and num <= 127
def capitalize(s): """capitalize(s) -> string Return a copy of the string s with only its first character capitalized. """ return s.capitalize()
def pairwise_comparison(column1,var1,column2,var2): """ Arg: column1 --> column name 1 in df column2 --> column name 2 in df var1---> 3 cases: abbreviation in column 1 (seeking better model) abbreviation in column 1 (seeking lesser value in column1 in co...