content
stringlengths
42
6.51k
def setup_config(config): """ This method is called so the config may be modified after it has been populated from the config file + env variables but before the connections/states are created. """ config['optional_1'] = 'optional_value_1' return config
def any_id2key(record_id): """ Creates a (real_id: int, thing: str) pair which allows ordering mixed collections of real and virtual events. The first item of the pair is the event's real id, the second one is either an empty string (for real events) or the datestring (for virtual ones) :param...
def reverse_bit(num): """Turn an LSB byte to an MSB byte, and vice versa. Used for SPI as it is LSB for the PN532, but 99% of SPI implementations are MSB only!""" result = 0 for _ in range(8): result <<= 1 result += (num & 1) num >>= 1 return result
def backslash(dir): """ Add '/' to the end of a path if not already the last character. Adds '/' to end of a path (meant to make formatting of directory path `dir` consistently have the slash). **Parameters** **dir** : string Path to a directory. **Returns** *...
def validateFilename(value): """ Validate filename. """ if 0 == len(value): raise ValueError("Filename for spatial database not specified.") return value
def rotation(r=0): """Set the display rotation Valid values: 0 90 180 270""" global _rotation if r in [0, 90, 180, 270]: _rotation = r return True else: raise ValueError('Rotation must be 0, 90, 180 or 270 degrees')
def messageCollector(collectedMessages, printMessages=False) : """Return a natsListener message collector to collect NATS messages into the `collectedMessages` dict provided. NATS messages stored in an list associated with each distinct message subject. """ if collectedMessages is None : return None ...
def parse_asterisk(sequence, composites): """ parses a string like '*/*' and returns all available variants with '*' being replaced by composite names in 'composites'. """ sequences = [] for k in range(len(sequence)): if sequence[k] == '*': for c in composites: ...
def tokenize(s): """Tokenize a string.""" ret = [] add = False digraph = False for c in s: if c in '[]<>$(){}=@~*': if digraph: ret[-1] += c digraph = False else: ret.append(c) add = False elif c == '...
def calculateFrameTime(speed, ratio): """ Calculates the frame time interval from chopper parameters. Chopper speed in rpm given, but calculations are in Hz. The interval is the time between pulses of chopper 5 because chopper 5 has only 2 slits returns the frame time in s """ speed /=...
def exception_message(x, *args): """ """ x = x.replace('\n', ' ').replace('\t', '') return x.format(*args) if args else x
def interleave(list1, list2): """Convert two lists to a single interleaved list""" if len(list1) != len(list2): raise ValueError("Lists are not the same length") return [val for pair in zip(list1, list2) for val in pair]
def get_fraction(interval,bore_dict): """ calculate the clay fraction for a borehole. :param interval: a tuple (from_depth, to_depth ) :param bore_dict: dictionary {(from_depth, to_depth): lithology_type} :return: clay fraction for a bore hole in a specific interval """ clay_amount = 0 i...
def normalize(bbox): """ Normalise EPSG:4326 bbox order. Returns normalized bbox, and whether it was flipped on horizontal axis. """ flip_h = False bbox = list(bbox) while bbox[0] < -180.0: bbox[0] += 360.0 bbox[2] += 360.0 if bbox[0] > bbox[2]: bbox = (bbox[0], bbox[...
def duplicate(list_a: list): """Problem 14: Duplicate the Elements of a list. Parameters ---------- list_a : list The input list Returns ------- list A list of duplicated elements in order Raises ------ TypeError If the given argument is not of `list` t...
def strip_html(text): """ removes anything enclosed in and including <> """ import re return re.compile(r'<.*?>').sub('', text)
def format_references(section): """Format the "References" section.""" def format_item(item): return ' - **[{0}]** {1}'.format(item[0], item[1].strip()) return '!!! attention "References"\n{0}'.format('\n'.join( map(format_item, section)))
def remove_dup(words): """ remove duplicated words """ words = words.split(" ") prev_word = words[0] sentence = [prev_word] for w_idx in range(1, len(words)): cur_word = words[w_idx] if cur_word == prev_word: continue else: sentence.append(cur...
def firewall_policy_payload(passed_keywords: dict) -> dict: """Create a properly formatted firewall policy payload. Supports create and update operations. Single policy only. { "resources": [ { "clone_id": "string", "description": "string", ...
def check_candidates_against_protected(candidates, protected): """ use sets to check whether there is any common membership """ if bool(set(candidates) & set(protected)): return True else: return False
def prolog_escape(word): """escape Prolog meta characters""" return word.replace("\\","\\\\").replace("'","\\'")
def _slice_extent_axis(ext_min, ext_max, fctr): """Slice an extent into multiple extents along an axis.""" strd = (ext_max - ext_min) / fctr return [(ext_min + i * strd, ext_max - (fctr - i - 1) * strd) for i in range(fctr)]
def search(input, search_term="id", results=None): """Search through an input dictionary and return all the matches corresponding to a search term Parameters ---------- input: Dict The input dictionary. In the context of the Workflow Manager, this will probably be a json.dump of a w...
def td_lambda(rewards, n_step, gamma): """ paper : ... + low variance - high bias """ return list(map( lambda i: sum(map(lambda t_r: t_r[1] * gamma**t_r[0], enumerate(rewards[i:i+n_step]))), range(len(rewards))))
def clean_append(part_1, part_2): """ Safely append 2 parts together, handling None :param part_1: :param part_2: :return: """ if part_1: if part_2: return part_1 + part_2 return part_1 return part_2
def conjugate(p): """ Find the conjugate of a partition. E.g. len(p) = max(conjugate(p)) and vice versa. """ result = [] j = len(p) if j <= 0: return result while True: result.append(j) while len(result) >= p[j-1]: j -= 1 if j == 0: ...
def int_to_little_endian(n, length): """endian_to_little_endian takes an integer and returns the little-endian byte sequence of length""" # use the to_bytes method of n return n.to_bytes(length, "little")
def michaelis_menten_eq(x, a, b): """Michaelis Mentent equation""" return a * x / (b + x)
def way_roy(routing, start, end): """Return the route from the start to the end as a list for the Roy-Warshall algorithm""" route = [] current_node = start while current_node != end: route.append(current_node) current_node = routing[current_node][end] # Follow the routing matrix rou...
def format_cmd(cmd): """Return command in a valid format.""" if isinstance(cmd, str): cmd = [cmd] elif not isinstance(cmd, list): raise ValueError( "Command should be a list or a string and not {}".format(type(cmd)) ) return cmd
def __splitDegreeMinutes__(value): """ Transform DDDMM.MM to DDD, MM.MM """ val = str(value).split('.') val_min = val[0][-2] + val[0][-1] + '.' + val[1] val_deg = '' for i in range(len(val[0])-2): val_deg = val_deg + val[0][i] return int(val_deg), float(val_min)
def num_to_alpha(integ): """takes a numeral value and spits out the corresponding letter.""" translator = { 1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L', 13: 'M', 14: 'N', 15: 'O', 16: 'P', 17: 'Q', 18: 'R', 19:...
def make_get_bits(name, bits, shift): """ return a bool for single bits, signed int otherwise """ signmask = 1 << (bits - 1 + shift) lshift = bits + shift rshift = bits if bits == 1: return "bool(%s & 0x%x)" % (name, signmask) else: return "intmask(%s << (LONG_BIT-%d)) >> (LONG_B...
def normalize_dict(d): """Turn the dictionary values into percentages""" total = sum(d.values()) for k in d: d[k] = d[k] / total return d
def pixelscale_nyquist(wave, f_number): """Compute the output plane sampling which is Nyquist sampled for intensity. Parameters ---------- wave : float Wavelength in meters f_number : float Optical system F/# Returns ------- float Sampling in meters ""...
def _is_subrange(rng1, rng2): """Return True iff rng1 is wholly inside rng2""" # Nonpolymers should have an empty range if rng1 == (None, None) or rng2 == (None, None): return rng1 == rng2 else: return rng1[0] >= rng2[0] and rng1[1] <= rng2[1]
def collinear(coordinates): """ Passing thru one pt with some fixed slope \implies must exist only one such line Rmk. If we are to use slope, we must deal separately with one particular case: Vertical line. """ def slope(A, B, epsilon=1e-10): denominator = A[0] - B[0] numera...
def date_grouppings(date_read): """Extract date grouppings for given date.""" if date_read: year = date_read.year month = date_read.date().replace(day=1) else: year = None month = None return year, month
def _denormalize_mac(mac): """Takes a normalized mac address (all lowercase hex, no separators) and converts it to the TpLink format. Example:: _denormalize_mac('abcdef123456') == 'ab-cd-ef-12-34-56' """ return '-'.join((mac[i] + mac[i+1] for i in range(0, 12, 2)))
def dmp_zero(u): """ Return a multivariate zero. Examples ======== >>> from sympy.polys.densebasic import dmp_zero >>> dmp_zero(4) [[[[[]]]]] """ r = [] for i in range(u): r = [r] return r
def _latex_float(f, format=".3g"): """ http://stackoverflow.com/a/13490601 """ float_str = "{{0:{0}}}".format(format).format(f) if "e" in float_str: base, exponent = float_str.split("e") return r"{0}\times 10^{{{1}}}".format(base, int(exponent)) else: return float_str
def index_map(i, d): """ The index map used mapping the from 2D index to 1D index Parameters ---------- i : int, np.array the index in the 2D case. d : int the dimension to use for the 2D index. Returns ------- int, np.array 1D index. """ return 2 *...
def gini(sub_set): """Calculate the gini impurity.""" sub_set_len = len(sub_set) good = 0 for set_row in sub_set: if set_row[-1] > 6: good = good + 1 gini_impurity = 1 - (good / sub_set_len) ** 2 - ((sub_set_len - good) / sub_set_len) ** 2 return gini_impurity
def _mergeDiceDicts(d1, d2): """ A helper method, generally to be used with the "diceDict" method defined elsewhere. """ assert isinstance(d1, dict) and isinstance(d2, dict), "Invalid argument to mergeDiceDicts!" if len(d1) == 0: return d2 if len(d2) == 0: return d1 new...
def escape_apply_kwargs(val): """Replace {} as {{}} so that val is preserved after _apply_kwargs.""" return val.replace('{', "{{").replace('}', "}}")
def render_field(field): """ Use this need tag to get more control over the layout of your forms {% raw %}{% render_field form.my_field %} {% endraw %} """ return {'field': field}
def fuseinterval(intervals, dist): """ Check if two intervals are adjacent if they are fuse it and return only one interval Args: intervals a list of intervals Return a list of intervals """ # if we have only one interval return it if len(intervals) == 1: return intervals ...
def doppler_shift(frequency, relativeVelocity): """ DESCRIPTION: This function calculates the doppler shift of a given frequency when actual frequency and the relative velocity is passed. The function for the doppler shift is f' = f - f*(v/c). INPUTS: frequency (float) ...
def version_id_kw(version_id): """Helper to make versionId kwargs. Not all boto3 methods accept a None / empty versionId so dictionary expansion solves that problem. """ if version_id: return {"VersionId": version_id} else: return {}
def make_desc_dict(ecfp): """ Format tuple of fingerprint information into dictionary :param ecfp: Tuple of fingerprint features and values :return: dictionary of fingerprint features and values """ ecfp_feat, ecfp_val = zip(*ecfp) return ecfp_feat, ecfp_val
def get_url(path, scheme="http"): """ Return the full InfoQ URL """ return scheme + "://www.infoq.com" + path
def make_patch_instructions(source_list: dict, target_list: dict): """ possible combinations file in both and same ignore file in both and different copy file only in target delete file only in source copy """ files_source = set(source_list) fi...
def remove_duplicates(values): """ remove duplicate value in a list :param values: input list :return: no duplicate entry list """ output = [] seen = set() for value in values: # If value has not been encountered yet, # ... add it to both list and set. if value no...
def exif_image_needs_rotation(exif_tags): """ Returns True if EXIF orientation requires rotation """ return 'Image Orientation' in exif_tags \ and exif_tags['Image Orientation'].values[0] != 1
def tablefy_users(users): """ Build matrix that can be printed as table along with headers and urls Mimics the tablefy utility for the user model. Hard to use the other tablefy utility since we did not subclass user model """ headers = [] matrix = [] urls = [] if not users: ...
def string_is_int(string): """ Returns true if a string can be cast to an int returns false otherwise """ try: int(string) return True except ValueError: return False
def logged_dict_update(log_func, left, right): """Update a dict with any changes tracked via `log_func`.""" for k, v in right.items(): if k in left and left[k] != v: log_func( f"entry changed" f" {k} {left[k]} -> {v}") left[k] = v return le...
def name_to_components(name, factor=1, delimiter="_") -> dict: """Converts composition string to dictionary example: "MA_Pb0.5_Sn0.5_I3" -> {"MA":1, "Pb":0.5, "Sn":0.5, "I":3} Args: name (str): delimited string of composition factor (int, optional): factor by which to scale all componen...
def getChange(current, previous): """Get the Percentage Change. Parameters: current (int): Current value previous (int): Previous value Returns: int: Percentage Change """ if current == previous: return 0 try: return ((current - previous) / previous) * 100.0 e...
def quantize(x: int, q: int) -> int: """ Will quantize a continuous or discrete range into steps of q where anything between 0 and q will be clipped to q. """ return q * (x // q) if not 0 < x <= q else q
def get_percentage(position: int, length: int) -> str: """Format completion percentage in square brackets.""" percentage_message = f"{position * 100 // length}%".rjust(4) return f"[{percentage_message}]"
def split(n): """ Split string or Array >>> split("hello") ['he', 'llo'] >>> split([1,2,3,1,2,4]) [[1, 2, 3], [1, 2, 4]] """ return [ n[:len(n)//2:], n[len(n)//2::] ]
def kelvin(value): """ Convert Celsius to Kelvin """ return round(value + 273.15, 1)
def _between(input, values): """Checks if the given input is between the first two values in the list :param input: The input to check :type input: int/float :param values: The values to check :type values: :func:`list` :returns: True if the condition check passes, False otherwise :rtype: b...
def _gutenberg_simple_parse(raw_content): """Clean a project Gunteberg file content.""" content = raw_content # *** START OF THIS PROJECT GUTENBERG EBOOK THE RED BADGE OF COURAGE *** starts = [ '*** START OF THIS PROJECT GUTENBERG EBOOK', '***START OF THE PROJECT GUTENBERG EBOOK', '*** START O...
def shift_rows(state): """ Section 5.1.2: ShiftRows() Transformation !!! FUN FACT ALERT !!! Rotating a row by one position to the left is equivalent to polynomial multiplication by {01}x^3 + {00}x^2 + {00}x^1 + {00}x^0, modulo x^4 + 1 >>> shift_rows(b"ABCDefghIJKLmnop") bytearray(b'AfKpeJoDInChmBgL')...
def sex2int(x): """ Converti sesso""" try: return int(x=='male') except: return -1
def __f_get_dictionary_file( home_profile_path ): """ Get the file path of the 3 stored statistic information dictionaries """ return home_profile_path + '/stat_info_ref.json', \ home_profile_path + '/stat_info_home.json', \ home_profile_path + '/stat_info_start.json'
def parse(input): """Simplified to return list of lists of ints""" return [[int(val) for val in row] for row in input]
def abs(x): """ Assuems x is an int Returns x if x>= 0 and -x otherwise """ if x < -1: return -x else: return x
def nth_triangle_number(n): """ Compute the nth triangle number """ return n * (n + 1) // 2
def get_task_and_ann_id(ex): """ single string for task_id and annotation repeat idx """ return "%s_%s" % (ex["task_id"], str(ex["repeat_idx"]))
def handle_most_used_outputs(most_used_x): """ :param most_used_x: Element or list (e.g. from SQL-query output) which should only be one element :return: most_used_x if it's not a list. The first element of most_used_x after being sorted if it's a list. None if that list is empty. """ if isinsta...
def order(lst): """ Returns a new list with the original's data, sorted smallest to largest. """ ordered = [] while len(lst) != 0: smallest = lst[0] for i in range(len(lst)): if lst[i] < smallest: smallest = lst[i] ordered.append(smallest) ...
def conjugatePartition(p): """ Find the conjugate of a partition. E.g. len(p) = max(conjugate(p)) and vice versa. D. Eppstein, August 2005. """ p = sorted(filter(lambda x: x > 0, p), reverse=True) result = [] j = len(p) if j <= 0: return result while True: result...
def ten(hour_or_deg, minute=0.0, second=0.0): """ Converts a sexagesimal number to decimal IDL version can process string, but not in this version If h/d, m, and s are all scalar, the result is scalar, else an ndarray ** For negative value, h/d, m, and s MUST all be negative ** :param hour_or_de...
def percent_conv(val): """Convert an actual percentage (0.0-1.0) to 0-100 scale.""" if val is None: return None return round(val * 100.0, 1)
def taxe(solde, pourcentage): """Affiche la somme de la taxe en fonction du pourcentage """ taxe = dict() taxe["taxe"] = solde * pourcentage taxe["new solde"] = solde - taxe["taxe"] return taxe
def int_or_float(s): """ Modbus can't handle decimals, so we multiply any float by 10. :param s: string representation of a numeric value. :return: int """ try: return int(s) except ValueError: # if we have a float, # protocol requires multiply by 10 and cast to int ...
def line_intersection(line1, line2): """ get intersection of two lines :param line1: x1, y1 :param line2: x2, y2 :return: x, y of the intersection """ # https://stackoverflow.com/questions/20677795/how-do-i-compute-the-intersection-point-of-two-lines/20679579 xdiff = (line1[0][0] - line...
def get_errno(e): """ Return the errno of an exception, or the first argument if errno is not available. :param e: the exception object """ try: return e.errno except AttributeError: return e.args[0]
def one_obj_or_list(seq): """If there is one object in list - return object, otherwise return list""" if len(seq) == 1: return seq[0] return seq
def if_(*args): """Implements the 'if' operator with support for multiple elseif-s.""" for i in range(0, len(args) - 1, 2): if args[i]: return args[i + 1] if len(args) % 2: return args[-1] else: return None
def pyintbitcount(a): """Return number of set bits (1s) in a Python integer. >>> pyintbitcount(0b0011101) 4""" cnt = 0 while a: a &= a - 1 cnt += 1 return cnt
def checksum(number): """Calculate the checksum over the number. A valid number should have a checksum of 0.""" return (sum((9 - i) * int(n) for i, n in enumerate(number[:-1])) - int(number[-1])) % 11
def gettext(nodelist): """ get text data from nodelist """ result = "" for node in nodelist: if node.nodeType == node.TEXT_NODE or node.nodeType == node.CDATA_SECTION_NODE: stripped = node.data.strip() if stripped: result += stripped return result
def isMAGPYABS(filename): """ Checks whether a file is ASCII DIDD (Tihany) format. """ try: temp = open(filename, 'rt') line = temp.readline() line = temp.readline() except: return False if not line.startswith('Miren'): return False return True
def compareThresh(value,threshold,mode,inclusive, *, default=False): """Returns a boolean only if value satisfies the threshold test. In case of failure of any sort, returns the default value (which defaults to 'False'). Accepted mode values are '<', '>', '<=' and '>='.""" #normalizing input i...
def model_set(model): """Converts a model from a dictionary representation to a set representation. Given a ``model`` represented by a dictionary mapping atoms to Boolean values, this function returns the *set* of atoms that are mapped to ``True`` in the dictionary. Paramters --------- model ...
def negative_exist(arr: list) -> int: """ >>> negative_exist([-2,-8,-9]) -2 >>> [negative_exist(arr) for arr in test_data] [-2, 0, 0, 0, 0] """ arr = arr or [0] max = arr[0] for i in arr: if i >= 0: return 0 elif max <= i: max = i ...
def conv_alphapos(pos, num_cols): """ Converts a position to a letter and number pos: int """ col = pos % num_cols row = pos // num_cols return "{}{}".format(chr(ord("a") + col), row + 1)
def _list_type(output, searchresults): """for each key in searchresults, format output for key and val list""" for key, val in searchresults.items(): output += '\t{}\n'.format(key) for v in val: output += '\t\t{}\n'.format(v) return output
def sort_by_index(a, idx, reverse=False): """ Sort an array of array by index Input: a: a 2D array, e.g., [[1, "a"], [2, "b"]] idx: the index to sort the arrays inside the array, e.g., 0 """ return sorted(a, key=lambda t: t[idx], reverse=reverse)
def format_number(number): """standardizes numbers in contacts""" chars_to_remove = " ()-" for char in chars_to_remove: number = number.replace(char, "") if number[0:2] != '+1': number = '+1' + number return number
def split_every_n_characters(n: int, s: str) -> list: """Split a string every `n` characters. :param n: the number that determines the length of output strings :param s: any string :return: a list of strings where all of them are `n` characters long (except the last one) :link: https://stackoverflow...
def numDecodings(s): """ :type s: str :rtype: int """ if s == '': return 1 if s[0] == '0': return 0 if len(s) == 1: return 1 dp = [0] * (len(s) - 1) for i in range(1, len(s)): if s[i] == '0' and (s[i - 1] > '2' or s[i - 1] == '0'): return ...
def ascii_pattern(value): """ Build an "object" that indicates that the ``pattern`` is an ASCII string """ return {'type':'ascii', 'value':value}
def _eval_meta_as_summary(meta): """some crude heuristics for now most are implemented on bot-side with domain whitelists""" if meta == '': return False if len(meta)>500: return False if 'login' in meta.lower(): return False return True
def encode_uvarint(number: int) -> bytes: """Pack `number` into varint bytes""" buf = b"" while True: towrite = number & 0x7F number >>= 7 if number: buf += bytes((towrite | 0x80,)) else: buf += bytes((towrite,)) break return buf
def solution(string) -> str: """ reverses the string value passed into it :param string: :return: """ return string[::-1]