content
stringlengths
42
6.51k
def _validate_structure(structure): """Validates the structure of the given observables collection. The collection must either be a dict, or a (list or tuple) of dicts. Args: structure: A candidate collection of observables. Returns: A boolean that is `True` if `structure` is either a list or a tuple, or `False` otherwise. Raises: ValueError: If `structure` is neither a dict nor a (list or tuple) of dicts. """ is_nested = isinstance(structure, (list, tuple)) if is_nested: is_valid = all(isinstance(obj, dict) for obj in structure) else: is_valid = isinstance(structure, dict) if not is_valid: raise ValueError( '`observables` should be a dict, or a (list or tuple) of dicts' ': got {}'.format(structure)) return is_nested
def is_iterable(x): """Is the argument an iterable?""" try: iter(x) except TypeError: return False return True
def get_e_activity(data, meta): """ Returns activity of named component @ In, data, dict, request for data @ In, meta, dict, state information @ Out, data, dict, filled data @ In, meta, dict, state information """ data = {'driver': meta['HERON']['activity']['electricity']} return data, meta
def convert_by_engine_keys_to_regex(lookup_by_engine): """ Convert all the keys in a lookup_by_engine to a regex """ keys = set() for d in lookup_by_engine.values(): for k in d.keys(): if isinstance(k, str): keys.add(k) keys = list(keys) keys.sort(key=lambda item: (len(item), item), reverse=True) return "|".join(keys)
def match(word, allowed_letters): """checks if a given word can be built from the allowed letters exclusivly. Each allowed letter may only occur once""" allowed_letters = [letter.lower() for letter in allowed_letters] word = [letter.lower() for letter in word] for letter in word: if letter not in allowed_letters: return False for letter in word: if letter not in allowed_letters: return False else: index = allowed_letters.index(letter) allowed_letters = allowed_letters[:index] + allowed_letters[index+1:] return True
def host_and_page(url): """ Splits a `url` into the hostname and the rest of the url. """ url = url.split('//')[1] parts = url.split('/') host = parts[0] page = "/".join(parts[1:]) return host, '/' + page
def euclidean_gcd(a: int, b: int) -> int: """ Examples: >>> euclidean_gcd(3, 5) 1 >>> euclidean_gcd(6, 3) 3 """ while b: a, b = b, a % b return a
def short_bubble_sort(integer_list): """ This implementation is just the same as the normal bubble sort but it can recognize that the list is sorted if no exchanges are made in one pass """ exchanged = True for passnum in range(len(integer_list), 1, -1): exchanged = False for i in range(passnum-1): if integer_list[i] > integer_list[i+1]: exchanged = True integer_list[i], integer_list[i+1] = integer_list[i+1], integer_list[i] if not exchanged: break return integer_list
def file_path_to_dto(file_path): """Converts a `file_path` return value to a `FilePath` Swift DTO value. Args: file_path: A value returned from `file_path`. Returns: A `FilePath` Swift DTO value, which is either a string or a `struct` containing the following fields: * `_`: The file path. * `f`: `True` if the path is a folder. * `t`: Maps to `FilePath.FileType`: * "p" for `.project` * "e" for `.external` * "g" for `.generated` * "i" for `.internal` """ if not file_path: return None ret = {} if file_path.is_folder: ret["f"] = True if file_path.type != "p": ret["t"] = file_path.type if ret: ret["_"] = file_path.path # `FilePath` allows a `string` to imply a `.project` file return ret if ret else file_path.path
def inches_to_pixels(inches): """ Converts Inches into Pixels """ pixels = inches / 0.0104166666667 return round(pixels, 0)
def merge(numbers_list): """ Mergesort algorithm :param numbers_list: list of number to order :return: new list with numbers ordered """ if len(numbers_list) <= 1: return numbers_list result = [] # identify the middle item mid = len(numbers_list) // 2 numbers_list_a = merge(numbers_list[:mid]) numbers_list_b = merge(numbers_list[mid:]) i = 0 j = 0 while i < len(numbers_list_a) and j < len(numbers_list_b): if numbers_list_a[i] <= numbers_list_b[j]: result.append(numbers_list_a[i]) i += 1 else: result.append(numbers_list_b[j]) j += 1 if i >= len(numbers_list_a): result += numbers_list_b[j:] else: result += numbers_list_a[i:] return result
def try_parse(value, default=0, type=int): """Try to parse the input value into certian type. Return default on error. """ try: return type(value) except (TypeError, ValueError): return default
def lin_thresh(x: float, objective: str, upper: float, lower: float, buffer: float, **kwargs): """ Transform values using a linear threshold :param x: Input valid :param objective: 'maximize', 'minimize' or 'range' :param upper: Upper bound for transforming values ('range' and 'maximize' only) :param lower: Lower bound for transforming values ('range' and 'minimize' only) :param buffer: Buffer between thresholds which will be on a linear scale :param kwargs: :return: """ if objective == 'maximize': if x >= upper: y = 1.0 elif x <= upper-buffer: y = 0.0 else: y = (x - (upper-buffer)) / (upper - (upper-buffer)) elif objective == 'minimize': if x <= lower: y = 1.0 elif x >= lower+buffer: y = 0.0 else: y = (x - (lower+buffer)) / (lower - (lower+buffer)) elif objective == 'range': if lower <= x <= upper: y = 1.0 else: if x <= lower-buffer: y = 0.0 elif lower-buffer < x < lower: y = (x - (lower-buffer)) / (lower - (lower-buffer)) elif x >= upper+buffer: y = 0.0 else: y = (x - (upper+buffer)) / (upper - (upper+buffer)) else: print("linThresh objective must be either \'minimize\' or \'maximize\' or \'range\'") raise return y
def get_3d_indices(indices, layout="NCDHW"): """Get 3d indices""" if layout == "NDHWC": n, z, y, x, c = indices cc = None elif layout == "NCDHW": n, c, z, y, x = indices cc = None else: n, c, z, y, x, cc = indices return n, c, z, y, x, cc
def As_Dollars_Pad(Number): """Format Dollars amounts to strings & Pad Right 10 Spaces""" Number_Display = f"${Number:,.2f}" Number_Display = f"{Number_Display:>10}" return Number_Display
def uppercase(string: str): """Safely recast a string to uppercase""" try: return string.upper() except AttributeError: return string
def lorenz(amplitude: float, fwhm: float, x: int, x_0: float): """Model of the frequency response.""" return amplitude * ((fwhm / 2.0) ** 2) / ((x - x_0) ** 2 + (fwhm / 2.0) ** 2)
def judge_checksum(content: bytes) -> bool: """ Judge if the checksum is right or not. :param content: the content of segment :return: A bool """ even_sum = 0x0 odd_sum = 0x0 for i in range(len(content)): b = content[i] if i % 2: odd_sum += b odd_sum %= 256 else: even_sum += b even_sum %= 256 return even_sum == 0 and odd_sum == 0
def to_list(obj): """ Wraps an object in a list if it's not already one """ if isinstance(obj, list): return obj return [obj]
def compact(iterable): """ Removes None items from `iterable`. Examples: ```python from flashback.iterating import compact for user_id in compact([1058, None, 85, 9264, 19475, None]): print(user_id) #=> 1058 #=> 85 #=> 9264 #=> 19475 ``` Params: iterable (Iterable<Any>): the iterable to remove None from Returns: tuple<Any>: the iterable without duplicates """ return tuple(item for item in iterable if item is not None)
def iterative(x, y): """ Find the GCD or HCF of two numbers. :return: returns the hcf of two numbers. """ x, y = max(x, y), min(x, y) while y: x, y = y, x%y return x
def value_right(self, other): """ Returns the value of the type instance calling an to use in an operator method, namely when the method's instance is on the left side of the expression. """ return self if isinstance(other, self.__class__) else self.value
def to_java_map(map_var, keys_values): """Generate code to put a list of key-value pairs into a Java Map instance. map_var - The variable name of the Java Map instance. keys_values - A list of 2-tuples containing a key and value pair. """ result = [] for k, v in keys_values: result.append('%s.put(%s, %s);' % (map_var, k, v)) return '\n'.join(result)
def escape_html(str): """Return an HTML-escaped version of STR.""" return str.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
def preprocess_gdelt_gkg_tone(x): """ For GDELT GKG """ res = dict() res['tone'] = float(x[0]) res['positive_score'] = x[1] res['negative_score'] = x[2] res['polarity'] = x[3] res['activity_reference_density'] = x[4] res['group_reference_density'] = x[5] return res
def is_palindrome(s): """ (str) -> bool Return True if s is a palindrome, False otherwise. """ return s == s[::-1]
def get_jobs_by_type(data_dict): """ Examines 'algo' and creates new dict where the key is the value of 'algo' and value is a list of jobs (each one a dict) run with that 'algo' :param data_dict: :return: :rtype: dict """ jobtype_dict = dict() for entry in data_dict: if data_dict[entry]['algo'] not in jobtype_dict: jobtype_dict[data_dict[entry]['algo']] = [] jobtype_dict[data_dict[entry]['algo']].append(data_dict[entry]) return jobtype_dict
def _idify(value): """Coerce value to valid path component.""" # Must be strings. Can not contain '@' return str(value).replace('@', '_')
def linlin(x, smi, sma, dmi, dma): """Linear mapping Parameters ---------- x : float input value smi : float input range's minimum sma : float input range's maximum dmi : float input range's minimum dma : Returns ------- _ : float mapped output """ return (x - smi) / (sma - smi) * (dma - dmi) + dmi
def symbol_type_to_human(type): """Convert a symbol type as printed by nm into a human-readable name.""" return { 'b': 'bss', 'd': 'data', 'r': 'read-only data', 't': 'code', 'u': 'weak symbol', # Unique global. 'w': 'weak symbol', 'v': 'weak symbol' }[type]
def f(t, T): """ returns -1, 0, or 1 based on relationship between t and T throws IndexError """ if(t > 0 and t < float(T/2)): return 1 elif(t == float(T/2)): return 0 elif(t > float(T/2) and t < T): return -1 raise IndexError("Out of function domain")
def parse_arxiv_url(url): """ examples is http://arxiv.org/abs/1512.08756v2 we want to extract the raw id and the version """ _, idversion = url.rsplit('/', 1) pid, ver = idversion.rsplit('v', 1) return pid, int(ver)
def uint8_to_byte(i): """ Utility function that converts an unsigned integer to its byte representation in little endian order. If `i` is not representable in a single byte it will raise OverflowError. Args: i (int): integer to convert Returns: bytes: the byte representation Raises: OverflowError: if `i` is not representable in 1 byte """ return i.to_bytes(1, byteorder='little', signed=False)
def _memoized_fibonacci_aux(n: int, memo: dict) -> int: """Auxiliary function of memoized_fibonacci.""" if n == 0 or n == 1: return n if n not in memo: memo[n] = _memoized_fibonacci_aux(n - 1, memo) + \ _memoized_fibonacci_aux(n - 2, memo) return memo[n]
def _any_weight_initialized(keras_model): """Check if any weights has been initialized in the Keras model. Args: keras_model: An instance of compiled keras model. Returns: boolean, True if at least one weight has been initialized, else False. Currently keras initialize all weights at get_session(). """ if keras_model is None: return False for layer in keras_model.layers: for weight in layer.weights: if hasattr(weight, '_keras_initialized'): return True return False
def is_bool(x): """Tests if something is a boolean""" return isinstance(x, bool)
def which(arg: str): """Return fullpath of arg, or None if file not exist""" import os try: fpath = os.path.split(arg) if not fpath: return None if os.path.isfile(arg): return arg for path in os.environ["PATH"].split(os.pathsep): f = os.path.join(path, arg) if os.path.isfile(f): return f except Exception: pass return None
def time2secs(timestr): """Converts time in format hh:mm:ss to number of seconds.""" h, m, s = timestr.split(':') return int(h) * 3600 + int(m) * 60 + int(s)
def unit_vector(v): """Return the unit vector of the points v = (a,b)""" h = ((v[0]**2)+(v[1]**2))**0.5 if h == 0: h = 0.000000000000001 ua = v[0] / h ub = v[1] / h return (ua, ub)
def undamaged_example( session_id, array_id, start, end, ): """ S03 P09, P10, P11, P12 2:11:22 4,090 P11 dropped from min ~15 to ~30 S04 P09, P10, P11, P12 2:29:36 5,563 S05 P13, p14, p15, P16 2:31:44 4,939 U03 missing (crashed) S06 P13, p14, p15, P16 2:30:06 5,097 S07 p17, P18, p19, P20 2:26:53 3,656 S17 p17, P18, p19, P20 2:32:16 5,892 S08 P21, P22, P23, P24 2:31:35 6,175 S16 P21, P22, P23, P24 2:32:19 5,004 S12 P33, P34, P35, p36 2:29:24 3,300 Last 15 minutes of U05 missing (Kinect was accidentally turned off) S13 P33, P34, P35, p36 2:30:11 4,193 S19 p49, P50, P51, p52 2:32:38 4,292 P52 mic unreliable S20 p49, P50, P51, p52 2:18:04 5,365 S18 p41, P42, p43, p44 2:42:23 4,907 S22 p41, P42, p43, p44 2:35:44 4,758 U03 missing S23 p53, P54, P55, p56 2:58:43 7,054 Neighbour interrupts S24 p53, P54, P55, p56 2:37:09 5,695 P54 mic unreliable, P53 disconnects for bathroom """ # session_id = ex['session_id'] if session_id in ['S05', 'S22'] and array_id in ['U03']: return False # if session_id in ['S03'] and array_id in ['P11'] and time 15-30: # return False return True
def _TransformOperationWarnings(metadata): """Returns a count of operations if any are present.""" if 'warnings' in metadata: return len(metadata['warnings']) return ''
def parse_signature(signature): """ Breaks 'func(address)(uint256)' into ['func', '(address)', '(uint256)'] """ parts = [] stack = [] start = 0 for end, letter in enumerate(signature): if letter == '(': stack.append(letter) if not parts: parts.append(signature[start:end]) start = end if letter == ')': stack.pop() if not stack: # we are only interested in outermost groups parts.append(signature[start:end + 1]) start = end + 1 return parts
def square_area(x): """Takes a dimension of a square and calculates its area :param x: a number :return: Area of the square >>> square_area(5) 25""" area = x**2 return area
def del_start(x, start): """ >>> l = [1,2,3,4] >>> del_start(l, 2) [1, 2] >>> l = [1,2,3,4,5,6,7] >>> del_start(l, 20) [1, 2, 3, 4, 5, 6, 7] >>> del_start(l, 8) [1, 2, 3, 4, 5, 6, 7] >>> del_start(l, 4) [1, 2, 3, 4] >>> del_start(l, -2) [1, 2] >>> l [1, 2] >>> del_start(l, -2) [] >>> del_start(l, 2) [] >>> del_start(l, -2) [] >>> del_start(l, 20) [] >>> del_start([1,2,3,4], -20) [] >>> del_start([1,2,3,4], 0) [] """ del x[start:] return x
def find_largest_digit(n): """ :param n: int, a number input by the user :return: the largest digit in n """ if 0 <= n < 10: return n else: if n < 0: return find_largest_digit(-n) else: if (n % 10) <= ((n % 100 - n % 10)/10): return find_largest_digit((n-n % 10)//10) else: return find_largest_digit((n//10) - ((n//10) % 10) + (n % 10))
def skip_leading_ws_with_indent(s, i, tab_width): """Skips leading whitespace and returns (i, indent), - i points after the whitespace - indent is the width of the whitespace, assuming tab_width wide tabs.""" count = 0; n = len(s) while i < n: ch = s[i] if ch == ' ': count += 1 i += 1 elif ch == '\t': count += (abs(tab_width) - (count % abs(tab_width))) i += 1 else: break return i, count
def manhattan_distance(point_1, point_2): """Return Manhattan distance between two points.""" return sum(abs(a - b) for a, b in zip(point_1, point_2))
def new_in_list(my_list, idx, element): """ Replaces an element in a list at a specific position Without modifying the original list """ l_len = len(my_list) if idx >= l_len or idx < 0: return (my_list) new_list = my_list[:] new_list[idx] = element return (new_list)
def parse_range( range_string ): """ Parse a range object from a string of the form: <start>:<stop>[:<step>] No validation is performed on <start>, <stop>, <step>. Takes 1 argument: range_string - Returns 1 value: range_object - range() object. """ components = list( map( int, range_string.split( ":" ) ) ) if len( components ) == 1: components = [components[0], components[0]] # adjust the end so it is inclusive rather than following Python's exclusive # semantics. this makes things less surprising to end users. components[1] += 1 try: range_object = range( *components ) except: range_object = None return range_object
def validateAuth(auth): """ validates an authentication dictionary to look for specific keys, returns a boolean result """ return ('user' in auth and 'password' in auth)
def wrap_css_lines(css, line_length): """Wrap the lines of the given CSS to an approximate length.""" lines = [] line_start = 0 for i, char in enumerate(css): # It's safe to break after `}` characters. if char == '}' and (i - line_start >= line_length): lines.append(css[line_start:i + 1]) line_start = i + 1 if line_start < len(css): lines.append(css[line_start:]) return '\n'.join(lines)
def contains_unusual_content(result: dict) -> bool: """ returns True if the response indicates the PDF contains unusual content (Launch, Sound, Movie, ResetForm, ImportData and JavaScript actions) by checking if ISO 19005.1 clause 6.6.1 is among the failure reasons. :param result: The parsed JSON response from POSTing a PDF to verapdf :return: True if the PDF contains unusual content, otherwise False """ assertions = result["testAssertions"] for assertion in assertions: status = assertion["status"] specification = assertion["ruleId"]["specification"] clause = assertion["ruleId"]["clause"] if status == "FAILED" and specification == "ISO_19005_1" and clause == "6.6.1": return True return False
def get_dicts_from_list(list_of_dicts, list_of_key_values, key='id'): """ Returns list of dictionaries with keys: @prm{key} equal to one from list @prm{list_of_key_values} from a list of dictionaries: @prm{list_of_dicts}. """ ret = [] for dictionary in list_of_dicts: if dictionary.get(key) == None: raise Exception("No key: " + key + " in dictionary.") if dictionary.get(key) in list_of_key_values: ret.append(dictionary) return ret
def escape_markdown(string: str, codeblock: bool = False) -> str: """Escape the markdown of a given string. Args: string (str): The ``str`` that will have markdown escaped. codeblock (bool): The ``bool`` that tells if the escaped content will be in a code block. Returns: str: The ``str`` that has markdown escaped. """ string = string.replace('```', '`\u200D``') if not codeblock: string = string.replace('*', '\\*').replace('~', '\\~').replace('_', '\\_').replace('`', '\\`') return string
def next_arg(args, flag, case=False): """ :param list args: The list of command line arguments :param str flag: The list of command line arguments :param bool case: Pay attention to case sensitivity """ lookup_args = args if case else [_.lower() for _ in args] flag = flag if case else flag.lower() if flag in lookup_args: index = lookup_args.index(flag) arg_index = index + 1 if arg_index < len(args): return args[arg_index]
def filter_numeric(s): """If the given string is numeric, return a numeric value for it""" if s.isnumeric(): return int(s) else: try: fval = float(s) return fval except ValueError: return s
def L_v(t_air): """ Calculate latent heat of vaporization at a given temperature. Stull, pg. 641 Args: t_air (float) : Air temperature [deg C] Returns: lv : Latent heat of vaporization at t_air [J kg^-1] """ lv = (2.501 - 0.00237 * t_air) * 1e6 return lv
def empty_if_none(x): """Returns an empty list if passed None otherwise the argument""" if x: return x else: return []
def class_to_str(cl): """Converts the label of a class to the corresponding name """ return "positive" if cl == 1 else "negative"
def _create_input_remove_video_order(removed, PK): """remove video order""" orders = [] for uri in removed: input = { "TableName": "primary_table", "Key": {"PK": {"S": PK}, "SK": {"S": uri}}, } orders.append({"Delete": input}) print("remove video order setted") return orders
def asy_number(value) -> str: """Format an asymptote number""" return "%.5g" % value
def clean_mentions(line): """Escape anything that could resolve to mention.""" return line.replace("@", "@\u200b")
def _sort_and_unpack(states, return_states=None): """Maintain input order (even with parallelization on)""" states = sorted(states, key=lambda s: s[0]) states = {n: [s[1][n] for s in states] for n in states[0][1].keys()} for n, s in states.items(): if len(s) == 1: states[n] = s[0] if len(states) == 1 and return_states is None: states = states["readout"] return states
def fib_iter(n): """[summary] Works iterative approximate O(n) Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n must be positive integer' fib_1 = 0 fib_2 = 1 res = 0 if n <= 1: return n for _ in range(n-1): res = fib_1 + fib_2 fib_1 = fib_2 fib_2 = res return res
def f1score(precision_value, recall_value, eps=1e-5): """ Calculating F1-score from precision and recall to reduce computation redundancy. Args: precision_value: precision (0-1) recall_value: recall (0-1) Returns: F1 score (0-1) """ numerator = 2 * (precision_value * recall_value) denominator = precision_value + recall_value + eps return numerator / denominator
def fill_change_date_object(timestamp): """ change date object: { timestamp: timestamp } """ return dict(timestamp=timestamp)
def apply_polarity(value, polarity): """ Combine value and polarity. # Arguments value: int >= 0, Absolute value. polarity: int, Value indicating the sign. Value is considered to be negative when `polarity == 0`. Any non-zero polarity indicates positive value. # Return Integer with absolute value of `value` and sign indicated by `polarity`. """ return value if polarity != 0 else -value
def merge(left, right): """Merges two arrays together from smallest to largest""" result = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 # Add unsorted from left side while i < len(left): result.append(left[i]) i += 1 # Add unsorted from right side while j < len(right): result.append(right[j]) j += 1 return result
def get_resource_id_from_type_name(type_name): """Returns the key from type_name. Args: type_name (str): Type name. Returns: str: Resource id. """ if '/' in type_name: return type_name.split('/')[-1] return type_name
def confusion_matrix(match=lambda document:False, documents=[(None,False)]): """ Returns the reliability of a binary classifier, as a tuple with the amount of true positives (TP), true negatives (TN), false positives (FP), false negatives (FN). The classifier is a function that returns True or False for a document. The list of documents contains (document, bool)-tuples, where True means a document that should be identified as relevant (True) by the classifier. """ TN = TP = FN = FP = 0 for document, b1 in documents: b2 = match(document) if b1 and b2: TP += 1 # true positive elif not b1 and not b2: TN += 1 # true negative elif not b1 and b2: FP += 1 # false positive (type I error) elif b1 and not b2: FN += 1 # false negative (type II error) return TP, TN, FP, FN
def list_to_dict(lst): """ Takes a list an turns it into a list :param lst: the list that will be turned into a dict """ if len(lst) % 2 != 1: odd_indexes = [] even_indexes = [] for i in range(len(lst)): if i % 2 == 0: odd_indexes.append(lst[i]) elif i % 2 == 1 or i == 0: even_indexes.append(lst[i]) final_dict = dict(zip(odd_indexes, even_indexes)) return final_dict else: print("The list needs to have an even amount of")
def add_values_to_config(defaults, values, source): """Given a defaults dictionary (structured like configurable_defaults above) and a possibly nested config dict, combine the two and return a new dict, structured like cfg_defaults. Every node will have at least 'type', 'source' and 'value' keys.""" result = {} for key in list(defaults.keys()) + list(values.keys()): value = values.get(key) default = defaults.get(key) if key not in defaults: if isinstance(values[key], dict): result[key] = { "type": "map", "source": None, "value": add_values_to_config({}, value, source), } else: result[key] = {"type": "any", "source": source, "value": value} elif key not in values: result[key] = default else: if default["source"] == "database": assert source != "default" result[key] = dict(default, configured_value=value) elif default["type"] == "map": if not isinstance(value, dict): raise TypeError( f"Value found where dict expected at {key}: {value} in {source}" ) result[key] = { "type": "map", "source": None, "value": add_values_to_config(default["value"], value, source), } else: result[key] = {"type": "any", "source": source, "value": value} return result
def get_keydefs(doc, soort, keydefs=None): """build dictionary of key combo definitions """ if not keydefs: keydefs = {} context = '' for line in doc: line = line.strip() if not line or line.startswith(';') or line.startswith('#'): continue elif line.startswith('['): context = line.strip('[]') if context in keydefs or context.lower() in ('info', 'version'): context = '' else: keydefs[context] = [] elif context: keydata, definition = line.split('=', 1) platform = '' feature = '' if "=" in definition: extra, definition = definition.split('=', 1) keydata = '='.join((keydata, extra)).replace('"', ' ') if ',' in keydata: extra, keydata = keydata.split(',') got_platform = got_feature = False for word in extra.split(): if got_platform: platform = word got_platform = False elif got_feature: feature = word got_feature = False elif word.lower() == 'platform': got_platform = True elif word.lower() == 'feature': got_feature = True keydefs[context].append([platform, feature, keydata.strip(), soort, definition.strip()]) return keydefs
def split_seconds(total_seconds, days=False, integer=None): """[summary] Args: total_seconds (int or float): total number of seconds. days (bool, optional): If true, it will return a 4-length tuple, including the days. Defaults to False. integer (bool or None, optional): If True, the seconds returned will be an integer. If False, no conversion will be made. If None and the remaining seconds are 0, it will return the seconds (0) as an int, regardless that it was int or float. Defaults to None. Returns: tuple: 3-length tuple: (hours, seconds, minutes). If days is True, it will be a 4-length tuple: (days, hours, seconds, minutes). """ total_minutes = total_seconds // 60 seconds = total_seconds % 60 hours = int(total_minutes // 60) minutes = int(total_minutes % 60) seconds = round(seconds, 2) if integer is True: seconds = round(seconds, 0) elif integer is None: if seconds == int(seconds): seconds = int(seconds) if not days: return hours, minutes, seconds days = hours // 24 hours = hours % 24 return days, hours, minutes, seconds
def merge_clusters(articles): """Merges articles of every cluster into one article object.""" clusters = [] cluster_ids = set([article['cluster_id'] for article in articles]) for id in cluster_ids: body = [] for article in articles: if article['cluster_id'] == id: body += article['body'] data = {'cluster_id': id, 'body': body, 'summaries': []} clusters.append(data) return clusters
def newEmpty(name,location=None,parentCenter=None,**kw): """ Create a new Null Object @type name: string @param name: name of the empty @type location: list @param location: position of the null object @type parentCenter: list @param parentCenter: position of the parent object @type kw: dictionary @param kw: you can add your own keyword @rtype: hostObject @return: the null object """ empty=None# if location != None : if parentCenter != None : location = location - parentCenter #set the position of the object to location return empty
def modified(number, percent): """return the amount (or any other number) with added margin given by percent parameter (result has type float) """ if percent: return number * (100 + percent) / 100. else: return float(number)
def phase2(l, sum): """ Since we no longer assume an ordered list, the classic solution would be to calculate the diff on each element and save into memory. Than ask if we already seen a desired diff in the past, in case we did, return True Complexity O(n) """ m = set() for element in l: diff = sum - element if diff in m: print("found diff {} for elemnt {}".format(diff, element)) return True else: print("checking element {} adding {} to m>{}".format(element, diff, m)) m.add(diff) return False
def render_text(content): """ a simple renderer for text documents: replace new lines with <br> """ return "<br>".join(content.splitlines())
def _format_quad_str(quad): """Format a 4-element tuple of integers into a string of the form xxxx.xx.x.xxx""" return '{}.{}.{}.{}'.format(*quad)
def prod(it): """Compute the product of sequence of numbers ``it``. """ x = 1 for i in it: x *= i return x
def remove_hyphens(words): """ :param words: A list of words, some of which may contain hyphens :return: The same list, but all hyphenated words are split into parts and added back, in the same order """ hyphenated = [] # will break if I have cross correlation and cross-correlation will always just take second for i, word in enumerate(words): hyph_parts = word.split('-') if len(hyph_parts) > 1: hyphenated.append(word) words.pop(i) for part in reversed(hyph_parts): if len(part) > 0: words.insert(i, part) return words, hyphenated
def filter_on_provided_extension(input_list, ext): """Takes in a list of files, returns filtered list of files that have the correct extension """ temp_list = [] for item in input_list: if item.endswith(ext): temp_list.append(item) return temp_list
def joinName(parts): """joinName(parts) Join the parts of an object name, taking dots and indexing into account. """ name = ".".join(parts) return name.replace(".[", "[")
def list_contains_only_os(lst): """Check whether the given list contains only o's""" for elem in lst: if elem != "O": return False return True
def format_test_id(test_id) -> str: """Format numeric to 0-padded string""" return f"{test_id:0>5}"
def string2array(value): """ covert a long string format into a list :param value: a string that can be split by "," :type value: str :return: the array of flaoting numbers from a sring :rtype: [float,float,....] """ value = value.replace("[", "").replace("]", "") value = value.split(",") # print("def string2array", value) return [float(i)for i in value]
def get_filenames_add_username(files, username): """ Adds the username to the end of a file name :param files: List of file names :param username: Username to append :return: filename with appended username """ filenames = [] for file in files: filenames.append(file + username) return filenames
def get_game_name(json): """Returns game name from json file.""" data = json app_id = '' if data is None: return None for dict_key in data.keys(): app_id = dict_key if data[app_id]['success']: return data[app_id]['data']['name'] return None
def _parse_positive_int_param(request, query_params, param_name): """Parses and asserts a positive (>0) integer query parameter. Args: request: The http request object. query_params: Dictionary of query parameters. param_name: Name of the parameter. Returns: None if parameter not present. -1 if parameter is not a positive integer. """ param = query_params.get(param_name) if not param: return None try: param = int(param) if param <= 0: raise ValueError() return param except ValueError: request.respond('query parameter "%s" must be integer > 0' % param_name, 'text/plain', 400) return -1
def average(v, state): """ Parameters ---------- v : number The next element of the input stream of the agent. state: (n, cumulative) The state of the agent where n : number The value of the next element in the agent's input stream. cumulative : number The sum of the values that the agent has received on its input stream. Returns ------- (mean, state) mean : floating point number The average of the values received so far by the agent state : (n, cumulative) The new state of the agent. """ n, cumulative = state n += 1 cumulative += v mean = cumulative/float(n) state = (n, cumulative) return (mean, state)
def select(population, to_retain): """Go through all of the warroirs and check which ones are best fit to breed and move on.""" #This starts off by sorting the population then gets all of the population dived by 2 using floor divison I think #that just makes sure it doesn't output as a pesky decimal. Then it takes one half of memebers which shall be females. # which tend to be not as strong as males(Not being sexist just science thats how we are built.) So the front half will be #The lower digits because we sorted it then the upper half will be males. Then it finishes off by getting the strongest males and #females and returns them. sorted_pop = sorted(population) to_keep_by_sex = to_retain//2 members = len(sorted_pop)//2 females = sorted_pop[:members] males = sorted_pop[members:] strong_females = females[-to_keep_by_sex:] strong_males = males[-to_keep_by_sex:] return strong_males, strong_females
def split_errors(errors): """Splits errors into (user_errors, synthetic_errors). Arguments: errors: A list of lists of _Message, which is a list of bundles of associated messages. Returns: (user_errors, synthetic_errors), where both user_errors and synthetic_errors are lists of lists of _Message. synthetic_errors will contain all bundles that reference any synthetic source_location, and user_errors will contain the rest. The intent is that user_errors can be shown to end users, while synthetic_errors should generally be suppressed. """ synthetic_errors = [] user_errors = [] for error_block in errors: if any(message.location.is_synthetic for message in error_block): synthetic_errors.append(error_block) else: user_errors.append(error_block) return user_errors, synthetic_errors
def eqvalue(x): """ Checks whether all values of the iterable `x` are identical and returns that value if true, and otherwise raises a `ValueError` exception. >>> eqvalue([1, 1, 1]) 1 """ items = iter(x) first = next(items) for item in items: if item != first: raise ValueError("Values are not identical: {}, {}".format(first, item)) return first
def split_items(num, items): """Split off the first num items in the sequence. Args: num: int. Split into a list of num. items: str. A str of "+" and "=". Returns: Two str which are sequences, the first with the first num items and the second with the remaining items. """ return items[:num], items[num:]
def varSum_to_var(idx_new, series, win_size, mean_current, varSum): """ Returns the running variance based on a given time period. sources: http://subluminal.wordpress.com/2008/07/31/running-standard-deviations/ Keyword arguments: idx_new -- current index or location of the value in the series series -- list or tuple of data to average mean_current -- current average of the given period varSum -- current powersumavg of the given period """ if win_size < 1: raise ValueError("period must be 1 or greater") if idx_new <= 0: return 0.0 if mean_current == None: raise ValueError("asma of None invalid when bar > 0") if varSum == None: raise ValueError("powsumavg of None invalid when bar > 0") windowsize = idx_new + 1.0 if windowsize >= win_size: windowsize = win_size return (varSum * windowsize - windowsize * mean_current * mean_current) / windowsize
def generate_non_gap_position_lookup(seq): """ Creates a list of positions which correspond to the position of that base in a gapless sequence :param seq: string :return: list """ length = len(seq) num_gaps = 0 lookup = [] for i in range(0, length): base = seq[i] if base == '-': num_gaps += 1 lookup.append(-1) else: lookup.append(i - num_gaps) return lookup
def camelize(key): """Convert a python_style_variable_name to lowerCamelCase. Examples -------- >>> camelize('variable_name') 'variableName' >>> camelize('variableName') 'variableName' """ return ''.join(x.capitalize() if i > 0 else x for i, x in enumerate(key.split('_')))
def choices_to_dict(t): """ Converts a ChoiceField two-tuple to a dict (for JSON) Assumes i[0][0] is always unique """ d = {} for i in t: k = str(i[0]) d[k] = i[1] return d
def findY(A,B,x): """ given a line formed by 2 points A and B returns the value of y at x on that line """ if B[0] - A[0] == 0: return 0 m = (B[1]-A[1]) / (B[0]-A[0]) b = A[1] - m*A[0] return m*x + b