repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
numberoverzero/bloop
bloop/conditions.py
ReferenceTracker._value_ref
def _value_ref(self, column, value, *, dumped=False, inner=False): """inner=True uses column.typedef.inner_type instead of column.typedef""" ref = ":v{}".format(self.next_index) # Need to dump this value if not dumped: typedef = column.typedef for segment in path...
python
def _value_ref(self, column, value, *, dumped=False, inner=False): """inner=True uses column.typedef.inner_type instead of column.typedef""" ref = ":v{}".format(self.next_index) # Need to dump this value if not dumped: typedef = column.typedef for segment in path...
[ "def", "_value_ref", "(", "self", ",", "column", ",", "value", ",", "*", ",", "dumped", "=", "False", ",", "inner", "=", "False", ")", ":", "ref", "=", "\":v{}\"", ".", "format", "(", "self", ".", "next_index", ")", "# Need to dump this value", "if", "...
inner=True uses column.typedef.inner_type instead of column.typedef
[ "inner", "=", "True", "uses", "column", ".", "typedef", ".", "inner_type", "instead", "of", "column", ".", "typedef" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L166-L181
numberoverzero/bloop
bloop/conditions.py
ReferenceTracker.any_ref
def any_ref(self, *, column, value=missing, dumped=False, inner=False): """Returns a NamedTuple of (name, type, value) for any type of reference. .. code-block:: python # Name ref >>> tracker.any_ref(column=User.email) Reference(name='email', type='name', value=None...
python
def any_ref(self, *, column, value=missing, dumped=False, inner=False): """Returns a NamedTuple of (name, type, value) for any type of reference. .. code-block:: python # Name ref >>> tracker.any_ref(column=User.email) Reference(name='email', type='name', value=None...
[ "def", "any_ref", "(", "self", ",", "*", ",", "column", ",", "value", "=", "missing", ",", "dumped", "=", "False", ",", "inner", "=", "False", ")", ":", "# Can't use None since it's a legal value for comparisons (attribute_not_exists)", "if", "value", "is", "missi...
Returns a NamedTuple of (name, type, value) for any type of reference. .. code-block:: python # Name ref >>> tracker.any_ref(column=User.email) Reference(name='email', type='name', value=None) # Value ref >>> tracker.any_ref(column=User.email, value...
[ "Returns", "a", "NamedTuple", "of", "(", "name", "type", "value", ")", "for", "any", "type", "of", "reference", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L183-L227
numberoverzero/bloop
bloop/conditions.py
ReferenceTracker.pop_refs
def pop_refs(self, *refs): """Decrement the usage of each ref by 1. If this was the last use of a ref, remove it from attr_names or attr_values. """ for ref in refs: name = ref.name count = self.counts[name] # Not tracking this ref if coun...
python
def pop_refs(self, *refs): """Decrement the usage of each ref by 1. If this was the last use of a ref, remove it from attr_names or attr_values. """ for ref in refs: name = ref.name count = self.counts[name] # Not tracking this ref if coun...
[ "def", "pop_refs", "(", "self", ",", "*", "refs", ")", ":", "for", "ref", "in", "refs", ":", "name", "=", "ref", ".", "name", "count", "=", "self", ".", "counts", "[", "name", "]", "# Not tracking this ref", "if", "count", "<", "1", ":", "continue", ...
Decrement the usage of each ref by 1. If this was the last use of a ref, remove it from attr_names or attr_values.
[ "Decrement", "the", "usage", "of", "each", "ref", "by", "1", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L229-L253
numberoverzero/bloop
bloop/conditions.py
ConditionRenderer.render
def render(self, obj=None, condition=None, atomic=False, update=False, filter=None, projection=None, key=None): """Main entry point for rendering multiple expressions. All parameters are optional, except obj when atomic or update are True. :param obj: *(Optional)* An object to render an atomic...
python
def render(self, obj=None, condition=None, atomic=False, update=False, filter=None, projection=None, key=None): """Main entry point for rendering multiple expressions. All parameters are optional, except obj when atomic or update are True. :param obj: *(Optional)* An object to render an atomic...
[ "def", "render", "(", "self", ",", "obj", "=", "None", ",", "condition", "=", "None", ",", "atomic", "=", "False", ",", "update", "=", "False", ",", "filter", "=", "None", ",", "projection", "=", "None", ",", "key", "=", "None", ")", ":", "if", "...
Main entry point for rendering multiple expressions. All parameters are optional, except obj when atomic or update are True. :param obj: *(Optional)* An object to render an atomic condition or update expression for. Required if update or atomic are true. Default is False. :param ...
[ "Main", "entry", "point", "for", "rendering", "multiple", "expressions", ".", "All", "parameters", "are", "optional", "except", "obj", "when", "atomic", "or", "update", "are", "True", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L299-L339
numberoverzero/bloop
bloop/conditions.py
ConditionRenderer.rendered
def rendered(self): """The rendered wire format for all conditions that have been rendered. Rendered conditions are never cleared. A new :class:`~bloop.conditions.ConditionRenderer` should be used for each operation.""" expressions = {k: v for (k, v) in self.expressions.items() if v is not Non...
python
def rendered(self): """The rendered wire format for all conditions that have been rendered. Rendered conditions are never cleared. A new :class:`~bloop.conditions.ConditionRenderer` should be used for each operation.""" expressions = {k: v for (k, v) in self.expressions.items() if v is not Non...
[ "def", "rendered", "(", "self", ")", ":", "expressions", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "self", ".", "expressions", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "if", "self", ".", "refs", ".", "...
The rendered wire format for all conditions that have been rendered. Rendered conditions are never cleared. A new :class:`~bloop.conditions.ConditionRenderer` should be used for each operation.
[ "The", "rendered", "wire", "format", "for", "all", "conditions", "that", "have", "been", "rendered", ".", "Rendered", "conditions", "are", "never", "cleared", ".", "A", "new", ":", "class", ":", "~bloop", ".", "conditions", ".", "ConditionRenderer", "should", ...
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L388-L396
numberoverzero/bloop
bloop/stream/stream.py
Stream._unpack
def _unpack(self, record, key, expected): """Replaces the attr dict at the given key with an instance of a Model""" attrs = record.get(key) if attrs is None: return obj = unpack_from_dynamodb( attrs=attrs, expected=expected, model=self.mode...
python
def _unpack(self, record, key, expected): """Replaces the attr dict at the given key with an instance of a Model""" attrs = record.get(key) if attrs is None: return obj = unpack_from_dynamodb( attrs=attrs, expected=expected, model=self.mode...
[ "def", "_unpack", "(", "self", ",", "record", ",", "key", ",", "expected", ")", ":", "attrs", "=", "record", ".", "get", "(", "key", ")", "if", "attrs", "is", "None", ":", "return", "obj", "=", "unpack_from_dynamodb", "(", "attrs", "=", "attrs", ",",...
Replaces the attr dict at the given key with an instance of a Model
[ "Replaces", "the", "attr", "dict", "at", "the", "given", "key", "with", "an", "instance", "of", "a", "Model" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/stream.py#L79-L91
numberoverzero/bloop
bloop/stream/shard.py
reformat_record
def reformat_record(record): """Repack a record into a cleaner structure for consumption.""" return { "key": record["dynamodb"].get("Keys", None), "new": record["dynamodb"].get("NewImage", None), "old": record["dynamodb"].get("OldImage", None), "meta": { "created_at"...
python
def reformat_record(record): """Repack a record into a cleaner structure for consumption.""" return { "key": record["dynamodb"].get("Keys", None), "new": record["dynamodb"].get("NewImage", None), "old": record["dynamodb"].get("OldImage", None), "meta": { "created_at"...
[ "def", "reformat_record", "(", "record", ")", ":", "return", "{", "\"key\"", ":", "record", "[", "\"dynamodb\"", "]", ".", "get", "(", "\"Keys\"", ",", "None", ")", ",", "\"new\"", ":", "record", "[", "\"dynamodb\"", "]", ".", "get", "(", "\"NewImage\"",...
Repack a record into a cleaner structure for consumption.
[ "Repack", "a", "record", "into", "a", "cleaner", "structure", "for", "consumption", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L287-L303
numberoverzero/bloop
bloop/stream/shard.py
unpack_shards
def unpack_shards(shards, stream_arn, session): """List[Dict] -> Dict[shard_id, Shard]. Each Shards' parent/children are hooked up with the other Shards in the list. """ if not shards: return {} # When unpacking tokens, shard id key is "shard_id" # When unpacking DescribeStream respons...
python
def unpack_shards(shards, stream_arn, session): """List[Dict] -> Dict[shard_id, Shard]. Each Shards' parent/children are hooked up with the other Shards in the list. """ if not shards: return {} # When unpacking tokens, shard id key is "shard_id" # When unpacking DescribeStream respons...
[ "def", "unpack_shards", "(", "shards", ",", "stream_arn", ",", "session", ")", ":", "if", "not", "shards", ":", "return", "{", "}", "# When unpacking tokens, shard id key is \"shard_id\"", "# When unpacking DescribeStream responses, shard id key is \"ShardId\"", "if", "\"Shar...
List[Dict] -> Dict[shard_id, Shard]. Each Shards' parent/children are hooked up with the other Shards in the list.
[ "List", "[", "Dict", "]", "-", ">", "Dict", "[", "shard_id", "Shard", "]", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L306-L329
numberoverzero/bloop
bloop/stream/shard.py
Shard.token
def token(self): """JSON-serializable representation of the current Shard state. The token is enough to rebuild the Shard as part of rebuilding a Stream. :returns: Shard state as a json-friendly dict :rtype: dict """ if self.iterator_type in RELATIVE_ITERATORS: ...
python
def token(self): """JSON-serializable representation of the current Shard state. The token is enough to rebuild the Shard as part of rebuilding a Stream. :returns: Shard state as a json-friendly dict :rtype: dict """ if self.iterator_type in RELATIVE_ITERATORS: ...
[ "def", "token", "(", "self", ")", ":", "if", "self", ".", "iterator_type", "in", "RELATIVE_ITERATORS", ":", "logger", ".", "warning", "(", "\"creating shard token at non-exact location \\\"{}\\\"\"", ".", "format", "(", "self", ".", "iterator_type", ")", ")", "tok...
JSON-serializable representation of the current Shard state. The token is enough to rebuild the Shard as part of rebuilding a Stream. :returns: Shard state as a json-friendly dict :rtype: dict
[ "JSON", "-", "serializable", "representation", "of", "the", "current", "Shard", "state", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L127-L149
numberoverzero/bloop
bloop/stream/shard.py
Shard.walk_tree
def walk_tree(self): """Generator that yields each :class:`~bloop.stream.shard.Shard` by walking the shard's children in order.""" shards = collections.deque([self]) while shards: shard = shards.popleft() yield shard shards.extend(shard.children)
python
def walk_tree(self): """Generator that yields each :class:`~bloop.stream.shard.Shard` by walking the shard's children in order.""" shards = collections.deque([self]) while shards: shard = shards.popleft() yield shard shards.extend(shard.children)
[ "def", "walk_tree", "(", "self", ")", ":", "shards", "=", "collections", ".", "deque", "(", "[", "self", "]", ")", "while", "shards", ":", "shard", "=", "shards", ".", "popleft", "(", ")", "yield", "shard", "shards", ".", "extend", "(", "shard", ".",...
Generator that yields each :class:`~bloop.stream.shard.Shard` by walking the shard's children in order.
[ "Generator", "that", "yields", "each", ":", "class", ":", "~bloop", ".", "stream", ".", "shard", ".", "Shard", "by", "walking", "the", "shard", "s", "children", "in", "order", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L151-L157
numberoverzero/bloop
bloop/stream/shard.py
Shard.jump_to
def jump_to(self, *, iterator_type, sequence_number=None): """Move to a new position in the shard using the standard parameters to GetShardIterator. :param str iterator_type: "trim_horizon", "at_sequence", "after_sequence", "latest" :param str sequence_number: *(Optional)* Sequence number to us...
python
def jump_to(self, *, iterator_type, sequence_number=None): """Move to a new position in the shard using the standard parameters to GetShardIterator. :param str iterator_type: "trim_horizon", "at_sequence", "after_sequence", "latest" :param str sequence_number: *(Optional)* Sequence number to us...
[ "def", "jump_to", "(", "self", ",", "*", ",", "iterator_type", ",", "sequence_number", "=", "None", ")", ":", "# Just a simple wrapper; let the caller handle RecordsExpired", "self", ".", "iterator_id", "=", "self", ".", "session", ".", "get_shard_iterator", "(", "s...
Move to a new position in the shard using the standard parameters to GetShardIterator. :param str iterator_type: "trim_horizon", "at_sequence", "after_sequence", "latest" :param str sequence_number: *(Optional)* Sequence number to use with at/after sequence. Default is None.
[ "Move", "to", "a", "new", "position", "in", "the", "shard", "using", "the", "standard", "parameters", "to", "GetShardIterator", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L159-L173
numberoverzero/bloop
bloop/stream/shard.py
Shard.seek_to
def seek_to(self, position): """Move the Shard's iterator to the earliest record after the :class:`~datetime.datetime` time. Returns the first records at or past ``position``. If the list is empty, the seek failed to find records, either because the Shard is exhausted or it reached the...
python
def seek_to(self, position): """Move the Shard's iterator to the earliest record after the :class:`~datetime.datetime` time. Returns the first records at or past ``position``. If the list is empty, the seek failed to find records, either because the Shard is exhausted or it reached the...
[ "def", "seek_to", "(", "self", ",", "position", ")", ":", "# 0) We have no way to associate the date with a position,", "# so we have to scan the shard from the beginning.", "self", ".", "jump_to", "(", "iterator_type", "=", "\"trim_horizon\"", ")", "position", "=", "int",...
Move the Shard's iterator to the earliest record after the :class:`~datetime.datetime` time. Returns the first records at or past ``position``. If the list is empty, the seek failed to find records, either because the Shard is exhausted or it reached the HEAD of an open Shard. :param ...
[ "Move", "the", "Shard", "s", "iterator", "to", "the", "earliest", "record", "after", "the", ":", "class", ":", "~datetime", ".", "datetime", "time", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L175-L204
numberoverzero/bloop
bloop/stream/shard.py
Shard.load_children
def load_children(self): """If the Shard doesn't have any children, tries to find some from DescribeStream. If the Shard is open this won't find any children, so an empty response doesn't mean the Shard will **never** have children. """ # Child count is fixed the first time any ...
python
def load_children(self): """If the Shard doesn't have any children, tries to find some from DescribeStream. If the Shard is open this won't find any children, so an empty response doesn't mean the Shard will **never** have children. """ # Child count is fixed the first time any ...
[ "def", "load_children", "(", "self", ")", ":", "# Child count is fixed the first time any of the following happen:", "# 0 :: stream closed or throughput decreased", "# 1 :: shard was open for ~4 hours", "# 2 :: throughput increased", "if", "self", ".", "children", ":", "return", "sel...
If the Shard doesn't have any children, tries to find some from DescribeStream. If the Shard is open this won't find any children, so an empty response doesn't mean the Shard will **never** have children.
[ "If", "the", "Shard", "doesn", "t", "have", "any", "children", "tries", "to", "find", "some", "from", "DescribeStream", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L206-L250
numberoverzero/bloop
bloop/stream/shard.py
Shard.get_records
def get_records(self): """Get the next set of records in this shard. An empty list doesn't guarantee the shard is exhausted. :returns: A list of reformatted records. May be empty. """ # Won't be able to find new records. if self.exhausted: return [] # Alre...
python
def get_records(self): """Get the next set of records in this shard. An empty list doesn't guarantee the shard is exhausted. :returns: A list of reformatted records. May be empty. """ # Won't be able to find new records. if self.exhausted: return [] # Alre...
[ "def", "get_records", "(", "self", ")", ":", "# Won't be able to find new records.", "if", "self", ".", "exhausted", ":", "return", "[", "]", "# Already caught up, just the one call please.", "if", "self", ".", "empty_responses", ">=", "CALLS_TO_REACH_HEAD", ":", "retur...
Get the next set of records in this shard. An empty list doesn't guarantee the shard is exhausted. :returns: A list of reformatted records. May be empty.
[ "Get", "the", "next", "set", "of", "records", "in", "this", "shard", ".", "An", "empty", "list", "doesn", "t", "guarantee", "the", "shard", "is", "exhausted", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/shard.py#L252-L271
numberoverzero/bloop
bloop/engine.py
Engine.bind
def bind(self, model, *, skip_table_setup=False): """Create backing tables for a model and its non-abstract subclasses. :param model: Base model to bind. Can be abstract. :param skip_table_setup: Don't create or verify the table in DynamoDB. Default is False. :raises bloop.exceptions....
python
def bind(self, model, *, skip_table_setup=False): """Create backing tables for a model and its non-abstract subclasses. :param model: Base model to bind. Can be abstract. :param skip_table_setup: Don't create or verify the table in DynamoDB. Default is False. :raises bloop.exceptions....
[ "def", "bind", "(", "self", ",", "model", ",", "*", ",", "skip_table_setup", "=", "False", ")", ":", "# Make sure we're looking at models", "validate_is_model", "(", "model", ")", "concrete", "=", "set", "(", "filter", "(", "lambda", "m", ":", "not", "m", ...
Create backing tables for a model and its non-abstract subclasses. :param model: Base model to bind. Can be abstract. :param skip_table_setup: Don't create or verify the table in DynamoDB. Default is False. :raises bloop.exceptions.InvalidModel: if ``model`` is not a subclass of :class:`~bloo...
[ "Create", "backing", "tables", "for", "a", "model", "and", "its", "non", "-", "abstract", "subclasses", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L115-L165
numberoverzero/bloop
bloop/engine.py
Engine.delete
def delete(self, *objs, condition=None, atomic=False): """Delete one or more objects. :param objs: objects to delete. :param condition: only perform each delete if this condition holds. :param bool atomic: only perform each delete if the local and DynamoDB versions of the object match. ...
python
def delete(self, *objs, condition=None, atomic=False): """Delete one or more objects. :param objs: objects to delete. :param condition: only perform each delete if this condition holds. :param bool atomic: only perform each delete if the local and DynamoDB versions of the object match. ...
[ "def", "delete", "(", "self", ",", "*", "objs", ",", "condition", "=", "None", ",", "atomic", "=", "False", ")", ":", "objs", "=", "set", "(", "objs", ")", "validate_not_abstract", "(", "*", "objs", ")", "for", "obj", "in", "objs", ":", "self", "."...
Delete one or more objects. :param objs: objects to delete. :param condition: only perform each delete if this condition holds. :param bool atomic: only perform each delete if the local and DynamoDB versions of the object match. :raises bloop.exceptions.ConstraintViolation: if the condi...
[ "Delete", "one", "or", "more", "objects", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L167-L184
numberoverzero/bloop
bloop/engine.py
Engine.load
def load(self, *objs, consistent=False): """Populate objects from DynamoDB. :param objs: objects to delete. :param bool consistent: Use `strongly consistent reads`__ if True. Default is False. :raises bloop.exceptions.MissingKey: if any object doesn't provide a value for a key column. ...
python
def load(self, *objs, consistent=False): """Populate objects from DynamoDB. :param objs: objects to delete. :param bool consistent: Use `strongly consistent reads`__ if True. Default is False. :raises bloop.exceptions.MissingKey: if any object doesn't provide a value for a key column. ...
[ "def", "load", "(", "self", ",", "*", "objs", ",", "consistent", "=", "False", ")", ":", "get_table_name", "=", "self", ".", "_compute_table_name", "objs", "=", "set", "(", "objs", ")", "validate_not_abstract", "(", "*", "objs", ")", "table_index", ",", ...
Populate objects from DynamoDB. :param objs: objects to delete. :param bool consistent: Use `strongly consistent reads`__ if True. Default is False. :raises bloop.exceptions.MissingKey: if any object doesn't provide a value for a key column. :raises bloop.exceptions.MissingObjects: if ...
[ "Populate", "objects", "from", "DynamoDB", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L186-L239
numberoverzero/bloop
bloop/engine.py
Engine.query
def query(self, model_or_index, key, filter=None, projection="all", consistent=False, forward=True): """Create a reusable :class:`~bloop.search.QueryIterator`. :param model_or_index: A model or index to query. For example, ``User`` or ``User.by_email``. :param key: Key condition. ...
python
def query(self, model_or_index, key, filter=None, projection="all", consistent=False, forward=True): """Create a reusable :class:`~bloop.search.QueryIterator`. :param model_or_index: A model or index to query. For example, ``User`` or ``User.by_email``. :param key: Key condition. ...
[ "def", "query", "(", "self", ",", "model_or_index", ",", "key", ",", "filter", "=", "None", ",", "projection", "=", "\"all\"", ",", "consistent", "=", "False", ",", "forward", "=", "True", ")", ":", "if", "isinstance", "(", "model_or_index", ",", "Index"...
Create a reusable :class:`~bloop.search.QueryIterator`. :param model_or_index: A model or index to query. For example, ``User`` or ``User.by_email``. :param key: Key condition. This must include an equality against the hash key, and optionally one of a restricted set of condit...
[ "Create", "a", "reusable", ":", "class", ":", "~bloop", ".", "search", ".", "QueryIterator", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L241-L268
numberoverzero/bloop
bloop/engine.py
Engine.save
def save(self, *objs, condition=None, atomic=False): """Save one or more objects. :param objs: objects to save. :param condition: only perform each save if this condition holds. :param bool atomic: only perform each save if the local and DynamoDB versions of the object match. :r...
python
def save(self, *objs, condition=None, atomic=False): """Save one or more objects. :param objs: objects to save. :param condition: only perform each save if this condition holds. :param bool atomic: only perform each save if the local and DynamoDB versions of the object match. :r...
[ "def", "save", "(", "self", ",", "*", "objs", ",", "condition", "=", "None", ",", "atomic", "=", "False", ")", ":", "objs", "=", "set", "(", "objs", ")", "validate_not_abstract", "(", "*", "objs", ")", "for", "obj", "in", "objs", ":", "self", ".", ...
Save one or more objects. :param objs: objects to save. :param condition: only perform each save if this condition holds. :param bool atomic: only perform each save if the local and DynamoDB versions of the object match. :raises bloop.exceptions.ConstraintViolation: if the condition (or...
[ "Save", "one", "or", "more", "objects", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L270-L287
numberoverzero/bloop
bloop/engine.py
Engine.scan
def scan(self, model_or_index, filter=None, projection="all", consistent=False, parallel=None): """Create a reusable :class:`~bloop.search.ScanIterator`. :param model_or_index: A model or index to scan. For example, ``User`` or ``User.by_email``. :param filter: Filter condition. Only matching...
python
def scan(self, model_or_index, filter=None, projection="all", consistent=False, parallel=None): """Create a reusable :class:`~bloop.search.ScanIterator`. :param model_or_index: A model or index to scan. For example, ``User`` or ``User.by_email``. :param filter: Filter condition. Only matching...
[ "def", "scan", "(", "self", ",", "model_or_index", ",", "filter", "=", "None", ",", "projection", "=", "\"all\"", ",", "consistent", "=", "False", ",", "parallel", "=", "None", ")", ":", "if", "isinstance", "(", "model_or_index", ",", "Index", ")", ":", ...
Create a reusable :class:`~bloop.search.ScanIterator`. :param model_or_index: A model or index to scan. For example, ``User`` or ``User.by_email``. :param filter: Filter condition. Only matching objects will be included in the results. :param projection: "all", "count", a list of ...
[ "Create", "a", "reusable", ":", "class", ":", "~bloop", ".", "search", ".", "ScanIterator", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L289-L314
numberoverzero/bloop
bloop/engine.py
Engine.stream
def stream(self, model, position): """Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering. .. code-block:: pycon # Create a user so we have a record >>> engine = Engine() >>> user = User(id=3, email="user@domain.com") ...
python
def stream(self, model, position): """Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering. .. code-block:: pycon # Create a user so we have a record >>> engine = Engine() >>> user = User(id=3, email="user@domain.com") ...
[ "def", "stream", "(", "self", ",", "model", ",", "position", ")", ":", "validate_not_abstract", "(", "model", ")", "if", "not", "model", ".", "Meta", ".", "stream", "or", "not", "model", ".", "Meta", ".", "stream", ".", "get", "(", "\"arn\"", ")", ":...
Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering. .. code-block:: pycon # Create a user so we have a record >>> engine = Engine() >>> user = User(id=3, email="user@domain.com") >>> engine.save(user) >>> user.ema...
[ "Create", "a", ":", "class", ":", "~bloop", ".", "stream", ".", "Stream", "that", "provides", "approximate", "chronological", "ordering", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L316-L355
numberoverzero/bloop
bloop/engine.py
Engine.transaction
def transaction(self, mode="w"): """ Create a new :class:`~bloop.transactions.ReadTransaction` or :class:`~bloop.transactions.WriteTransaction`. As a context manager, calling commit when the block exits: .. code-block:: pycon >>> engine = Engine() >>> user = Us...
python
def transaction(self, mode="w"): """ Create a new :class:`~bloop.transactions.ReadTransaction` or :class:`~bloop.transactions.WriteTransaction`. As a context manager, calling commit when the block exits: .. code-block:: pycon >>> engine = Engine() >>> user = Us...
[ "def", "transaction", "(", "self", ",", "mode", "=", "\"w\"", ")", ":", "if", "mode", "==", "\"r\"", ":", "cls", "=", "ReadTransaction", "elif", "mode", "==", "\"w\"", ":", "cls", "=", "WriteTransaction", "else", ":", "raise", "ValueError", "(", "f\"unkn...
Create a new :class:`~bloop.transactions.ReadTransaction` or :class:`~bloop.transactions.WriteTransaction`. As a context manager, calling commit when the block exits: .. code-block:: pycon >>> engine = Engine() >>> user = User(id=3, email="user@domain.com") >>> twe...
[ "Create", "a", "new", ":", "class", ":", "~bloop", ".", "transactions", ".", "ReadTransaction", "or", ":", "class", ":", "~bloop", ".", "transactions", ".", "WriteTransaction", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/engine.py#L357-L394
numberoverzero/bloop
bloop/types.py
Type._dump
def _dump(self, value, **kwargs): """Entry point for serializing values. Most custom types should use :func:`~bloop.types.Type.dynamo_dump`. This wraps the return value of :func:`~bloop.types.Type.dynamo_dump` in DynamoDB's wire format. For example, serializing a string enum to an int: ...
python
def _dump(self, value, **kwargs): """Entry point for serializing values. Most custom types should use :func:`~bloop.types.Type.dynamo_dump`. This wraps the return value of :func:`~bloop.types.Type.dynamo_dump` in DynamoDB's wire format. For example, serializing a string enum to an int: ...
[ "def", "_dump", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "value", "=", "self", ".", "dynamo_dump", "(", "value", ",", "*", "*", "kwargs", ")", "if", "value", "is", "None", ":", "return", "value", "return", "{", "self", ".", "...
Entry point for serializing values. Most custom types should use :func:`~bloop.types.Type.dynamo_dump`. This wraps the return value of :func:`~bloop.types.Type.dynamo_dump` in DynamoDB's wire format. For example, serializing a string enum to an int: .. code-block:: python value =...
[ "Entry", "point", "for", "serializing", "values", ".", "Most", "custom", "types", "should", "use", ":", "func", ":", "~bloop", ".", "types", ".", "Type", ".", "dynamo_dump", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/types.py#L101-L120
numberoverzero/bloop
bloop/types.py
Type._load
def _load(self, value, **kwargs): """Entry point for deserializing values. Most custom types should use :func:`~bloop.types.Type.dynamo_load`. This unpacks DynamoDB's wire format and calls :func:`~bloop.types.Type.dynamo_load` on the inner value. For example, deserializing an int to a string e...
python
def _load(self, value, **kwargs): """Entry point for deserializing values. Most custom types should use :func:`~bloop.types.Type.dynamo_load`. This unpacks DynamoDB's wire format and calls :func:`~bloop.types.Type.dynamo_load` on the inner value. For example, deserializing an int to a string e...
[ "def", "_load", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "if", "value", "is", "not", "None", ":", "value", "=", "next", "(", "iter", "(", "value", ".", "values", "(", ")", ")", ")", "return", "self", ".", "dynamo_load", "(", ...
Entry point for deserializing values. Most custom types should use :func:`~bloop.types.Type.dynamo_load`. This unpacks DynamoDB's wire format and calls :func:`~bloop.types.Type.dynamo_load` on the inner value. For example, deserializing an int to a string enum: .. code-block:: python ...
[ "Entry", "point", "for", "deserializing", "values", ".", "Most", "custom", "types", "should", "use", ":", "func", ":", "~bloop", ".", "types", ".", "Type", ".", "dynamo_load", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/types.py#L122-L139
numberoverzero/bloop
bloop/types.py
DynamicType.backing_type_for
def backing_type_for(value): """Returns the DynamoDB backing type for a given python value's type :: 4 -> 'N' ['x', 3] -> 'L' {2, 4} -> 'SS' """ if isinstance(value, str): vtype = "S" elif isinstance(value, bytes): vty...
python
def backing_type_for(value): """Returns the DynamoDB backing type for a given python value's type :: 4 -> 'N' ['x', 3] -> 'L' {2, 4} -> 'SS' """ if isinstance(value, str): vtype = "S" elif isinstance(value, bytes): vty...
[ "def", "backing_type_for", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "vtype", "=", "\"S\"", "elif", "isinstance", "(", "value", ",", "bytes", ")", ":", "vtype", "=", "\"B\"", "# NOTE: numbers.Number check must come **AFTER...
Returns the DynamoDB backing type for a given python value's type :: 4 -> 'N' ['x', 3] -> 'L' {2, 4} -> 'SS'
[ "Returns", "the", "DynamoDB", "backing", "type", "for", "a", "given", "python", "value", "s", "type" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/types.py#L637-L674
numberoverzero/bloop
examples/replication.py
stream_replicate
def stream_replicate(): """Monitor changes in approximately real-time and replicate them""" stream = primary.stream(SomeDataBlob, "trim_horizon") next_heartbeat = pendulum.now() while True: now = pendulum.now() if now >= next_heartbeat: stream.heartbeat() next_hea...
python
def stream_replicate(): """Monitor changes in approximately real-time and replicate them""" stream = primary.stream(SomeDataBlob, "trim_horizon") next_heartbeat = pendulum.now() while True: now = pendulum.now() if now >= next_heartbeat: stream.heartbeat() next_hea...
[ "def", "stream_replicate", "(", ")", ":", "stream", "=", "primary", ".", "stream", "(", "SomeDataBlob", ",", "\"trim_horizon\"", ")", "next_heartbeat", "=", "pendulum", ".", "now", "(", ")", "while", "True", ":", "now", "=", "pendulum", ".", "now", "(", ...
Monitor changes in approximately real-time and replicate them
[ "Monitor", "changes", "in", "approximately", "real", "-", "time", "and", "replicate", "them" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/examples/replication.py#L42-L58
numberoverzero/bloop
bloop/stream/coordinator.py
_move_stream_endpoint
def _move_stream_endpoint(coordinator, position): """Move to the "trim_horizon" or "latest" of the entire stream.""" # 0) Everything will be rebuilt from DescribeStream. stream_arn = coordinator.stream_arn coordinator.roots.clear() coordinator.active.clear() coordinator.buffer.clear() # 1) ...
python
def _move_stream_endpoint(coordinator, position): """Move to the "trim_horizon" or "latest" of the entire stream.""" # 0) Everything will be rebuilt from DescribeStream. stream_arn = coordinator.stream_arn coordinator.roots.clear() coordinator.active.clear() coordinator.buffer.clear() # 1) ...
[ "def", "_move_stream_endpoint", "(", "coordinator", ",", "position", ")", ":", "# 0) Everything will be rebuilt from DescribeStream.", "stream_arn", "=", "coordinator", ".", "stream_arn", "coordinator", ".", "roots", ".", "clear", "(", ")", "coordinator", ".", "active",...
Move to the "trim_horizon" or "latest" of the entire stream.
[ "Move", "to", "the", "trim_horizon", "or", "latest", "of", "the", "entire", "stream", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/coordinator.py#L214-L240
numberoverzero/bloop
bloop/stream/coordinator.py
_move_stream_time
def _move_stream_time(coordinator, time): """Scan through the *entire* Stream for the first record after ``time``. This is an extremely expensive, naive algorithm that starts at trim_horizon and simply dumps records into the void until the first hit. General improvements in performance are tough; we c...
python
def _move_stream_time(coordinator, time): """Scan through the *entire* Stream for the first record after ``time``. This is an extremely expensive, naive algorithm that starts at trim_horizon and simply dumps records into the void until the first hit. General improvements in performance are tough; we c...
[ "def", "_move_stream_time", "(", "coordinator", ",", "time", ")", ":", "if", "time", ">", "datetime", ".", "datetime", ".", "now", "(", "datetime", ".", "timezone", ".", "utc", ")", ":", "_move_stream_endpoint", "(", "coordinator", ",", "\"latest\"", ")", ...
Scan through the *entire* Stream for the first record after ``time``. This is an extremely expensive, naive algorithm that starts at trim_horizon and simply dumps records into the void until the first hit. General improvements in performance are tough; we can use the fact that Shards have a max life of 24...
[ "Scan", "through", "the", "*", "entire", "*", "Stream", "for", "the", "first", "record", "after", "time", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/coordinator.py#L243-L271
numberoverzero/bloop
bloop/stream/coordinator.py
_move_stream_token
def _move_stream_token(coordinator, token): """Move to the Stream position described by the token. The following rules are applied when interpolation is required: - If a shard does not exist (past the trim_horizon) it is ignored. If that shard had children, its children are also checked against the ...
python
def _move_stream_token(coordinator, token): """Move to the Stream position described by the token. The following rules are applied when interpolation is required: - If a shard does not exist (past the trim_horizon) it is ignored. If that shard had children, its children are also checked against the ...
[ "def", "_move_stream_token", "(", "coordinator", ",", "token", ")", ":", "stream_arn", "=", "coordinator", ".", "stream_arn", "=", "token", "[", "\"stream_arn\"", "]", "# 0) Everything will be rebuilt from the DescribeStream masked by the token.", "coordinator", ".", "roots...
Move to the Stream position described by the token. The following rules are applied when interpolation is required: - If a shard does not exist (past the trim_horizon) it is ignored. If that shard had children, its children are also checked against the existing shards. - If none of the shards in the...
[ "Move", "to", "the", "Stream", "position", "described", "by", "the", "token", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/coordinator.py#L274-L328
numberoverzero/bloop
bloop/stream/coordinator.py
Coordinator.advance_shards
def advance_shards(self): """Poll active shards for records and insert them into the buffer. Rotate exhausted shards. Returns immediately if the buffer isn't empty. """ # Don't poll shards when there are pending records. if self.buffer: return # 0) Collect ...
python
def advance_shards(self): """Poll active shards for records and insert them into the buffer. Rotate exhausted shards. Returns immediately if the buffer isn't empty. """ # Don't poll shards when there are pending records. if self.buffer: return # 0) Collect ...
[ "def", "advance_shards", "(", "self", ")", ":", "# Don't poll shards when there are pending records.", "if", "self", ".", "buffer", ":", "return", "# 0) Collect new records from all active shards.", "record_shard_pairs", "=", "[", "]", "for", "shard", "in", "self", ".", ...
Poll active shards for records and insert them into the buffer. Rotate exhausted shards. Returns immediately if the buffer isn't empty.
[ "Poll", "active", "shards", "for", "records", "and", "insert", "them", "into", "the", "buffer", ".", "Rotate", "exhausted", "shards", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/coordinator.py#L77-L94
numberoverzero/bloop
bloop/stream/coordinator.py
Coordinator.heartbeat
def heartbeat(self): """Keep active shards with "trim_horizon", "latest" iterators alive by advancing their iterators.""" for shard in self.active: if shard.sequence_number is None: records = next(shard) # Success! This shard now has an ``at_sequence`` iterat...
python
def heartbeat(self): """Keep active shards with "trim_horizon", "latest" iterators alive by advancing their iterators.""" for shard in self.active: if shard.sequence_number is None: records = next(shard) # Success! This shard now has an ``at_sequence`` iterat...
[ "def", "heartbeat", "(", "self", ")", ":", "for", "shard", "in", "self", ".", "active", ":", "if", "shard", ".", "sequence_number", "is", "None", ":", "records", "=", "next", "(", "shard", ")", "# Success! This shard now has an ``at_sequence`` iterator", "if", ...
Keep active shards with "trim_horizon", "latest" iterators alive by advancing their iterators.
[ "Keep", "active", "shards", "with", "trim_horizon", "latest", "iterators", "alive", "by", "advancing", "their", "iterators", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/coordinator.py#L96-L104
numberoverzero/bloop
bloop/stream/coordinator.py
Coordinator.token
def token(self): """JSON-serializable representation of the current Stream state. Use :func:`Engine.stream(YourModel, token) <bloop.engine.Engine.stream>` to create an identical stream, or :func:`stream.move_to(token) <bloop.stream.Stream.move_to>` to move an existing stream to this position. ...
python
def token(self): """JSON-serializable representation of the current Stream state. Use :func:`Engine.stream(YourModel, token) <bloop.engine.Engine.stream>` to create an identical stream, or :func:`stream.move_to(token) <bloop.stream.Stream.move_to>` to move an existing stream to this position. ...
[ "def", "token", "(", "self", ")", ":", "# 0) Trace roots and active shards", "active_ids", "=", "[", "]", "shard_tokens", "=", "[", "]", "for", "root", "in", "self", ".", "roots", ":", "for", "shard", "in", "root", ".", "walk_tree", "(", ")", ":", "shard...
JSON-serializable representation of the current Stream state. Use :func:`Engine.stream(YourModel, token) <bloop.engine.Engine.stream>` to create an identical stream, or :func:`stream.move_to(token) <bloop.stream.Stream.move_to>` to move an existing stream to this position. :returns: Stream sta...
[ "JSON", "-", "serializable", "representation", "of", "the", "current", "Stream", "state", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/coordinator.py#L131-L160
numberoverzero/bloop
bloop/stream/coordinator.py
Coordinator.remove_shard
def remove_shard(self, shard, drop_buffered_records=False): """Remove a Shard from the Coordinator. Drops all buffered records from the Shard. If the Shard is active or a root, it is removed and any children promoted to those roles. :param shard: The shard to remove :type shard: :cla...
python
def remove_shard(self, shard, drop_buffered_records=False): """Remove a Shard from the Coordinator. Drops all buffered records from the Shard. If the Shard is active or a root, it is removed and any children promoted to those roles. :param shard: The shard to remove :type shard: :cla...
[ "def", "remove_shard", "(", "self", ",", "shard", ",", "drop_buffered_records", "=", "False", ")", ":", "try", ":", "self", ".", "roots", ".", "remove", "(", "shard", ")", "except", "ValueError", ":", "# Wasn't a root Shard", "pass", "else", ":", "self", "...
Remove a Shard from the Coordinator. Drops all buffered records from the Shard. If the Shard is active or a root, it is removed and any children promoted to those roles. :param shard: The shard to remove :type shard: :class:`~bloop.stream.shard.Shard` :param bool drop_buffered_record...
[ "Remove", "a", "Shard", "from", "the", "Coordinator", ".", "Drops", "all", "buffered", "records", "from", "the", "Shard", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/coordinator.py#L162-L195
numberoverzero/bloop
bloop/stream/coordinator.py
Coordinator.move_to
def move_to(self, position): """Set the Coordinator to a specific endpoint or time, or load state from a token. :param position: "trim_horizon", "latest", :class:`~datetime.datetime`, or a :attr:`Coordinator.token <bloop.stream.coordinator.Coordinator.token>` """ if isinstan...
python
def move_to(self, position): """Set the Coordinator to a specific endpoint or time, or load state from a token. :param position: "trim_horizon", "latest", :class:`~datetime.datetime`, or a :attr:`Coordinator.token <bloop.stream.coordinator.Coordinator.token>` """ if isinstan...
[ "def", "move_to", "(", "self", ",", "position", ")", ":", "if", "isinstance", "(", "position", ",", "collections", ".", "abc", ".", "Mapping", ")", ":", "move", "=", "_move_stream_token", "elif", "hasattr", "(", "position", ",", "\"timestamp\"", ")", "and"...
Set the Coordinator to a specific endpoint or time, or load state from a token. :param position: "trim_horizon", "latest", :class:`~datetime.datetime`, or a :attr:`Coordinator.token <bloop.stream.coordinator.Coordinator.token>`
[ "Set", "the", "Coordinator", "to", "a", "specific", "endpoint", "or", "time", "or", "load", "state", "from", "a", "token", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/coordinator.py#L197-L211
numberoverzero/bloop
bloop/stream/buffer.py
heap_item
def heap_item(clock, record, shard): """Create a tuple of (ordering, (record, shard)) for use in a RecordBuffer.""" # Primary ordering is by event creation time. # However, creation time is *approximate* and has whole-second resolution. # This means two events in the same shard within one second can't b...
python
def heap_item(clock, record, shard): """Create a tuple of (ordering, (record, shard)) for use in a RecordBuffer.""" # Primary ordering is by event creation time. # However, creation time is *approximate* and has whole-second resolution. # This means two events in the same shard within one second can't b...
[ "def", "heap_item", "(", "clock", ",", "record", ",", "shard", ")", ":", "# Primary ordering is by event creation time.", "# However, creation time is *approximate* and has whole-second resolution.", "# This means two events in the same shard within one second can't be ordered.", "ordering...
Create a tuple of (ordering, (record, shard)) for use in a RecordBuffer.
[ "Create", "a", "tuple", "of", "(", "ordering", "(", "record", "shard", "))", "for", "use", "in", "a", "RecordBuffer", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/buffer.py#L4-L18
numberoverzero/bloop
bloop/stream/buffer.py
RecordBuffer.push
def push(self, record, shard): """Push a new record into the buffer :param dict record: new record :param shard: Shard the record came from :type shard: :class:`~bloop.stream.shard.Shard` """ heapq.heappush(self.heap, heap_item(self.clock, record, shard))
python
def push(self, record, shard): """Push a new record into the buffer :param dict record: new record :param shard: Shard the record came from :type shard: :class:`~bloop.stream.shard.Shard` """ heapq.heappush(self.heap, heap_item(self.clock, record, shard))
[ "def", "push", "(", "self", ",", "record", ",", "shard", ")", ":", "heapq", ".", "heappush", "(", "self", ".", "heap", ",", "heap_item", "(", "self", ".", "clock", ",", "record", ",", "shard", ")", ")" ]
Push a new record into the buffer :param dict record: new record :param shard: Shard the record came from :type shard: :class:`~bloop.stream.shard.Shard`
[ "Push", "a", "new", "record", "into", "the", "buffer" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/buffer.py#L39-L46
numberoverzero/bloop
bloop/stream/buffer.py
RecordBuffer.push_all
def push_all(self, record_shard_pairs): """Push multiple (record, shard) pairs at once, with only one :meth:`heapq.heapify` call to maintain order. :param record_shard_pairs: list of ``(record, shard)`` tuples (see :func:`~bloop.stream.buffer.RecordBuffer.push`). """ # Faste...
python
def push_all(self, record_shard_pairs): """Push multiple (record, shard) pairs at once, with only one :meth:`heapq.heapify` call to maintain order. :param record_shard_pairs: list of ``(record, shard)`` tuples (see :func:`~bloop.stream.buffer.RecordBuffer.push`). """ # Faste...
[ "def", "push_all", "(", "self", ",", "record_shard_pairs", ")", ":", "# Faster than inserting one at a time; the heap is sorted once after all inserts.", "for", "record", ",", "shard", "in", "record_shard_pairs", ":", "item", "=", "heap_item", "(", "self", ".", "clock", ...
Push multiple (record, shard) pairs at once, with only one :meth:`heapq.heapify` call to maintain order. :param record_shard_pairs: list of ``(record, shard)`` tuples (see :func:`~bloop.stream.buffer.RecordBuffer.push`).
[ "Push", "multiple", "(", "record", "shard", ")", "pairs", "at", "once", "with", "only", "one", ":", "meth", ":", "heapq", ".", "heapify", "call", "to", "maintain", "order", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/buffer.py#L48-L58
numberoverzero/bloop
bloop/models.py
loaded_columns
def loaded_columns(obj: BaseModel): """Yields each (name, value) tuple for all columns in an object that aren't missing""" for column in sorted(obj.Meta.columns, key=lambda c: c.name): value = getattr(obj, column.name, missing) if value is not missing: yield column.name, value
python
def loaded_columns(obj: BaseModel): """Yields each (name, value) tuple for all columns in an object that aren't missing""" for column in sorted(obj.Meta.columns, key=lambda c: c.name): value = getattr(obj, column.name, missing) if value is not missing: yield column.name, value
[ "def", "loaded_columns", "(", "obj", ":", "BaseModel", ")", ":", "for", "column", "in", "sorted", "(", "obj", ".", "Meta", ".", "columns", ",", "key", "=", "lambda", "c", ":", "c", ".", "name", ")", ":", "value", "=", "getattr", "(", "obj", ",", ...
Yields each (name, value) tuple for all columns in an object that aren't missing
[ "Yields", "each", "(", "name", "value", ")", "tuple", "for", "all", "columns", "in", "an", "object", "that", "aren", "t", "missing" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/models.py#L583-L588
numberoverzero/bloop
bloop/models.py
unpack_from_dynamodb
def unpack_from_dynamodb(*, attrs, expected, model=None, obj=None, engine=None, context=None, **kwargs): """Push values by dynamo_name into an object""" context = context or {"engine": engine} engine = engine or context.get("engine", None) if not engine: raise ValueError("You must provide engine...
python
def unpack_from_dynamodb(*, attrs, expected, model=None, obj=None, engine=None, context=None, **kwargs): """Push values by dynamo_name into an object""" context = context or {"engine": engine} engine = engine or context.get("engine", None) if not engine: raise ValueError("You must provide engine...
[ "def", "unpack_from_dynamodb", "(", "*", ",", "attrs", ",", "expected", ",", "model", "=", "None", ",", "obj", "=", "None", ",", "engine", "=", "None", ",", "context", "=", "None", ",", "*", "*", "kwargs", ")", ":", "context", "=", "context", "or", ...
Push values by dynamo_name into an object
[ "Push", "values", "by", "dynamo_name", "into", "an", "object" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/models.py#L591-L608
numberoverzero/bloop
bloop/models.py
setdefault
def setdefault(obj, field, default): """Set an object's field to default if it doesn't have a value""" setattr(obj, field, getattr(obj, field, default))
python
def setdefault(obj, field, default): """Set an object's field to default if it doesn't have a value""" setattr(obj, field, getattr(obj, field, default))
[ "def", "setdefault", "(", "obj", ",", "field", ",", "default", ")", ":", "setattr", "(", "obj", ",", "field", ",", "getattr", "(", "obj", ",", "field", ",", "default", ")", ")" ]
Set an object's field to default if it doesn't have a value
[ "Set", "an", "object", "s", "field", "to", "default", "if", "it", "doesn", "t", "have", "a", "value" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/models.py#L751-L753
numberoverzero/bloop
bloop/models.py
bind_column
def bind_column(model, name, column, force=False, recursive=False, copy=False) -> Column: """Bind a column to the model with the given name. This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily attach a new column to an existing model: .. code-block:: pyt...
python
def bind_column(model, name, column, force=False, recursive=False, copy=False) -> Column: """Bind a column to the model with the given name. This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily attach a new column to an existing model: .. code-block:: pyt...
[ "def", "bind_column", "(", "model", ",", "name", ",", "column", ",", "force", "=", "False", ",", "recursive", "=", "False", ",", "copy", "=", "False", ")", "->", "Column", ":", "if", "not", "subclassof", "(", "model", ",", "BaseModel", ")", ":", "rai...
Bind a column to the model with the given name. This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily attach a new column to an existing model: .. code-block:: python import bloop.models class User(BaseModel): id = Column(String, ...
[ "Bind", "a", "column", "to", "the", "model", "with", "the", "given", "name", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/models.py#L820-L940
numberoverzero/bloop
bloop/models.py
bind_index
def bind_index(model, name, index, force=False, recursive=True, copy=False) -> Index: """Bind an index to the model with the given name. This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily attach a new index to an existing model: .. code-bloc...
python
def bind_index(model, name, index, force=False, recursive=True, copy=False) -> Index: """Bind an index to the model with the given name. This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily attach a new index to an existing model: .. code-bloc...
[ "def", "bind_index", "(", "model", ",", "name", ",", "index", ",", "force", "=", "False", ",", "recursive", "=", "True", ",", "copy", "=", "False", ")", "->", "Index", ":", "if", "not", "subclassof", "(", "model", ",", "BaseModel", ")", ":", "raise",...
Bind an index to the model with the given name. This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily attach a new index to an existing model: .. code-block:: python import bloop.models class User(BaseModel): ...
[ "Bind", "an", "index", "to", "the", "model", "with", "the", "given", "name", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/models.py#L943-L1047
numberoverzero/bloop
bloop/models.py
refresh_index
def refresh_index(meta, index) -> None: """Recalculate the projection, hash_key, and range_key for the given index. :param meta: model.Meta to find columns by name :param index: The index to refresh """ # All projections include model + index keys projection_keys = set.union(meta.keys, index.ke...
python
def refresh_index(meta, index) -> None: """Recalculate the projection, hash_key, and range_key for the given index. :param meta: model.Meta to find columns by name :param index: The index to refresh """ # All projections include model + index keys projection_keys = set.union(meta.keys, index.ke...
[ "def", "refresh_index", "(", "meta", ",", "index", ")", "->", "None", ":", "# All projections include model + index keys", "projection_keys", "=", "set", ".", "union", "(", "meta", ".", "keys", ",", "index", ".", "keys", ")", "proj", "=", "index", ".", "proj...
Recalculate the projection, hash_key, and range_key for the given index. :param meta: model.Meta to find columns by name :param index: The index to refresh
[ "Recalculate", "the", "projection", "hash_key", "and", "range_key", "for", "the", "given", "index", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/models.py#L1050-L1076
numberoverzero/bloop
bloop/models.py
unbind
def unbind(meta, name=None, dynamo_name=None) -> None: """Unconditionally remove any columns or indexes bound to the given name or dynamo_name. .. code-block:: python import bloop.models class User(BaseModel): id = Column(String, hash_key=True) email = Column(String, ...
python
def unbind(meta, name=None, dynamo_name=None) -> None: """Unconditionally remove any columns or indexes bound to the given name or dynamo_name. .. code-block:: python import bloop.models class User(BaseModel): id = Column(String, hash_key=True) email = Column(String, ...
[ "def", "unbind", "(", "meta", ",", "name", "=", "None", ",", "dynamo_name", "=", "None", ")", "->", "None", ":", "if", "name", "is", "not", "None", ":", "columns", "=", "{", "x", "for", "x", "in", "meta", ".", "columns", "if", "x", ".", "name", ...
Unconditionally remove any columns or indexes bound to the given name or dynamo_name. .. code-block:: python import bloop.models class User(BaseModel): id = Column(String, hash_key=True) email = Column(String, dynamo_name="e") by_email = GlobalSecondaryIndex(p...
[ "Unconditionally", "remove", "any", "columns", "or", "indexes", "bound", "to", "the", "given", "name", "or", "dynamo_name", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/models.py#L1079-L1151
numberoverzero/bloop
bloop/models.py
BaseModel._load
def _load(cls, attrs, *, context, **kwargs): """ dict (dynamo name) -> obj """ return unpack_from_dynamodb( model=cls, attrs=attrs or {}, expected=cls.Meta.columns, context=context, **kwargs)
python
def _load(cls, attrs, *, context, **kwargs): """ dict (dynamo name) -> obj """ return unpack_from_dynamodb( model=cls, attrs=attrs or {}, expected=cls.Meta.columns, context=context, **kwargs)
[ "def", "_load", "(", "cls", ",", "attrs", ",", "*", ",", "context", ",", "*", "*", "kwargs", ")", ":", "return", "unpack_from_dynamodb", "(", "model", "=", "cls", ",", "attrs", "=", "attrs", "or", "{", "}", ",", "expected", "=", "cls", ".", "Meta",...
dict (dynamo name) -> obj
[ "dict", "(", "dynamo", "name", ")", "-", ">", "obj" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/models.py#L207-L213
numberoverzero/bloop
bloop/models.py
BaseModel._dump
def _dump(cls, obj, *, context, **kwargs): """ obj -> dict """ if obj is None: return None dump = context["engine"]._dump filtered = filter( lambda item: item[1] is not None, (( column.dynamo_name, dump(column.typedef, g...
python
def _dump(cls, obj, *, context, **kwargs): """ obj -> dict """ if obj is None: return None dump = context["engine"]._dump filtered = filter( lambda item: item[1] is not None, (( column.dynamo_name, dump(column.typedef, g...
[ "def", "_dump", "(", "cls", ",", "obj", ",", "*", ",", "context", ",", "*", "*", "kwargs", ")", ":", "if", "obj", "is", "None", ":", "return", "None", "dump", "=", "context", "[", "\"engine\"", "]", ".", "_dump", "filtered", "=", "filter", "(", "...
obj -> dict
[ "obj", "-", ">", "dict" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/models.py#L216-L227
numberoverzero/bloop
bloop/session.py
is_valid_superset
def is_valid_superset(actual_projection, index): """Returns True if the actual index is a valid superset of the expected index""" projection_type = actual_projection["ProjectionType"] if projection_type == "ALL": return True meta = index.model.Meta # all index types provide index keys and mo...
python
def is_valid_superset(actual_projection, index): """Returns True if the actual index is a valid superset of the expected index""" projection_type = actual_projection["ProjectionType"] if projection_type == "ALL": return True meta = index.model.Meta # all index types provide index keys and mo...
[ "def", "is_valid_superset", "(", "actual_projection", ",", "index", ")", ":", "projection_type", "=", "actual_projection", "[", "\"ProjectionType\"", "]", "if", "projection_type", "==", "\"ALL\"", ":", "return", "True", "meta", "=", "index", ".", "model", ".", "...
Returns True if the actual index is a valid superset of the expected index
[ "Returns", "True", "if", "the", "actual", "index", "is", "a", "valid", "superset", "of", "the", "expected", "index" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L664-L685
numberoverzero/bloop
bloop/session.py
SessionWrapper.save_item
def save_item(self, item): """Save an object to DynamoDB. :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.update_item`. :raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met. """ try: self.dynamodb_client.update_item...
python
def save_item(self, item): """Save an object to DynamoDB. :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.update_item`. :raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met. """ try: self.dynamodb_client.update_item...
[ "def", "save_item", "(", "self", ",", "item", ")", ":", "try", ":", "self", ".", "dynamodb_client", ".", "update_item", "(", "*", "*", "item", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as", "error", ":", "handle_constraint_violation"...
Save an object to DynamoDB. :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.update_item`. :raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.
[ "Save", "an", "object", "to", "DynamoDB", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L60-L69
numberoverzero/bloop
bloop/session.py
SessionWrapper.delete_item
def delete_item(self, item): """Delete an object in DynamoDB. :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.delete_item`. :raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met. """ try: self.dynamodb_client.delete_...
python
def delete_item(self, item): """Delete an object in DynamoDB. :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.delete_item`. :raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met. """ try: self.dynamodb_client.delete_...
[ "def", "delete_item", "(", "self", ",", "item", ")", ":", "try", ":", "self", ".", "dynamodb_client", ".", "delete_item", "(", "*", "*", "item", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as", "error", ":", "handle_constraint_violatio...
Delete an object in DynamoDB. :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.delete_item`. :raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.
[ "Delete", "an", "object", "in", "DynamoDB", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L71-L80
numberoverzero/bloop
bloop/session.py
SessionWrapper.load_items
def load_items(self, items): """Loads any number of items in chunks, handling continuation tokens. :param items: Unpacked in chunks into "RequestItems" for :func:`boto3.DynamoDB.Client.batch_get_item`. """ loaded_items = {} requests = collections.deque(create_batch_get_chunks(it...
python
def load_items(self, items): """Loads any number of items in chunks, handling continuation tokens. :param items: Unpacked in chunks into "RequestItems" for :func:`boto3.DynamoDB.Client.batch_get_item`. """ loaded_items = {} requests = collections.deque(create_batch_get_chunks(it...
[ "def", "load_items", "(", "self", ",", "items", ")", ":", "loaded_items", "=", "{", "}", "requests", "=", "collections", ".", "deque", "(", "create_batch_get_chunks", "(", "items", ")", ")", "while", "requests", ":", "request", "=", "requests", ".", "pop",...
Loads any number of items in chunks, handling continuation tokens. :param items: Unpacked in chunks into "RequestItems" for :func:`boto3.DynamoDB.Client.batch_get_item`.
[ "Loads", "any", "number", "of", "items", "in", "chunks", "handling", "continuation", "tokens", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L82-L104
numberoverzero/bloop
bloop/session.py
SessionWrapper.search_items
def search_items(self, mode, request): """Invoke query/scan by name. Response always includes "Count" and "ScannedCount" :param str mode: "query" or "scan" :param request: Unpacked into :func:`boto3.DynamoDB.Client.query` or :func:`boto3.DynamoDB.Client.scan` """ valida...
python
def search_items(self, mode, request): """Invoke query/scan by name. Response always includes "Count" and "ScannedCount" :param str mode: "query" or "scan" :param request: Unpacked into :func:`boto3.DynamoDB.Client.query` or :func:`boto3.DynamoDB.Client.scan` """ valida...
[ "def", "search_items", "(", "self", ",", "mode", ",", "request", ")", ":", "validate_search_mode", "(", "mode", ")", "method", "=", "getattr", "(", "self", ".", "dynamodb_client", ",", "mode", ")", "try", ":", "response", "=", "method", "(", "*", "*", ...
Invoke query/scan by name. Response always includes "Count" and "ScannedCount" :param str mode: "query" or "scan" :param request: Unpacked into :func:`boto3.DynamoDB.Client.query` or :func:`boto3.DynamoDB.Client.scan`
[ "Invoke", "query", "/", "scan", "by", "name", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L124-L139
numberoverzero/bloop
bloop/session.py
SessionWrapper.create_table
def create_table(self, table_name, model): """Create the model's table. Returns True if the table is being created, False otherwise. Does not wait for the table to create, and does not validate an existing table. Will not raise "ResourceInUseException" if the table exists or is being created. ...
python
def create_table(self, table_name, model): """Create the model's table. Returns True if the table is being created, False otherwise. Does not wait for the table to create, and does not validate an existing table. Will not raise "ResourceInUseException" if the table exists or is being created. ...
[ "def", "create_table", "(", "self", ",", "table_name", ",", "model", ")", ":", "table", "=", "create_table_request", "(", "table_name", ",", "model", ")", "try", ":", "self", ".", "dynamodb_client", ".", "create_table", "(", "*", "*", "table", ")", "is_cre...
Create the model's table. Returns True if the table is being created, False otherwise. Does not wait for the table to create, and does not validate an existing table. Will not raise "ResourceInUseException" if the table exists or is being created. :param str table_name: The name of the table ...
[ "Create", "the", "model", "s", "table", ".", "Returns", "True", "if", "the", "table", "is", "being", "created", "False", "otherwise", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L141-L159
numberoverzero/bloop
bloop/session.py
SessionWrapper.describe_table
def describe_table(self, table_name): """ Polls until the table is ready, then returns the first result when the table was ready. The returned dict is standardized to ensure all fields are present, even when empty or across different DynamoDB API versions. TTL information is als...
python
def describe_table(self, table_name): """ Polls until the table is ready, then returns the first result when the table was ready. The returned dict is standardized to ensure all fields are present, even when empty or across different DynamoDB API versions. TTL information is als...
[ "def", "describe_table", "(", "self", ",", "table_name", ")", ":", "if", "table_name", "in", "self", ".", "_tables", ":", "return", "self", ".", "_tables", "[", "table_name", "]", "status", ",", "description", "=", "None", ",", "{", "}", "calls", "=", ...
Polls until the table is ready, then returns the first result when the table was ready. The returned dict is standardized to ensure all fields are present, even when empty or across different DynamoDB API versions. TTL information is also inserted. :param table_name: The name of the ta...
[ "Polls", "until", "the", "table", "is", "ready", "then", "returns", "the", "first", "result", "when", "the", "table", "was", "ready", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L161-L204
numberoverzero/bloop
bloop/session.py
SessionWrapper.validate_table
def validate_table(self, table_name, model): """Polls until a creating table is ready, then verifies the description against the model's requirements. The model may have a subset of all GSIs and LSIs on the table, but the key structure must be exactly the same. The table must have a stream if ...
python
def validate_table(self, table_name, model): """Polls until a creating table is ready, then verifies the description against the model's requirements. The model may have a subset of all GSIs and LSIs on the table, but the key structure must be exactly the same. The table must have a stream if ...
[ "def", "validate_table", "(", "self", ",", "table_name", ",", "model", ")", ":", "actual", "=", "self", ".", "describe_table", "(", "table_name", ")", "if", "not", "compare_tables", "(", "model", ",", "actual", ")", ":", "raise", "TableMismatch", "(", "\"T...
Polls until a creating table is ready, then verifies the description against the model's requirements. The model may have a subset of all GSIs and LSIs on the table, but the key structure must be exactly the same. The table must have a stream if the model expects one, but not the other way around. Wh...
[ "Polls", "until", "a", "creating", "table", "is", "ready", "then", "verifies", "the", "description", "against", "the", "model", "s", "requirements", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L206-L269
numberoverzero/bloop
bloop/session.py
SessionWrapper.enable_ttl
def enable_ttl(self, table_name, model): """Calls UpdateTimeToLive on the table according to model.Meta["ttl"] :param table_name: The name of the table to enable the TTL setting on :param model: The model to get TTL settings from """ self._tables.pop(table_name, None) tt...
python
def enable_ttl(self, table_name, model): """Calls UpdateTimeToLive on the table according to model.Meta["ttl"] :param table_name: The name of the table to enable the TTL setting on :param model: The model to get TTL settings from """ self._tables.pop(table_name, None) tt...
[ "def", "enable_ttl", "(", "self", ",", "table_name", ",", "model", ")", ":", "self", ".", "_tables", ".", "pop", "(", "table_name", ",", "None", ")", "ttl_name", "=", "model", ".", "Meta", ".", "ttl", "[", "\"column\"", "]", ".", "dynamo_name", "reques...
Calls UpdateTimeToLive on the table according to model.Meta["ttl"] :param table_name: The name of the table to enable the TTL setting on :param model: The model to get TTL settings from
[ "Calls", "UpdateTimeToLive", "on", "the", "table", "according", "to", "model", ".", "Meta", "[", "ttl", "]" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L271-L286
numberoverzero/bloop
bloop/session.py
SessionWrapper.enable_backups
def enable_backups(self, table_name, model): """Calls UpdateContinuousBackups on the table according to model.Meta["continuous_backups"] :param table_name: The name of the table to enable Continuous Backups on :param model: The model to get Continuous Backups settings from """ s...
python
def enable_backups(self, table_name, model): """Calls UpdateContinuousBackups on the table according to model.Meta["continuous_backups"] :param table_name: The name of the table to enable Continuous Backups on :param model: The model to get Continuous Backups settings from """ s...
[ "def", "enable_backups", "(", "self", ",", "table_name", ",", "model", ")", ":", "self", ".", "_tables", ".", "pop", "(", "table_name", ",", "None", ")", "request", "=", "{", "\"TableName\"", ":", "table_name", ",", "\"PointInTimeRecoverySpecification\"", ":",...
Calls UpdateContinuousBackups on the table according to model.Meta["continuous_backups"] :param table_name: The name of the table to enable Continuous Backups on :param model: The model to get Continuous Backups settings from
[ "Calls", "UpdateContinuousBackups", "on", "the", "table", "according", "to", "model", ".", "Meta", "[", "continuous_backups", "]" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L288-L302
numberoverzero/bloop
bloop/session.py
SessionWrapper.describe_stream
def describe_stream(self, stream_arn, first_shard=None): """Wraps :func:`boto3.DynamoDBStreams.Client.describe_stream`, handling continuation tokens. :param str stream_arn: Stream arn, usually from the model's ``Meta.stream["arn"]``. :param str first_shard: *(Optional)* If provided, only shards...
python
def describe_stream(self, stream_arn, first_shard=None): """Wraps :func:`boto3.DynamoDBStreams.Client.describe_stream`, handling continuation tokens. :param str stream_arn: Stream arn, usually from the model's ``Meta.stream["arn"]``. :param str first_shard: *(Optional)* If provided, only shards...
[ "def", "describe_stream", "(", "self", ",", "stream_arn", ",", "first_shard", "=", "None", ")", ":", "description", "=", "{", "\"Shards\"", ":", "[", "]", "}", "request", "=", "{", "\"StreamArn\"", ":", "stream_arn", ",", "\"ExclusiveStartShardId\"", ":", "f...
Wraps :func:`boto3.DynamoDBStreams.Client.describe_stream`, handling continuation tokens. :param str stream_arn: Stream arn, usually from the model's ``Meta.stream["arn"]``. :param str first_shard: *(Optional)* If provided, only shards after this shard id will be returned. :return: All shards i...
[ "Wraps", ":", "func", ":", "boto3", ".", "DynamoDBStreams", ".", "Client", ".", "describe_stream", "handling", "continuation", "tokens", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L304-L332
numberoverzero/bloop
bloop/session.py
SessionWrapper.get_shard_iterator
def get_shard_iterator(self, *, stream_arn, shard_id, iterator_type, sequence_number=None): """Wraps :func:`boto3.DynamoDBStreams.Client.get_shard_iterator`. :param str stream_arn: Stream arn. Usually :data:`Shard.stream_arn <bloop.stream.shard.Shard.stream_arn>`. :param str shard_id: Shard id...
python
def get_shard_iterator(self, *, stream_arn, shard_id, iterator_type, sequence_number=None): """Wraps :func:`boto3.DynamoDBStreams.Client.get_shard_iterator`. :param str stream_arn: Stream arn. Usually :data:`Shard.stream_arn <bloop.stream.shard.Shard.stream_arn>`. :param str shard_id: Shard id...
[ "def", "get_shard_iterator", "(", "self", ",", "*", ",", "stream_arn", ",", "shard_id", ",", "iterator_type", ",", "sequence_number", "=", "None", ")", ":", "real_iterator_type", "=", "validate_stream_iterator_type", "(", "iterator_type", ")", "request", "=", "{",...
Wraps :func:`boto3.DynamoDBStreams.Client.get_shard_iterator`. :param str stream_arn: Stream arn. Usually :data:`Shard.stream_arn <bloop.stream.shard.Shard.stream_arn>`. :param str shard_id: Shard identifier. Usually :data:`Shard.shard_id <bloop.stream.shard.Shard.shard_id>`. :param str itera...
[ "Wraps", ":", "func", ":", "boto3", ".", "DynamoDBStreams", ".", "Client", ".", "get_shard_iterator", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L334-L360
numberoverzero/bloop
bloop/session.py
SessionWrapper.get_stream_records
def get_stream_records(self, iterator_id): """Wraps :func:`boto3.DynamoDBStreams.Client.get_records`. :param iterator_id: Iterator id. Usually :data:`Shard.iterator_id <bloop.stream.shard.Shard.iterator_id>`. :return: Dict with "Records" list (may be empty) and "NextShardIterator" str (may not...
python
def get_stream_records(self, iterator_id): """Wraps :func:`boto3.DynamoDBStreams.Client.get_records`. :param iterator_id: Iterator id. Usually :data:`Shard.iterator_id <bloop.stream.shard.Shard.iterator_id>`. :return: Dict with "Records" list (may be empty) and "NextShardIterator" str (may not...
[ "def", "get_stream_records", "(", "self", ",", "iterator_id", ")", ":", "try", ":", "return", "self", ".", "stream_client", ".", "get_records", "(", "ShardIterator", "=", "iterator_id", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as", "e...
Wraps :func:`boto3.DynamoDBStreams.Client.get_records`. :param iterator_id: Iterator id. Usually :data:`Shard.iterator_id <bloop.stream.shard.Shard.iterator_id>`. :return: Dict with "Records" list (may be empty) and "NextShardIterator" str (may not exist). :rtype: dict :raises bloop.ex...
[ "Wraps", ":", "func", ":", "boto3", ".", "DynamoDBStreams", ".", "Client", ".", "get_records", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L362-L378
numberoverzero/bloop
bloop/session.py
SessionWrapper.transaction_read
def transaction_read(self, items): """ Wraps :func:`boto3.DynamoDB.Client.db.transact_get_items`. :param items: Unpacked into "TransactionItems" for :func:`boto3.DynamoDB.Client.transact_get_items` :raises bloop.exceptions.TransactionCanceled: if the transaction was canceled. :r...
python
def transaction_read(self, items): """ Wraps :func:`boto3.DynamoDB.Client.db.transact_get_items`. :param items: Unpacked into "TransactionItems" for :func:`boto3.DynamoDB.Client.transact_get_items` :raises bloop.exceptions.TransactionCanceled: if the transaction was canceled. :r...
[ "def", "transaction_read", "(", "self", ",", "items", ")", ":", "try", ":", "return", "self", ".", "dynamodb_client", ".", "transact_get_items", "(", "TransactItems", "=", "items", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as", "error"...
Wraps :func:`boto3.DynamoDB.Client.db.transact_get_items`. :param items: Unpacked into "TransactionItems" for :func:`boto3.DynamoDB.Client.transact_get_items` :raises bloop.exceptions.TransactionCanceled: if the transaction was canceled. :return: Dict with "Records" list
[ "Wraps", ":", "func", ":", "boto3", ".", "DynamoDB", ".", "Client", ".", "db", ".", "transact_get_items", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L380-L393
numberoverzero/bloop
bloop/session.py
SessionWrapper.transaction_write
def transaction_write(self, items, client_request_token): """ Wraps :func:`boto3.DynamoDB.Client.db.transact_write_items`. :param items: Unpacked into "TransactionItems" for :func:`boto3.DynamoDB.Client.transact_write_items` :param client_request_token: Idempotency token valid for 10 mi...
python
def transaction_write(self, items, client_request_token): """ Wraps :func:`boto3.DynamoDB.Client.db.transact_write_items`. :param items: Unpacked into "TransactionItems" for :func:`boto3.DynamoDB.Client.transact_write_items` :param client_request_token: Idempotency token valid for 10 mi...
[ "def", "transaction_write", "(", "self", ",", "items", ",", "client_request_token", ")", ":", "try", ":", "self", ".", "dynamodb_client", ".", "transact_write_items", "(", "TransactItems", "=", "items", ",", "ClientRequestToken", "=", "client_request_token", ")", ...
Wraps :func:`boto3.DynamoDB.Client.db.transact_write_items`. :param items: Unpacked into "TransactionItems" for :func:`boto3.DynamoDB.Client.transact_write_items` :param client_request_token: Idempotency token valid for 10 minutes from first use. Unpacked into "ClientRequestToken" :...
[ "Wraps", ":", "func", ":", "boto3", ".", "DynamoDB", ".", "Client", ".", "db", ".", "transact_write_items", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L395-L412
numberoverzero/bloop
bloop/search.py
check_hash_key
def check_hash_key(query_on, key): """Only allows == against query_on.hash_key""" return ( isinstance(key, BaseCondition) and (key.operation == "==") and (key.column is query_on.hash_key) )
python
def check_hash_key(query_on, key): """Only allows == against query_on.hash_key""" return ( isinstance(key, BaseCondition) and (key.operation == "==") and (key.column is query_on.hash_key) )
[ "def", "check_hash_key", "(", "query_on", ",", "key", ")", ":", "return", "(", "isinstance", "(", "key", ",", "BaseCondition", ")", "and", "(", "key", ".", "operation", "==", "\"==\"", ")", "and", "(", "key", ".", "column", "is", "query_on", ".", "hash...
Only allows == against query_on.hash_key
[ "Only", "allows", "==", "against", "query_on", ".", "hash_key" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/search.py#L131-L137
numberoverzero/bloop
bloop/search.py
check_range_key
def check_range_key(query_on, key): """BeginsWith, Between, or any Comparison except '!=' against query_on.range_key""" return ( isinstance(key, BaseCondition) and key.operation in ("begins_with", "between", "<", ">", "<=", ">=", "==") and key.column is query_on.range_key )
python
def check_range_key(query_on, key): """BeginsWith, Between, or any Comparison except '!=' against query_on.range_key""" return ( isinstance(key, BaseCondition) and key.operation in ("begins_with", "between", "<", ">", "<=", ">=", "==") and key.column is query_on.range_key )
[ "def", "check_range_key", "(", "query_on", ",", "key", ")", ":", "return", "(", "isinstance", "(", "key", ",", "BaseCondition", ")", "and", "key", ".", "operation", "in", "(", "\"begins_with\"", ",", "\"between\"", ",", "\"<\"", ",", "\">\"", ",", "\"<=\""...
BeginsWith, Between, or any Comparison except '!=' against query_on.range_key
[ "BeginsWith", "Between", "or", "any", "Comparison", "except", "!", "=", "against", "query_on", ".", "range_key" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/search.py#L140-L146
numberoverzero/bloop
bloop/search.py
Search.prepare
def prepare(self): """Constructs a :class:`~bloop.search.PreparedSearch`.""" p = PreparedSearch() p.prepare( engine=self.engine, mode=self.mode, model=self.model, index=self.index, key=self.key, filter=self.filter, ...
python
def prepare(self): """Constructs a :class:`~bloop.search.PreparedSearch`.""" p = PreparedSearch() p.prepare( engine=self.engine, mode=self.mode, model=self.model, index=self.index, key=self.key, filter=self.filter, ...
[ "def", "prepare", "(", "self", ")", ":", "p", "=", "PreparedSearch", "(", ")", "p", ".", "prepare", "(", "engine", "=", "self", ".", "engine", ",", "mode", "=", "self", ".", "mode", ",", "model", "=", "self", ".", "model", ",", "index", "=", "sel...
Constructs a :class:`~bloop.search.PreparedSearch`.
[ "Constructs", "a", ":", "class", ":", "~bloop", ".", "search", ".", "PreparedSearch", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/search.py#L200-L215
numberoverzero/bloop
bloop/search.py
PreparedSearch.prepare
def prepare( self, engine=None, mode=None, model=None, index=None, key=None, filter=None, projection=None, consistent=None, forward=None, parallel=None): """Validates the search parameters and builds the base request dict for each Query/Scan call.""" self.prepare_iterator_cls(en...
python
def prepare( self, engine=None, mode=None, model=None, index=None, key=None, filter=None, projection=None, consistent=None, forward=None, parallel=None): """Validates the search parameters and builds the base request dict for each Query/Scan call.""" self.prepare_iterator_cls(en...
[ "def", "prepare", "(", "self", ",", "engine", "=", "None", ",", "mode", "=", "None", ",", "model", "=", "None", ",", "index", "=", "None", ",", "key", "=", "None", ",", "filter", "=", "None", ",", "projection", "=", "None", ",", "consistent", "=", ...
Validates the search parameters and builds the base request dict for each Query/Scan call.
[ "Validates", "the", "search", "parameters", "and", "builds", "the", "base", "request", "dict", "for", "each", "Query", "/", "Scan", "call", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/search.py#L245-L257
numberoverzero/bloop
bloop/search.py
SearchIterator.count
def count(self): """Number of items that have been loaded from DynamoDB so far, including buffered items.""" if self.request["Select"] == "COUNT": while not self.exhausted: next(self, None) return self._count
python
def count(self): """Number of items that have been loaded from DynamoDB so far, including buffered items.""" if self.request["Select"] == "COUNT": while not self.exhausted: next(self, None) return self._count
[ "def", "count", "(", "self", ")", ":", "if", "self", ".", "request", "[", "\"Select\"", "]", "==", "\"COUNT\"", ":", "while", "not", "self", ".", "exhausted", ":", "next", "(", "self", ",", "None", ")", "return", "self", ".", "_count" ]
Number of items that have been loaded from DynamoDB so far, including buffered items.
[ "Number", "of", "items", "that", "have", "been", "loaded", "from", "DynamoDB", "so", "far", "including", "buffered", "items", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/search.py#L366-L371
numberoverzero/bloop
bloop/search.py
SearchIterator.scanned
def scanned(self): """Number of items that DynamoDB evaluated, before any filter was applied.""" if self.request["Select"] == "COUNT": while not self.exhausted: next(self, None) return self._scanned
python
def scanned(self): """Number of items that DynamoDB evaluated, before any filter was applied.""" if self.request["Select"] == "COUNT": while not self.exhausted: next(self, None) return self._scanned
[ "def", "scanned", "(", "self", ")", ":", "if", "self", ".", "request", "[", "\"Select\"", "]", "==", "\"COUNT\"", ":", "while", "not", "self", ".", "exhausted", ":", "next", "(", "self", ",", "None", ")", "return", "self", ".", "_scanned" ]
Number of items that DynamoDB evaluated, before any filter was applied.
[ "Number", "of", "items", "that", "DynamoDB", "evaluated", "before", "any", "filter", "was", "applied", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/search.py#L374-L379
numberoverzero/bloop
bloop/search.py
SearchIterator.first
def first(self): """Return the first result. If there are no results, raises :exc:`~bloop.exceptions.ConstraintViolation`. :return: The first result. :raises bloop.exceptions.ConstraintViolation: No results. """ self.reset() value = next(self, None) if value is ...
python
def first(self): """Return the first result. If there are no results, raises :exc:`~bloop.exceptions.ConstraintViolation`. :return: The first result. :raises bloop.exceptions.ConstraintViolation: No results. """ self.reset() value = next(self, None) if value is ...
[ "def", "first", "(", "self", ")", ":", "self", ".", "reset", "(", ")", "value", "=", "next", "(", "self", ",", "None", ")", "if", "value", "is", "None", ":", "raise", "ConstraintViolation", "(", "\"{} did not find any results.\"", ".", "format", "(", "se...
Return the first result. If there are no results, raises :exc:`~bloop.exceptions.ConstraintViolation`. :return: The first result. :raises bloop.exceptions.ConstraintViolation: No results.
[ "Return", "the", "first", "result", ".", "If", "there", "are", "no", "results", "raises", ":", "exc", ":", "~bloop", ".", "exceptions", ".", "ConstraintViolation", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/search.py#L389-L399
numberoverzero/bloop
bloop/search.py
SearchIterator.one
def one(self): """Return the unique result. If there is not exactly one result, raises :exc:`~bloop.exceptions.ConstraintViolation`. :return: The unique result. :raises bloop.exceptions.ConstraintViolation: Not exactly one result. """ first = self.first() second...
python
def one(self): """Return the unique result. If there is not exactly one result, raises :exc:`~bloop.exceptions.ConstraintViolation`. :return: The unique result. :raises bloop.exceptions.ConstraintViolation: Not exactly one result. """ first = self.first() second...
[ "def", "one", "(", "self", ")", ":", "first", "=", "self", ".", "first", "(", ")", "second", "=", "next", "(", "self", ",", "None", ")", "if", "second", "is", "not", "None", ":", "raise", "ConstraintViolation", "(", "\"{} found more than one result.\"", ...
Return the unique result. If there is not exactly one result, raises :exc:`~bloop.exceptions.ConstraintViolation`. :return: The unique result. :raises bloop.exceptions.ConstraintViolation: Not exactly one result.
[ "Return", "the", "unique", "result", ".", "If", "there", "is", "not", "exactly", "one", "result", "raises", ":", "exc", ":", "~bloop", ".", "exceptions", ".", "ConstraintViolation", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/search.py#L401-L412
numberoverzero/bloop
bloop/search.py
SearchIterator.reset
def reset(self): """Reset to the initial state, clearing the buffer and zeroing count and scanned.""" self.buffer.clear() self._count = 0 self._scanned = 0 self._exhausted = False self.request.pop("ExclusiveStartKey", None)
python
def reset(self): """Reset to the initial state, clearing the buffer and zeroing count and scanned.""" self.buffer.clear() self._count = 0 self._scanned = 0 self._exhausted = False self.request.pop("ExclusiveStartKey", None)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "buffer", ".", "clear", "(", ")", "self", ".", "_count", "=", "0", "self", ".", "_scanned", "=", "0", "self", ".", "_exhausted", "=", "False", "self", ".", "request", ".", "pop", "(", "\"Exclusive...
Reset to the initial state, clearing the buffer and zeroing count and scanned.
[ "Reset", "to", "the", "initial", "state", "clearing", "the", "buffer", "and", "zeroing", "count", "and", "scanned", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/search.py#L414-L420
numberoverzero/bloop
bloop/transactions.py
TxType.by_alias
def by_alias(cls, name: str) -> "TxType": """get a type by the common bloop operation name: get/check/delete/save""" return { "get": TxType.Get, "check": TxType.Check, "delete": TxType.Delete, "save": TxType.Update, }[name]
python
def by_alias(cls, name: str) -> "TxType": """get a type by the common bloop operation name: get/check/delete/save""" return { "get": TxType.Get, "check": TxType.Check, "delete": TxType.Delete, "save": TxType.Update, }[name]
[ "def", "by_alias", "(", "cls", ",", "name", ":", "str", ")", "->", "\"TxType\"", ":", "return", "{", "\"get\"", ":", "TxType", ".", "Get", ",", "\"check\"", ":", "TxType", ".", "Check", ",", "\"delete\"", ":", "TxType", ".", "Delete", ",", "\"save\"", ...
get a type by the common bloop operation name: get/check/delete/save
[ "get", "a", "type", "by", "the", "common", "bloop", "operation", "name", ":", "get", "/", "check", "/", "delete", "/", "save" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/transactions.py#L36-L43
numberoverzero/bloop
bloop/transactions.py
Transaction.prepare
def prepare(self): """ Create a new PreparedTransaction that can be committed. This is called automatically when exiting the transaction as a context: .. code-block:: python >>> engine = Engine() >>> tx = WriteTransaction(engine) >>> prepared = tx.p...
python
def prepare(self): """ Create a new PreparedTransaction that can be committed. This is called automatically when exiting the transaction as a context: .. code-block:: python >>> engine = Engine() >>> tx = WriteTransaction(engine) >>> prepared = tx.p...
[ "def", "prepare", "(", "self", ")", ":", "tx", "=", "PreparedTransaction", "(", ")", "tx", ".", "prepare", "(", "engine", "=", "self", ".", "engine", ",", "mode", "=", "self", ".", "mode", ",", "items", "=", "self", ".", "_items", ",", ")", "return...
Create a new PreparedTransaction that can be committed. This is called automatically when exiting the transaction as a context: .. code-block:: python >>> engine = Engine() >>> tx = WriteTransaction(engine) >>> prepared = tx.prepare() >>> prepared.commi...
[ "Create", "a", "new", "PreparedTransaction", "that", "can", "be", "committed", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/transactions.py#L135-L162
numberoverzero/bloop
bloop/transactions.py
PreparedTransaction.prepare
def prepare(self, engine, mode, items) -> None: """ Create a unique transaction id and dumps the items into a cached request object. """ self.tx_id = str(uuid.uuid4()).replace("-", "") self.engine = engine self.mode = mode self.items = items self._prepare_...
python
def prepare(self, engine, mode, items) -> None: """ Create a unique transaction id and dumps the items into a cached request object. """ self.tx_id = str(uuid.uuid4()).replace("-", "") self.engine = engine self.mode = mode self.items = items self._prepare_...
[ "def", "prepare", "(", "self", ",", "engine", ",", "mode", ",", "items", ")", "->", "None", ":", "self", ".", "tx_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", "self", ".", "engine", ...
Create a unique transaction id and dumps the items into a cached request object.
[ "Create", "a", "unique", "transaction", "id", "and", "dumps", "the", "items", "into", "a", "cached", "request", "object", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/transactions.py#L186-L194
numberoverzero/bloop
bloop/transactions.py
PreparedTransaction.commit
def commit(self) -> None: """ Commit the transaction with a fixed transaction id. A read transaction can call commit() any number of times, while a write transaction can only use the same tx_id for 10 minutes from the first call. """ now = datetime.now(timezone.utc) ...
python
def commit(self) -> None: """ Commit the transaction with a fixed transaction id. A read transaction can call commit() any number of times, while a write transaction can only use the same tx_id for 10 minutes from the first call. """ now = datetime.now(timezone.utc) ...
[ "def", "commit", "(", "self", ")", "->", "None", ":", "now", "=", "datetime", ".", "now", "(", "timezone", ".", "utc", ")", "if", "self", ".", "first_commit_at", "is", "None", ":", "self", ".", "first_commit_at", "=", "now", "if", "self", ".", "mode"...
Commit the transaction with a fixed transaction id. A read transaction can call commit() any number of times, while a write transaction can only use the same tx_id for 10 minutes from the first call.
[ "Commit", "the", "transaction", "with", "a", "fixed", "transaction", "id", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/transactions.py#L213-L233
numberoverzero/bloop
bloop/transactions.py
ReadTransaction.load
def load(self, *objs) -> "ReadTransaction": """ Add one or more objects to be loaded in this transaction. At most 10 items can be loaded in the same transaction. All objects will be loaded each time you call commit(). :param objs: Objects to add to the set that are loaded in ...
python
def load(self, *objs) -> "ReadTransaction": """ Add one or more objects to be loaded in this transaction. At most 10 items can be loaded in the same transaction. All objects will be loaded each time you call commit(). :param objs: Objects to add to the set that are loaded in ...
[ "def", "load", "(", "self", ",", "*", "objs", ")", "->", "\"ReadTransaction\"", ":", "self", ".", "_extend", "(", "[", "TxItem", ".", "new", "(", "\"get\"", ",", "obj", ")", "for", "obj", "in", "objs", "]", ")", "return", "self" ]
Add one or more objects to be loaded in this transaction. At most 10 items can be loaded in the same transaction. All objects will be loaded each time you call commit(). :param objs: Objects to add to the set that are loaded in this transaction. :return: this transaction for chaining...
[ "Add", "one", "or", "more", "objects", "to", "be", "loaded", "in", "this", "transaction", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/transactions.py#L267-L280
numberoverzero/bloop
bloop/transactions.py
WriteTransaction.check
def check(self, obj, condition) -> "WriteTransaction": """ Add a condition which must be met for the transaction to commit. While the condition is checked against the provided object, that object will not be modified. It is only used to provide the hash and range key to apply the condi...
python
def check(self, obj, condition) -> "WriteTransaction": """ Add a condition which must be met for the transaction to commit. While the condition is checked against the provided object, that object will not be modified. It is only used to provide the hash and range key to apply the condi...
[ "def", "check", "(", "self", ",", "obj", ",", "condition", ")", "->", "\"WriteTransaction\"", ":", "self", ".", "_extend", "(", "[", "TxItem", ".", "new", "(", "\"check\"", ",", "obj", ",", "condition", ")", "]", ")", "return", "self" ]
Add a condition which must be met for the transaction to commit. While the condition is checked against the provided object, that object will not be modified. It is only used to provide the hash and range key to apply the condition to. At most 10 items can be checked, saved, or deleted in the...
[ "Add", "a", "condition", "which", "must", "be", "met", "for", "the", "transaction", "to", "commit", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/transactions.py#L300-L317
numberoverzero/bloop
bloop/transactions.py
WriteTransaction.save
def save(self, *objs, condition=None, atomic=False) -> "WriteTransaction": """ Add one or more objects to be saved in this transaction. At most 10 items can be checked, saved, or deleted in the same transaction. The same idempotency token will be used for a single prepared transaction,...
python
def save(self, *objs, condition=None, atomic=False) -> "WriteTransaction": """ Add one or more objects to be saved in this transaction. At most 10 items can be checked, saved, or deleted in the same transaction. The same idempotency token will be used for a single prepared transaction,...
[ "def", "save", "(", "self", ",", "*", "objs", ",", "condition", "=", "None", ",", "atomic", "=", "False", ")", "->", "\"WriteTransaction\"", ":", "self", ".", "_extend", "(", "[", "TxItem", ".", "new", "(", "\"save\"", ",", "obj", ",", "condition", "...
Add one or more objects to be saved in this transaction. At most 10 items can be checked, saved, or deleted in the same transaction. The same idempotency token will be used for a single prepared transaction, which allows you to safely call commit on the PreparedCommit object multiple times. ...
[ "Add", "one", "or", "more", "objects", "to", "be", "saved", "in", "this", "transaction", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/transactions.py#L319-L333
ska-sa/montblanc
montblanc/impl/rime/tensorflow/cube_dim_transcoder.py
CubeDimensionTranscoder.encode
def encode(self, cube_dimensions): """ Produces a numpy array of integers which encode the supplied cube dimensions. """ return np.asarray([getattr(cube_dimensions[d], s) for d in self._dimensions for s in self._schema], dtype=np.int32)
python
def encode(self, cube_dimensions): """ Produces a numpy array of integers which encode the supplied cube dimensions. """ return np.asarray([getattr(cube_dimensions[d], s) for d in self._dimensions for s in self._schema], dtype=np.int32)
[ "def", "encode", "(", "self", ",", "cube_dimensions", ")", ":", "return", "np", ".", "asarray", "(", "[", "getattr", "(", "cube_dimensions", "[", "d", "]", ",", "s", ")", "for", "d", "in", "self", ".", "_dimensions", "for", "s", "in", "self", ".", ...
Produces a numpy array of integers which encode the supplied cube dimensions.
[ "Produces", "a", "numpy", "array", "of", "integers", "which", "encode", "the", "supplied", "cube", "dimensions", "." ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/impl/rime/tensorflow/cube_dim_transcoder.py#L43-L51
ska-sa/montblanc
montblanc/impl/rime/tensorflow/cube_dim_transcoder.py
CubeDimensionTranscoder.decode
def decode(self, descriptor): """ Produce a list of dictionaries for each dimension in this transcoder """ i = iter(descriptor) n = len(self._schema) # Add the name key to our schema schema = self._schema + ('name',) # For each dimensions, generator takes n items off ite...
python
def decode(self, descriptor): """ Produce a list of dictionaries for each dimension in this transcoder """ i = iter(descriptor) n = len(self._schema) # Add the name key to our schema schema = self._schema + ('name',) # For each dimensions, generator takes n items off ite...
[ "def", "decode", "(", "self", ",", "descriptor", ")", ":", "i", "=", "iter", "(", "descriptor", ")", "n", "=", "len", "(", "self", ".", "_schema", ")", "# Add the name key to our schema", "schema", "=", "self", ".", "_schema", "+", "(", "'name'", ",", ...
Produce a list of dictionaries for each dimension in this transcoder
[ "Produce", "a", "list", "of", "dictionaries", "for", "each", "dimension", "in", "this", "transcoder" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/impl/rime/tensorflow/cube_dim_transcoder.py#L53-L67
ska-sa/montblanc
install/cub.py
dl_cub
def dl_cub(cub_url, cub_archive_name): """ Download cub archive from cub_url and store it in cub_archive_name """ with open(cub_archive_name, 'wb') as f: remote_file = urllib2.urlopen(cub_url) meta = remote_file.info() # The server may provide us with the size of the file. cl_he...
python
def dl_cub(cub_url, cub_archive_name): """ Download cub archive from cub_url and store it in cub_archive_name """ with open(cub_archive_name, 'wb') as f: remote_file = urllib2.urlopen(cub_url) meta = remote_file.info() # The server may provide us with the size of the file. cl_he...
[ "def", "dl_cub", "(", "cub_url", ",", "cub_archive_name", ")", ":", "with", "open", "(", "cub_archive_name", ",", "'wb'", ")", "as", "f", ":", "remote_file", "=", "urllib2", ".", "urlopen", "(", "cub_url", ")", "meta", "=", "remote_file", ".", "info", "(...
Download cub archive from cub_url and store it in cub_archive_name
[ "Download", "cub", "archive", "from", "cub_url", "and", "store", "it", "in", "cub_archive_name" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/install/cub.py#L33-L63
ska-sa/montblanc
install/cub.py
sha_hash_file
def sha_hash_file(filename): """ Compute the SHA1 hash of filename """ hash_sha = hashlib.sha1() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(1024*1024), b""): hash_sha.update(chunk) return hash_sha.hexdigest()
python
def sha_hash_file(filename): """ Compute the SHA1 hash of filename """ hash_sha = hashlib.sha1() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(1024*1024), b""): hash_sha.update(chunk) return hash_sha.hexdigest()
[ "def", "sha_hash_file", "(", "filename", ")", ":", "hash_sha", "=", "hashlib", ".", "sha1", "(", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "for", "chunk", "in", "iter", "(", "lambda", ":", "f", ".", "read", "(", "1024"...
Compute the SHA1 hash of filename
[ "Compute", "the", "SHA1", "hash", "of", "filename" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/install/cub.py#L65-L73
ska-sa/montblanc
install/cub.py
install_cub
def install_cub(mb_inc_path): """ Downloads and installs cub into mb_inc_path """ cub_url = 'https://github.com/NVlabs/cub/archive/1.6.4.zip' cub_sha_hash = '0d5659200132c2576be0b3959383fa756de6105d' cub_version_str = 'Current release: v1.6.4 (12/06/2016)' cub_zip_file = 'cub.zip' cub_zip_dir = ...
python
def install_cub(mb_inc_path): """ Downloads and installs cub into mb_inc_path """ cub_url = 'https://github.com/NVlabs/cub/archive/1.6.4.zip' cub_sha_hash = '0d5659200132c2576be0b3959383fa756de6105d' cub_version_str = 'Current release: v1.6.4 (12/06/2016)' cub_zip_file = 'cub.zip' cub_zip_dir = ...
[ "def", "install_cub", "(", "mb_inc_path", ")", ":", "cub_url", "=", "'https://github.com/NVlabs/cub/archive/1.6.4.zip'", "cub_sha_hash", "=", "'0d5659200132c2576be0b3959383fa756de6105d'", "cub_version_str", "=", "'Current release: v1.6.4 (12/06/2016)'", "cub_zip_file", "=", "'cub.z...
Downloads and installs cub into mb_inc_path
[ "Downloads", "and", "installs", "cub", "into", "mb_inc_path" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/install/cub.py#L97-L161
ska-sa/montblanc
install/tensorflow_ops_ext.py
cuda_architecture_flags
def cuda_architecture_flags(device_info): """ Emit a list of architecture flags for each CUDA device found ['--gpu-architecture=sm_30', '--gpu-architecture=sm_52'] """ # Figure out the necessary device architectures if len(device_info['devices']) == 0: archs = ['--gpu-architecture=sm_30'...
python
def cuda_architecture_flags(device_info): """ Emit a list of architecture flags for each CUDA device found ['--gpu-architecture=sm_30', '--gpu-architecture=sm_52'] """ # Figure out the necessary device architectures if len(device_info['devices']) == 0: archs = ['--gpu-architecture=sm_30'...
[ "def", "cuda_architecture_flags", "(", "device_info", ")", ":", "# Figure out the necessary device architectures", "if", "len", "(", "device_info", "[", "'devices'", "]", ")", "==", "0", ":", "archs", "=", "[", "'--gpu-architecture=sm_30'", "]", "log", ".", "info", ...
Emit a list of architecture flags for each CUDA device found ['--gpu-architecture=sm_30', '--gpu-architecture=sm_52']
[ "Emit", "a", "list", "of", "architecture", "flags", "for", "each", "CUDA", "device", "found", "[", "--", "gpu", "-", "architecture", "=", "sm_30", "--", "gpu", "-", "architecture", "=", "sm_52", "]" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/install/tensorflow_ops_ext.py#L63-L80
ska-sa/montblanc
install/tensorflow_ops_ext.py
create_tensorflow_extension
def create_tensorflow_extension(nvcc_settings, device_info): """ Create an extension that builds the custom tensorflow ops """ import tensorflow as tf import glob use_cuda = (bool(nvcc_settings['cuda_available']) and tf.test.is_built_with_cuda()) # Source and includes source_path = os....
python
def create_tensorflow_extension(nvcc_settings, device_info): """ Create an extension that builds the custom tensorflow ops """ import tensorflow as tf import glob use_cuda = (bool(nvcc_settings['cuda_available']) and tf.test.is_built_with_cuda()) # Source and includes source_path = os....
[ "def", "create_tensorflow_extension", "(", "nvcc_settings", ",", "device_info", ")", ":", "import", "tensorflow", "as", "tf", "import", "glob", "use_cuda", "=", "(", "bool", "(", "nvcc_settings", "[", "'cuda_available'", "]", ")", "and", "tf", ".", "test", "."...
Create an extension that builds the custom tensorflow ops
[ "Create", "an", "extension", "that", "builds", "the", "custom", "tensorflow", "ops" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/install/tensorflow_ops_ext.py#L82-L152
ska-sa/montblanc
montblanc/examples/standalone.py
CustomSourceProvider.updated_dimensions
def updated_dimensions(self): """ Inform montblanc about dimension sizes """ return [("ntime", args.ntime), # Timesteps ("nchan", args.nchan), # Channels ("na", args.na), # Antenna ("npsrc", len(lm_coords))]
python
def updated_dimensions(self): """ Inform montblanc about dimension sizes """ return [("ntime", args.ntime), # Timesteps ("nchan", args.nchan), # Channels ("na", args.na), # Antenna ("npsrc", len(lm_coords))]
[ "def", "updated_dimensions", "(", "self", ")", ":", "return", "[", "(", "\"ntime\"", ",", "args", ".", "ntime", ")", ",", "# Timesteps", "(", "\"nchan\"", ",", "args", ".", "nchan", ")", ",", "# Channels", "(", "\"na\"", ",", "args", ".", "na", ")", ...
Inform montblanc about dimension sizes
[ "Inform", "montblanc", "about", "dimension", "sizes" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/examples/standalone.py#L45-L50
ska-sa/montblanc
montblanc/examples/standalone.py
CustomSourceProvider.point_lm
def point_lm(self, context): """ Supply point source lm coordinates to montblanc """ # Shape (npsrc, 2) (ls, us), _ = context.array_extents(context.name) return np.asarray(lm_coords[ls:us], dtype=context.dtype)
python
def point_lm(self, context): """ Supply point source lm coordinates to montblanc """ # Shape (npsrc, 2) (ls, us), _ = context.array_extents(context.name) return np.asarray(lm_coords[ls:us], dtype=context.dtype)
[ "def", "point_lm", "(", "self", ",", "context", ")", ":", "# Shape (npsrc, 2)", "(", "ls", ",", "us", ")", ",", "_", "=", "context", ".", "array_extents", "(", "context", ".", "name", ")", "return", "np", ".", "asarray", "(", "lm_coords", "[", "ls", ...
Supply point source lm coordinates to montblanc
[ "Supply", "point", "source", "lm", "coordinates", "to", "montblanc" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/examples/standalone.py#L52-L57
ska-sa/montblanc
montblanc/examples/standalone.py
CustomSourceProvider.point_stokes
def point_stokes(self, context): """ Supply point source stokes parameters to montblanc """ # Shape (npsrc, ntime, 4) (ls, us), (lt, ut), (l, u) = context.array_extents(context.name) data = np.empty(context.shape, context.dtype) data[ls:us,:,l:u] = np.asarray(lm_stokes)[ls:us,N...
python
def point_stokes(self, context): """ Supply point source stokes parameters to montblanc """ # Shape (npsrc, ntime, 4) (ls, us), (lt, ut), (l, u) = context.array_extents(context.name) data = np.empty(context.shape, context.dtype) data[ls:us,:,l:u] = np.asarray(lm_stokes)[ls:us,N...
[ "def", "point_stokes", "(", "self", ",", "context", ")", ":", "# Shape (npsrc, ntime, 4)", "(", "ls", ",", "us", ")", ",", "(", "lt", ",", "ut", ")", ",", "(", "l", ",", "u", ")", "=", "context", ".", "array_extents", "(", "context", ".", "name", "...
Supply point source stokes parameters to montblanc
[ "Supply", "point", "source", "stokes", "parameters", "to", "montblanc" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/examples/standalone.py#L59-L67
ska-sa/montblanc
montblanc/examples/standalone.py
CustomSourceProvider.uvw
def uvw(self, context): """ Supply UVW antenna coordinates to montblanc """ # Shape (ntime, na, 3) (lt, ut), (la, ua), (l, u) = context.array_extents(context.name) # Create empty UVW coordinates data = np.empty(context.shape, context.dtype) data[:,:,0] = np.arange(la+1,...
python
def uvw(self, context): """ Supply UVW antenna coordinates to montblanc """ # Shape (ntime, na, 3) (lt, ut), (la, ua), (l, u) = context.array_extents(context.name) # Create empty UVW coordinates data = np.empty(context.shape, context.dtype) data[:,:,0] = np.arange(la+1,...
[ "def", "uvw", "(", "self", ",", "context", ")", ":", "# Shape (ntime, na, 3)", "(", "lt", ",", "ut", ")", ",", "(", "la", ",", "ua", ")", ",", "(", "l", ",", "u", ")", "=", "context", ".", "array_extents", "(", "context", ".", "name", ")", "# Cre...
Supply UVW antenna coordinates to montblanc
[ "Supply", "UVW", "antenna", "coordinates", "to", "montblanc" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/examples/standalone.py#L69-L81
ska-sa/montblanc
setup.py
reinitialize_command
def reinitialize_command(self, command, reinit_subcommands): """ Monkeypatch distutils.Distribution.reinitialize_command() to match behavior of Distribution.get_command_obj() This fixes a problem where 'pip install -e' does not reinitialise options using the setup(options={...}) variable for the bui...
python
def reinitialize_command(self, command, reinit_subcommands): """ Monkeypatch distutils.Distribution.reinitialize_command() to match behavior of Distribution.get_command_obj() This fixes a problem where 'pip install -e' does not reinitialise options using the setup(options={...}) variable for the bui...
[ "def", "reinitialize_command", "(", "self", ",", "command", ",", "reinit_subcommands", ")", ":", "cmd_obj", "=", "_DISTUTILS_REINIT", "(", "self", ",", "command", ",", "reinit_subcommands", ")", "options", "=", "self", ".", "command_options", ".", "get", "(", ...
Monkeypatch distutils.Distribution.reinitialize_command() to match behavior of Distribution.get_command_obj() This fixes a problem where 'pip install -e' does not reinitialise options using the setup(options={...}) variable for the build_ext command. This also effects other option sourcs such as setup.c...
[ "Monkeypatch", "distutils", ".", "Distribution", ".", "reinitialize_command", "()", "to", "match", "behavior", "of", "Distribution", ".", "get_command_obj", "()", "This", "fixes", "a", "problem", "where", "pip", "install", "-", "e", "does", "not", "reinitialise", ...
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/setup.py#L64-L79
ska-sa/montblanc
montblanc/util/__init__.py
nr_of_baselines
def nr_of_baselines(na, auto_correlations=False): """ Compute the number of baselines for the given number of antenna. Can specify whether auto-correlations should be taken into account """ m = (na-1) if auto_correlations is False else (na+1) return (na*m)//2
python
def nr_of_baselines(na, auto_correlations=False): """ Compute the number of baselines for the given number of antenna. Can specify whether auto-correlations should be taken into account """ m = (na-1) if auto_correlations is False else (na+1) return (na*m)//2
[ "def", "nr_of_baselines", "(", "na", ",", "auto_correlations", "=", "False", ")", ":", "m", "=", "(", "na", "-", "1", ")", "if", "auto_correlations", "is", "False", "else", "(", "na", "+", "1", ")", "return", "(", "na", "*", "m", ")", "//", "2" ]
Compute the number of baselines for the given number of antenna. Can specify whether auto-correlations should be taken into account
[ "Compute", "the", "number", "of", "baselines", "for", "the", "given", "number", "of", "antenna", ".", "Can", "specify", "whether", "auto", "-", "correlations", "should", "be", "taken", "into", "account" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L43-L51
ska-sa/montblanc
montblanc/util/__init__.py
nr_of_antenna
def nr_of_antenna(nbl, auto_correlations=False): """ Compute the number of antenna for the given number of baselines. Can specify whether auto-correlations should be taken into account """ t = 1 if auto_correlations is False else -1 return int(t + math.sqrt(1 + 8*nbl)) // 2
python
def nr_of_antenna(nbl, auto_correlations=False): """ Compute the number of antenna for the given number of baselines. Can specify whether auto-correlations should be taken into account """ t = 1 if auto_correlations is False else -1 return int(t + math.sqrt(1 + 8*nbl)) // 2
[ "def", "nr_of_antenna", "(", "nbl", ",", "auto_correlations", "=", "False", ")", ":", "t", "=", "1", "if", "auto_correlations", "is", "False", "else", "-", "1", "return", "int", "(", "t", "+", "math", ".", "sqrt", "(", "1", "+", "8", "*", "nbl", ")...
Compute the number of antenna for the given number of baselines. Can specify whether auto-correlations should be taken into account
[ "Compute", "the", "number", "of", "antenna", "for", "the", "given", "number", "of", "baselines", ".", "Can", "specify", "whether", "auto", "-", "correlations", "should", "be", "taken", "into", "account" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L53-L61
ska-sa/montblanc
montblanc/util/__init__.py
array_bytes
def array_bytes(shape, dtype): """ Estimates the memory in bytes required for an array of the supplied shape and dtype """ return np.product(shape)*np.dtype(dtype).itemsize
python
def array_bytes(shape, dtype): """ Estimates the memory in bytes required for an array of the supplied shape and dtype """ return np.product(shape)*np.dtype(dtype).itemsize
[ "def", "array_bytes", "(", "shape", ",", "dtype", ")", ":", "return", "np", ".", "product", "(", "shape", ")", "*", "np", ".", "dtype", "(", "dtype", ")", ".", "itemsize" ]
Estimates the memory in bytes required for an array of the supplied shape and dtype
[ "Estimates", "the", "memory", "in", "bytes", "required", "for", "an", "array", "of", "the", "supplied", "shape", "and", "dtype" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L79-L81
ska-sa/montblanc
montblanc/util/__init__.py
random_like
def random_like(ary=None, shape=None, dtype=None): """ Returns a random array of the same shape and type as the supplied array argument, or the supplied shape and dtype """ if ary is not None: shape, dtype = ary.shape, ary.dtype elif shape is None or dtype is None: raise ValueErr...
python
def random_like(ary=None, shape=None, dtype=None): """ Returns a random array of the same shape and type as the supplied array argument, or the supplied shape and dtype """ if ary is not None: shape, dtype = ary.shape, ary.dtype elif shape is None or dtype is None: raise ValueErr...
[ "def", "random_like", "(", "ary", "=", "None", ",", "shape", "=", "None", ",", "dtype", "=", "None", ")", ":", "if", "ary", "is", "not", "None", ":", "shape", ",", "dtype", "=", "ary", ".", "shape", ",", "ary", ".", "dtype", "elif", "shape", "is"...
Returns a random array of the same shape and type as the supplied array argument, or the supplied shape and dtype
[ "Returns", "a", "random", "array", "of", "the", "same", "shape", "and", "type", "as", "the", "supplied", "array", "argument", "or", "the", "supplied", "shape", "and", "dtype" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L96-L113
ska-sa/montblanc
montblanc/util/__init__.py
flatten
def flatten(nested): """ Return a flatten version of the nested argument """ flat_return = list() def __inner_flat(nested,flat): for i in nested: __inner_flat(i, flat) if isinstance(i, list) else flat.append(i) return flat __inner_flat(nested,flat_return) return flat_r...
python
def flatten(nested): """ Return a flatten version of the nested argument """ flat_return = list() def __inner_flat(nested,flat): for i in nested: __inner_flat(i, flat) if isinstance(i, list) else flat.append(i) return flat __inner_flat(nested,flat_return) return flat_r...
[ "def", "flatten", "(", "nested", ")", ":", "flat_return", "=", "list", "(", ")", "def", "__inner_flat", "(", "nested", ",", "flat", ")", ":", "for", "i", "in", "nested", ":", "__inner_flat", "(", "i", ",", "flat", ")", "if", "isinstance", "(", "i", ...
Return a flatten version of the nested argument
[ "Return", "a", "flatten", "version", "of", "the", "nested", "argument" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L115-L126
ska-sa/montblanc
montblanc/util/__init__.py
dict_array_bytes
def dict_array_bytes(ary, template): """ Return the number of bytes required by an array Arguments --------------- ary : dict Dictionary representation of an array template : dict A dictionary of key-values, used to replace any string values in the array with concrete in...
python
def dict_array_bytes(ary, template): """ Return the number of bytes required by an array Arguments --------------- ary : dict Dictionary representation of an array template : dict A dictionary of key-values, used to replace any string values in the array with concrete in...
[ "def", "dict_array_bytes", "(", "ary", ",", "template", ")", ":", "shape", "=", "shape_from_str_tuple", "(", "ary", "[", "'shape'", "]", ",", "template", ")", "dtype", "=", "dtype_from_str", "(", "ary", "[", "'dtype'", "]", ",", "template", ")", "return", ...
Return the number of bytes required by an array Arguments --------------- ary : dict Dictionary representation of an array template : dict A dictionary of key-values, used to replace any string values in the array with concrete integral values Returns ----------...
[ "Return", "the", "number", "of", "bytes", "required", "by", "an", "array" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L128-L149
ska-sa/montblanc
montblanc/util/__init__.py
dict_array_bytes_required
def dict_array_bytes_required(arrays, template): """ Return the number of bytes required by a dictionary of arrays. Arguments --------------- arrays : list A list of dictionaries defining the arrays template : dict A dictionary of key-values, used to replace any stri...
python
def dict_array_bytes_required(arrays, template): """ Return the number of bytes required by a dictionary of arrays. Arguments --------------- arrays : list A list of dictionaries defining the arrays template : dict A dictionary of key-values, used to replace any stri...
[ "def", "dict_array_bytes_required", "(", "arrays", ",", "template", ")", ":", "return", "np", ".", "sum", "(", "[", "dict_array_bytes", "(", "ary", ",", "template", ")", "for", "ary", "in", "arrays", "]", ")" ]
Return the number of bytes required by a dictionary of arrays. Arguments --------------- arrays : list A list of dictionaries defining the arrays template : dict A dictionary of key-values, used to replace any string values in the arrays with concrete integral values...
[ "Return", "the", "number", "of", "bytes", "required", "by", "a", "dictionary", "of", "arrays", "." ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L151-L171
ska-sa/montblanc
montblanc/util/__init__.py
viable_dim_config
def viable_dim_config(bytes_available, arrays, template, dim_ord, nsolvers=1): """ Returns the number of timesteps possible, given the registered arrays and a memory budget defined by bytes_available Arguments ---------------- bytes_available : int The memory budget, or availabl...
python
def viable_dim_config(bytes_available, arrays, template, dim_ord, nsolvers=1): """ Returns the number of timesteps possible, given the registered arrays and a memory budget defined by bytes_available Arguments ---------------- bytes_available : int The memory budget, or availabl...
[ "def", "viable_dim_config", "(", "bytes_available", ",", "arrays", ",", "template", ",", "dim_ord", ",", "nsolvers", "=", "1", ")", ":", "if", "not", "isinstance", "(", "dim_ord", ",", "list", ")", ":", "raise", "TypeError", "(", "'dim_ord should be a list'", ...
Returns the number of timesteps possible, given the registered arrays and a memory budget defined by bytes_available Arguments ---------------- bytes_available : int The memory budget, or available number of bytes for solving the problem. arrays : list List of dictionaries d...
[ "Returns", "the", "number", "of", "timesteps", "possible", "given", "the", "registered", "arrays", "and", "a", "memory", "budget", "defined", "by", "bytes_available" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L180-L299
ska-sa/montblanc
montblanc/util/__init__.py
shape_from_str_tuple
def shape_from_str_tuple(sshape, variables, ignore=None): """ Substitutes string values in the supplied shape parameter with integer variables stored in a dictionary Parameters ---------- sshape : tuple/string composed of integers and strings. The strings should related to integral prop...
python
def shape_from_str_tuple(sshape, variables, ignore=None): """ Substitutes string values in the supplied shape parameter with integer variables stored in a dictionary Parameters ---------- sshape : tuple/string composed of integers and strings. The strings should related to integral prop...
[ "def", "shape_from_str_tuple", "(", "sshape", ",", "variables", ",", "ignore", "=", "None", ")", ":", "if", "ignore", "is", "None", ":", "ignore", "=", "[", "]", "if", "not", "isinstance", "(", "sshape", ",", "tuple", ")", "and", "not", "isinstance", "...
Substitutes string values in the supplied shape parameter with integer variables stored in a dictionary Parameters ---------- sshape : tuple/string composed of integers and strings. The strings should related to integral properties registered with this Solver object variables : dict...
[ "Substitutes", "string", "values", "in", "the", "supplied", "shape", "parameter", "with", "integer", "variables", "stored", "in", "a", "dictionary" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L324-L352
ska-sa/montblanc
montblanc/util/__init__.py
shape_list
def shape_list(l,shape,dtype): """ Shape a list of lists into the appropriate shape and data type """ return np.array(l, dtype=dtype).reshape(shape)
python
def shape_list(l,shape,dtype): """ Shape a list of lists into the appropriate shape and data type """ return np.array(l, dtype=dtype).reshape(shape)
[ "def", "shape_list", "(", "l", ",", "shape", ",", "dtype", ")", ":", "return", "np", ".", "array", "(", "l", ",", "dtype", "=", "dtype", ")", ".", "reshape", "(", "shape", ")" ]
Shape a list of lists into the appropriate shape and data type
[ "Shape", "a", "list", "of", "lists", "into", "the", "appropriate", "shape", "and", "data", "type" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L354-L356
ska-sa/montblanc
montblanc/util/__init__.py
array_convert_function
def array_convert_function(sshape_one, sshape_two, variables): """ Return a function defining the conversion process between two NumPy arrays of different shapes """ if not isinstance(sshape_one, tuple): sshape_one = (sshape_one,) if not isinstance(sshape_two, tuple): sshape_two = (sshape_two,) s_o...
python
def array_convert_function(sshape_one, sshape_two, variables): """ Return a function defining the conversion process between two NumPy arrays of different shapes """ if not isinstance(sshape_one, tuple): sshape_one = (sshape_one,) if not isinstance(sshape_two, tuple): sshape_two = (sshape_two,) s_o...
[ "def", "array_convert_function", "(", "sshape_one", ",", "sshape_two", ",", "variables", ")", ":", "if", "not", "isinstance", "(", "sshape_one", ",", "tuple", ")", ":", "sshape_one", "=", "(", "sshape_one", ",", ")", "if", "not", "isinstance", "(", "sshape_t...
Return a function defining the conversion process between two NumPy arrays of different shapes
[ "Return", "a", "function", "defining", "the", "conversion", "process", "between", "two", "NumPy", "arrays", "of", "different", "shapes" ]
train
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L358-L385