content
stringlengths
42
6.51k
def atmt(R0, T0, ALPHA, GAMM2, DELM2, C1, C2, C3, C4, C5, C6, R): """ Internal routine used by REFRO Refractive index and derivative with respect to height for the troposphere. Given: R0 d height of observer from centre of the Earth (metre) T0 d temperature at the observer (deg K) ALPHA d alpha ) GAMM2 d gamma minus 2 ) see HMNAO paper DELM2 d delta minus 2 ) C1 d useful term ) C2 d useful term ) C3 d useful term ) see source C4 d useful term ) of slRFRO C5 d useful term ) C6 d useful term ) R d current distance from the centre of the Earth (metre) Returned: T d temperature at R (deg K) DN d refractive index at R RDNDR d R rate the refractive index is changing at R Note that in the optical case C5 and C6 are zero. P.T.Wallace Starlink 30 May 1997 Copyright (C) 1997 Rutherford Appleton Laboratory Copyright (C) 1995 Association of Universities for Research in Astronomy Inc. """ T = max(min(T0 - ALPHA * (R - R0), 320.0), 100.0) TT0 = T / T0 TT0GM2 = TT0**GAMM2 TT0DM2 = TT0**DELM2 DN = 1.0 + (C1 * TT0GM2 - (C2 - C5 / T) * TT0DM2) * TT0 RDNDR = R * (-C3 * TT0GM2 + (C4 - C6 / TT0) * TT0DM2) return T, DN, RDNDR
def check_queue(queue, config): """ Check length and policy of a single queue :param queue: Queue form rabbit :param config: Desired queue state :return: length of a queue and lists of warnings and errors """ warnings = [] errors = [] length = queue['messages_ready'] if length > config['critical']: errors.append(length) elif length > config['warning']: warnings.append(length) policy = config.get('policy') queue_policy = queue.get('effective_policy_definition') if policy and policy != queue_policy: errors.append('Wrong queue policy') return length, warnings, errors
def makeup(_x, n): """ Increase the length of _x to be n by duplicating some elements :param _x: input length :param n: output size :return: list of length n with all original and additional duplicate elements from _x """ x = [] for i in range(n): x.append(_x[i % len(_x)]) return x
def is_palindrome(s: str) -> bool: """Returns True if s is a palindrome. Otherwise, False.""" assert type(s) == str, "Strings only." if not s: return True if s[0] != s[-1]: return False return is_palindrome(s[1:-1])
def parse_iterator_result(result): """Gets features, labels from result.""" if isinstance(result, (list, tuple)): if len(result) != 2: raise ValueError( 'input_fn should return (features, labels) as a len 2 tuple.') return result[0], result[1] return result, None
def split_by(string_val, num=8): """Splits a string into substrings with a length of given number.""" return [string_val[i:i+num] for i in range(0, len(string_val), num)]
def get_hdp_type(requested_type): """Get the integer representing the model type for the buildHdpUtils.c program :param requested_type: string associated with each type of hdp model :return: integer associated with that """ hdp_types = { "singleLevelFixed": 0, "singleLevelPrior": 1, "multisetFixed": 2, "multisetPrior": 3, "compFixed": 4, "compPrior": 5, "middleNtsFixed": 6, "middleNtsPrior": 7, "groupMultisetFixed": 8, "groupMultisetPrior": 9, "singleLevelPrior2": 10, "multisetPrior2": 11, "multisetPriorEcoli": 12, "singleLevelPriorEcoli": 13, "singleLevelFixedCanonical": 14, "singleLevelFixedM6A": 15 } assert (requested_type in list(hdp_types.keys())), "Requested HDP type is invalid, got {}".format(requested_type) return hdp_types[requested_type]
def findNth(haystack, needle, n): """ Finds the location of the n-th occurunce of needle in haystack :param haystack: String that we want to parse for the n-th occurunce of needle :param needle: String that we want to find in haystack :param n: one more than the number of occurunces of needle we want to skip in haystack :return: int for the location of the n-th occurunce of needle in haystack, return -1 if not found """ start = haystack.find(needle) while start >= 0 and n > 1: start = haystack.find(needle, start+len(needle)) n -= 1 return start
def distance(x1, y1, z1, x2, y2, z2, round_out=False): """ distance between two points in space for orthogonal axes. """ import math as m d = m.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2) if round_out: return round(d, round_out) else: return d
def balance_weights(labels): """ Generates a mapping of class weights that will re-weight a training set in a balanced way such that weight(label) = len(obs) / freq(label in obs). """ counts = {} for l in labels: counts[l] = counts.get(l, 0) + 1 return {l: (len(labels) / counts[l]) for l in counts}
def exclude(ex1, ex2): """Return the number on the interval [1,3] that is neither ex1 nor ex2 Parameters ---------- ex1 : int The first number to exclude (1, 2 or 3) ex2 : int The second number to exclude (1, 2 or 3) Returns ------- int The number (1, 2 or 3) not excluded """ if (ex1 == 1 and ex2 == 2) or (ex1 == 2 and ex2 == 1): return 3 elif (ex1 == 1 and ex2 == 3) or (ex1 == 3 and ex2 == 1): return 2 elif (ex1 == 2 and ex2 == 3) or (ex1 == 3 and ex2 == 2): return 1 else: raise Exception('exclude only works for 1, 2, 3')
def valueAndSymbol(current, last, show_delta): """Combine values and symbols.""" delta = abs(current - last) if last < current: symbolAndValue = ( "(&uArr; {}) {}".format(delta, current) if show_delta else "&uArr; {}".format(current) ) elif last > current: symbolAndValue = ( "(&dArr; {}) {}".format(delta, current) if show_delta else "&dArr; {}".format(current) ) else: symbolAndValue = "&equals; {}".format(current) return symbolAndValue
def Set_Interface_Client(interface="", address=""): """ configure for client to get gateway """ Client = ( "interface "+ interface + "\nip address "+ address + "\nexit\n" ) return Client
def _full_gap_columns(sequences): """ Return a boolean list, where True indicates a full gap column. >>> _full_gap_columns(["Q-V-Q-"]) [False, True, False, True, False, True] >>> seqs = ["Q-V-Q-", "--VH--"] >>> _full_gap_columns(seqs) [False, True, False, False, False, True] """ gaps = [residue == '-' for residue in sequences[0]] n_seqs = len(sequences) if n_seqs > 1: for i in range(1, n_seqs): sequence = sequences[i] for (j, residue) in enumerate(sequence): if residue != '-': gaps[j] = False return gaps
def label(s): """Return a string formatted as a label for s.""" return s.replace('_', ' ').capitalize()
def apply_mask(xy): """ Apply bitmask to value. Args: xy: A tuple with the bit of the mask and the bit to mask (mask, value). Returns: The bit after being masked. """ if xy[0] == 'X': return xy[1] else: return xy[0]
def histograph(list = [ ]): """ A histograph is a histogram where the unique items in a list are keys, and the counts of each item is the value for that key. The format is in XAYA graph format (values are lists) Definition: Get the set of distinct items in a list Count the number of times each item appears """ histoGraph = {} # Get the set of distinct items in a list distinctItems = set(list) # Count the number of times each item appears for item in distinctItems: histoGraph[item] = [list.count(item)] return histoGraph
def warning(text: str) -> str: """Get text prefixed with a warning emoji. Returns ------- str The new message. """ return "\N{WARNING SIGN} {}".format(text)
def merge_sort(m): """Always breaks the array into arrays of not more than 2 elements, and sort all of them, then merge the arrays (sort each elements again when merging).""" mlen = len(m) if mlen <= 2: try: x, y = m[0], m[1] if x > y: m[0], m[1] = y, x except IndexError: pass return m mhalf = mlen // 2 l = merge_sort(m[:mhalf]) r = merge_sort(m[mhalf:]) merged = [] while l and r: merged.append(l.pop(0) if l[0] <= r[0] else r.pop(0)) return merged + l + r
def make_schedule(n,pattern): """ Make up an auditing schedule (a list of sample size s values to use) start with 0 do pattern, then pattern repeated by multipied by last/first, etc. end with n note that last/first does not need to be an integer. make_schedule(1000,[1,2]) # --> 0,1,2,4,8,16,32,64,128,256,512,1000 make_schedule(1000,[1,2,5,10]) # --> 0,1,2,5,10,20,50,100,200,500,1000 make_schedule(1000,[5,6]) # --> 0,5,6,7,8,10,12,14,17,21,25,30,37,44,53,64,77,... """ schedule = [ 0 ] multiplier = 1 next_s = 1 while schedule[-1] < n: for x in pattern: next_s = int(x*multiplier) next_s = min(n,next_s) if next_s > schedule[-1]: schedule.append(next_s) multiplier *= float(pattern[-1])/float(pattern[0]) return schedule
def tuple_swap(i, j): """Swap with tuple unpacking""" (i, j) = (j, i) return i, j
def velocity(ek, m): """ Calculate and return the value of velocity using given values of the params How to Use: Give arguments for ek and m params, *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERSTAND AND USE.' Parameters: ek (int): kinetic energy in Joule m (int):mass in kg Returns: int: the value of velocity in m/s """ import math v = math.sqrt((2 * ek) / m) return v
def get_child_object(obj, child_name): """Return the child object Arguments: obj {object} -- parent object child_name {str} -- cild name Returns: object -- child object """ if hasattr(obj, '__getattr__'): try: return obj.__getattr__(child_name) except AttributeError: pass if hasattr(obj, '__getattribute__'): try: return obj.__getattribute__(child_name) except AttributeError: pass if hasattr(obj, '__getitem__'): try: return obj.__getitem__(child_name) except AttributeError: pass
def lerp(a, b, t): """ blend the value from start to end based on the weight :param a: start value :type a: float :param b: end value :type b: float :param t: the weight :type t: float :return: the value in between :rtype: float """ return a * (1 - t) + b * t
def tryDivide(x, y): """ Try to divide two numbers""" s = 0.0 if y != 0.0: s = x / y return s
def scale(v: float, a: float, b: float, c: float, d: float) -> float: """Scale a value, v on a line with anchor points a,b to new anchors c,d.""" v01 = (v - a) / (b - a) return c - v01 * (c - d)
def isBool(x): """ Returns True, if x is a boolean. >>> isBool(True) True >>> isBool(False) True >>> isBool(1) True >>> isBool(0) True >>> isBool(2) False >>> isBool('true') False """ if isinstance(x, int) and x in [0,1]: return True return isinstance(x, bool)
def vector_add(v, w): """adds two vectors componentwise""" return [v_i + w_i for v_i, w_i in zip(v,w)]
def boundary_overflow(posX, posY): """ Correct coordinates for boudary overflow Treating the 8x8 boundaries as if they don't exist. (8,8) is the same as (0,0), (-1,-1) same as (7,7) """ x_field = posX y_field = posY if x_field > 7: x_field = 0 if x_field < 0: x_field = 7 if y_field > 7: y_field = 0 if y_field < 0: y_field = 7 return [x_field, y_field]
def convert_time(seconds): """Takes seconds as input and turns it into minutes or hours, if necessary. Parameters ---------- seconds : float Time in seconds. Returns ------- time : float Magnitude of time. unit : str Time unit. Either be seconds, minutes or hours. """ unit = "seconds" time = seconds if time >= 60: time = time / 60 unit = "minutes" if time >= 60: time = time / 60 unit = "hours" return time, unit
def _strip_instances(iterable, excluded_instances=None): """ Parameters ---------- iterable: list, dict, tuple Iterable (in most cases a dask task graph). excluded_instances: Names of excluded types, which will not be stripped. The default is None. Returns ------- list, dict, tuple Iterable only with built-in types. """ if excluded_instances is None: excluded_instances = list() if isinstance(iterable, list): stripped_iterable = list() for item in iterable: stripped_iterable.append(_strip_instances(item, excluded_instances)) return stripped_iterable elif isinstance(iterable, tuple): stripped_iterable = list() for item in iterable: stripped_iterable.append(_strip_instances(item, excluded_instances)) return tuple(stripped_iterable) elif isinstance(iterable, dict): stripped_iterable = dict() for key, value in iterable.items(): stripped_iterable[key] = _strip_instances(value, excluded_instances) return stripped_iterable elif isinstance(iterable, (int, bool, float, str)) or iterable is None: return iterable else: try: full_name = iterable.__module__ + "." + iterable.__name__ except: full_name = ( iterable.__class__.__module__ + "." + iterable.__class__.__name__ ) if full_name in excluded_instances: return iterable else: return callable
def merge_sort(data): """ :param data: :return: >>> merge_sort([3,4,5,2,1]) [1, 2, 3, 4, 5] """ if len(data) < 2: return data def _merge(left, right): def meg(): while left and right: yield (left if left[0] < right[0] else right).pop(0) yield from left yield from right return list(meg()) mid = len(data) // 2 return _merge(merge_sort(data[0:mid]), merge_sort(data[mid:]))
def isSubset(s1, s2): """Returns whether s1 is a subset of s2""" if len(s1) == 0: return True if s1[0] in s2: i = s2.index(s1[0]) return isSubset(s1[1:], s2[:i] + s2[i+1:]) else: return False
def pad_sentence_batch(sentence_batch, pad_int): """ pad the batch sequence, make sure every batch has same sequence_length :param sentence_batch: :param pad_int: :return: """ max_sentence = max([len(sentence) for sentence in sentence_batch]) return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]
def assert_shapes_compatible(lhs, rhs): """Check if the shape of two tensors are broadcast-compatible.""" # This is a stricter-than-necessary check for broadcast-comptability, # but it's error-prone to allow broadcasting to insert new dimensions so # we don't allow that. if len(lhs) != len(rhs): return False for lhs_dim, rhs_dim in zip(lhs, rhs): # A dimension of 1 will be broadcasted to match the other tensor's dimension if lhs_dim == 1 or rhs_dim == 1: continue assert lhs_dim == rhs_dim, (f"Tensors with shape {lhs} and {rhs} cannot " f"be broadcasted together")
def add16(buf, value): """Add a littleendian 16bit value to buffer""" buf.append(value & 0xff) value >>= 8 buf.append(value & 0xff) return buf
def remove_every_other(my_list): """Remove every other element in a list.""" return my_list[::2]
def reduce_headers(content, level, indent=1): """ replaces the #* with level number of # :param content: :type content: :param level: :type level: :param indent: :type indent: :return: :rtype: """ ignore = False lines = content.splitlines() headers = [] out = [] for line in lines: if line.startswith("`"): ignore = not ignore if line.startswith("#") and not ignore: line = line.replace("#" * level, "#") line = line.replace("# ", "#" * (indent - 1) + " ") out.append(line) return out
def white_bw(w,h): """ retorna una imatge en blanc en el format blanc i negre >>> white_bw(3,3) ('1', [[255, 255, 255], [255, 255, 255], [255, 255, 255]]) >>> white_bw(1,1) ('1', [[255]]) """ i=0 l=[] while i<(h): j=0 l_2=[] while j<(w): l_2+=[(255)] j+=1 l+=[l_2] i+=1 return ('1',l)
def expand_request_pixels(request, radius=1): """ Expand request by `radius` pixels. Returns None for non-vals requests or point requests. """ if request["mode"] != "vals": # do nothing with time and meta requests return None width, height = request["width"], request["height"] x1, y1, x2, y2 = request["bbox"] pwidth, pheight = x2 - x1, y2 - y1 if pwidth == 0 or pheight == 0: # cannot dilate a point request return None amount_x = pwidth / width * radius amount_y = pheight / height * radius new_request = request.copy() new_request["bbox"] = (x1 - amount_x, y1 - amount_x, x2 + amount_y, y2 + amount_y) new_request["width"] += 2 * radius new_request["height"] += 2 * radius return new_request
def dB_to_amplitude(SNR): """Returns the amplitude ratio, converted from decibels. Arguments --------- SNR : float The ratio in decibels to convert. Example ------- round(dB_to_amplitude(SNR=10), 3) 3.162 dB_to_amplitude(SNR=0) 1.0 """ return 10 ** (SNR / 20)
def getShelfFromCardName(cardName): """ cardName is expected to be of the form 'gem-shelfXX-amcYY' where XX & YY are integers """ shelf = (cardName.split("-")[1]) shelf = int(shelf.strip("shelf")) return shelf
def is_lower_freq(freq1: str, freq2: str) -> bool: """Tests freq1 has a lower or equal frequency than freq2. Lower frequencies cannot be converted to higher frequencies due to lower resolution. Args: freq1: frequency 1 freq2: frequency 2 Returns: bool: frequency 1 is lower than or euqal to frequency 2 """ freq = ["H", "D", "B", "W", "M", "Q", "Y"] freq = dict(zip(freq, [*range(0, len(freq))])) return freq[freq1] >= freq[freq2]
def synchronous_events_intersection(sse1, sse2, intersection='linkwise'): """ Given two sequences of synchronous events (SSEs) `sse1` and `sse2`, each consisting of a pool of positions `(iK, jK)` of matrix entries and associated synchronous events `SK`, finds the intersection among them. The intersection can be performed 'pixelwise' or 'linkwise'. * if 'pixelwise', it yields a new SSE which retains only events in `sse1` whose pixel position matches a pixel position in `sse2`. This operation is not symmetric: `intersection(sse1, sse2) != intersection(sse2, sse1)`. * if 'linkwise', an additional step is performed where each retained synchronous event `SK` in `sse1` is intersected with the corresponding event in `sse2`. This yields a symmetric operation: `intersection(sse1, sse2) = intersection(sse2, sse1)`. Both `sse1` and `sse2` must be provided as dictionaries of the type .. centered:: {(i1, j1): S1, (i2, j2): S2, ..., (iK, jK): SK}, where each `i`, `j` is an integer and each `S` is a set of neuron IDs. Parameters ---------- sse1, sse2 : dict Each is a dictionary of pixel positions `(i, j)` as keys and sets `S` of synchronous events as values (see above). intersection : {'pixelwise', 'linkwise'}, optional The type of intersection to perform among the two SSEs (see above). Default: 'linkwise'. Returns ------- sse_new : dict A new SSE (same structure as `sse1` and `sse2`) which retains only the events of `sse1` associated to keys present both in `sse1` and `sse2`. If `intersection = 'linkwise'`, such events are additionally intersected with the associated events in `sse2`. See Also -------- ASSET.extract_synchronous_events : extract SSEs from given spike trains """ sse_new = sse1.copy() for pixel1 in sse1.keys(): if pixel1 not in sse2.keys(): del sse_new[pixel1] if intersection == 'linkwise': for pixel1, link1 in sse_new.items(): sse_new[pixel1] = link1.intersection(sse2[pixel1]) if len(sse_new[pixel1]) == 0: del sse_new[pixel1] elif intersection == 'pixelwise': pass else: raise ValueError( "intersection (=%s) can only be" % intersection + " 'pixelwise' or 'linkwise'") return sse_new
def compare_location_and_region(first_file, second_file): """ Compares versions for osfstoragefiles - Compares location['bucket'] and location['object']. Also compares version region_ids. """ first_loc = first_file['versions__location'] second_loc = second_file['versions__location'] if first_loc and second_loc: return first_loc['bucket'] == second_loc['bucket'] and \ first_loc['object'] == second_loc['object'] and \ first_file['versions__region_id'] == first_file['versions__region_id'] return False
def _x_to_lon(x, zoom): """ :param x: :param zoom: :return: """ return x / pow(2, zoom) * 360.0 - 180.0
def decode_reverse(string): """ Encodes a string with the reverse ciphering method :param string: :return decoded string: """ return str(string)[::-1]
def get_params_phrase(params): """Create params phrase recursively """ keys = [key for key in params] keys.sort() key_count = len(keys) if key_count == 0: return "" phrase = "" if isinstance(params[keys[0]], dict) is not True: phrase += f'{keys[0]}.{params[keys[0]]}' elif bool(params[keys[0]]) is not True: phrase += f'{keys[0]}' else: phrase += f'{keys[0]}.{get_params_phrase(params[keys[0]])}' for i in range(1, key_count): key = keys[i] if isinstance(params[key], dict) is not True: phrase += f'.{key}.{params[key]}' elif bool(params[key]) is not True: phrase += f'.{key}' else: phrase += f'.{key}.{get_params_phrase(params[key])}' return phrase
def is_special(ip_address): """Determine if the address is SPECIAL Note: This is super bad, improve it """ special = {'224.0.0.251': 'multicast_dns', 'ff02::fb': 'multicast_dns'} return special[ip_address] if ip_address in special else False
def number_to_base(n, b): """ translates a decimal number to a different base in a list of digits Args: n: the decimal number b: the new base Returns: A list of digits in the new base """ if n == 0: return [0] digits = [] while n: digits.append(int(n % b)) n //= b return digits[::-1]
def get_short_name(longname): """ Returns the shortname of an input object. """ return longname.rsplit('|', 1)[-1]
def split_recursive(lst): """ Recursively splits the lst into two equal (unless len(lst) is odd) halves with a single scan of lst, driver function for aux """ def aux(lst, l, r, i, j): """ Main recursive function for split_recursive """ if not lst: return (l, r) elif i < j + 1: return aux(lst[1:], l + [r[0]], r[1:] + [lst[0]], i + 1, j) else: return aux(lst[1:], l, r + [lst[0]], i, j + 1) return aux(lst[1:], [lst[0]], [], 1, 0)
def _normalise_service_name(name): """ To be able to safely compare service names. The output is not meant to be human-readable. Copied from `upload_draft_service_pdfs.py` """ return ( name.lower() .replace("-", "") .replace("_", "") .replace(":", "") .replace(" ", "") .replace(".csv", "") )
def mergedicts(*a): """ Merge a list of dictionaries. """ result = {} for d in a: result.update(d) return result
def int_to_mask(mask_int): """ Convert int to mask Args: mask_int ('int'): prefix length is convert to mask Returns: mask value """ bin_arr = ["0" for i in range(32)] for i in range(int(mask_int)): bin_arr[i] = "1" tmpmask = ["".join(bin_arr[i * 8:i * 8 + 8]) for i in range(4)] tmpmask = [str(int(tmpstr, 2)) for tmpstr in tmpmask] return ".".join(tmpmask)
def JoinFilters(clauses, operator='AND'): """Join the clauses with the operator. This function surrounds each clause with a set of parentheses and joins the clauses with the operator. Args: clauses: List of strings. Each string is a clause in the filter. operator: Logical operator used to join the clauses Returns: The clauses joined by the operator. """ return (' ' + operator + ' ').join(clauses)
def is_type_name(type_name): """Does not handle keywords. """ return type_name[0].isupper()
def format_hex_width(value, width): """! @brief Formats the value as hex of the specified bit width. @param value Integer value to be formatted. @param width Bit width, must be one of 8, 16, 32, 64. @return String with (width / 8) hex digits. Does not have a "0x" prefix. """ if width == 8: return "%02x" % value elif width == 16: return "%04x" % value elif width == 32: return "%08x" % value elif width == 64: return "%016x" % value else: raise ValueError("unrecognized register width (%d)" % width)
def gray_code(n): """ Generate a Gray code sequence of bit string with length n. Args: n: The size for each element in the Gray code Returns: An array of strings forming a Gray code """ if n == 1: return ["0", "1"] else: g_previous = gray_code(n - 1) mirrored_paste = g_previous + g_previous[::-1] g_current = mirrored_paste[:] for i in range(2 ** n): if i < 2 ** (n - 1): g_current[i] = g_current[i] + "0" else: g_current[i] = g_current[i] + "1" return g_current
def eval_token(token): """ convert string token to int, float or str """ if token.isnumeric(): return int(token) try: return float(token) except: return token
def splice_before(base, search, splice, post_splice="_"): """Splice in a string before a given substring. Args: base: String in which to splice. search: Splice before this substring. splice: Splice in this string; falls back to a "." if not found. post_splice: String to add after the spliced string if found. If only a "." is found, ``post_splice`` will be added before ``splice`` instead. Defaults to "_". Returns: ``base`` with ``splice`` spliced in before ``search`` if found, separated by ``post_splice``, falling back to splicing before the first "." with ``post_splice`` placed in front of ``splice`` instead. If neither ``search`` nor ``.`` are found, simply returns ``base``. """ i = base.rfind(search) if i == -1: # fallback to splicing before extension i = base.rfind(".") if i == -1: return base else: # turn post-splice into pre-splice delimiter, assuming that the # absence of search string means delimiter is not before the ext splice = post_splice + splice post_splice = "" return base[0:i] + splice + post_splice + base[i:]
def preprocess_remove_gray(raw_img): """ The preprocess function for removing the gray portion of the image.Please note that here we also normalize the values between 0.0 and 1.0 for the neural network. Parameters ---------- raw_img : array The array to be processed Returns ---------- raw_img: array The processed array """ for row in range(0, len(raw_img)): for column in range(0, len(raw_img[row])): if raw_img[row][column] < 128: raw_img[row][column] = 0 else: raw_img[row][column] = 255 # 1.0 return raw_img
def checkPayoff(T, R, P, S): """-> True, if T > R > P > S and 2R > T+S""" return T > R and R > P and P > S and 2*R > T+S
def _is_number(s: str) -> bool: # pylint: disable=invalid-name """Return True if string is a number.""" return s.replace(".", "", 1).isdigit()
def form_array_from_string_line(line): """Begins the inversion count process by reading in the stdin file. Args: line: A string of input line (usually from a text file) with integers contained within, separated by spaces. Returns: array: List object (Python's standard 'array' type) featuring each of the integers as a separate item in the list.""" array = [int(n) for n in line.split()] return array
def frac(n): """ This function calculates, for a given integer n, the fraction 1/2(n-1) """ if n > 1: return 1/(2+frac(n-1)) else: return 1/2
def trans_matrix(M): """Take the transpose of a matrix.""" n = len(M) return [[ M[i][j] for i in range(n)] for j in range(n)]
def get_radio_button_label(field_value, label_list): """Return human-readable label for problem choices form value.""" for value, text in label_list: if value == field_value: return text # Something probably went wrong. Return something safe. return u'Unknown'
def flatten(l, ltypes=(list, tuple, set)): """ Flatten a list or tuple that contains additional lists or tuples. Like the numpy flatten, but for python types. Parameters ---------- l: tuple or list, The data that is to be flattened ltypes: tuple, Data types to attempt to flatten Returns ------- list See Also -------- numpy.flatten() Notes ----- This code was taken from: <http://rightfootin.blogspot.com.au/2006/09/more-on-python-flatten.html> Examples -------- >>> a=[[1,3,4,1], ('test', 'this'), [5,2]] >>> flatten(a) [1, 3, 4, 1, 'test', 'this', 5, 2] """ ltype = type(l) l = list(l) i = 0 while i < len(l): while isinstance(l[i], ltypes): if not l[i]: l.pop(i) i -= 1 break else: l[i:i + 1] = l[i] i += 1 return ltype(l)
def is_even(x): """return true if x is even.""" return x//2*2 == x
def is_valid_file(ext, argument): """ Checks if file format is compatible """ formats = { 'input_dataset_path': ['csv'], 'output_results_path': ['csv'], 'output_plot_path': ['png'] } return ext in formats[argument]
def removeDuplicates(seq): """ Remove duplicates from seq while preserving order """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def unify_table(table): """Given a list of rows (i.e. a table), this function returns a new table in which all rows have an equal amount of columns. If all full column is empty (i.e. all rows have that field empty), the column is removed. """ max_fields = max(map(lambda row: len(row), table)) empty_cols = [True] * max_fields output = [] for row in table: curr_len = len(row) if curr_len < max_fields: row += [''] * (max_fields - curr_len) output.append(row) # register empty columns (to be removed at the end) for i in range(len(row)): if row[i].strip(): empty_cols[i] = False # remove empty columns from all rows table = output output = [] for row in table: cols = [] for i in range(len(row)): should_remove = empty_cols[i] if not should_remove: cols.append(row[i]) output.append(cols) return output
def split_dict_type(dtype): """Checks if dtype is a dictionary type, then return the types E.g.: split_dict_type(Dict[str, int]) -> str, int split_dict_type(str) -> str, None """ if isinstance(dtype, type): return dtype, None is_dict = hasattr(dtype, "__args__") and len(dtype.__args__) == 2 and dtype._name == "Dict" if is_dict: return dtype.__args__ else: return dtype, None
def infer_xml_schema(xml_doc_obj): """ This function determines which schema should be used to validate the xml within the file """ try: # look for ".xsd" attribute on root tag for _name, value in xml_doc_obj.getroot().items(): if ".xsd" in value.lower(): return value except AttributeError: pass try: # use name of root tag as the name of the xsd return xml_doc_obj.getroot().tag + ".xsd" except BaseException as err: print(err) print("WARNING: using default - couldn't fine root tag") return "BES.xsd"
def binary_search(sorted_list, target): """Find where a number lies in a sorted list. Return lowest item that is greater than or equal to target, or None if no item in list greater than or equal to target """ if sorted_list==[]: return None if len(sorted_list)==1: if target <= sorted_list[0]: return 0 return None mid_index = int(len(sorted_list)/2)-1 mid_value = sorted_list[mid_index] if target <= mid_value: return binary_search(sorted_list[0:mid_index+1], target) else: return mid_index + 1 + binary_search(sorted_list[mid_index+1:], target)
def _acceptableNumber(text: str, negationAllowed=True, periodAllowed=True, containsDigits=False) -> bool: """Private helper function to check if a number meets criteria for being a Float/Int. Args: text (str): The string to check. negationAllowed (bool, optional): If a negative sign is ok. Defaults to True. periodAllowed (bool, optional): If a period is ok (i.e. float is ok). Defaults to True. containsDigits (bool, optional): Do not use. Defaults to False. Returns: bool: If number meets the criteria.=. """ if text == '': return containsDigits x = text[0] if x == '-': return negationAllowed and _acceptableNumber(text[1:], False, periodAllowed, containsDigits) if x == '.': return periodAllowed and _acceptableNumber(text[1:], False, False, containsDigits) if x.isdigit(): return _acceptableNumber(text[1:], False, periodAllowed, True) return False
def last_blank(src): """Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. """ if not src: return False ll = src.splitlines()[-1] return (ll == '') or ll.isspace()
def get_list_of_failed_test_cases(console_output): """ Return list of failed test cases from ATF console output :param console_output: plain text of ATF console output :return: list of failed test cases """ failed_list = [] for line in console_output.split("\n"): pos = line.find("[FAIL]") if pos != -1: failed_list.append(line[0:pos]) return failed_list
def differential_reflectance(signal, reference): """Return '(signal - reference) / signal'.""" return (signal - reference)/(signal)
def filter_sobject_list(sobject_list): """ Takes a list of FeedItem/FeedComment and returns the list with only the fields that we care about, with normalized keys. """ sobject_type = sobject_list[0]['attributes']['type'] if sobject_list else None fields = ('Body' if sobject_type == 'FeedItem' else 'CommentBody', 'Id' if sobject_type == 'FeedItem' else 'FeedItemId', 'ParentId', 'CreatedById', 'CreatedDate') filtered_sobject_list = [ {key: x[key] for key in fields} for x in sobject_list ] for sobject in filtered_sobject_list: # Normalize all body fields to be called "Body". if 'CommentBody' in sobject: sobject['Body'] = sobject.pop('CommentBody') # Normalize all feed item ID fields to be called "FeedItemId". if 'FeedItemId' not in sobject: sobject['FeedItemId'] = sobject.pop('Id') return filtered_sobject_list
def eucl_dist_output_shape(shapes): """Returns shape. Args: shapes : shape of euclidean distance. Returns: Shape of euclidean distance. """ shape1, shape2 = shapes return (shape1[0], 1)
def occurrences(string, sub): """ string count with overlapping occurrences """ count = start = 0 while True: start = string.find(sub, start) + 1 if start > 0: count+=1 else: return count
def _split2(list_): """ Splits a list in 2 sublists. """ list_length = len(list_) if (list_length == 2): return (list_, []) else: midpoint = int(list_length / 2) return (list_[0:midpoint + 1], list_[midpoint:list_length])
def merge_3d_mappings(pdb_data, pdb_curated_data): """ Merge PDB data from automatic Rfam mapping and a curated list. If a pdb_id is found in the curated list, but not found in the automatic mapping, it is added to a merged list. """ for rfam_acc in pdb_curated_data.keys(): curated_data = pdb_curated_data[rfam_acc] if rfam_acc in pdb_data: for pdb_id in curated_data: if pdb_id not in pdb_data[rfam_acc]: pdb_data[rfam_acc].append(pdb_id) else: pdb_data[rfam_acc] = curated_data return pdb_data
def create_test_file(data,file): """ """ with open(file,"w") as f: y_batch = [] for (x, y) in data: input_raw="" input_raw+=' '.join(x)+'\n' f.write(input_raw) y_batch += [y] return y_batch
def j_shift(curr_shape, shiftX, shiftY): """ Helper to modify the in_shape tuple by jitter amounts """ return curr_shape[:-2] + (curr_shape[-2] - shiftY, curr_shape[-1] - shiftX)
def remove_machine_specification(input_yaml): """ Will remove the machine specifications from a supplied bundle. :param input_yaml: Juju bundle to strip machinens from :type input_yaml: dict :returns: bundle without machine placements :rtype: dict """ machines = input_yaml.pop("machines", None) input_series = input_yaml.get('series', None) if machines: for (name, details) in machines.items(): if details['series']: if input_series and details['series'] != input_series: raise Exception("Mixing series is not supported") input_yaml['series'] = details['series'] input_series = input_yaml['series'] for (application_name, application) in input_yaml['services'].items(): application.pop("to", None) return input_yaml
def get_filename(filename): """remove path""" def lt(f, x): f=f.split(x) f=f[len(f)-1] return f return lt(lt(filename, '\\'), '/')
def removeExtension(file): """returns filename without extension""" if not file[-4:] == "webm": return file[:-4] else: return file[:-5]
def aligned_indices(i, j, spacing): """ Check if two indices are aligned. Two indices are aligned if they differ by an Integer*spacing. """ try: return int((i - j)/spacing) == (i - j)/spacing except TypeError: return False
def calc_acc(fn: float, fp: float, tp: float, tn: float) -> float: """ :param fn: false negative miss :param fp: false positive or false alarm :param tp: true positive or hit :param tn: true negative or correct rejection :return: accuracy """ try: calc = (tp + tn) / (tp + tn + fn + fp) except ZeroDivisionError: calc = 0 return calc
def byte_to_hex_str(n): """Returns a 2 character hex string for a given byte value `n`. """ if n > 255 or n < 0: raise ValueError() return '%02x' % n
def day_to_int(day): """ day: a string representing the day of the week Returns an integer e.g. "MONDAY" -> 0, "TUESDAY" -> 1, etc. """ days = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"] return days.index(day.upper())
def _full_link(provider, word): """Return a website link for dictionary provider and word.""" return 'http://' + provider + word
def Checksum(payload, payload_size): """Calculates the checksum of the payload. Args: payload: (string) The payload string for which checksum needs to be calculated. payload_size: (int) The number of bytes in the payload. Returns: The checksum of the payload. """ checksum = 0 length = min(payload_size, len(payload)) for i in range (0, length): checksum += ord(payload[i]) return checksum
def wordfreq(text, is_filename=False): """Return a dictionary of words and word counts in a string.""" if is_filename: with open(text) as f: text = f.read() freqs = {} for word in text.split(): lword = word.lower() freqs[lword] = freqs.get(lword, 0) + 1 return freqs
def remove_empty(input_list, category='Both'): """ remove empty element :param input_list: list, consists of elements which may be empty :param category: string, denote the requirements, including All, Both, Left, Right :return: list """ assert isinstance(input_list, list) if category == 'All': # all empty elements return [tmp for tmp in input_list if tmp] else: if not input_list: return [] else: begin = 0 end = len(input_list) for i in range(len(input_list)): if input_list[i]: begin = i break for i in range(len(input_list)-1, -1, -1): if input_list[i]: end = i + 1 break if category == 'Both': # both direction return input_list[begin:end] elif category == 'Left': return input_list[begin:] elif category == 'Right': return input_list[:end] else: print('warning: invalid category') return []
def lerp(x, x0, x1, y0, y1): """ Linearly interpolate between points (x0, y0) and (x1, y1) to get the value of y at x. :param x: :param x0: :param x1: :param y0: :param y1: :return: """ t = (x - x0) / (x1 - x0) return (1 - t) * y0 + t * y1
def is_in_range(x, min=None, max=None): """Returns ``True`` if `x` is in range; ``False`` otherwise.""" if min and x < min or max and x > max: return False return True