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 next field is to be displayed, otherwise False. Returns a tuple containing:: [0] True if next field is to be placed on next row [1] Amount of padding (0..11) to be added from end of last field or start of row [2] Position of next free space after new element """ if not display: # Field not to be displayed return (False, 0, pos_prev) if (offset < pos_prev) or (offset+width > 12): # Force to next row next_row = True padding = offset else: # Same row next_row = False padding = offset - pos_prev pos_next = offset + width return (next_row, padding, pos_next)
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 would be None. """ if not chunk_id or chunk_id[0] != 'c': raise ValueError("unexpected chunk id") n = chunk_id.find('-') # go to first underscore if n == 1: return None # no partition partition = int(chunk_id[1:n]) return 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(): key = "{}_{}".format(port, variable_name) flat[key] = values return flat
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 = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' '0123456789-._~') for index, item in enumerate(result): if index == 0: continue try: ch = int(item[:2], 16) except ValueError: continue if chr(ch) in unreserved: result[index] = chr(ch) + item[2:] else: result[index] = '%%%02X%s' % (ch, item[2:]) return ''.join(result)
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 '{}')".format(letter)) # A = 65, but we want A = 1 idSum += value return idSum
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 svn return None
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 entity == 'NS' or entity == 'NSI': return resp.get('operationState') else: return resp.get('_admin', {}).get('operationalState')
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] = True return True
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: `list_in` with `item` inserted """ if index + 1 < len(list_in): list_in.extend([0] * (index + 1 - len(list_in))) return list_in
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 if s == population: return 1 numerator = 1 denominator = 1 for i in range(s+1, population + 1): numerator *= i denominator *= (i - s) return numerator/denominator
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", None) x_calculated = calculated_position.get("x", None) y_calculated = calculated_position.get("y", None) w_calculated = calculated_position.get("width", None) h_calculated = calculated_position.get("height", None) x1 = x_actual if(x_actual > x_calculated) else x_calculated y1 = y_actual if(y_actual > y_calculated) else y_calculated x2 = (x_actual + w_actual - 1) if((x_actual + w_actual - 1) < (x_calculated + w_calculated -1)) else (x_calculated + w_calculated - 1) y3 = (y_actual + h_actual -1) if((y_actual + h_actual -1) < (y_calculated + h_calculated -1)) else (y_calculated + h_calculated - 1) x = x1 y = y1 w = x2 - x1 + 1 h = y3 - y1 + 1 return {"x": x, "y": y, "width": w, "height": h}
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((std / max_error), 2.0)
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, rhs_part in enumerate(rhs_label): label[idx] = rhs_part or label[idx] return label
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: ValueError """ if plugin_type not in available_plugin_types: raise ValueError('`Type must be one of the following: %s, but `%s` was given.' % ( ', '.join(available_plugin_types.keys()), plugin_type)) return available_plugin_types[plugin_type](configuration, plugin_configuration_data)
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: if letter not in rcDict: raise ValueError('Error: nucleotide not A, C, G, T, N found in string') else: rcSeq = rcSeq + rcDict[letter] return(rcSeq[::-1])
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, len(args), 2): if args[i]: result = args[i-1] break else: result = args[-1] return result
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[r+1] res+=1 else: l+=1 arr[l] += arr[l-1] res+=1 return res
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("[")] return ctype
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() or c == '.') return float(s)
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 layer names designating the ith output of calling the layer cannot occur within a layer name apart from at the end, so this utility function removes these. Parameters ---------- input_name: str, required A Keras layer name. strip_right_of_last_backslash: bool, optional, (default = True) Should we strip anything past the last backslash in the name? This can be useful for controlling scopes. strip_numerics_after_underscores: bool, optional, (default = True) If there are numerical values after an underscore at the end of the layer name, this flag specifies whether or not to remove them. """ # Always strip anything after :, as these will be numerical # counts of the number of times the layer has been called, # which cannot be included in a layer name. if ':' in input_name: input_name = input_name.split(':')[0] if '/' in input_name and strip_right_of_last_backslash: input_name = input_name.rsplit('/', 1)[0] if input_name.split('_')[-1].isdigit() and strip_numerics_after_underscores: input_name = '_'.join(input_name.split('_')[:-1]) return input_name
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. """ if not is_original and word in memo: return memo[word] for i in range(1, len(word)): # O(C) time left = word[:i] right = word[i:] if left in memo and memo[left] is True and _is_composed(right, False, memo): return True memo[word] = False return False
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 - 1) * 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 steppings at the start than at the end. The idea is that when the values are small, even small changes can greatly affect the behaviour of a system (such as the heap sizes of GC), so we want to explore smaller values at a finer granularity. For each n, we define n' = n + spread_factor / (N - 1) * (1 + 2 + ... + n-2 + n-1) For a consecutive pair (n-1, n), we can see that they are additionally (n-1) / (N-1) * spread_factor apart. For a special case when n = N, we have N' = N + N/2 * spread_factor, and (N'-1, N') is spread_factor apart. Let's concretely use spread_factor = 1 as as example. Let N and n be the same. So we have spread_factor / (N - 1) = 1/7 n = 0, n' = 0, n = 1, n' = 1. n = 2, n' = 2 + 1/7 n = 3, n' = 3 + 1/7 + 2/7 = 3 + 3/7 ... n = 7, n' = 7 + 1/7 + 2/7 + ... + 6/7 = 7 + 21/7 = 10 n = 8, n' = 8 + 1/7 + 2/7 + ... + 7/7 = 8 + 28/7 = 12 Parameters ---------- N : int Denominator spread_factor : int How much coarser is the spacing at the end relative to start spread_factor = 0 doesn't change the sequence at all n: int Nominator """ sum_1_n_minus_1 = (n*n - n) / 2 return n + spread_factor / (N - 1) * sum_1_n_minus_1
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: seq = str(seq).replace(p, '') tokens = str(seq).split(delim) if addStartToken: tokens.insert(0, '<START>') if addEndToken: tokens.append('<END>') return tokens
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 = len(op.shape)//2 #sites this operator acts on if site+oplength > N: raise IndexError("Sites, oplength ", site, oplength, "inconsistent with chain of length", N) X = chainopfunc(here, site, X, None) X = chainopfunc(site, site+oplength, X, op) here = site+oplength return chainnormfunc(here, X, Y)
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: axratio = ( 1.173 - 0.5165 * D_eq + 0.4698 * D_eq ** 2 - 0.1317 * D_eq ** 3 - 8.5e-3 * D_eq ** 4 ) else: axratio = ( 1.065 - 6.25e-2 * D_eq - 3.99e-3 * D_eq ** 2 + 7.66e-4 * D_eq ** 3 - 4.095e-5 * D_eq ** 4 ) return 1.0 / axratio
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 convert :param nb: nb of bit pseudo shifts to add :return: 32+n bit conversion result """ return ((val << nb) + (val & (0xFFFFFFFF >> (32 - nb)))) & 0xFFFFFFFFFFFFFFFF
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_flag: Boolean """ output["modifications"].append("Removed Back Ticks") return content_data.replace("`", ""), True
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 union of a and b. """ c = {} for key in a: if key in b: aval = a[key] bval = b.pop(key) if isinstance(aval, dict) and isinstance(bval, dict): c[key] = CombineDicts(aval, bval) else: c[key] = aval + bval else: c[key] = a[key] for key in b: c[key] = b[key] return c
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 ttt gamestate """ #check if previous move caused a win on vertical line if (ttt_board[0][y] == ttt_board[1][y] == ttt_board[2][y]): if (ttt_board[0][y] == "-" or ttt_board[1][y] == "-" or ttt_board[2][y] == "-"): return False return True #check if previous move caused a win on horizontal line if ttt_board[x][0] == ttt_board[x][1] == ttt_board[x][2]: if ttt_board[x][0] == "-" or ttt_board[x][1] == "-" or ttt_board[x][2] == "-": return False return True #check if previous move was on the main diagonal and caused a win if x == y and ttt_board[0][0] == ttt_board[1][1] == ttt_board[2][2]: if x == y and ttt_board[0][0] == "-" or ttt_board[1][1] == "-" or ttt_board[2][2] == "-": return False return True #check if previous move was on the secondary diagonal and caused a win if x + y == 2 and ttt_board[0][2] == ttt_board[1][1] == ttt_board[2][0]: if x + y == 2 and ttt_board[0][2] == "-" or ttt_board[1][1] == "-" or ttt_board[2][0] == "-": return False return True return False
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. This will be useless when http://code.djangoproject.com/changeset/14395 will be merge in a stable django version giving us a templates tag for deactivating localization. """ value = str(value) return value.replace(',', '.')
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 (-> 11) 12 -> -1 (-> 11) 13 -> -2 (-> 11) 14 -> 0 (-> 14) 15 -> -1 (-> 14) 16 -> -2 (-> 14) 17 -> 0 (-> 17) 18 -> -1 (-> 17) 19 -> -2 (-> 17) 20 -> 0 (-> 20) 21 -> -1 (-> 20) 22 -> -2 (-> 20) 23 -> 0 (-> 23) :param current_hour: :return: """ base_hours_for_forecast = (2, 5, 8, 11, 14, 17, 20, 23) offset_hours = 0 if current_hour < 2: offset_hours = -(current_hour + 1) else: for h in reversed(base_hours_for_forecast): if current_hour >= h: offset_hours = h - current_hour break return offset_hours
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.extend(attrs[3:]) stack = attrs for i in range(how_much_to_ignore): stack = stack[2] while stack: result.append(stack[1]) stack = stack[2] return result
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 a ValueError, else True. """ valid_operators = ["+", "-", "*", "/"] try: float(thing) return False except ValueError: return thing not in valid_operators
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 = (end - i*i) // i + 1 is_prime[i*i::i] = [0] * index_length return [n for n, p in enumerate(is_prime) if p]
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 viewport is larger than the document; we just show it at the top: >>> bounded_viewport(15, 1000, 45) 0 Above the top of the document (below y=0) there is nothing to be seen: >>> bounded_viewport(500, 200, -100) 0 Below the bottom of the document (below document_size) there is nothing to be seen: >>> bounded_viewport(500, 200, 400) 300 Open question: is it useful to return a smaller viewport if the document is actually smaller? For now, I have no use for it yet, so we just return the viewport_pos. """ if document_size < viewport_size: return 0 if viewport_pos < 0: return 0 return min(document_size - viewport_size, viewport_pos)
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.find('@') > 0: return 'acct:'+userid # Catchall: Guess at http: if nothing else works. return 'http://'+userid
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 of any shape compatible for broadcasting. """ m = len(A) n = len(A[0]) if check and m * n > 64: raise Exception('Too large. Use numpy.dot') C = [] for j in range(m): c = 0.0 for i in range(n): c += A[j][i] * b[i] C.append(c) return C
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.""" out_errors = [] for key in errors: for msg in errors[key]: if key != 'non_field_errors': out_errors.append('{}: {}'.format(key, msg)) else: out_errors.append(msg) return out_errors
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.endswith("Token"): return "TokenSyntax" return kind + "Syntax"
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 return string.decode(encoding)
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(val)}" return val
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 marked as False, this it is a prime if primes[p]: # mark all the multiples of number as False for i in range(p * 2, n + 1, p): primes[i] = False p += 1 # getting all primes primes = [element for element in range(2, n) if primes[element]] return primes
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 = len(fals_pos) FN = len(fals_neg) return TP, FP, FN
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, **kwargs) if not isinstance(s, str) and s is not None: raise TypeError( errorMsg + ". Got type %s"%str(type(s)) ) if s is not None: colorspace = s return colorspace
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 """ return a*(x**b)
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 coordinate of the right-modified local minimum """ slope = ds[minpoint] while slope < tau and slope > 0 and minpoint > 0 and minpoint < len(ds)-1: minpoint += 1 slope = ds[minpoint] return minpoint
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 chunks = [] # Chunks into chunk size, and append to chunks list for i in range(0, len(sentences), chunk_size): chunks.append(' '.join(sentences[i:i+chunk_size])) return 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 = [] for item in raw_data: output_tuple = tuple(item) processed_data.append(output_tuple) return 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://modoboa.org/ns/sync-token/3145</d:sync-token> </d:prop> <d:status>HTTP/1.1 200 OK</d:status> </d:propstat> </d:response> </d:multistatus> """ return {"status_code": 200, "content": content}
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 longest border length for i in range(1, n): # compute f[i] while w[k] != w[i] and k > 0: k = f[k - 1] # mismatch: try the next border if w[k] == w[i]: # last characters match k += 1 # we can increment the border length f[i] = k # we found the maximal border of w[:i + 1] return f
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] + a[1] - b[0] - b[1])) / 2 width = height = 2 * radius + 1 board = [[0] * height for _ in range(width)] center = (radius, radius) for x in range(width): for y in range(height): board[x][y] = int(hex_distance((x, y), center) <= radius) return board
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_time_two) total_sec = 60 * 60 * 24 delta_time = delta_time / total_sec return 1 / (1 + delta_time)
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 = {} for box in bboxes: if box.label not in bboxes_per_label: bboxes_per_label[box.label] = [] bboxes_per_label[box.label].append(box) return 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) - text_len)) if size < 0: return f"{offset}{text}" else: return f"{text}{offset}"
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 </DartMeasurementFile>\n'%(diffImage) tag += '<DartMeasurementFile name="ValidImage" type="image/png"> %s </DartMeasurementFile>'%(validImage) if oss is not None: oss.write(tag) return tag
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 element > value: continue if element == value: value = 0 _shallow_list.append(element) break if element < value: _shallow_list.append(element) value -= element if value != 0: return [] return _shallow_list
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(', '): if '-' in id_string: ids_range = id_string.split('-') first = int(ids_range[0]) last = int(ids_range[1]) ids.extend(range(first, last + 1)) else: ids.append(int(id_string)) return ids
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!") return something else: # print(something) return something
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. """ return len(stencil) != len(set(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 mapped to zero :type min_value: float :param max_value: the value that will be mapped to one :type max_value: float :returns: float -- the normalized value """ return (value - min_value) / (max_value - min_value)
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 comparison to column2) empty strong (seeking greater value in column2 in comparison to column1) var2---> 3 cases: abbreviation in column 2 (seeking better model) abbreviation in column 2 (seeking greater value in column2 in comparison to column1) empty strong (seeking lesser value in column1 in comparison to column2) Return: 2 cases: abbreviation of column name in which is smaller/greater depending on function use Function: list comprehension , put two column together (zip) used to find data set with a smaller/greater value """ return [var1 if r < c else var2 for r,c in zip(column1,column2)]