INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Freeze and shrink the graph based on a checkpoint and the output node names.
def freeze_from_checkpoint(input_checkpoint, output_file_path, output_node_names): """Freeze and shrink the graph based on a checkpoint and the output node names.""" check_input_checkpoint(input_checkpoint) output_node_names = output_node_names_string_as_list(output_node_names) with tf.Session() as se...
Freeze and shrink the graph based on a session and the output node names.
def freeze(sess, output_file_path, output_node_names): """Freeze and shrink the graph based on a session and the output node names.""" with TemporaryDirectory() as temp_dir_name: checkpoint_path = os.path.join(temp_dir_name, 'model.ckpt') tf.train.Saver().save(sess, checkpoint_path) fre...
Save a small version of the graph based on a session and the output node names.
def save_graph_only(sess, output_file_path, output_node_names, as_text=False): """Save a small version of the graph based on a session and the output node names.""" for node in sess.graph_def.node: node.device = '' graph_def = graph_util.extract_sub_graph(sess.graph_def, output_node_names) outpu...
Save a small version of the graph based on a checkpoint and the output node names.
def save_graph_only_from_checkpoint(input_checkpoint, output_file_path, output_node_names, as_text=False): """Save a small version of the graph based on a checkpoint and the output node names.""" check_input_checkpoint(input_checkpoint) output_node_names = output_node_names_string_as_list(output_node_names...
Save the weights of the trainable variables each one in a different file in output_path.
def save_weights(sess, output_path, conv_var_names=None, conv_transpose_var_names=None): """Save the weights of the trainable variables, each one in a different file in output_path.""" if not conv_var_names: conv_var_names = [] if not conv_transpose_var_names: conv_transpose_var_names = [] ...
Save the weights of the trainable variables given a checkpoint each one in a different file in output_path.
def save_weights_from_checkpoint(input_checkpoint, output_path, conv_var_names=None, conv_transpose_var_names=None): """Save the weights of the trainable variables given a checkpoint, each one in a different file in output_path.""" check_input_checkpoint(input_checkpoint) with tf.Session() as sess: ...
Return a TensorFlow saver from a checkpoint containing the metagraph.
def restore_from_checkpoint(sess, input_checkpoint): """Return a TensorFlow saver from a checkpoint containing the metagraph.""" saver = tf.train.import_meta_graph('{}.meta'.format(input_checkpoint)) saver.restore(sess, input_checkpoint) return saver
Parse the tag instantiate the class.
def parse(cls, parser, token): """ Parse the tag, instantiate the class. :type parser: django.template.base.Parser :type token: django.template.base.Token """ tag_name, args, kwargs = parse_token_kwargs( parser, token, allowed_kwargs=cls.allowed_k...
The default Django render () method for the tag.
def render(self, context): """ The default Django render() method for the tag. This method resolves the filter expressions, and calls :func:`render_tag`. """ # Resolve token kwargs tag_args = [expr.resolve(context) for expr in self.args] if self.compile_args else self.ar...
Render the tag with all arguments resolved to their actual values.
def render_tag(self, context, *tag_args, **tag_kwargs): """ Render the tag, with all arguments resolved to their actual values. """ raise NotImplementedError("{0}.render_tag() is not implemented!".format(self.__class__.__name__))
Validate the syntax of the template tag.
def validate_args(cls, tag_name, *args, **kwargs): """ Validate the syntax of the template tag. """ if cls.min_args is not None and len(args) < cls.min_args: if cls.min_args == 1: raise TemplateSyntaxError("'{0}' tag requires at least {1} argument".format(tag_...
Return the context data for the included template.
def get_context_data(self, parent_context, *tag_args, **tag_kwargs): """ Return the context data for the included template. """ raise NotImplementedError("{0}.get_context_data() is not implemented.".format(self.__class__.__name__))
Wrap the context data in a: class: ~django. template. Context object.
def get_context(self, parent_context, data): """ Wrap the context data in a :class:`~django.template.Context` object. :param parent_context: The context of the parent template. :type parent_context: :class:`~django.template.Context` :param data: The result from :func:`get_contex...
Rendering of the tag. It either assigns the value as variable or renders it.
def render_tag(self, context, *tag_args, **tag_kwargs): """ Rendering of the tag. It either assigns the value as variable, or renders it. """ if self.as_var: # Assign the value in the parent context context[self.as_var] = self.get_value(context, *tag_args, **tag_k...
Parse the as var syntax.
def parse(cls, parser, token): """ Parse the "as var" syntax. """ bits, as_var = parse_as_var(parser, token) tag_name, args, kwargs = parse_token_kwargs(parser, bits, ('template',) + cls.allowed_kwargs, compile_args=cls.compile_args, compile_kwargs=cls.compile_kwargs) # ...
Rendering of the tag. It either assigns the value as variable or renders it.
def render_tag(self, context, *tag_args, **tag_kwargs): """ Rendering of the tag. It either assigns the value as variable, or renders it. """ # Be very explicit about which base functionality is used: # Using super() for mixin support will not work nicely anyway here. if ...
Return the context data for the inclusion tag.
def get_context_data(self, parent_context, *tag_args, **tag_kwargs): """ Return the context data for the inclusion tag. Returns ``{'value': self.get_value(parent_context, *tag_args, **tag_kwargs)}`` by default. """ if 'template' not in self.allowed_kwargs: # The over...
Create a TensorFlow Session from a Caffe model.
def caffe_to_tensorflow_session(caffe_def_path, caffemodel_path, inputs, graph_name='Graph', conversion_out_dir_path=None, use_padding_same=False): """Create a TensorFlow Session from a Caffe model.""" try: # noinspection PyUnresolvedReferences from caffeflow impo...
Freeze and shrink the graph based on a Caffe model the input tensors and the output node names.
def freeze(caffe_def_path, caffemodel_path, inputs, output_file_path, output_node_names, graph_name='Graph', conversion_out_dir_path=None, checkpoint_out_path=None, use_padding_same=False): """Freeze and shrink the graph based on a Caffe model, the input tensors and the output node names.""" with caf...
Save a small version of the graph based on a Caffe model the input tensors and the output node names.
def save_graph_only(caffe_def_path, caffemodel_path, inputs, output_file_path, output_node_names, graph_name='Graph', use_padding_same=False): """Save a small version of the graph based on a Caffe model, the input tensors and the output node names.""" with caffe_to_tensorflow_session(caffe_d...
Save the weights of the trainable variables each one in a different file in output_path.
def save_weights(caffe_def_path, caffemodel_path, inputs, output_path, graph_name='Graph', conv_var_names=None, conv_transpose_var_names=None, use_padding_same=False): """Save the weights of the trainable variables, each one in a different file in output_path.""" with caffe_to_tensorflow_sessio...
Make a sequence into rows of num_columns columns.
def make_rows(num_columns, seq): """ Make a sequence into rows of num_columns columns. >>> tuple(make_rows(2, [1, 2, 3, 4, 5])) ((1, 4), (2, 5), (3, None)) >>> tuple(make_rows(3, [1, 2, 3, 4, 5])) ((1, 3, 5), (2, 4, None)) """ # calculate the minimum number of rows necessary to fit the list in # num_columns C...
Split a sequence into two sequences: the first is elements that return False for func ( element ) and the second for True for func ( element ). By default func is bool so uses the truth value of the object.
def bisect(seq, func=bool): """ Split a sequence into two sequences: the first is elements that return False for func(element) and the second for True for func(element). By default, func is ``bool``, so uses the truth value of the object. >>> is_odd = lambda n: n%2 >>> even, odd = bisect(range(5), is_odd) >>>...
Take a sequence and break it up into chunks of the specified size. The last chunk may be smaller than size.
def grouper_nofill_str(n, iterable): """ Take a sequence and break it up into chunks of the specified size. The last chunk may be smaller than size. This works very similar to grouper_nofill, except it works with strings as well. >>> tuple(grouper_nofill_str(3, 'foobarbaz')) ('foo', 'bar', 'baz') You can sti...
* Deprecated *: Use more_itertools. collapse instead.
def flatten(subject, test=None): """ *Deprecated*: Use more_itertools.collapse instead. """ warnings.warn( "Use more_itertools.collapse instead", DeprecationWarning, stacklevel=2) return list(more_itertools.collapse(subject, base_type=(bytes,)))
Yield every other item from the iterable
def every_other(iterable): """ Yield every other item from the iterable >>> ' '.join(every_other('abcdefg')) 'a c e g' """ items = iter(iterable) while True: try: yield next(items) next(items) except StopIteration: return
Given an iterable with items that may come in as sequential duplicates remove those duplicates.
def remove_duplicates(iterable, key=None): """ Given an iterable with items that may come in as sequential duplicates, remove those duplicates. Unlike unique_justseen, this function does not remove triplicates. >>> ' '.join(remove_duplicates('abcaabbccaaabbbcccbcbc')) 'a b c a b c a a b b c c b c b c' >>> ' '....
Get the next value from an iterable but also return an iterable that will subsequently return that value and the rest of the original iterable.
def peek(iterable): """ Get the next value from an iterable, but also return an iterable that will subsequently return that value and the rest of the original iterable. >>> l = iter([1,2,3]) >>> val, l = peek(l) >>> val 1 >>> list(l) [1, 2, 3] """ peeker, original = itertools.tee(iterable) return next(pee...
Like takewhile but takes a peekable iterable and doesn t consume the non - matching item.
def takewhile_peek(predicate, iterable): """ Like takewhile, but takes a peekable iterable and doesn't consume the non-matching item. >>> items = Peekable(range(10)) >>> is_small = lambda n: n < 4 >>> small_items = takewhile_peek(is_small, items) >>> list(small_items) [0, 1, 2, 3] >>> list(items) [4, 5, 6...
Like pairwise except returns n - tuples of adjacent items. s - > ( s0 s1... sn ) ( s1 s2... s ( n + 1 ))...
def nwise(iter, n): """ Like pairwise, except returns n-tuples of adjacent items. s -> (s0,s1,...,sn), (s1,s2,...,s(n+1)), ... """ iterset = [iter] while len(iterset) < n: iterset[-1:] = itertools.tee(iterset[-1]) next(iterset[-1], None) return six.moves.zip(*iterset)
Given an iterable return a new iterable which yields triples of ( pre item post ) where pre and post are the items preceeding and following the item ( or None if no such item is appropriate ). pre and post will always be pre_size and post_size in length.
def window(iter, pre_size=1, post_size=1): """ Given an iterable, return a new iterable which yields triples of (pre, item, post), where pre and post are the items preceeding and following the item (or None if no such item is appropriate). pre and post will always be pre_size and post_size in length. >>> example...
Given the total number of items determine the number of items that can be added to each bin with a limit on the bin size.
def partition_items(count, bin_size): """ Given the total number of items, determine the number of items that can be added to each bin with a limit on the bin size. So if you want to partition 11 items into groups of 3, you'll want three of three and one of two. >>> partition_items(11, 3) [3, 3, 3, 2] But if...
Like grouper but balance the rows to minimize fill per row. balanced_rows ( 3 ABCDEFG x ) -- > ABC DEx FGx
def balanced_rows(n, iterable, fillvalue=None): """ Like grouper, but balance the rows to minimize fill per row. balanced_rows(3, 'ABCDEFG', 'x') --> ABC DEx FGx" """ iterable, iterable_copy = itertools.tee(iterable) count = len(tuple(iterable_copy)) for allocation in partition_items(count, n): row = itertools...
Given an object always return an iterable. If the item is not already iterable return a tuple containing only the item. If item is None an empty iterable is returned.
def always_iterable(item): """ Given an object, always return an iterable. If the item is not already iterable, return a tuple containing only the item. If item is None, an empty iterable is returned. >>> always_iterable([1,2,3]) <list_iterator...> >>> always_iterable('foo') <tuple_iterator...> >>> always_ite...
Call each callable in callables suppressing any exceptions supplied. If no exception classes are supplied all Exceptions will be suppressed.
def suppress_exceptions(callables, *exceptions): """ Call each callable in callables, suppressing any exceptions supplied. If no exception classes are supplied, all Exceptions will be suppressed. >>> import functools >>> c1 = functools.partial(int, 'a') >>> c2 = functools.partial(int, '10') >>> list(suppress_ex...
Yield duplicate items from any number of sorted iterables of items
def duplicates(*iterables, **kwargs): """ Yield duplicate items from any number of sorted iterables of items >>> items_a = [1, 2, 3] >>> items_b = [0, 3, 4, 5, 6] >>> list(duplicates(items_a, items_b)) [(3, 3)] It won't behave as you expect if the iterables aren't ordered >>> items_b.append(1) >>> list(dupl...
Assert that for all items in the iterable they re in order based on comp
def assert_ordered(iterable, key=lambda x: x, comp=operator.le): """ Assert that for all items in the iterable, they're in order based on comp >>> list(assert_ordered(range(5))) [0, 1, 2, 3, 4] >>> list(assert_ordered(range(5), comp=operator.ge)) Traceback (most recent call last): ... AssertionError: 0 < 1 >>...
Given revision sets old and new each containing a series of revisions of some set of objects collate them based on these rules:
def collate_revs(old, new, key=lambda x: x, merge=lambda old, new: new): """ Given revision sets old and new, each containing a series of revisions of some set of objects, collate them based on these rules: - all items from each set are yielded in stable order - items in old are yielded first - items in new are...
Iterate over items in the dict yielding the first one but allowing it to be mutated during the process. >>> d = dict ( a = 1 ) >>> it = _mutable_iter ( d ) >>> next ( it ) ( a 1 ) >>> d {} >>> d. update ( b = 2 ) >>> list ( it ) [ ( b 2 ) ]
def _mutable_iter(dict): """ Iterate over items in the dict, yielding the first one, but allowing it to be mutated during the process. >>> d = dict(a=1) >>> it = _mutable_iter(d) >>> next(it) ('a', 1) >>> d {} >>> d.update(b=2) >>> list(it) [('b', 2)] """ while dict: prev_key = next(iter(dict)) yield ...
Given a partition_dict result if the partition missed swap the before and after.
def _swap_on_miss(partition_result): """ Given a partition_dict result, if the partition missed, swap the before and after. """ before, item, after = partition_result return (before, item, after) if item else (after, item, before)
Given an ordered dictionary of items and a key in that dict return an ordered dict of items before the keyed item and an ordered dict of items after.
def partition_dict(items, key): """ Given an ordered dictionary of items and a key in that dict, return an ordered dict of items before, the keyed item, and an ordered dict of items after. >>> od = collections.OrderedDict(zip(range(5), 'abcde')) >>> before, item, after = partition_dict(od, 3) >>> before Ordere...
Run through the sequence until n queues are created and return them. If fewer are created return those plus empty iterables to compensate.
def get_first_n_queues(self, n): """ Run through the sequence until n queues are created and return them. If fewer are created, return those plus empty iterables to compensate. """ try: while len(self.queues) < n: self.__fetch__() except StopIteration: pass values = list(self.queues.values()) ...
Resets the iterator to the start.
def reset(self): """ Resets the iterator to the start. Any remaining values in the current iteration are discarded. """ self.__iterator, self.__saved = itertools.tee(self.__saved)
Parse the remainder of the token to find a as varname statement.
def parse_as_var(parser, token): """ Parse the remainder of the token, to find a "as varname" statement. :param parser: The "parser" object that ``@register.tag`` provides. :type parser: :class:`~django.template.Parser` :param token: The "token" object that ``@register.tag`` provides. :type tok...
Allow the template tag arguments to be like a normal Python function with * args and ** kwargs.
def parse_token_kwargs(parser, token, allowed_kwargs=None, compile_args=True, compile_kwargs=True): """ Allow the template tag arguments to be like a normal Python function, with *args and **kwargs. :param parser: The "parser" object that ``@register.tag`` provides. :type parser: :class:`~django.templa...
Decorator to register class tags
def template_tag(library, name): """ Decorator to register class tags :param library: The template tag library, typically instantiated as ``register = Library()``. :type library: :class:`~django.template.Library` :param name: The name of the template tag :type name: str Example: .. co...
A descendant is a child many steps down.
def descendant(self, chain_path): """ A descendant is a child many steps down. """ public_child = self.hdkeychain chain_step_bytes = 4 max_bits_per_step = 2**31 chain_steps = [ int(chain_path[i:i+chain_step_bytes*2], 16) % max_bits_per_step for i i...
Derived from code from pybitcointools ( https:// github. com/ vbuterin/ pybitcointools ) by Vitalik Buterin
def bip32_serialize(rawtuple): """ Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin """ vbytes, depth, fingerprint, i, chaincode, key = rawtuple i = encode(i, 256, 4) chaincode = encode(hash_to_int(chaincode), 256, 32) keydata = b'\x00...
Derived from code from pybitcointools ( https:// github. com/ vbuterin/ pybitcointools ) by Vitalik Buterin
def bip32_deserialize(data): """ Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin """ dbin = changebase(data, 58, 256) if bin_dbl_sha256(dbin[:-4])[:4] != dbin[-4:]: raise Exception("Invalid checksum") vbytes = dbin[0:4] depth ...
: return: List of table names in the database.: rtype: list
def fetch_table_names(self, include_system_table=False): """ :return: List of table names in the database. :rtype: list """ result = self.__cur.execute("SELECT name FROM sqlite_master WHERE TYPE='table'") if result is None: return [] table_names = [r...
Get sqlite_master table information as a list of dictionaries.
def fetch_sqlite_master(self): """ Get sqlite_master table information as a list of dictionaries. :return: sqlite_master table information. :rtype: list :Sample Code: .. code:: python from sqliteschema import SQLiteSchemaExtractor p...
Yields each node of object graph in postorder.
def object_iter(obj, parent=None, parent_key=None, idx=None, siblings=None): """Yields each node of object graph in postorder.""" obj_node = Node(value=obj, parent=parent, parent_key=parent_key, siblings=siblings, idx=idx) if isinstance(obj, list): _siblings = len(o...
Appy selector to obj and return matching nodes.
def select(selector, obj): """Appy selector to obj and return matching nodes. If only one node is found, return it, otherwise return a list of matches. Returns False on syntax error. None if no results found. """ parser = Parser(obj) try: return parser.parse(selector) except Select...
Accept a list of tokens. Returns matched nodes of self. obj.
def parse(self, selector): """Accept a list of tokens. Returns matched nodes of self.obj.""" log.debug(self.obj) tokens = lex(selector) if self.peek(tokens, 'operator') == '*': self.match(tokens, 'operator') results = list(object_iter(self.obj)) else: ...
Production for a full selector.
def selector_production(self, tokens): """Production for a full selector.""" validators = [] # the following productions should return predicate functions. if self.peek(tokens, 'type'): type_ = self.match(tokens, 'type') validators.append(self.type_production(ty...
Find nodes in rhs which have parents in lhs.
def parents(self, lhs, rhs): """Find nodes in rhs which have parents in lhs.""" return [node for node in rhs if node.parent in lhs]
Return nodes from rhs which have ancestors in lhs.
def ancestors(self, lhs, rhs): """Return nodes from rhs which have ancestors in lhs.""" def _search(node): if node in lhs: return True if not node.parent: return False return _search(node.parent) return [node for node in rhs i...
Find nodes in rhs having common parents in lhs.
def siblings(self, lhs, rhs): """Find nodes in rhs having common parents in lhs.""" parents = [node.parent for node in lhs] return [node for node in rhs if node.parent in parents]
Parse args and pass them to pclass_func_validator.
def nth_child_production(self, lexeme, tokens): """Parse args and pass them to pclass_func_validator.""" args = self.match(tokens, 'expr') pat = self.nth_child_pat.match(args) if pat.group(5): a = 2 b = 1 if pat.group(5) == 'odd' else 0 elif pat.group(6...
Apply each validator in validators to each node in obj.
def _match_nodes(self, validators, obj): """Apply each validator in validators to each node in obj. Return each node in obj which matches all validators. """ results = [] for node in object_iter(obj): if all([validate(node) for validate in validators]): ...
Sends ICMP echo requests to destination dst count times. Returns a deferred which fires when responses are finished.
def ping(dst, count, inter=0.2, maxwait=1000, size=64): """Sends ICMP echo requests to destination `dst` `count` times. Returns a deferred which fires when responses are finished. """ def _then(result, p): p.stopListening() return result d = defer.Deferred() p = ICMPPort(0, ICMP...
Make an HTTP request and return the body
def getBody(self, url, method='GET', headers={}, data=None, socket=None): """Make an HTTP request and return the body """ if not 'User-Agent' in headers: headers['User-Agent'] = ['Tensor HTTP checker'] return self.request(url, method, headers, data, socket)
Expire any items in the cache older than age seconds
def expire(self, age): """Expire any items in the cache older than `age` seconds""" now = time.time() cache = self._acquire_cache() expired = [k for k, v in cache.items() if (now - v[0]) > age] for k in expired: if k in cache: del cache[k] ...
Set a key k to value v
def set(self, k, v): """Set a key `k` to value `v`""" self.store[k] = (time.time(), v) self._persist()
Returns key contents and modify time
def get(self, k): """Returns key contents, and modify time""" if self._changed(): self._read() if k in self.store: return tuple(self.store[k]) else: return None
Return True if key k exists
def contains(self, k): """Return True if key `k` exists""" if self._changed(): self._read() return k in self.store.keys()
Given a record timestamp verify the chain integrity.
def chain_check(cls, timestamp: int) -> bool: """ Given a record timestamp, verify the chain integrity. :param timestamp: UNIX time / POSIX time / Epoch time :return: 'True' if the timestamp fits the chain. 'False' otherwise. """ # Creation is messy. # You want ...
Get the first ( oldest ) record available. Since the first record IS a known value in the system we can load it from constants.
def get_first_record( cls, download: bool=True ) -> NistBeaconValue: """ Get the first (oldest) record available. Since the first record IS a known value in the system we can load it from constants. :param download: 'True' will always reach out to NIST to get...
Convert a string of JSON which represents a NIST randomness beacon value into a NistBeaconValue object.
def from_json(cls, input_json: str) -> 'NistBeaconValue': """ Convert a string of JSON which represents a NIST randomness beacon value into a 'NistBeaconValue' object. :param input_json: JSON to build a 'Nist RandomnessBeaconValue' from :return: A 'NistBeaconValue' object, 'None...
Convert a string of XML which represents a NIST Randomness Beacon value into a NistBeaconValue object.
def from_xml(cls, input_xml: str) -> 'NistBeaconValue': """ Convert a string of XML which represents a NIST Randomness Beacon value into a 'NistBeaconValue' object. :param input_xml: XML to build a 'NistBeaconValue' from :return: A 'NistBeaconValue' object, 'None' otherwise ...
Returns a minified version of the javascript content
def rendered_content(self): """Returns a 'minified' version of the javascript content""" template = self.resolve_template(self.template_name) if django.VERSION[1] < 8: if template.name.endswith('.min'): return super(MinifiedJsTemplateResponse, self).rendered_content ...
Passes each parsed log line to fn This is a better idea than storing a giant log file in memory
def get_fn(self, fn, max_lines=None): """Passes each parsed log line to `fn` This is a better idea than storing a giant log file in memory """ stat = os.stat(self.logfile) if (stat.st_ino == self.lastInode) and (stat.st_size == self.lastSize): # Nothing new ...
Returns a big list of all log lines since the last run
def get(self, max_lines=None): """Returns a big list of all log lines since the last run """ rows = [] self.get_fn(lambda row: rows.append(row), max_lines=max_lines) return rows
Create a token referencing the object id with extra data.
def create_token(self, obj_id, extra_data): """Create a token referencing the object id with extra data. Note random data is added to ensure that no two tokens are identical. """ return self.dumps( dict( id=obj_id, data=extra_data, ...
Validate secret link token.
def validate_token(self, token, expected_data=None): """Validate secret link token. :param token: Token value. :param expected_data: A dictionary of key/values that must be present in the data part of the token (i.e. included via ``extra_data`` in ``create_token``). ...
Load data in a token.
def load_token(self, token, force=False): """Load data in a token. :param token: Token to load. :param force: Load token data even if signature expired. Default: False. """ try: data = self.loads(token) except SignatureExpired as e: ...
Get cryptographic engine.
def engine(self): """Get cryptographic engine.""" if not hasattr(self, '_engine'): from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes digest = hashes.Hash(hashe...
Create a token referencing the object id with extra data.
def create_token(self, obj_id, extra_data): """Create a token referencing the object id with extra data.""" return self.engine.encrypt( super(EncryptedTokenMixIn, self).create_token(obj_id, extra_data) )
Load data in a token.
def load_token(self, token, force=False): """Load data in a token. :param token: Token to load. :param force: Load token data even if signature expired. Default: False. """ return super(EncryptedTokenMixIn, self).load_token( self.engine.decrypt(...
Multiple algorithm - compatible token validation.
def compat_validate_token(cls, *args, **kwargs): """Multiple algorithm-compatible token validation.""" data = None for algorithm in SUPPORTED_DIGEST_ALGORITHMS: data = cls(algorithm_name=algorithm).validate_token( *args, **kwargs) if not data: # move to n...
Create the secret link token.
def create_token(cls, obj_id, data, expires_at=None): """Create the secret link token.""" if expires_at: s = TimedSecretLinkSerializer(expires_at=expires_at) else: s = SecretLinkSerializer() return s.create_token(obj_id, data)
Validate a secret link token ( non - expiring + expiring ).
def validate_token(cls, token, expected_data=None): """Validate a secret link token (non-expiring + expiring).""" for algorithm in SUPPORTED_DIGEST_ALGORITHMS: s = SecretLinkSerializer(algorithm_name=algorithm) st = TimedSecretLinkSerializer(algorithm_name=algorithm) ...
Validate a secret link token ( non - expiring + expiring ).
def load_token(cls, token, force=False): """Validate a secret link token (non-expiring + expiring).""" for algorithm in SUPPORTED_DIGEST_ALGORITHMS: s = SecretLinkSerializer(algorithm_name=algorithm) st = TimedSecretLinkSerializer(algorithm_name=algorithm) for seriali...
32bit counter aggregator with wrapping
def Counter32(a, b, delta): """32bit counter aggregator with wrapping """ if b < a: c = 4294967295 - a return (c + b) / float(delta) return (b - a) / float(delta)
64bit counter aggregator with wrapping
def Counter64(a, b, delta): """64bit counter aggregator with wrapping """ if b < a: c = 18446744073709551615 - a return (c + b) / float(delta) return (b - a) / float(delta)
Counter derivative
def Counter(a, b, delta): """Counter derivative """ if b < a: return None return (b - a) / float(delta)
Method to calculate and format an average duration safely
def average_duration(total_duration, visits): """ Method to calculate and format an average duration safely """ if not visits: seconds = 0 else: seconds = int(round(total_duration / Decimal(visits))) duration = timedelta(seconds=seconds) return str(duration)
Setup output processors
def setupOutputs(self, config): """Setup output processors""" if self.proto == 'tcp': defaultOutput = { 'output': 'tensor.outputs.riemann.RiemannTCP', 'server': self.server, 'port': self.port } else: defaultOutp...
Sets up source objects from the given config
def setupSources(self, config): """Sets up source objects from the given config""" sources = config.get('sources', []) for source in sources: src = self.createSource(source) self.setupTriggers(source, src) self.sources.append(src)
Callback that all event sources call when they have a new event or list of events
def sendEvent(self, source, events): """Callback that all event sources call when they have a new event or list of events """ if isinstance(events, list): self.eventCounter += len(events) else: self.eventCounter += 1 events = [events] ...
Watchdog timer function.
def sourceWatchdog(self): """Watchdog timer function. Recreates sources which have not generated events in 10*interval if they have watchdog set to true in their configuration """ for i, source in enumerate(self.sources): if not source.config.get('watchdog', False):...
Converts the input format to a regular expression as well as extracting fields
def _parse_format(self, format): """ Converts the input format to a regular expression, as well as extracting fields Raises an exception if it couldn't compile the generated regex. """ format = format.strip() format = re.sub('[ \t]+',' ',format) ...
Parses a single line from the log file and returns a dictionary of it s contents.
def parse(self, line): """ Parses a single line from the log file and returns a dictionary of it's contents. Raises and exception if it couldn't parse the line """ line = line.strip() match = self._regex.match(line) if match: data = {...
Validate that date is in the future.
def validate_expires_at(form, field): """Validate that date is in the future.""" if form.accept.data: if not field.data or datetime.utcnow().date() >= field.data: raise validators.StopValidation(_( "Please provide a future date." )) if not field.data or \ ...
Validate that accept have not been set.
def validate_accept(form, field): """Validate that accept have not been set.""" if field.data and form.reject.data: raise validators.ValidationError( _("Both reject and accept cannot be set at the same time.") )
Validate that accept have not been set.
def validate_reject(form, field): """Validate that accept have not been set.""" if field.data and form.accept.data: raise validators.ValidationError( _("Both reject and accept cannot be set at the same time.") )
Validate message.
def validate_message(form, field): """Validate message.""" if form.reject.data and not field.data.strip(): raise validators.ValidationError( _("You are required to provide message to the requester when" " you reject a request.") )
Verify token and save in session if it s valid.
def verify_token(): """Verify token and save in session if it's valid.""" try: from .models import SecretLink token = request.args['token'] # if the token is valid if token and SecretLink.validate_token(token, {}): # then save in session the token session[...
Flask application initialization.
def init_app(self, app): """Flask application initialization.""" app.before_request(verify_token) self.init_config(app) state = _AppState(app=app) app.extensions['zenodo-accessrequests'] = state
Return a basic meaningful name based on device type
def name(self): """ Return a basic meaningful name based on device type """ if ( self.device_type and self.device_type.code in (DeviceType.MOBILE, DeviceType.TABLET) ): return self.device else: return self.browser