content
stringlengths
42
6.51k
def to_hex(number, width): """Convert number to hex value with specified width. Will be padded by zero to fill the width. """ format_string = '{{0:0{0}X}}'.format(width) return format_string.format(number)
def green(text): """Returns a string with ANSI codes for green color and reset color wrapping the provided text. """ return '\033[32m%s\033[39m' % text
def log_file_path(log_path, date_string, suffix): """ Create log file path. The arg date_string must be in the form: yyyymmdd Inputs: log_path: directory string date_string: date string in the form yyyymmdd suffix: suffix string """ return("%s.%s%s" % (log_path, date_string, suffix))
def precision(tp, fp): """ :param tp: :param fp: :return: """ return tp/(tp+fp)
def column_filter(column): """standardize column names""" return column.replace(' ', '_').replace('-', '_').lower().strip()
def to_decimal(number: str) -> int: """Convert other bases to decimal""" if number[0:2] == "0b": # binary return int(number[2:], 2) if number[0:2] == "0x": # hex return int(number[2:], 16) if number[0:2] == "0o": # octal return int(number[2:], 8) if number[0:2] == "0d": # decimal return int(number[2:], 10) # default - decimal return int(number)
def bytedivider(nbytes): """ Given an integer (probably a long integer returned by os.getsize() ) it returns a tuple of (megabytes, kilobytes, bytes). This can be more easily converted into a formatted string to display the size of the file. """ mb, remainder = divmod(nbytes, 1048576) kb, rb = divmod(remainder, 1024) return (mb, kb, rb)
def split_string_by_n(bitstring: str, n: int) -> list: """ Split a string every n number of characters (or less if the 'remaining characters' < n ) this way we can sperate the data for an etire video into a list based on the resolution of a frame. bitstring -- a string containing bits n -- split the string every n characters, for example to split a 1920 x 1080 frame, this would be 1920*1080 = 2073600 """ bit_list = [] for i in range(0, len(bitstring), n): bit_list.append(bitstring[i : i + n]) return bit_list
def quick_find_max_sum_interval(a_list): """ Prac 3 Hall of Fame @purpose variant of Kadane's Algorithm for maximum subarray problems, to find the max sum interval in this case, using dynamic programming @param a_list: The list to be passed to find max sum interval indices @Complexity: O(N) - Worst Case: Iterating through the list of N items O(1) - Best Case: Empty list @Precondition: An array of numerical values has to be passed @Postcondition: Returns the min and max indices for the max sum interval """ currentMax = a_list[0] maxSum = a_list[0] i_min = i_min_tmp = 0 i_max = 0 for i in range(1, len(a_list)): if currentMax >= 0: currentMax += a_list[i] else: currentMax = a_list[i] i_min_tmp = i if maxSum <= currentMax: i_max = i i_min = i_min_tmp maxSum = currentMax #print("Maximum sum is " + str(float(maxSum))) return i_min, i_max
def _get_decoded_dict(the_dict: dict) -> dict: """This method might be over kill, but redis appears to be sending back non ASCII data, so this method prunes all possible non usable data, to something that's usable. @note: This should be revisited! """ new_dict = {} for key, value in the_dict.items(): try: new_dict[key] = value.decode('ascii') except AttributeError: new_dict[key] = value return new_dict
def cql_type_to_gemini(cql_type, is_frozen=False): """ Convert a cql type representation to the gemini json one. Limitations: * no support for udt * limited nested complex types support """ if isinstance(cql_type, str): return cql_type elif len(cql_type) == 1: return cql_type[0] else: is_frozen_type = is_frozen gemini_type = {} token = cql_type.pop(0) if isinstance(token, (list, tuple)): return cql_type_to_gemini(token, is_frozen_type) elif token == 'frozen': return cql_type_to_gemini(cql_type.pop(0), True) elif token == 'map': subtypes = cql_type.pop(0) gemini_type['key_type'] = cql_type_to_gemini(subtypes[0], is_frozen_type) gemini_type['value_type'] = cql_type_to_gemini(subtypes[1], is_frozen_type) elif token == 'list': gemini_type['kind'] = 'list' gemini_type['type'] = cql_type_to_gemini(cql_type.pop(0)[0], is_frozen_type) elif token == 'set': gemini_type['kind'] = 'set' gemini_type['type'] = cql_type_to_gemini(cql_type.pop(0)[0], is_frozen_type) elif token == 'tuple': gemini_type['types'] = cql_type.pop(0) gemini_type['frozen'] = is_frozen_type return gemini_type
def str_binary_or(s1, s2): """ returns a string of 1 and 0 specifying if letters are the same or not test1,test2 ==> 11110 use .find('0') to determine the first diff character. """ return ''.join(str(int(a == b)) for a, b in zip(s1, s2))
def verifyIsCloseEnough(number1, number2, margin = 0.05): """ Return true if number1 is within margin of number 2. """ max_diff = number2 * margin return (abs(number1 - number2) < max_diff)
def is_valid_instant(x): """ Returns true iff x is a well-shaped concrete time instant (i.e. has a numeric position). """ try: return hasattr(x, "inTimePosition") and len(x.inTimePosition) > 0 and \ len(x.inTimePosition[0].numericPosition) > 0 except TypeError: return False
def str_or_list_like(x): """Determine if x is list-list (list, tuple) using duck-typing. Here is a set of Attributes for different classes | x | type(x) | x.strip | x.__getitem__ | x.__iter__ | | aa | <class 'str'> | True | True | True | | ['a', 'b'] | <class 'list'> | False | True | True | | ('a', 'b') | <class 'tuple'> | False | True | True | | {'b', 'a'} | <class 'set'> | False | False | True | | {'a': 1, 'b': 2} | <class 'dict'> | False | True | True | """ if hasattr(x, "strip"): return "str" elif hasattr(x, "__getitem__") or hasattr(x, "__iter__"): return "list_like" else: return "others"
def stripColours(msg): """Strip colours (and other formatting) from the given string""" while chr(3) in msg: color_pos = msg.index(chr(3)) strip_length = 1 color_f = 0 color_b = 0 comma = False for i in range(color_pos + 1, len(msg) if len(msg) < color_pos + 6 else color_pos + 6): if msg[i] == ",": if comma or color_f == 0: break else: comma = True elif msg[i].isdigit(): if color_b == 2 or (not comma and color_f == 2): break elif comma: color_b += 1 else: color_f += 1 else: break strip_length += 1 msg = msg[:color_pos] + msg[color_pos + strip_length:] # bold, italic, underline, plain, reverse msg = msg.replace(chr(2), "").replace(chr(29), "").replace(chr(31), "").replace(chr(15), "").replace(chr(22), "") return msg
def get_next_page(resp_json): """Description.""" if "navigationLinks" in resp_json: if "next" in resp_json["navigationLinks"][0]["ref"]: return resp_json["navigationLinks"][0]["href"] else: if len(resp_json["navigationLinks"]) == 2: if "next" in resp_json["navigationLinks"][1]["ref"]: return resp_json["navigationLinks"][1]["href"] return False
def extract_keywords(lst_dict, kw): """Extract the value associated to a specific keyword in a list of dictionaries. Returns the list of values extracted from the keywords. Parameters ---------- lst_dict : python list of dictionaries list to extract keywords from kw : string keyword to extract from dictionary """ lst = [di[kw] for di in lst_dict] return lst
def prompt_dependent(independent: str) -> str: """Prompt the user for the dependent variable to use for calculation >>> prompt_dependent('Annual CO2 emissions of Brazil') 'Amazon Precipitation' >>> prompt_dependent('Estimated Natural Forest Cover') Would you like to calculate for CO2 or precipitation >? co2 Please enter 'CO2' or 'precipitation' >? CO2 'Annual CO2 emissions of Brazil' """ if independent == 'Estimated Natural Forest Cover': dependent = input('Would you like to calculate for CO2 or precipitation') while dependent not in {'precipitation', 'CO2'}: dependent = input('Please enter \'CO2\' or \'precipitation\'') if dependent == 'CO2': return 'Annual CO2 emissions of Brazil' return 'Amazon Precipitation'
def is_prima_facie(c_and_e, c_true, e_true, events): """ Determines whether c is a prima facie cause of e. Parameters: c_and_e: number of times both events were true in a time window c_true: number of times the cause was true in a time window e_true: number of times the effect was true in a window events: the total number of events Returns: boolean """ if c_true == 0: return(False) result = c_and_e / c_true > e_true / events return(result)
def _is_int(v): """int testing""" return isinstance(v, int)
def get_intersection_point_yaxis(y): """ Get the intersection point between a line and x axis """ if str(y) == '-0.0': y = 0.0 if 0.0 <= y <= 1.0: return (0.0, y) return None
def check_rms_edf(task_list): """Parse the YAML for the required field for RMS and EDF algorithms. .. literalinclude:: ../../wikipedia.yaml :language: yaml :linenos: :param task_list: List of task descriptors, as in the example above. :type task_list: List of dictionaries. :return: True for success, False otherwise. :rtype: bool """ ############## # validate the input format first. some fields are expected for rms ############## # must have at least 2 tasks if len(task_list) <= 1: print ("ERROR: the task list must have more than 1 task. Found", len(task_list)) return False # check if all tasks have the mandatory fields print ('checking the task list ... ', end='') for task in task_list: if 'name' not in task: print ("\nERROR: field 'name' not found in task") return False if 'exec_time' not in task: print ("\nERROR: field 'exec_time' not found in task") return False if 'period' not in task: print ("\nERROR: field 'period' not found in task") return False if 'deadline' not in task: print ("\nERROR: field 'deadline' not found in task") return False # each task must have a name (str), exec_time (N), deadline (N), period (N) for task in task_list: if type(task['name']) is not str: print ("\nERROR: string expected in the 'name' field. Got",type(task['name'])) return False if type(task['exec_time']) is not int: print ("\nERROR: int expected in the 'exec_time' field. Got",type(task['exec_time'])) return False if task['exec_time'] <= 0: print ("\nERROR: 'exec_time' field must be a positive integer. Got",task['exec_time']) return False if type(task['period']) is not int: print ("\nERROR: int expected in the 'period' field. Got",type(task['period'])) return False if task['period'] <= 0: print ("\nERROR: 'period' field must be a positive integer. Got",task['period']) return False if type(task['deadline']) is not int: print ("\nERROR: int expected in the 'deadline' field. Got",type(task['deadline'])) return False if task['deadline'] <= 0: print ("\nERROR: 'deadline' field must be a positive integer. Got",task['deadline']) return False print ('passed !') return True
def concat_to_address(ip, port): """ ip: str for address to concat, like "127.0.0.1" port: str for port, like "2379" return: str like "127.0.0.1:2379" return None if ip or port is None """ if ip is None or port is None: return None return ip.strip() + ":" + port.strip()
def counting_sort(num_arr, cur, base): """ Modified counting sort :param num_arr: array of Number-s :param cur: current index of numeral :param base: base of radix sort :return: sorted array of Number-s """ count_arr = [0 for _ in range(base + 1)] res = [None] * len(num_arr) for el in num_arr: count_arr[el[cur]] += 1 for i in range(1, base + 1): count_arr[i] += count_arr[i - 1] for i in range(len(num_arr) - 1, -1, -1): res[count_arr[num_arr[i][cur]] - 1] = num_arr[i] count_arr[num_arr[i][cur]] -= 1 return res
def list_to_string(inlist, endsep="and", addquote=False): """ This pretty-formats a list as string output, adding an optional alternative separator to the second to last entry. If `addquote` is `True`, the outgoing strings will be surrounded by quotes. Args: inlist (list): The list to print. endsep (str, optional): If set, the last item separator will be replaced with this value. addquote (bool, optional): This will surround all outgoing values with double quotes. Returns: liststr (str): The list represented as a string. Examples: ```python # no endsep: [1,2,3] -> '1, 2, 3' # with endsep=='and': [1,2,3] -> '1, 2 and 3' # with addquote and endsep [1,2,3] -> '"1", "2" and "3"' ``` """ if not endsep: endsep = "," else: endsep = " " + endsep if not inlist: return "" if addquote: if len(inlist) == 1: return "\"%s\"" % inlist[0] return ", ".join("\"%s\"" % v for v in inlist[:-1]) + "%s %s" % (endsep, "\"%s\"" % inlist[-1]) else: if len(inlist) == 1: return str(inlist[0]) return ", ".join(str(v) for v in inlist[:-1]) + "%s %s" % (endsep, inlist[-1])
def preprocess_call_name(name): """ map an event name to a preprocess call name """ return 'preprocess_{}'.format(name)
def tokendict_to_list(input_dict): """ converts dict (loaded jason) in message format to lists in message format """ # outs each sentence str in body in a temp list message_list = [] body_list = [] for item in input_dict['body']: body_list.append(input_dict['body'][item]) # splits at ' ' each word in each sentence, keeping sentences # in their own lists, and puts it all in another list body_list2 = [] for sent in body_list: sent = sent.split() body_list2.append(sent) # apends each string and the body list to the empty message_list for item in input_dict: if item != 'body': message_list.append(input_dict[item]) else: message_list.append(body_list2) return message_list
def to_float(s): """Convert a column to floats usage: new_var = data.apply(lambda f : to_int(f['COLNAME']) , axis = 1) """ try: s1 = float(s) return s1 except ValueError: return s
def make_link_list(linklist): """Turn linklist into string.""" l = "" for u in linklist: l = l + " " + u # check size isn't bigger than 255 o = l[1:len(l)] if len(o) > 255: o = o[:254] return o
def log_level_int(log_level): """ This function returns the integer log level from a string. Used for compatibility across HELICS and FNCS Inputs log_level - Log level string Outputs log level integer """ logLevels = {'ERROR': 0,'WARNING': 1,'INFO': 2,'DEBUG': 3,'DEBUG1': 4, 'DEBUG2': 5,'DEBUG3': 6,'DEBUG4': 7} if log_level in logLevels: return logLevels[log_level] else: print("WARNING: unknown log level specified") return 2
def counter(i=0, f=10, p=1): """ :param i: Beggining of the counter :param f: End of the counter :param p: Distance between consecutive numbers in the sequece :return: List with the entire sequence """ p = abs(p) if p == 0: p = 1 if f < i: p = p * -1 contagem = [] while True: contagem += [i] i += p if i >= f and p > 0: break elif i <= f and p < 0: break return contagem
def extract(a,b): """Find common string in two separate strings""" m = min(len(a),len(b)) for i in range(m): if a[i] != b[i]: return a[:i] return a[:m]
def _removeDuplicatesOneLevel(aList): """ Remove first level duplicates. """ result = [] if aList == []: return if type(aList) != type([]): return aList for elem in aList: if elem not in result: result.append(elem) return result
def add_intstr(istr): """Takes a positive number as a string, returns the integer sum of its digits. """ sum = 0 for i in istr: sum += int(i) return sum
def product(A): """ Return the accumulated product of an array. """ def prod(a, b): n = b - a if n < 24: p = 1 for k in range(a, b + 1): p *= A[k] return p m = (a + b) // 2 return prod(a, m) * prod(m + 1, b) return prod(0, len(A) - 1)
def zero2none(v): """Zero -> None.""" if v == 0: return None return v
def _dot(fqdn): """ Append a dot to a fully qualified domain name. DNS and Designate expect FQDNs to end with a dot, but human's conventionally don't do that. """ return '{0}.'.format(fqdn)
def starlist_line(tokens): """Starlist token lines.""" return "".join(tokens)
def report(config_id=1, name='mock', state='Completed', start='/Date(1351118760000)/', end='/Date(1351118760001)/', duration='00:00:00', errors=None, outcome='OK', diagnostics='OK'): """Base mock report.""" return { 'BackupConfigurationId': config_id, 'BackupConfigurationName': name, 'State': state, 'StartTime': start, 'CompletedTime': end, 'Duration': duration, 'NumErrors': len(errors) if errors else 0, 'ErrorList': errors, 'Reason': outcome, 'Diagnostics': diagnostics }
def format_bytes(input_bytes, precision=2): """ Format an integer number of input_bytes to a human readable string. If input_bytes is negative, this method raises ArithmeticError """ import math if input_bytes < 0: raise ArithmeticError("Only Positive Integers Allowed") if input_bytes != 0: exponent = math.floor(math.log(input_bytes, 1024)) else: exponent = 0 return "%.*f%s" % ( precision, input_bytes / (1024 ** exponent), ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][int(exponent)] )
def decode_bs_word(word: int): """ decode word in the bistream file :param word: word :return: meaning """ # 001 xx RRRRRRRRRxxxxx RR xxxxxxxxxxx # 111 # 000 11 # 000 00 11111111111111 0 # 000 00 00000000000000 11 00000000000 # 000 00 00000000000000 00 11111111111 header_type = (0xE000_0000 & word) >> 29 op_code = (0x1800_0000 & word) >> 27 reg_addr = (0x07FF_E000 & word) >> 13 wc_pt1 = (0x3FF & word) wc_pt2 = (0x07FF_FFFF & word) reg_addr_dict = { 0x00: ("CRC", "RW", "CRC Register"), 0x01: ("FAR", "RW", "Frame Address Register"), 0x02: ("FDRI", "W", "Frame Data Register, Input Register (write configuration data)"), 0x03: ("FDRO", "R", "Frame Data Register, Output Register (read configuration data)"), 0x04: ("CMD", "RW", "Command Register"), 0x05: ("CTL0", "RW", "Control Register 0"), 0x06: ("MASK", "RW", "Masking Register for CTL0 and CTL1"), 0x07: ("STAT", "R", "Status Register"), 0x08: ("LOUT", "W", "Legacy Output Register for daisy chain"), 0x09: ("COR0", "RW", "Configuration Option Register 0"), 0x0A: ("MFWR", "W", "Multiple Frame Write Register"), 0x0B: ("CBC", "W", "Initial CBC Value Register"), 0x0C: ("IDCODE", "RW", "Device ID Register"), 0x0D: ("AXSS", "RW", "User Access Register"), 0x0E: ("COR1", "RW", "Configuration Option Register 1"), 0x10: ("WBSTAR", "RW", "Warm Boot Start Address Register"), 0x11: ("TIMER", "RW", "Watchdog Timer Register"), 0x13: ("CRC?", "RW", "CRC Register??"), 0x16: ("BOOTSTS", "R", "Boot History Status Register "), 0x18: ("CTL1", "RW", "Control Register 1"), 0x1F: ("BSPI", "RW", "BPI/SPI Configuration Options Register") } if header_type == 0x1: header_type_str = "PT1" if op_code == 0x0: op_code_str = "NOP" elif op_code == 0x1: op_code_str = "R" elif op_code == 0x2: op_code_str = "W" else: op_code_str = "--" if reg_addr in reg_addr_dict.keys(): reg = reg_addr_dict[reg_addr] else: reg = None wc = wc_pt1 return {'header_type':header_type_str, 'op_code': op_code_str, 'reg': reg, 'wc': wc } elif header_type == 0x2: header_type_str = "PT2" wc = wc_pt2 return {'header_type':header_type_str, 'wc': wc } else: header_type_str = "--" return {'header_type':header_type_str }
def merge(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def str_set_of_candidates(candset, cand_names=None): """ Nicely format a set of candidates. .. doctest:: >>> print(str_set_of_candidates({0, 1, 3, 2})) {0, 1, 2, 3} >>> print(str_set_of_candidates({0, 3, 1}, cand_names="abcde")) {a, b, d} Parameters ---------- candset : iterable of int An iteratble of candidates. cand_names : list of str or str, optional List of symbolic names for every candidate. Returns ------- str """ if cand_names is None: named = sorted(str(cand) for cand in candset) else: named = sorted(str(cand_names[cand]) for cand in candset) return "{" + ", ".join(named) + "}"
def ranges(nums): """ input : a set of numbers (floats or ints) output : list of tuples, one tuple for each string of consecutively increasing numbers in nums each tuple contains two numbers: the first and last values from each consecutively incresing string """ nums = sorted(set(nums)) gaps = [[s, e] for s, e in zip(nums, nums[1:]) if s+1 < e] edges = iter(nums[:1] + sum(gaps, []) + nums[-1:]) return list(zip(edges, edges))
def class_indices(classes_arr): """Returns a dict with classes mapped to indices""" size = len(classes_arr) return {classes_arr[i]: i for i in range(size)}
def getVec3(default_value, init_value = [0.0, 0.0, 0.0]): """ Return vec3 with a given default/fallback value. """ return_value = init_value.copy() if default_value is None or len(default_value) < 3: return return_value index = 0 for number in default_value: return_value[index] = number index += 1 if index == 3: return return_value return return_value
def linear_conv(value, old_min, old_max, new_min, new_max): """ A simple linear conversion of one value from one scale to another Returns: Value in the new scale """ return ((value - old_min) / (old_max - old_min)) * ((new_max - new_min) + new_min)
def _quote(expr: str) -> str: """Quote a string, if not already quoted.""" if expr.startswith("'") and expr.endswith("'"): return expr return f"'{expr}'"
def parse_links(s): """ Parse URLs from Link header >>> links = parse_links( ... '<https://api.github.com/repos?page=2>; rel="next", ' ... '<https://api.github.com/repos?page=5>; rel="last"') >>> list(links.keys()) ['next', 'last'] >>> links['next'] 'https://api.github.com/repos?page=2' >>> links['last'] 'https://api.github.com/repos?page=5' """ links = {} for link in s.split(","): url, rel = link.strip().split(";") url = url.strip(" <>") rel = rel.strip().replace("rel=", "").strip('"') links[rel] = url return links
def decode_ber(ber): """ Decodes an array of bytes to an integer value If the first byte in the BER length field does not have the high bit set (0x80), then that single byte represents an integer between 0 and 127 and indicates the number of Value bytes that immediately follows. If the high bit is set, then the lower seven bits indicate how many bytes follow that make up a length field """ length = ber[0] bytes_read = 1 if length > 127: bytes_read += length & 127 # Strip off the high bit length = 0 for i in range(1, bytes_read): length += ber[i] << (8 * (bytes_read - i - 1)) return length, bytes_read
def localisation_formatting(localisation): """ This function takes a localisation and format it to be used with google API. param: company localisation return: formatted company localisation """ localisation = localisation.replace(' ', '+') return localisation
def bitwise_dot(x, y): """Compute the dot product of two integers bitwise.""" def bit_parity(i): n = bin(i).count("1") return int(n % 2) return bit_parity(x & y)
def parse_single_assignment(assignment): """ Parse the useful information from a single assignment. :param assignment: All information of a single assignment. :type assignment: dict(str, str) :return: The id, due_date and name of an assignment. :rtype: tuple(int, int, str) """ assignment_id = assignment['cmid'] name = assignment['name'] due_date = assignment['duedate'] return assignment_id, due_date, name
def midpoint(pair1, pair2): """find and return the midpoint between the two given points""" x = (pair1[0] + pair2[0])/2 y = (pair1[1] + pair2[1])/2 return x, y
def escapeBelString(belstring): """Escape double quotes in BEL string""" return belstring.replace('"', '\\"')
def sizeof_fmt(num, suffix='B'): """ Returns human-readable version of file size Source: https://stackoverflow.com/a/1094933 """ for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def find_average_score(generation): """ Generation is a dictionary with the subjects and score. Returns the average score of that generation """ sum = 0 for score in generation.values(): sum += score return sum/len(generation.values())
def contains(query, include, exclude=None): """ Is anything from `include` in `query` that doesn't include anything from `exclude` `query` can be any iterator that is not a generator """ if isinstance(include, str): include = [include] condition_A = any(x in query for x in include) if exclude is not None: if type(exclude) == str: exclude = [exclude] condition_B = all(x not in query for x in exclude) return all([condition_A, condition_B]) else: return condition_A
def descendants(cls: type) -> list: """ Return a list of all descendant classes of a class Arguments: cls (type): Class from which to identify descendants Returns: subclasses (list): List of all descendant classes """ subclasses = cls.__subclasses__() for subclass in subclasses: subclasses.extend(descendants(subclass)) return(subclasses)
def validate_office_types(office_type): """ Method to validate office types :params: office type :response: boolean """ office_types = ["local","federal","state", "legistlative"] if office_type not in office_types: return False return True
def transpose_table(table): """Transpose the table for further adaptation""" new_table = [] for row in table: for i, value in enumerate(row): if i != 0: new_row = [row[0], i, value] new_table.append(new_row) return new_table
def normalize_unique_together(unique_together): """ unique_together can be either a tuple of tuples, or a single tuple of two strings. Normalize it to a tuple of tuples, so that calling code can uniformly expect that. """ if unique_together and not isinstance(unique_together[0], (tuple, list)): unique_together = (unique_together,) return unique_together
def parenthesise(s, parens = True): """ Put parentheses around a string if requested. """ if parens: return '(%s)' % s else: return s
def jinja2_targetpage(env, target): """Returns the page basename (without ".html") of a link target. E.g. "authors.html#Shakespeare" yields "authors" """ return (target.split("#")[0]).split(".")[0]
def check_element_equal(lst): """ Check that all elements in an iterable are the same. :params lst: iterable object to be checked :type lst: np.array, list, tuple :return: result of element equality check :rtype: bool """ return lst[1:] == lst[:-1]
def cleanup_wiki_string(line): """Helper for :meth:`_cleanup_wikisaurus` Args: line (str): line to be cleaned up from wiki markup Returns: (str): cleaned up string """ line = line.strip("=") line = line.lower() if line: if not "beginlist" in line and not "endlist" in line: line = line.replace("ws|", "") # {{ws|pedestrianize}} {{qualifier|dated}} cases if line.count("{{") > 1: line = line.split("{{")[1] line = line.strip() if "|" in line: line = line.split("|")[0] line = line.replace("}", "") line = line.replace("{", "") # still sometimes get things like ws ---- if line.startswith("ws"): # will give False if there aren't any letters if line[2:].isupper() or line[2:].islower(): pass return line
def get_mac_a(output: bytes) -> bytes: """Support function to get the 64-bit network authentication code (MAC-A) from OUT1, the output of 3GPP f1 function. :param output: OUT1 :returns: OUT1[0] .. OUT1[63] """ edge = 8 # = ceil(63/8) return output[:edge]
def numbers_to_strings(argument): """allocator mode num to str.""" switcher = { 0: "direct", 1: "cycle", 2: "unified", 3: "je_direct", 4: "je_cycle", 5: "je_unified", } return switcher.get(argument, "cycle")
def int_hex(data_in, mode=0): """ converts list elements from int to hex and back mode : int to hex (0) , hex to int (1) """ data_out = [] if mode == 0: for i in range(len(data_in)): data_out.append(format(data_in[i], '02x')) return data_out for i in range(len(data_in)): data_out.append(int(data_in[i], 16)) return data_out
def time_in_range(start, end, x_time): """ See if a time falls within range """ if start <= end: return start <= x_time <= end return end <= x_time <= start
def round_filters(filters, width_coefficient, depth_divisor=8): """Round number of filters based on depth multiplier.""" min_depth = depth_divisor filters *= width_coefficient new_filters = max(min_depth, int(filters + depth_divisor / 2) // depth_divisor * depth_divisor) # Make sure that round down does not go down by more than 10%. if new_filters < 0.9 * filters: new_filters += depth_divisor return int(new_filters)
def is_permutation(a: str, b: str) -> bool: """Check if a is a permutation of b Args: a: a string b: another string Returns: True if a is a permutation of b, False otherwise """ counter = {} for char in a: counter[char] = counter.get(char, 0) + 1 for char in b: counter[char] = counter.get(char, 0) - 1 return all(value == 0 for value in counter.values())
def LineColour(argument): """Dictionary for switching line colours where appropriate""" switcher = { 'Black': 'k', 'Red': 'r', 'Green': 'g', 'Blue': 'b' } return switcher.get(argument, argument)
def _parse_wamd_gps(gpsfirst): """WAMD "GPS First" waypoints are in one of these two formats: SM3, SM4, (the correct format): WGS..., LAT, N|S, LON, E|W [, alt...] EMTouch: WGS..., [-]LAT, [-]LON[,alt...] Produces (lat, lon, altitude) float tuple. """ if not gpsfirst: return None if isinstance(gpsfirst, bytes): gpsfirst = gpsfirst.decode('utf-8') vals = tuple(val.strip() for val in gpsfirst.split(',')) datum, vals = vals[0], vals[1:] if vals[1] in ('N', 'S'): # Standard format lat, lon = float(vals[0]), float(vals[2]) if vals[1] == 'S': lat *= -1 if vals[3] == 'W': lon *= -1 alt = int(round(float(vals[4]))) if len(vals) > 4 else None else: # EMTouch format lat, lon = float(vals[0]), float(vals[1]) alt = int(round(float(vals[2]))) if len(vals) > 2 else None return lat, lon, alt
def result_table_to_string(table): """Converts a resulting SQL table to a human-readable string.""" string_val = ( "\t" + "\n\t".join([str(row) for row in table[: min(len(table), 5)]]) + "\n" ) if len(table) > 5: string_val += "... and %d more rows.\n" % (len(table) - 5) return string_val
def teardown(message): """Finalize the processing pipeline and return the errors list. """ et, err_list = message return err_list
def cat_id_to_real_id(catId): """ Note coco has 80 classes, but the catId ranges from 1 to 90! Args: realId: id in coco datasets. Returns: id for our training set. """ cat_id_to_real_id = \ {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 13: 12, 14: 13, 15: 14, 16: 15, 17: 16, 18: 17, 19: 18, 20: 19, 21: 20, 22: 21, 23: 22, 24: 23, 25: 24, 27: 25, 28: 26, 31: 27, 32: 28, 33: 29, 34: 30, 35: 31, 36: 32, 37: 33, 38: 34, 39: 35, 40: 36, 41: 37, 42: 38, 43: 39, 44: 40, 46: 41, 47: 42, 48: 43, 49: 44, 50: 45, 51: 46, 52: 47, 53: 48, 54: 49, 55: 50, 56: 51, 57: 52, 58: 53, 59: 54, 60: 55, 61: 56, 62: 57, 63: 58, 64: 59, 65: 60, 67: 61, 70: 62, 72: 63, 73: 64, 74: 65, 75: 66, 76: 67, 77: 68, 78: 69, 79: 70, 80: 71, 81: 72, 82: 73, 84: 74, 85: 75, 86: 76, 87: 77, 88: 78, 89: 79, 90: 80} return cat_id_to_real_id[catId]
def _pkornone(account): """ Devuelve clave primaria de un objeto Account. Si account es None, devuelve None """ if account is None: return None return account.pk
def fis_trimf(x:float, a:float, b:float, c:float): """Triangular Member Function""" t1 = (x - a) / (b - a) t2 = (c - x) / (c - b) if (a == b) and (b == c): return float(x == a) if (a == b): return (t2 * float(b <= x) * float(x <= c)) if (b == c): return (t1 * float(a <= x) * float(x <= b)) return max(min(t1, t2), 0)
def keyword(text): """ Formats keywords by -lowercasing all letters -replacing ' ' with '_' -replacing '-' with '_' """ text = str(text).lower() text = text.replace("-", " ") return text
def parse_name(ldap_entry): """Return the user's first and last name as a 2-tuple. This is messy because there's apparently no canonical field to pull the user's first and last name from and also because the user's surname field (for example) may contain a title at the end (like "Bob Smith, Assistant Professor"). """ first_name = ldap_entry.get( 'givenName', ldap_entry.get('preferredcn', ldap_entry.get('cn', ['']))) first_name = first_name[0].split(' ')[0] if 'sn' in ldap_entry: last_name = ldap_entry['sn'][0].split(',', 1)[0] else: last_name = ldap_entry.get('preferredcn', ldap_entry.get('cn', [''])) last_name = last_name[0].split(',', 1)[0].split(' ')[-1] return first_name, last_name
def hex_to_rgb(hex): """ Returns RGB values for a hex color string. """ hex = hex.lstrip("#") if len(hex) < 6: hex += hex[-1] * (6-len(hex)) r, g, b = hex[0:2], hex[2:4], hex[4:] r, g, b = [int(n, 16)/255.0 for n in (r, g, b)] return r, g, b
def setValue(size=0, value=0.0): """ Return a python list with every value initialised to value. """ lst = [] i = 0 while i < size: lst.append(value) i += 1 return lst
def validate_num(n): """Attempt to typecast n as an integer.""" try: n = int(n) except: print('Error validating number. Please only use positive integers.') return 0 else: return n
def geterr(obj): """ Returns false if there are no errors in a network response, else a tuple of (code integer, description string) """ error = obj.get("error") if not error: return False return (error["code"], error["description"])
def _is_mgmt_url(path): """ small helper to test if URL is for management API. """ return path.startswith("/mgmt/")
def bracket(a, f, s=0.001, m=2): """ Finds an interval [a,b] where the function f is unimodal Args: a: Starting point f: Objective function s: Initial step size m: scaling factor for the step size Returns: A list with the lower and upper bounds of the interval in wich f is supposedly unimodal """ bracket = [a] b = a + s bracket = [a, b] fa = f(a) fb = f(b) if fa >= fb: c = b + s fc = f(c) while fc < fb: b = c fb = fc s = s*m c = c + s fc = f(c) bracket = [a, c] elif fa < fb: c = a - s fc = f(c) while fc < fa: a = c fa = fc s = s*m c = c - s fc = f(c) bracket = [c, b] return bracket
def move_item_to_front(lst, item): """ Move an item to the front of a list. :param lst: the list :type lst: list or tuple :param item: the item, which must be in `lst` :returns: the list, with the item moved to front :rtype: tuple """ lst = list(lst) lst.insert(0, lst.pop(lst.index(item))) return tuple(lst)
def list_diff(l1,l2): """ Return set difference l1\l2. Assumes l1 and l2 are generators of hashable things """ sl2 = set(l2) return [s for s in l1 if s not in sl2]
def switchUser(username, password, event, hideError=False): """Attempts to switch the current user on the fly. If the given username and password fail, this function will return False. If it succeeds, then all currently opened windows are closed, the user is switched, and windows are then re-opened in the states that they were in. If an event object is passed to this function, the parent window of the event object will not be re-opened after a successful user switch. This is to support the common case of having a switch-user screen that you want to disappear after the switch takes place. Args: username (str): The username to try and switch to. password (str): The password to authenticate with. event (object): If specified, the enclosing window for this event's component will be closed in the switch user process. hideError (bool): If True (1), no error will be shown if the switch user function fails. (default: 0) Returns: bool: False(0) if the switch user operation failed, True (1) otherwise. """ print(username, password, event, hideError) return True
def __renumber(dictionary) : """Renumber the values of the dictionary from 0 to n """ count = 0 ret = dictionary.copy() new_values = dict([]) for key in dictionary.keys() : value = dictionary[key] new_value = new_values.get(value, -1) if new_value == -1 : new_values[value] = count new_value = count count = count + 1 ret[key] = new_value return ret
def transposta_matriz(M): """Calcula a transposta de uma matriz.""" lin = len(M[0]) col = len(M) MT = [] for l in range(lin): linha = [] for c in range(col): linha.append(M[c][l]) MT.append(linha) return MT
def from_digit(n): """ 0 <= n < 16 """ return '0123456789ABCDEF'[n]
def list_removeDuplicates(alist): """ Removes duplicates from an input list """ #d = {} #print alist #for x in alist: #d[x] = x #alist = d.values() alist = list(set(alist)) return alist
def createGrid(nx, ny): """ Create a grid position array. """ direction = 0 positions = [] if (nx > 1) or (ny > 1): half_x = int(nx/2) half_y = int(ny/2) for i in range(-half_y, half_y+1): for j in range(-half_x, half_x+1): if not ((i==0) and (j==0)): if ((direction%2)==0): positions.append([j,i]) else: positions.append([-j,i]) direction += 1 return positions
def strip_leading_dashdash(name): """Remove leading ``'--'`` if present.""" if name.startswith('--'): return name[2:] else: return name
def get_mapping(d): """ Reports fields and types of a dictionary recursively :param object: dictionary to search :type object:dict """ mapp=dict() for x in d: if type(d[x])==list: mapp[x]=str(type(d[x][0]).__name__) elif type(d[x])==dict: mapp[x]=get_mapping(d[x]) else: mapp[x]=str(type(d[x]).__name__) return mapp
def filter_bcg_candidate_peaks(bcg_indices, bcg_peak_values, ecg_indices): """ get corrent bcg peaks by choose closest peaks at ecg_indices """ peak_indices = [] peak_values = [] num_bcg_indices = len(bcg_indices) num_ecg_indices = len(ecg_indices) bcg_id = 0 ecg_id = 0 while (ecg_id < num_ecg_indices and bcg_id + 1 < num_bcg_indices): bcg_index = bcg_indices[bcg_id] next_bcg_index = bcg_indices[bcg_id+1] ecg_index = ecg_indices[ecg_id] #next_ecg_index = ecg_indices[ecg_id+1] if abs(bcg_index - ecg_index) < abs(next_bcg_index - ecg_index): peak_indices.append(bcg_index) peak_value = bcg_peak_values[bcg_id] peak_values.append(peak_value) ecg_id += 1 bcg_id += 1 return peak_indices, peak_values
def get_namespace(type_or_context): """ Utility function to extract the namespace from a type (@odata.type) or context (@odata.context) :param type_or_context: the type or context value :type type_or_context: str :return: the namespace """ if '#' in type_or_context: type_or_context = type_or_context.rsplit('#', 1)[1] return type_or_context.rsplit('.', 1)[0]