id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
13,300
gamechanger/mongothon
mongothon/model.py
Model.apply_defaults
def apply_defaults(self): """Apply schema defaults to this document.""" self.emit('will_apply_defaults') self.schema.apply_defaults(self) self.emit('did_apply_defaults')
python
def apply_defaults(self): """Apply schema defaults to this document.""" self.emit('will_apply_defaults') self.schema.apply_defaults(self) self.emit('did_apply_defaults')
[ "def", "apply_defaults", "(", "self", ")", ":", "self", ".", "emit", "(", "'will_apply_defaults'", ")", "self", ".", "schema", ".", "apply_defaults", "(", "self", ")", "self", ".", "emit", "(", "'did_apply_defaults'", ")" ]
Apply schema defaults to this document.
[ "Apply", "schema", "defaults", "to", "this", "document", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/model.py#L106-L110
13,301
gamechanger/mongothon
mongothon/model.py
Model.reload
def reload(self): """Reloads the current model's data from the underlying database record, updating it in-place.""" self.emit('will_reload') self.populate(self.collection.find_one(type(self)._id_spec(self['_id']))) self.emit('did_reload')
python
def reload(self): """Reloads the current model's data from the underlying database record, updating it in-place.""" self.emit('will_reload') self.populate(self.collection.find_one(type(self)._id_spec(self['_id']))) self.emit('did_reload')
[ "def", "reload", "(", "self", ")", ":", "self", ".", "emit", "(", "'will_reload'", ")", "self", ".", "populate", "(", "self", ".", "collection", ".", "find_one", "(", "type", "(", "self", ")", ".", "_id_spec", "(", "self", "[", "'_id'", "]", ")", "...
Reloads the current model's data from the underlying database record, updating it in-place.
[ "Reloads", "the", "current", "model", "s", "data", "from", "the", "underlying", "database", "record", "updating", "it", "in", "-", "place", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/model.py#L195-L200
13,302
gamechanger/mongothon
mongothon/model.py
Model.on
def on(cls, event, handler_func=None): """ Registers a handler function whenever an instance of the model emits the given event. This method can either called directly, passing a function reference: MyModel.on('did_save', my_function) ...or as a decorator of the fu...
python
def on(cls, event, handler_func=None): """ Registers a handler function whenever an instance of the model emits the given event. This method can either called directly, passing a function reference: MyModel.on('did_save', my_function) ...or as a decorator of the fu...
[ "def", "on", "(", "cls", ",", "event", ",", "handler_func", "=", "None", ")", ":", "if", "handler_func", ":", "cls", ".", "handler_registrar", "(", ")", ".", "register", "(", "event", ",", "handler_func", ")", "return", "def", "register", "(", "fn", ")...
Registers a handler function whenever an instance of the model emits the given event. This method can either called directly, passing a function reference: MyModel.on('did_save', my_function) ...or as a decorator of the function to be registered. @MyModel.on('did_save...
[ "Registers", "a", "handler", "function", "whenever", "an", "instance", "of", "the", "model", "emits", "the", "given", "event", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/model.py#L203-L227
13,303
gamechanger/mongothon
mongothon/model.py
Model._emit
def _emit(self, event, document, *args, **kwargs): """ Inner version of emit which passes the given document as the primary argument to handler functions. """ self.handler_registrar().apply(event, document, *args, **kwargs)
python
def _emit(self, event, document, *args, **kwargs): """ Inner version of emit which passes the given document as the primary argument to handler functions. """ self.handler_registrar().apply(event, document, *args, **kwargs)
[ "def", "_emit", "(", "self", ",", "event", ",", "document", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "handler_registrar", "(", ")", ".", "apply", "(", "event", ",", "document", ",", "*", "args", ",", "*", "*", "kwargs", "...
Inner version of emit which passes the given document as the primary argument to handler functions.
[ "Inner", "version", "of", "emit", "which", "passes", "the", "given", "document", "as", "the", "primary", "argument", "to", "handler", "functions", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/model.py#L229-L234
13,304
gamechanger/mongothon
mongothon/model.py
Model.emit
def emit(self, event, *args, **kwargs): """ Emits an event call to all handler functions registered against this model's class and the given event type. """ self._emit(event, self, *args, **kwargs)
python
def emit(self, event, *args, **kwargs): """ Emits an event call to all handler functions registered against this model's class and the given event type. """ self._emit(event, self, *args, **kwargs)
[ "def", "emit", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_emit", "(", "event", ",", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Emits an event call to all handler functions registered against this model's class and the given event type.
[ "Emits", "an", "event", "call", "to", "all", "handler", "functions", "registered", "against", "this", "model", "s", "class", "and", "the", "given", "event", "type", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/model.py#L237-L242
13,305
gamechanger/mongothon
mongothon/model.py
Model.static_method
def static_method(cls, f): """Decorator which dynamically binds static methods to the model for later use.""" setattr(cls, f.__name__, staticmethod(f)) return f
python
def static_method(cls, f): """Decorator which dynamically binds static methods to the model for later use.""" setattr(cls, f.__name__, staticmethod(f)) return f
[ "def", "static_method", "(", "cls", ",", "f", ")", ":", "setattr", "(", "cls", ",", "f", ".", "__name__", ",", "staticmethod", "(", "f", ")", ")", "return", "f" ]
Decorator which dynamically binds static methods to the model for later use.
[ "Decorator", "which", "dynamically", "binds", "static", "methods", "to", "the", "model", "for", "later", "use", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/model.py#L267-L270
13,306
gamechanger/mongothon
mongothon/model.py
Model.class_method
def class_method(cls, f): """Decorator which dynamically binds class methods to the model for later use.""" setattr(cls, f.__name__, classmethod(f)) return f
python
def class_method(cls, f): """Decorator which dynamically binds class methods to the model for later use.""" setattr(cls, f.__name__, classmethod(f)) return f
[ "def", "class_method", "(", "cls", ",", "f", ")", ":", "setattr", "(", "cls", ",", "f", ".", "__name__", ",", "classmethod", "(", "f", ")", ")", "return", "f" ]
Decorator which dynamically binds class methods to the model for later use.
[ "Decorator", "which", "dynamically", "binds", "class", "methods", "to", "the", "model", "for", "later", "use", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/model.py#L273-L276
13,307
gamechanger/mongothon
mongothon/model.py
Model.scope
def scope(cls, f): """Decorator which can dynamically attach a query scope to the model.""" if not hasattr(cls, "scopes"): cls.scopes = copy(STANDARD_SCOPES) cls.scopes.append(f) def create_builder(self, *args, **kwargs): bldr = ScopeBuilder(cls, cls.scopes) ...
python
def scope(cls, f): """Decorator which can dynamically attach a query scope to the model.""" if not hasattr(cls, "scopes"): cls.scopes = copy(STANDARD_SCOPES) cls.scopes.append(f) def create_builder(self, *args, **kwargs): bldr = ScopeBuilder(cls, cls.scopes) ...
[ "def", "scope", "(", "cls", ",", "f", ")", ":", "if", "not", "hasattr", "(", "cls", ",", "\"scopes\"", ")", ":", "cls", ".", "scopes", "=", "copy", "(", "STANDARD_SCOPES", ")", "cls", ".", "scopes", ".", "append", "(", "f", ")", "def", "create_buil...
Decorator which can dynamically attach a query scope to the model.
[ "Decorator", "which", "can", "dynamically", "attach", "a", "query", "scope", "to", "the", "model", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/model.py#L285-L297
13,308
gamechanger/mongothon
mongothon/__init__.py
_module_name_from_previous_frame
def _module_name_from_previous_frame(num_frames_back): """ Returns the module name associated with a frame `num_frames_back` in the call stack. This function adds 1 to account for itself, so `num_frames_back` should be given relative to the caller. """ frm = inspect.stack()[num_frames_back + 1] ...
python
def _module_name_from_previous_frame(num_frames_back): """ Returns the module name associated with a frame `num_frames_back` in the call stack. This function adds 1 to account for itself, so `num_frames_back` should be given relative to the caller. """ frm = inspect.stack()[num_frames_back + 1] ...
[ "def", "_module_name_from_previous_frame", "(", "num_frames_back", ")", ":", "frm", "=", "inspect", ".", "stack", "(", ")", "[", "num_frames_back", "+", "1", "]", "return", "inspect", ".", "getmodule", "(", "frm", "[", "0", "]", ")", ".", "__name__" ]
Returns the module name associated with a frame `num_frames_back` in the call stack. This function adds 1 to account for itself, so `num_frames_back` should be given relative to the caller.
[ "Returns", "the", "module", "name", "associated", "with", "a", "frame", "num_frames_back", "in", "the", "call", "stack", ".", "This", "function", "adds", "1", "to", "account", "for", "itself", "so", "num_frames_back", "should", "be", "given", "relative", "to",...
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/__init__.py#L9-L16
13,309
gamechanger/mongothon
mongothon/__init__.py
create_model
def create_model(schema, collection, class_name=None): """ Main entry point to creating a new mongothon model. Both schema and Pymongo collection objects must be provided. Returns a new class which can be used as a model class. The class name of the model class by default is inferred from the ...
python
def create_model(schema, collection, class_name=None): """ Main entry point to creating a new mongothon model. Both schema and Pymongo collection objects must be provided. Returns a new class which can be used as a model class. The class name of the model class by default is inferred from the ...
[ "def", "create_model", "(", "schema", ",", "collection", ",", "class_name", "=", "None", ")", ":", "if", "not", "class_name", ":", "class_name", "=", "camelize", "(", "str", "(", "collection", ".", "name", ")", ")", "model_class", "=", "type", "(", "clas...
Main entry point to creating a new mongothon model. Both schema and Pymongo collection objects must be provided. Returns a new class which can be used as a model class. The class name of the model class by default is inferred from the provided collection (converted to camel case). Optionally, a cl...
[ "Main", "entry", "point", "to", "creating", "a", "new", "mongothon", "model", ".", "Both", "schema", "and", "Pymongo", "collection", "objects", "must", "be", "provided", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/__init__.py#L19-L42
13,310
gamechanger/mongothon
mongothon/__init__.py
create_model_offline
def create_model_offline(schema, collection_factory, class_name): """ Entry point for creating a new Mongothon model without instantiating a database connection. The collection is instead provided through a closure that is resolved upon the model's first database access. """ model_class = type(c...
python
def create_model_offline(schema, collection_factory, class_name): """ Entry point for creating a new Mongothon model without instantiating a database connection. The collection is instead provided through a closure that is resolved upon the model's first database access. """ model_class = type(c...
[ "def", "create_model_offline", "(", "schema", ",", "collection_factory", ",", "class_name", ")", ":", "model_class", "=", "type", "(", "class_name", ",", "(", "Model", ",", ")", ",", "dict", "(", "schema", "=", "schema", ",", "_collection_factory", "=", "sta...
Entry point for creating a new Mongothon model without instantiating a database connection. The collection is instead provided through a closure that is resolved upon the model's first database access.
[ "Entry", "point", "for", "creating", "a", "new", "Mongothon", "model", "without", "instantiating", "a", "database", "connection", ".", "The", "collection", "is", "instead", "provided", "through", "a", "closure", "that", "is", "resolved", "upon", "the", "model", ...
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/__init__.py#L45-L59
13,311
gamechanger/mongothon
mongothon/document.py
wrap
def wrap(value): """ Wraps the given value in a Document or DocumentList as applicable. """ if isinstance(value, Document) or isinstance(value, DocumentList): return value elif isinstance(value, dict): return Document(value) elif isinstance(value, list): return DocumentLi...
python
def wrap(value): """ Wraps the given value in a Document or DocumentList as applicable. """ if isinstance(value, Document) or isinstance(value, DocumentList): return value elif isinstance(value, dict): return Document(value) elif isinstance(value, list): return DocumentLi...
[ "def", "wrap", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Document", ")", "or", "isinstance", "(", "value", ",", "DocumentList", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "Doc...
Wraps the given value in a Document or DocumentList as applicable.
[ "Wraps", "the", "given", "value", "in", "a", "Document", "or", "DocumentList", "as", "applicable", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/document.py#L3-L14
13,312
gamechanger/mongothon
mongothon/document.py
unwrap
def unwrap(value): """ Unwraps the given Document or DocumentList as applicable. """ if isinstance(value, Document): return value.to_dict() elif isinstance(value, DocumentList): return value.to_list() else: return value
python
def unwrap(value): """ Unwraps the given Document or DocumentList as applicable. """ if isinstance(value, Document): return value.to_dict() elif isinstance(value, DocumentList): return value.to_list() else: return value
[ "def", "unwrap", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Document", ")", ":", "return", "value", ".", "to_dict", "(", ")", "elif", "isinstance", "(", "value", ",", "DocumentList", ")", ":", "return", "value", ".", "to_list", "("...
Unwraps the given Document or DocumentList as applicable.
[ "Unwraps", "the", "given", "Document", "or", "DocumentList", "as", "applicable", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/document.py#L17-L26
13,313
gamechanger/mongothon
mongothon/document.py
ChangeTracker.note_change
def note_change(self, key, value): """ Updates change state to reflect a change to a field. Takes care of ignoring no-ops, reversions and takes appropriate steps if the field was previously deleted or added to ensure the change state purely reflects the diff since last reset. ...
python
def note_change(self, key, value): """ Updates change state to reflect a change to a field. Takes care of ignoring no-ops, reversions and takes appropriate steps if the field was previously deleted or added to ensure the change state purely reflects the diff since last reset. ...
[ "def", "note_change", "(", "self", ",", "key", ",", "value", ")", ":", "# If we're changing the value and we haven't done so already, note it.", "if", "value", "!=", "self", ".", "_instance", "[", "key", "]", "and", "key", "not", "in", "self", ".", "_previous", ...
Updates change state to reflect a change to a field. Takes care of ignoring no-ops, reversions and takes appropriate steps if the field was previously deleted or added to ensure the change state purely reflects the diff since last reset.
[ "Updates", "change", "state", "to", "reflect", "a", "change", "to", "a", "field", ".", "Takes", "care", "of", "ignoring", "no", "-", "ops", "reversions", "and", "takes", "appropriate", "steps", "if", "the", "field", "was", "previously", "deleted", "or", "a...
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/document.py#L49-L62
13,314
gamechanger/mongothon
mongothon/document.py
ChangeTracker.note_addition
def note_addition(self, key, value): """ Updates the change state to reflect the addition of a field. Detects previous changes and deletions of the field and acts accordingly. """ # If we're adding a field we previously deleted, remove the deleted note. if key in self._de...
python
def note_addition(self, key, value): """ Updates the change state to reflect the addition of a field. Detects previous changes and deletions of the field and acts accordingly. """ # If we're adding a field we previously deleted, remove the deleted note. if key in self._de...
[ "def", "note_addition", "(", "self", ",", "key", ",", "value", ")", ":", "# If we're adding a field we previously deleted, remove the deleted note.", "if", "key", "in", "self", ".", "_deleted", ":", "# If the key we're adding back has a different value, then it's a change", "if...
Updates the change state to reflect the addition of a field. Detects previous changes and deletions of the field and acts accordingly.
[ "Updates", "the", "change", "state", "to", "reflect", "the", "addition", "of", "a", "field", ".", "Detects", "previous", "changes", "and", "deletions", "of", "the", "field", "and", "acts", "accordingly", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/document.py#L64-L76
13,315
gamechanger/mongothon
mongothon/document.py
ChangeTracker.note_deletion
def note_deletion(self, key): """ Notes the deletion of a field. """ # If we'rew deleting a key we previously added, then there is no diff if key in self._added: self._added.remove(key) else: # If the deleted key was previously changed, use the ori...
python
def note_deletion(self, key): """ Notes the deletion of a field. """ # If we'rew deleting a key we previously added, then there is no diff if key in self._added: self._added.remove(key) else: # If the deleted key was previously changed, use the ori...
[ "def", "note_deletion", "(", "self", ",", "key", ")", ":", "# If we'rew deleting a key we previously added, then there is no diff", "if", "key", "in", "self", ".", "_added", ":", "self", ".", "_added", ".", "remove", "(", "key", ")", "else", ":", "# If the deleted...
Notes the deletion of a field.
[ "Notes", "the", "deletion", "of", "a", "field", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/document.py#L78-L91
13,316
gamechanger/mongothon
mongothon/document.py
ChangeTracker.changes
def changes(self): """ Returns a dict containing just the fields which have changed on this Document since it was created or last saved, together with both their previous and current values doc['name'] # => 'bob' doc['name'] = 'clive' doc....
python
def changes(self): """ Returns a dict containing just the fields which have changed on this Document since it was created or last saved, together with both their previous and current values doc['name'] # => 'bob' doc['name'] = 'clive' doc....
[ "def", "changes", "(", "self", ")", ":", "return", "{", "key", ":", "(", "self", ".", "_previous", "[", "key", "]", ",", "self", ".", "_instance", "[", "key", "]", ")", "for", "key", "in", "self", ".", "_previous", "}" ]
Returns a dict containing just the fields which have changed on this Document since it was created or last saved, together with both their previous and current values doc['name'] # => 'bob' doc['name'] = 'clive' doc.changes # => {'name': ('bob...
[ "Returns", "a", "dict", "containing", "just", "the", "fields", "which", "have", "changed", "on", "this", "Document", "since", "it", "was", "created", "or", "last", "saved", "together", "with", "both", "their", "previous", "and", "current", "values" ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/document.py#L107-L118
13,317
gamechanger/mongothon
mongothon/document.py
Document.reset_all_changes
def reset_all_changes(self): """ Resets change tracking in this document, recursing into child Documents and DocumentLists. """ self.reset_changes() for value in self.values(): if isinstance(value, Document) or isinstance(value, DocumentList): ...
python
def reset_all_changes(self): """ Resets change tracking in this document, recursing into child Documents and DocumentLists. """ self.reset_changes() for value in self.values(): if isinstance(value, Document) or isinstance(value, DocumentList): ...
[ "def", "reset_all_changes", "(", "self", ")", ":", "self", ".", "reset_changes", "(", ")", "for", "value", "in", "self", ".", "values", "(", ")", ":", "if", "isinstance", "(", "value", ",", "Document", ")", "or", "isinstance", "(", "value", ",", "Docum...
Resets change tracking in this document, recursing into child Documents and DocumentLists.
[ "Resets", "change", "tracking", "in", "this", "document", "recursing", "into", "child", "Documents", "and", "DocumentLists", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/document.py#L161-L169
13,318
gamechanger/mongothon
mongothon/document.py
Document.populate
def populate(self, other): """Like update, but clears the contents first.""" self.clear() self.update(other) self.reset_all_changes()
python
def populate(self, other): """Like update, but clears the contents first.""" self.clear() self.update(other) self.reset_all_changes()
[ "def", "populate", "(", "self", ",", "other", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "update", "(", "other", ")", "self", ".", "reset_all_changes", "(", ")" ]
Like update, but clears the contents first.
[ "Like", "update", "but", "clears", "the", "contents", "first", "." ]
5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/document.py#L215-L219
13,319
msoulier/tftpy
tftpy/TftpPacketFactory.py
TftpPacketFactory.parse
def parse(self, buffer): """This method is used to parse an existing datagram into its corresponding TftpPacket object. The buffer is the raw bytes off of the network.""" log.debug("parsing a %d byte packet" % len(buffer)) (opcode,) = struct.unpack(str("!H"), buffer[:2]) ...
python
def parse(self, buffer): """This method is used to parse an existing datagram into its corresponding TftpPacket object. The buffer is the raw bytes off of the network.""" log.debug("parsing a %d byte packet" % len(buffer)) (opcode,) = struct.unpack(str("!H"), buffer[:2]) ...
[ "def", "parse", "(", "self", ",", "buffer", ")", ":", "log", ".", "debug", "(", "\"parsing a %d byte packet\"", "%", "len", "(", "buffer", ")", ")", "(", "opcode", ",", ")", "=", "struct", ".", "unpack", "(", "str", "(", "\"!H\"", ")", ",", "buffer",...
This method is used to parse an existing datagram into its corresponding TftpPacket object. The buffer is the raw bytes off of the network.
[ "This", "method", "is", "used", "to", "parse", "an", "existing", "datagram", "into", "its", "corresponding", "TftpPacket", "object", ".", "The", "buffer", "is", "the", "raw", "bytes", "off", "of", "the", "network", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketFactory.py#L28-L37
13,320
msoulier/tftpy
tftpy/TftpPacketFactory.py
TftpPacketFactory.__create
def __create(self, opcode): """This method returns the appropriate class object corresponding to the passed opcode.""" tftpassert(opcode in self.classes, "Unsupported opcode: %d" % opcode) packet = self.classes[opcode]() return packet
python
def __create(self, opcode): """This method returns the appropriate class object corresponding to the passed opcode.""" tftpassert(opcode in self.classes, "Unsupported opcode: %d" % opcode) packet = self.classes[opcode]() return packet
[ "def", "__create", "(", "self", ",", "opcode", ")", ":", "tftpassert", "(", "opcode", "in", "self", ".", "classes", ",", "\"Unsupported opcode: %d\"", "%", "opcode", ")", "packet", "=", "self", ".", "classes", "[", "opcode", "]", "(", ")", "return", "pac...
This method returns the appropriate class object corresponding to the passed opcode.
[ "This", "method", "returns", "the", "appropriate", "class", "object", "corresponding", "to", "the", "passed", "opcode", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketFactory.py#L39-L47
13,321
msoulier/tftpy
tftpy/TftpContexts.py
TftpMetrics.add_dup
def add_dup(self, pkt): """This method adds a dup for a packet to the metrics.""" log.debug("Recording a dup of %s", pkt) s = str(pkt) if s in self.dups: self.dups[s] += 1 else: self.dups[s] = 1 tftpassert(self.dups[s] < MAX_DUPS, "Max duplicates r...
python
def add_dup(self, pkt): """This method adds a dup for a packet to the metrics.""" log.debug("Recording a dup of %s", pkt) s = str(pkt) if s in self.dups: self.dups[s] += 1 else: self.dups[s] = 1 tftpassert(self.dups[s] < MAX_DUPS, "Max duplicates r...
[ "def", "add_dup", "(", "self", ",", "pkt", ")", ":", "log", ".", "debug", "(", "\"Recording a dup of %s\"", ",", "pkt", ")", "s", "=", "str", "(", "pkt", ")", "if", "s", "in", "self", ".", "dups", ":", "self", ".", "dups", "[", "s", "]", "+=", ...
This method adds a dup for a packet to the metrics.
[ "This", "method", "adds", "a", "dup", "for", "a", "packet", "to", "the", "metrics", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpContexts.py#L62-L70
13,322
msoulier/tftpy
tftpy/TftpContexts.py
TftpContext.checkTimeout
def checkTimeout(self, now): """Compare current time with last_update time, and raise an exception if we're over the timeout time.""" log.debug("checking for timeout on session %s", self) if now - self.last_update > self.timeout: raise TftpTimeout("Timeout waiting for traffic...
python
def checkTimeout(self, now): """Compare current time with last_update time, and raise an exception if we're over the timeout time.""" log.debug("checking for timeout on session %s", self) if now - self.last_update > self.timeout: raise TftpTimeout("Timeout waiting for traffic...
[ "def", "checkTimeout", "(", "self", ",", "now", ")", ":", "log", ".", "debug", "(", "\"checking for timeout on session %s\"", ",", "self", ")", "if", "now", "-", "self", ".", "last_update", ">", "self", ".", "timeout", ":", "raise", "TftpTimeout", "(", "\"...
Compare current time with last_update time, and raise an exception if we're over the timeout time.
[ "Compare", "current", "time", "with", "last_update", "time", "and", "raise", "an", "exception", "if", "we", "re", "over", "the", "timeout", "time", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpContexts.py#L121-L126
13,323
msoulier/tftpy
tftpy/TftpContexts.py
TftpContext.end
def end(self, close_fileobj=True): """Perform session cleanup, since the end method should always be called explicitely by the calling code, this works better than the destructor. Set close_fileobj to False so fileobj can be returned open.""" log.debug("in TftpContext.end - closi...
python
def end(self, close_fileobj=True): """Perform session cleanup, since the end method should always be called explicitely by the calling code, this works better than the destructor. Set close_fileobj to False so fileobj can be returned open.""" log.debug("in TftpContext.end - closi...
[ "def", "end", "(", "self", ",", "close_fileobj", "=", "True", ")", ":", "log", ".", "debug", "(", "\"in TftpContext.end - closing socket\"", ")", "self", ".", "sock", ".", "close", "(", ")", "if", "close_fileobj", "and", "self", ".", "fileobj", "is", "not"...
Perform session cleanup, since the end method should always be called explicitely by the calling code, this works better than the destructor. Set close_fileobj to False so fileobj can be returned open.
[ "Perform", "session", "cleanup", "since", "the", "end", "method", "should", "always", "be", "called", "explicitely", "by", "the", "calling", "code", "this", "works", "better", "than", "the", "destructor", ".", "Set", "close_fileobj", "to", "False", "so", "file...
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpContexts.py#L131-L140
13,324
msoulier/tftpy
tftpy/TftpContexts.py
TftpContext.sethost
def sethost(self, host): """Setter method that also sets the address property as a result of the host that is set.""" self.__host = host self.address = socket.gethostbyname(host)
python
def sethost(self, host): """Setter method that also sets the address property as a result of the host that is set.""" self.__host = host self.address = socket.gethostbyname(host)
[ "def", "sethost", "(", "self", ",", "host", ")", ":", "self", ".", "__host", "=", "host", "self", ".", "address", "=", "socket", ".", "gethostbyname", "(", "host", ")" ]
Setter method that also sets the address property as a result of the host that is set.
[ "Setter", "method", "that", "also", "sets", "the", "address", "property", "as", "a", "result", "of", "the", "host", "that", "is", "set", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpContexts.py#L146-L150
13,325
msoulier/tftpy
tftpy/TftpContexts.py
TftpContext.cycle
def cycle(self): """Here we wait for a response from the server after sending it something, and dispatch appropriate action to that response.""" try: (buffer, (raddress, rport)) = self.sock.recvfrom(MAX_BLKSIZE) except socket.timeout: log.warning("Timeout waiting ...
python
def cycle(self): """Here we wait for a response from the server after sending it something, and dispatch appropriate action to that response.""" try: (buffer, (raddress, rport)) = self.sock.recvfrom(MAX_BLKSIZE) except socket.timeout: log.warning("Timeout waiting ...
[ "def", "cycle", "(", "self", ")", ":", "try", ":", "(", "buffer", ",", "(", "raddress", ",", "rport", ")", ")", "=", "self", ".", "sock", ".", "recvfrom", "(", "MAX_BLKSIZE", ")", "except", "socket", ".", "timeout", ":", "log", ".", "warning", "(",...
Here we wait for a response from the server after sending it something, and dispatch appropriate action to that response.
[ "Here", "we", "wait", "for", "a", "response", "from", "the", "server", "after", "sending", "it", "something", "and", "dispatch", "appropriate", "action", "to", "that", "response", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpContexts.py#L165-L205
13,326
msoulier/tftpy
tftpy/TftpContexts.py
TftpContextClientDownload.start
def start(self): """Initiate the download.""" log.info("Sending tftp download request to %s" % self.host) log.info(" filename -> %s" % self.file_to_transfer) log.info(" options -> %s" % self.options) self.metrics.start_time = time.time() log.debug("Set metrics.star...
python
def start(self): """Initiate the download.""" log.info("Sending tftp download request to %s" % self.host) log.info(" filename -> %s" % self.file_to_transfer) log.info(" options -> %s" % self.options) self.metrics.start_time = time.time() log.debug("Set metrics.star...
[ "def", "start", "(", "self", ")", ":", "log", ".", "info", "(", "\"Sending tftp download request to %s\"", "%", "self", ".", "host", ")", "log", ".", "info", "(", "\" filename -> %s\"", "%", "self", ".", "file_to_transfer", ")", "log", ".", "info", "(", ...
Initiate the download.
[ "Initiate", "the", "download", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpContexts.py#L379-L422
13,327
msoulier/tftpy
tftpy/TftpContexts.py
TftpContextClientDownload.end
def end(self): """Finish up the context.""" TftpContext.end(self, not self.filelike_fileobj) self.metrics.end_time = time.time() log.debug("Set metrics.end_time to %s" % self.metrics.end_time) self.metrics.compute()
python
def end(self): """Finish up the context.""" TftpContext.end(self, not self.filelike_fileobj) self.metrics.end_time = time.time() log.debug("Set metrics.end_time to %s" % self.metrics.end_time) self.metrics.compute()
[ "def", "end", "(", "self", ")", ":", "TftpContext", ".", "end", "(", "self", ",", "not", "self", ".", "filelike_fileobj", ")", "self", ".", "metrics", ".", "end_time", "=", "time", ".", "time", "(", ")", "log", ".", "debug", "(", "\"Set metrics.end_tim...
Finish up the context.
[ "Finish", "up", "the", "context", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpContexts.py#L424-L429
13,328
msoulier/tftpy
tftpy/TftpClient.py
TftpClient.download
def download(self, filename, output, packethook=None, timeout=SOCK_TIMEOUT): """This method initiates a tftp download from the configured remote host, requesting the filename passed. It writes the file to output, which can be a file-like object or a path to a local file. If a packethook ...
python
def download(self, filename, output, packethook=None, timeout=SOCK_TIMEOUT): """This method initiates a tftp download from the configured remote host, requesting the filename passed. It writes the file to output, which can be a file-like object or a path to a local file. If a packethook ...
[ "def", "download", "(", "self", ",", "filename", ",", "output", ",", "packethook", "=", "None", ",", "timeout", "=", "SOCK_TIMEOUT", ")", ":", "# We're downloading.", "log", ".", "debug", "(", "\"Creating download context with the following params:\"", ")", "log", ...
This method initiates a tftp download from the configured remote host, requesting the filename passed. It writes the file to output, which can be a file-like object or a path to a local file. If a packethook is provided, it must be a function that takes a single parameter, which will be ...
[ "This", "method", "initiates", "a", "tftp", "download", "from", "the", "configured", "remote", "host", "requesting", "the", "filename", "passed", ".", "It", "writes", "the", "file", "to", "output", "which", "can", "be", "a", "file", "-", "like", "object", ...
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpClient.py#L35-L72
13,329
msoulier/tftpy
tftpy/TftpClient.py
TftpClient.upload
def upload(self, filename, input, packethook=None, timeout=SOCK_TIMEOUT): """This method initiates a tftp upload to the configured remote host, uploading the filename passed. It reads the file from input, which can be a file-like object or a path to a local file. If a packethook is provi...
python
def upload(self, filename, input, packethook=None, timeout=SOCK_TIMEOUT): """This method initiates a tftp upload to the configured remote host, uploading the filename passed. It reads the file from input, which can be a file-like object or a path to a local file. If a packethook is provi...
[ "def", "upload", "(", "self", ",", "filename", ",", "input", ",", "packethook", "=", "None", ",", "timeout", "=", "SOCK_TIMEOUT", ")", ":", "self", ".", "context", "=", "TftpContextClientUpload", "(", "self", ".", "host", ",", "self", ".", "iport", ",", ...
This method initiates a tftp upload to the configured remote host, uploading the filename passed. It reads the file from input, which can be a file-like object or a path to a local file. If a packethook is provided, it must be a function that takes a single parameter, which will be a cop...
[ "This", "method", "initiates", "a", "tftp", "upload", "to", "the", "configured", "remote", "host", "uploading", "the", "filename", "passed", ".", "It", "reads", "the", "file", "from", "input", "which", "can", "be", "a", "file", "-", "like", "object", "or",...
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpClient.py#L74-L107
13,330
msoulier/tftpy
tftpy/TftpPacketTypes.py
TftpPacketWithOptions.decode_options
def decode_options(self, buffer): """This method decodes the section of the buffer that contains an unknown number of options. It returns a dictionary of option names and values.""" fmt = b"!" options = {} log.debug("decode_options: buffer is: %s", repr(buffer)) ...
python
def decode_options(self, buffer): """This method decodes the section of the buffer that contains an unknown number of options. It returns a dictionary of option names and values.""" fmt = b"!" options = {} log.debug("decode_options: buffer is: %s", repr(buffer)) ...
[ "def", "decode_options", "(", "self", ",", "buffer", ")", ":", "fmt", "=", "b\"!\"", "options", "=", "{", "}", "log", ".", "debug", "(", "\"decode_options: buffer is: %s\"", ",", "repr", "(", "buffer", ")", ")", "log", ".", "debug", "(", "\"size of buffer ...
This method decodes the section of the buffer that contains an unknown number of options. It returns a dictionary of option names and values.
[ "This", "method", "decodes", "the", "section", "of", "the", "buffer", "that", "contains", "an", "unknown", "number", "of", "options", ".", "It", "returns", "a", "dictionary", "of", "option", "names", "and", "values", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketTypes.py#L56-L95
13,331
msoulier/tftpy
tftpy/TftpPacketTypes.py
TftpPacketInitial.encode
def encode(self): """Encode the packet's buffer from the instance variables.""" tftpassert(self.filename, "filename required in initial packet") tftpassert(self.mode, "mode required in initial packet") # Make sure filename and mode are bytestrings. filename = self.filename ...
python
def encode(self): """Encode the packet's buffer from the instance variables.""" tftpassert(self.filename, "filename required in initial packet") tftpassert(self.mode, "mode required in initial packet") # Make sure filename and mode are bytestrings. filename = self.filename ...
[ "def", "encode", "(", "self", ")", ":", "tftpassert", "(", "self", ".", "filename", ",", "\"filename required in initial packet\"", ")", "tftpassert", "(", "self", ".", "mode", ",", "\"mode required in initial packet\"", ")", "# Make sure filename and mode are bytestrings...
Encode the packet's buffer from the instance variables.
[ "Encode", "the", "packet", "s", "buffer", "from", "the", "instance", "variables", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketTypes.py#L132-L190
13,332
msoulier/tftpy
tftpy/TftpPacketTypes.py
TftpPacketDAT.encode
def encode(self): """Encode the DAT packet. This method populates self.buffer, and returns self for easy method chaining.""" if len(self.data) == 0: log.debug("Encoding an empty DAT packet") data = self.data if not isinstance(self.data, bytes): data = self...
python
def encode(self): """Encode the DAT packet. This method populates self.buffer, and returns self for easy method chaining.""" if len(self.data) == 0: log.debug("Encoding an empty DAT packet") data = self.data if not isinstance(self.data, bytes): data = self...
[ "def", "encode", "(", "self", ")", ":", "if", "len", "(", "self", ".", "data", ")", "==", "0", ":", "log", ".", "debug", "(", "\"Encoding an empty DAT packet\"", ")", "data", "=", "self", ".", "data", "if", "not", "isinstance", "(", "self", ".", "dat...
Encode the DAT packet. This method populates self.buffer, and returns self for easy method chaining.
[ "Encode", "the", "DAT", "packet", ".", "This", "method", "populates", "self", ".", "buffer", "and", "returns", "self", "for", "easy", "method", "chaining", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketTypes.py#L292-L305
13,333
msoulier/tftpy
tftpy/TftpPacketTypes.py
TftpPacketDAT.decode
def decode(self): """Decode self.buffer into instance variables. It returns self for easy method chaining.""" # We know the first 2 bytes are the opcode. The second two are the # block number. (self.blocknumber,) = struct.unpack(str("!H"), self.buffer[2:4]) log.debug("dec...
python
def decode(self): """Decode self.buffer into instance variables. It returns self for easy method chaining.""" # We know the first 2 bytes are the opcode. The second two are the # block number. (self.blocknumber,) = struct.unpack(str("!H"), self.buffer[2:4]) log.debug("dec...
[ "def", "decode", "(", "self", ")", ":", "# We know the first 2 bytes are the opcode. The second two are the", "# block number.", "(", "self", ".", "blocknumber", ",", ")", "=", "struct", ".", "unpack", "(", "str", "(", "\"!H\"", ")", ",", "self", ".", "buffer", ...
Decode self.buffer into instance variables. It returns self for easy method chaining.
[ "Decode", "self", ".", "buffer", "into", "instance", "variables", ".", "It", "returns", "self", "for", "easy", "method", "chaining", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketTypes.py#L307-L318
13,334
msoulier/tftpy
tftpy/TftpPacketTypes.py
TftpPacketERR.encode
def encode(self): """Encode the DAT packet based on instance variables, populating self.buffer, returning self.""" fmt = b"!HH%dsx" % len(self.errmsgs[self.errorcode]) log.debug("encoding ERR packet with fmt %s", fmt) self.buffer = struct.pack(fmt, ...
python
def encode(self): """Encode the DAT packet based on instance variables, populating self.buffer, returning self.""" fmt = b"!HH%dsx" % len(self.errmsgs[self.errorcode]) log.debug("encoding ERR packet with fmt %s", fmt) self.buffer = struct.pack(fmt, ...
[ "def", "encode", "(", "self", ")", ":", "fmt", "=", "b\"!HH%dsx\"", "%", "len", "(", "self", ".", "errmsgs", "[", "self", ".", "errorcode", "]", ")", "log", ".", "debug", "(", "\"encoding ERR packet with fmt %s\"", ",", "fmt", ")", "self", ".", "buffer",...
Encode the DAT packet based on instance variables, populating self.buffer, returning self.
[ "Encode", "the", "DAT", "packet", "based", "on", "instance", "variables", "populating", "self", ".", "buffer", "returning", "self", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketTypes.py#L399-L408
13,335
msoulier/tftpy
tftpy/TftpPacketTypes.py
TftpPacketERR.decode
def decode(self): "Decode self.buffer, populating instance variables and return self." buflen = len(self.buffer) tftpassert(buflen >= 4, "malformed ERR packet, too short") log.debug("Decoding ERR packet, length %s bytes", buflen) if buflen == 4: log.debug("Allowing th...
python
def decode(self): "Decode self.buffer, populating instance variables and return self." buflen = len(self.buffer) tftpassert(buflen >= 4, "malformed ERR packet, too short") log.debug("Decoding ERR packet, length %s bytes", buflen) if buflen == 4: log.debug("Allowing th...
[ "def", "decode", "(", "self", ")", ":", "buflen", "=", "len", "(", "self", ".", "buffer", ")", "tftpassert", "(", "buflen", ">=", "4", ",", "\"malformed ERR packet, too short\"", ")", "log", ".", "debug", "(", "\"Decoding ERR packet, length %s bytes\"", ",", "...
Decode self.buffer, populating instance variables and return self.
[ "Decode", "self", ".", "buffer", "populating", "instance", "variables", "and", "return", "self", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketTypes.py#L410-L429
13,336
msoulier/tftpy
tftpy/TftpPacketTypes.py
TftpPacketOACK.match_options
def match_options(self, options): """This method takes a set of options, and tries to match them with its own. It can accept some changes in those options from the server as part of a negotiation. Changed or unchanged, it will return a dict of the options so that the session can update i...
python
def match_options(self, options): """This method takes a set of options, and tries to match them with its own. It can accept some changes in those options from the server as part of a negotiation. Changed or unchanged, it will return a dict of the options so that the session can update i...
[ "def", "match_options", "(", "self", ",", "options", ")", ":", "for", "name", "in", "self", ".", "options", ":", "if", "name", "in", "options", ":", "if", "name", "==", "'blksize'", ":", "# We can accept anything between the min and max values.", "size", "=", ...
This method takes a set of options, and tries to match them with its own. It can accept some changes in those options from the server as part of a negotiation. Changed or unchanged, it will return a dict of the options so that the session can update itself to the negotiated options.
[ "This", "method", "takes", "a", "set", "of", "options", "and", "tries", "to", "match", "them", "with", "its", "own", ".", "It", "can", "accept", "some", "changes", "in", "those", "options", "from", "the", "server", "as", "part", "of", "a", "negotiation",...
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketTypes.py#L472-L494
13,337
msoulier/tftpy
tftpy/TftpStates.py
TftpState.handleOACK
def handleOACK(self, pkt): """This method handles an OACK from the server, syncing any accepted options.""" if len(pkt.options.keys()) > 0: if pkt.match_options(self.context.options): log.info("Successful negotiation of options") # Set options to OACK ...
python
def handleOACK(self, pkt): """This method handles an OACK from the server, syncing any accepted options.""" if len(pkt.options.keys()) > 0: if pkt.match_options(self.context.options): log.info("Successful negotiation of options") # Set options to OACK ...
[ "def", "handleOACK", "(", "self", ",", "pkt", ")", ":", "if", "len", "(", "pkt", ".", "options", ".", "keys", "(", ")", ")", ">", "0", ":", "if", "pkt", ".", "match_options", "(", "self", ".", "context", ".", "options", ")", ":", "log", ".", "i...
This method handles an OACK from the server, syncing any accepted options.
[ "This", "method", "handles", "an", "OACK", "from", "the", "server", "syncing", "any", "accepted", "options", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L39-L53
13,338
msoulier/tftpy
tftpy/TftpStates.py
TftpState.returnSupportedOptions
def returnSupportedOptions(self, options): """This method takes a requested options list from a client, and returns the ones that are supported.""" # We support the options blksize and tsize right now. # FIXME - put this somewhere else? accepted_options = {} for option in...
python
def returnSupportedOptions(self, options): """This method takes a requested options list from a client, and returns the ones that are supported.""" # We support the options blksize and tsize right now. # FIXME - put this somewhere else? accepted_options = {} for option in...
[ "def", "returnSupportedOptions", "(", "self", ",", "options", ")", ":", "# We support the options blksize and tsize right now.", "# FIXME - put this somewhere else?", "accepted_options", "=", "{", "}", "for", "option", "in", "options", ":", "if", "option", "==", "'blksize...
This method takes a requested options list from a client, and returns the ones that are supported.
[ "This", "method", "takes", "a", "requested", "options", "list", "from", "a", "client", "and", "returns", "the", "ones", "that", "are", "supported", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L55-L80
13,339
msoulier/tftpy
tftpy/TftpStates.py
TftpState.sendDAT
def sendDAT(self): """This method sends the next DAT packet based on the data in the context. It returns a boolean indicating whether the transfer is finished.""" finished = False blocknumber = self.context.next_block # Test hook if DELAY_BLOCK and DELAY_BLOCK == ...
python
def sendDAT(self): """This method sends the next DAT packet based on the data in the context. It returns a boolean indicating whether the transfer is finished.""" finished = False blocknumber = self.context.next_block # Test hook if DELAY_BLOCK and DELAY_BLOCK == ...
[ "def", "sendDAT", "(", "self", ")", ":", "finished", "=", "False", "blocknumber", "=", "self", ".", "context", ".", "next_block", "# Test hook", "if", "DELAY_BLOCK", "and", "DELAY_BLOCK", "==", "blocknumber", ":", "import", "time", "log", ".", "debug", "(", ...
This method sends the next DAT packet based on the data in the context. It returns a boolean indicating whether the transfer is finished.
[ "This", "method", "sends", "the", "next", "DAT", "packet", "based", "on", "the", "data", "in", "the", "context", ".", "It", "returns", "a", "boolean", "indicating", "whether", "the", "transfer", "is", "finished", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L82-L111
13,340
msoulier/tftpy
tftpy/TftpStates.py
TftpState.sendACK
def sendACK(self, blocknumber=None): """This method sends an ack packet to the block number specified. If none is specified, it defaults to the next_block property in the parent context.""" log.debug("In sendACK, passed blocknumber is %s", blocknumber) if blocknumber is None: ...
python
def sendACK(self, blocknumber=None): """This method sends an ack packet to the block number specified. If none is specified, it defaults to the next_block property in the parent context.""" log.debug("In sendACK, passed blocknumber is %s", blocknumber) if blocknumber is None: ...
[ "def", "sendACK", "(", "self", ",", "blocknumber", "=", "None", ")", ":", "log", ".", "debug", "(", "\"In sendACK, passed blocknumber is %s\"", ",", "blocknumber", ")", "if", "blocknumber", "is", "None", ":", "blocknumber", "=", "self", ".", "context", ".", ...
This method sends an ack packet to the block number specified. If none is specified, it defaults to the next_block property in the parent context.
[ "This", "method", "sends", "an", "ack", "packet", "to", "the", "block", "number", "specified", ".", "If", "none", "is", "specified", "it", "defaults", "to", "the", "next_block", "property", "in", "the", "parent", "context", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L113-L126
13,341
msoulier/tftpy
tftpy/TftpStates.py
TftpState.sendError
def sendError(self, errorcode): """This method uses the socket passed, and uses the errorcode to compose and send an error packet.""" log.debug("In sendError, being asked to send error %d", errorcode) errpkt = TftpPacketERR() errpkt.errorcode = errorcode if self.context.t...
python
def sendError(self, errorcode): """This method uses the socket passed, and uses the errorcode to compose and send an error packet.""" log.debug("In sendError, being asked to send error %d", errorcode) errpkt = TftpPacketERR() errpkt.errorcode = errorcode if self.context.t...
[ "def", "sendError", "(", "self", ",", "errorcode", ")", ":", "log", ".", "debug", "(", "\"In sendError, being asked to send error %d\"", ",", "errorcode", ")", "errpkt", "=", "TftpPacketERR", "(", ")", "errpkt", ".", "errorcode", "=", "errorcode", "if", "self", ...
This method uses the socket passed, and uses the errorcode to compose and send an error packet.
[ "This", "method", "uses", "the", "socket", "passed", "and", "uses", "the", "errorcode", "to", "compose", "and", "send", "an", "error", "packet", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L128-L140
13,342
msoulier/tftpy
tftpy/TftpStates.py
TftpState.sendOACK
def sendOACK(self): """This method sends an OACK packet with the options from the current context.""" log.debug("In sendOACK with options %s", self.context.options) pkt = TftpPacketOACK() pkt.options = self.context.options self.context.sock.sendto(pkt.encode().buffer, ...
python
def sendOACK(self): """This method sends an OACK packet with the options from the current context.""" log.debug("In sendOACK with options %s", self.context.options) pkt = TftpPacketOACK() pkt.options = self.context.options self.context.sock.sendto(pkt.encode().buffer, ...
[ "def", "sendOACK", "(", "self", ")", ":", "log", ".", "debug", "(", "\"In sendOACK with options %s\"", ",", "self", ".", "context", ".", "options", ")", "pkt", "=", "TftpPacketOACK", "(", ")", "pkt", ".", "options", "=", "self", ".", "context", ".", "opt...
This method sends an OACK packet with the options from the current context.
[ "This", "method", "sends", "an", "OACK", "packet", "with", "the", "options", "from", "the", "current", "context", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L142-L151
13,343
msoulier/tftpy
tftpy/TftpStates.py
TftpState.resendLast
def resendLast(self): "Resend the last sent packet due to a timeout." log.warning("Resending packet %s on sessions %s" % (self.context.last_pkt, self)) self.context.metrics.resent_bytes += len(self.context.last_pkt.buffer) self.context.metrics.add_dup(self.context.last_pkt) ...
python
def resendLast(self): "Resend the last sent packet due to a timeout." log.warning("Resending packet %s on sessions %s" % (self.context.last_pkt, self)) self.context.metrics.resent_bytes += len(self.context.last_pkt.buffer) self.context.metrics.add_dup(self.context.last_pkt) ...
[ "def", "resendLast", "(", "self", ")", ":", "log", ".", "warning", "(", "\"Resending packet %s on sessions %s\"", "%", "(", "self", ".", "context", ".", "last_pkt", ",", "self", ")", ")", "self", ".", "context", ".", "metrics", ".", "resent_bytes", "+=", "...
Resend the last sent packet due to a timeout.
[ "Resend", "the", "last", "sent", "packet", "due", "to", "a", "timeout", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L153-L168
13,344
msoulier/tftpy
tftpy/TftpStates.py
TftpState.handleDat
def handleDat(self, pkt): """This method handles a DAT packet during a client download, or a server upload.""" log.info("Handling DAT packet - block %d" % pkt.blocknumber) log.debug("Expecting block %s", self.context.next_block) if pkt.blocknumber == self.context.next_block: ...
python
def handleDat(self, pkt): """This method handles a DAT packet during a client download, or a server upload.""" log.info("Handling DAT packet - block %d" % pkt.blocknumber) log.debug("Expecting block %s", self.context.next_block) if pkt.blocknumber == self.context.next_block: ...
[ "def", "handleDat", "(", "self", ",", "pkt", ")", ":", "log", ".", "info", "(", "\"Handling DAT packet - block %d\"", "%", "pkt", ".", "blocknumber", ")", "log", ".", "debug", "(", "\"Expecting block %s\"", ",", "self", ".", "context", ".", "next_block", ")"...
This method handles a DAT packet during a client download, or a server upload.
[ "This", "method", "handles", "a", "DAT", "packet", "during", "a", "client", "download", "or", "a", "server", "upload", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L170-L207
13,345
msoulier/tftpy
tftpy/TftpStates.py
TftpServerState.serverInitial
def serverInitial(self, pkt, raddress, rport): """This method performs initial setup for a server context transfer, put here to refactor code out of the TftpStateServerRecvRRQ and TftpStateServerRecvWRQ classes, since their initial setup is identical. The method returns a boolean, sendoa...
python
def serverInitial(self, pkt, raddress, rport): """This method performs initial setup for a server context transfer, put here to refactor code out of the TftpStateServerRecvRRQ and TftpStateServerRecvWRQ classes, since their initial setup is identical. The method returns a boolean, sendoa...
[ "def", "serverInitial", "(", "self", ",", "pkt", ",", "raddress", ",", "rport", ")", ":", "options", "=", "pkt", ".", "options", "sendoack", "=", "False", "if", "not", "self", ".", "context", ".", "tidport", ":", "self", ".", "context", ".", "tidport",...
This method performs initial setup for a server context transfer, put here to refactor code out of the TftpStateServerRecvRRQ and TftpStateServerRecvWRQ classes, since their initial setup is identical. The method returns a boolean, sendoack, to indicate whether it is required to send an ...
[ "This", "method", "performs", "initial", "setup", "for", "a", "server", "context", "transfer", "put", "here", "to", "refactor", "code", "out", "of", "the", "TftpStateServerRecvRRQ", "and", "TftpStateServerRecvWRQ", "classes", "since", "their", "initial", "setup", ...
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L219-L291
13,346
msoulier/tftpy
tftpy/TftpStates.py
TftpStateServerRecvRRQ.handle
def handle(self, pkt, raddress, rport): "Handle an initial RRQ packet as a server." log.debug("In TftpStateServerRecvRRQ.handle") sendoack = self.serverInitial(pkt, raddress, rport) path = self.full_path log.info("Opening file %s for reading" % path) if os.path.exists(pat...
python
def handle(self, pkt, raddress, rport): "Handle an initial RRQ packet as a server." log.debug("In TftpStateServerRecvRRQ.handle") sendoack = self.serverInitial(pkt, raddress, rport) path = self.full_path log.info("Opening file %s for reading" % path) if os.path.exists(pat...
[ "def", "handle", "(", "self", ",", "pkt", ",", "raddress", ",", "rport", ")", ":", "log", ".", "debug", "(", "\"In TftpStateServerRecvRRQ.handle\"", ")", "sendoack", "=", "self", ".", "serverInitial", "(", "pkt", ",", "raddress", ",", "rport", ")", "path",...
Handle an initial RRQ packet as a server.
[ "Handle", "an", "initial", "RRQ", "packet", "as", "a", "server", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L297-L344
13,347
msoulier/tftpy
tftpy/TftpStates.py
TftpStateServerRecvWRQ.make_subdirs
def make_subdirs(self): """The purpose of this method is to, if necessary, create all of the subdirectories leading up to the file to the written.""" # Pull off everything below the root. subpath = self.full_path[len(self.context.root):] log.debug("make_subdirs: subpath is %s", s...
python
def make_subdirs(self): """The purpose of this method is to, if necessary, create all of the subdirectories leading up to the file to the written.""" # Pull off everything below the root. subpath = self.full_path[len(self.context.root):] log.debug("make_subdirs: subpath is %s", s...
[ "def", "make_subdirs", "(", "self", ")", ":", "# Pull off everything below the root.", "subpath", "=", "self", ".", "full_path", "[", "len", "(", "self", ".", "context", ".", "root", ")", ":", "]", "log", ".", "debug", "(", "\"make_subdirs: subpath is %s\"", "...
The purpose of this method is to, if necessary, create all of the subdirectories leading up to the file to the written.
[ "The", "purpose", "of", "this", "method", "is", "to", "if", "necessary", "create", "all", "of", "the", "subdirectories", "leading", "up", "to", "the", "file", "to", "the", "written", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L352-L369
13,348
msoulier/tftpy
tftpy/TftpStates.py
TftpStateServerRecvWRQ.handle
def handle(self, pkt, raddress, rport): "Handle an initial WRQ packet as a server." log.debug("In TftpStateServerRecvWRQ.handle") sendoack = self.serverInitial(pkt, raddress, rport) path = self.full_path if self.context.upload_open: f = self.context.upload_open(path, ...
python
def handle(self, pkt, raddress, rport): "Handle an initial WRQ packet as a server." log.debug("In TftpStateServerRecvWRQ.handle") sendoack = self.serverInitial(pkt, raddress, rport) path = self.full_path if self.context.upload_open: f = self.context.upload_open(path, ...
[ "def", "handle", "(", "self", ",", "pkt", ",", "raddress", ",", "rport", ")", ":", "log", ".", "debug", "(", "\"In TftpStateServerRecvWRQ.handle\"", ")", "sendoack", "=", "self", ".", "serverInitial", "(", "pkt", ",", "raddress", ",", "rport", ")", "path",...
Handle an initial WRQ packet as a server.
[ "Handle", "an", "initial", "WRQ", "packet", "as", "a", "server", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L371-L407
13,349
msoulier/tftpy
tftpy/TftpStates.py
TftpStateExpectACK.handle
def handle(self, pkt, raddress, rport): "Handle a packet, hopefully an ACK since we just sent a DAT." if isinstance(pkt, TftpPacketACK): log.debug("Received ACK for packet %d" % pkt.blocknumber) # Is this an ack to the one we just sent? if self.context.next_block == p...
python
def handle(self, pkt, raddress, rport): "Handle a packet, hopefully an ACK since we just sent a DAT." if isinstance(pkt, TftpPacketACK): log.debug("Received ACK for packet %d" % pkt.blocknumber) # Is this an ack to the one we just sent? if self.context.next_block == p...
[ "def", "handle", "(", "self", ",", "pkt", ",", "raddress", ",", "rport", ")", ":", "if", "isinstance", "(", "pkt", ",", "TftpPacketACK", ")", ":", "log", ".", "debug", "(", "\"Received ACK for packet %d\"", "%", "pkt", ".", "blocknumber", ")", "# Is this a...
Handle a packet, hopefully an ACK since we just sent a DAT.
[ "Handle", "a", "packet", "hopefully", "an", "ACK", "since", "we", "just", "sent", "a", "DAT", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L438-L469
13,350
msoulier/tftpy
tftpy/TftpStates.py
TftpStateExpectDAT.handle
def handle(self, pkt, raddress, rport): """Handle the packet in response to an ACK, which should be a DAT.""" if isinstance(pkt, TftpPacketDAT): return self.handleDat(pkt) # Every other packet type is a problem. elif isinstance(pkt, TftpPacketACK): # Umm, we ACK,...
python
def handle(self, pkt, raddress, rport): """Handle the packet in response to an ACK, which should be a DAT.""" if isinstance(pkt, TftpPacketDAT): return self.handleDat(pkt) # Every other packet type is a problem. elif isinstance(pkt, TftpPacketACK): # Umm, we ACK,...
[ "def", "handle", "(", "self", ",", "pkt", ",", "raddress", ",", "rport", ")", ":", "if", "isinstance", "(", "pkt", ",", "TftpPacketDAT", ")", ":", "return", "self", ".", "handleDat", "(", "pkt", ")", "# Every other packet type is a problem.", "elif", "isinst...
Handle the packet in response to an ACK, which should be a DAT.
[ "Handle", "the", "packet", "in", "response", "to", "an", "ACK", "which", "should", "be", "a", "DAT", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L473-L494
13,351
msoulier/tftpy
tftpy/TftpStates.py
TftpStateSentRRQ.handle
def handle(self, pkt, raddress, rport): """Handle the packet in response to an RRQ to the server.""" if not self.context.tidport: self.context.tidport = rport log.info("Set remote port for session to %s" % rport) # Now check the packet type and dispatch it properly. ...
python
def handle(self, pkt, raddress, rport): """Handle the packet in response to an RRQ to the server.""" if not self.context.tidport: self.context.tidport = rport log.info("Set remote port for session to %s" % rport) # Now check the packet type and dispatch it properly. ...
[ "def", "handle", "(", "self", ",", "pkt", ",", "raddress", ",", "rport", ")", ":", "if", "not", "self", ".", "context", ".", "tidport", ":", "self", ".", "context", ".", "tidport", "=", "rport", "log", ".", "info", "(", "\"Set remote port for session to ...
Handle the packet in response to an RRQ to the server.
[ "Handle", "the", "packet", "in", "response", "to", "an", "RRQ", "to", "the", "server", "." ]
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L556-L611
13,352
msoulier/tftpy
tftpy/TftpServer.py
TftpServer.stop
def stop(self, now=False): """Stop the server gracefully. Do not take any new transfers, but complete the existing ones. If force is True, drop everything and stop. Note, immediately will not interrupt the select loop, it will happen when the server returns on ready data, or a timeout. ...
python
def stop(self, now=False): """Stop the server gracefully. Do not take any new transfers, but complete the existing ones. If force is True, drop everything and stop. Note, immediately will not interrupt the select loop, it will happen when the server returns on ready data, or a timeout. ...
[ "def", "stop", "(", "self", ",", "now", "=", "False", ")", ":", "if", "now", ":", "self", ".", "shutdown_immediately", "=", "True", "else", ":", "self", ".", "shutdown_gracefully", "=", "True" ]
Stop the server gracefully. Do not take any new transfers, but complete the existing ones. If force is True, drop everything and stop. Note, immediately will not interrupt the select loop, it will happen when the server returns on ready data, or a timeout. ie. SOCK_TIMEOUT
[ "Stop", "the", "server", "gracefully", ".", "Do", "not", "take", "any", "new", "transfers", "but", "complete", "the", "existing", "ones", ".", "If", "force", "is", "True", "drop", "everything", "and", "stop", ".", "Note", "immediately", "will", "not", "int...
af2f2fe89a3bf45748b78703820efb0986a8207a
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpServer.py#L249-L258
13,353
avelkoski/FRB
fred/helpers/__init__.py
_fetch
def _fetch(url, ssl_verify = True): """ Helper funcation to fetch content from a given url. """ req = Request(url) if ssl_verify: page = urlopen(req) else: ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE page ...
python
def _fetch(url, ssl_verify = True): """ Helper funcation to fetch content from a given url. """ req = Request(url) if ssl_verify: page = urlopen(req) else: ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE page ...
[ "def", "_fetch", "(", "url", ",", "ssl_verify", "=", "True", ")", ":", "req", "=", "Request", "(", "url", ")", "if", "ssl_verify", ":", "page", "=", "urlopen", "(", "req", ")", "else", ":", "ctx", "=", "ssl", ".", "create_default_context", "(", ")", ...
Helper funcation to fetch content from a given url.
[ "Helper", "funcation", "to", "fetch", "content", "from", "a", "given", "url", "." ]
692bcf576e17bd1a81db2b7644f4f61aeb39e5c7
https://github.com/avelkoski/FRB/blob/692bcf576e17bd1a81db2b7644f4f61aeb39e5c7/fred/helpers/__init__.py#L25-L40
13,354
avelkoski/FRB
fred/helpers/__init__.py
_dict
def _dict(content): """ Helper funcation that converts text-based get response to a python dictionary for additional manipulation. """ if _has_pandas: data = _data_frame(content).to_dict(orient='records') else: response = loads(content) key = [x for x in response.keys() i...
python
def _dict(content): """ Helper funcation that converts text-based get response to a python dictionary for additional manipulation. """ if _has_pandas: data = _data_frame(content).to_dict(orient='records') else: response = loads(content) key = [x for x in response.keys() i...
[ "def", "_dict", "(", "content", ")", ":", "if", "_has_pandas", ":", "data", "=", "_data_frame", "(", "content", ")", ".", "to_dict", "(", "orient", "=", "'records'", ")", "else", ":", "response", "=", "loads", "(", "content", ")", "key", "=", "[", "x...
Helper funcation that converts text-based get response to a python dictionary for additional manipulation.
[ "Helper", "funcation", "that", "converts", "text", "-", "based", "get", "response", "to", "a", "python", "dictionary", "for", "additional", "manipulation", "." ]
692bcf576e17bd1a81db2b7644f4f61aeb39e5c7
https://github.com/avelkoski/FRB/blob/692bcf576e17bd1a81db2b7644f4f61aeb39e5c7/fred/helpers/__init__.py#L61-L72
13,355
avelkoski/FRB
fred/helpers/__init__.py
_data_frame
def _data_frame(content): """ Helper funcation that converts text-based get response to a pandas dataframe for additional manipulation. """ response = loads(content) key = [x for x in response.keys() if x in c.response_data][0] frame = DataFrame(response[key]) final_frame = _convert(fram...
python
def _data_frame(content): """ Helper funcation that converts text-based get response to a pandas dataframe for additional manipulation. """ response = loads(content) key = [x for x in response.keys() if x in c.response_data][0] frame = DataFrame(response[key]) final_frame = _convert(fram...
[ "def", "_data_frame", "(", "content", ")", ":", "response", "=", "loads", "(", "content", ")", "key", "=", "[", "x", "for", "x", "in", "response", ".", "keys", "(", ")", "if", "x", "in", "c", ".", "response_data", "]", "[", "0", "]", "frame", "="...
Helper funcation that converts text-based get response to a pandas dataframe for additional manipulation.
[ "Helper", "funcation", "that", "converts", "text", "-", "based", "get", "response", "to", "a", "pandas", "dataframe", "for", "additional", "manipulation", "." ]
692bcf576e17bd1a81db2b7644f4f61aeb39e5c7
https://github.com/avelkoski/FRB/blob/692bcf576e17bd1a81db2b7644f4f61aeb39e5c7/fred/helpers/__init__.py#L74-L83
13,356
avelkoski/FRB
fred/helpers/__init__.py
_tab
def _tab(content): """ Helper funcation that converts text-based get response to tab separated values for additional manipulation. """ response = _data_frame(content).to_csv(index=False,sep='\t') return response
python
def _tab(content): """ Helper funcation that converts text-based get response to tab separated values for additional manipulation. """ response = _data_frame(content).to_csv(index=False,sep='\t') return response
[ "def", "_tab", "(", "content", ")", ":", "response", "=", "_data_frame", "(", "content", ")", ".", "to_csv", "(", "index", "=", "False", ",", "sep", "=", "'\\t'", ")", "return", "response" ]
Helper funcation that converts text-based get response to tab separated values for additional manipulation.
[ "Helper", "funcation", "that", "converts", "text", "-", "based", "get", "response", "to", "tab", "separated", "values", "for", "additional", "manipulation", "." ]
692bcf576e17bd1a81db2b7644f4f61aeb39e5c7
https://github.com/avelkoski/FRB/blob/692bcf576e17bd1a81db2b7644f4f61aeb39e5c7/fred/helpers/__init__.py#L93-L99
13,357
avelkoski/FRB
fred/helpers/__init__.py
_pipe
def _pipe(content): """ Helper funcation that converts text-based get response to pipe separated values for additional manipulation. """ response = _data_frame(content).to_csv(index=False,sep='|') return response
python
def _pipe(content): """ Helper funcation that converts text-based get response to pipe separated values for additional manipulation. """ response = _data_frame(content).to_csv(index=False,sep='|') return response
[ "def", "_pipe", "(", "content", ")", ":", "response", "=", "_data_frame", "(", "content", ")", ".", "to_csv", "(", "index", "=", "False", ",", "sep", "=", "'|'", ")", "return", "response" ]
Helper funcation that converts text-based get response to pipe separated values for additional manipulation.
[ "Helper", "funcation", "that", "converts", "text", "-", "based", "get", "response", "to", "pipe", "separated", "values", "for", "additional", "manipulation", "." ]
692bcf576e17bd1a81db2b7644f4f61aeb39e5c7
https://github.com/avelkoski/FRB/blob/692bcf576e17bd1a81db2b7644f4f61aeb39e5c7/fred/helpers/__init__.py#L101-L107
13,358
avelkoski/FRB
fred/helpers/__init__.py
_get_request
def _get_request(url_root,api_key,path,response_type,params, ssl_verify): """ Helper funcation that requests a get response from FRED. """ url = _url_builder(url_root,api_key,path,params) content = _fetch(url, ssl_verify) response = _dispatch(response_type)(content) return response
python
def _get_request(url_root,api_key,path,response_type,params, ssl_verify): """ Helper funcation that requests a get response from FRED. """ url = _url_builder(url_root,api_key,path,params) content = _fetch(url, ssl_verify) response = _dispatch(response_type)(content) return response
[ "def", "_get_request", "(", "url_root", ",", "api_key", ",", "path", ",", "response_type", ",", "params", ",", "ssl_verify", ")", ":", "url", "=", "_url_builder", "(", "url_root", ",", "api_key", ",", "path", ",", "params", ")", "content", "=", "_fetch", ...
Helper funcation that requests a get response from FRED.
[ "Helper", "funcation", "that", "requests", "a", "get", "response", "from", "FRED", "." ]
692bcf576e17bd1a81db2b7644f4f61aeb39e5c7
https://github.com/avelkoski/FRB/blob/692bcf576e17bd1a81db2b7644f4f61aeb39e5c7/fred/helpers/__init__.py#L141-L148
13,359
NicolasLM/atoma
atoma/atom.py
parse_atom_file
def parse_atom_file(filename: str) -> AtomFeed: """Parse an Atom feed from a local XML file.""" root = parse_xml(filename).getroot() return _parse_atom(root)
python
def parse_atom_file(filename: str) -> AtomFeed: """Parse an Atom feed from a local XML file.""" root = parse_xml(filename).getroot() return _parse_atom(root)
[ "def", "parse_atom_file", "(", "filename", ":", "str", ")", "->", "AtomFeed", ":", "root", "=", "parse_xml", "(", "filename", ")", ".", "getroot", "(", ")", "return", "_parse_atom", "(", "root", ")" ]
Parse an Atom feed from a local XML file.
[ "Parse", "an", "Atom", "feed", "from", "a", "local", "XML", "file", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/atom.py#L275-L278
13,360
NicolasLM/atoma
atoma/atom.py
parse_atom_bytes
def parse_atom_bytes(data: bytes) -> AtomFeed: """Parse an Atom feed from a byte-string containing XML data.""" root = parse_xml(BytesIO(data)).getroot() return _parse_atom(root)
python
def parse_atom_bytes(data: bytes) -> AtomFeed: """Parse an Atom feed from a byte-string containing XML data.""" root = parse_xml(BytesIO(data)).getroot() return _parse_atom(root)
[ "def", "parse_atom_bytes", "(", "data", ":", "bytes", ")", "->", "AtomFeed", ":", "root", "=", "parse_xml", "(", "BytesIO", "(", "data", ")", ")", ".", "getroot", "(", ")", "return", "_parse_atom", "(", "root", ")" ]
Parse an Atom feed from a byte-string containing XML data.
[ "Parse", "an", "Atom", "feed", "from", "a", "byte", "-", "string", "containing", "XML", "data", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/atom.py#L281-L284
13,361
NicolasLM/atoma
atoma/rss.py
_get_link
def _get_link(element: Element) -> Optional[str]: """Attempt to retrieve item link. Use the GUID as a fallback if it is a permalink. """ link = get_text(element, 'link') if link is not None: return link guid = get_child(element, 'guid') if guid is not None and guid.attrib.get('isPe...
python
def _get_link(element: Element) -> Optional[str]: """Attempt to retrieve item link. Use the GUID as a fallback if it is a permalink. """ link = get_text(element, 'link') if link is not None: return link guid = get_child(element, 'guid') if guid is not None and guid.attrib.get('isPe...
[ "def", "_get_link", "(", "element", ":", "Element", ")", "->", "Optional", "[", "str", "]", ":", "link", "=", "get_text", "(", "element", ",", "'link'", ")", "if", "link", "is", "not", "None", ":", "return", "link", "guid", "=", "get_child", "(", "el...
Attempt to retrieve item link. Use the GUID as a fallback if it is a permalink.
[ "Attempt", "to", "retrieve", "item", "link", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/rss.py#L118-L131
13,362
NicolasLM/atoma
atoma/rss.py
parse_rss_file
def parse_rss_file(filename: str) -> RSSChannel: """Parse an RSS feed from a local XML file.""" root = parse_xml(filename).getroot() return _parse_rss(root)
python
def parse_rss_file(filename: str) -> RSSChannel: """Parse an RSS feed from a local XML file.""" root = parse_xml(filename).getroot() return _parse_rss(root)
[ "def", "parse_rss_file", "(", "filename", ":", "str", ")", "->", "RSSChannel", ":", "root", "=", "parse_xml", "(", "filename", ")", ".", "getroot", "(", ")", "return", "_parse_rss", "(", "root", ")" ]
Parse an RSS feed from a local XML file.
[ "Parse", "an", "RSS", "feed", "from", "a", "local", "XML", "file", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/rss.py#L212-L215
13,363
NicolasLM/atoma
atoma/rss.py
parse_rss_bytes
def parse_rss_bytes(data: bytes) -> RSSChannel: """Parse an RSS feed from a byte-string containing XML data.""" root = parse_xml(BytesIO(data)).getroot() return _parse_rss(root)
python
def parse_rss_bytes(data: bytes) -> RSSChannel: """Parse an RSS feed from a byte-string containing XML data.""" root = parse_xml(BytesIO(data)).getroot() return _parse_rss(root)
[ "def", "parse_rss_bytes", "(", "data", ":", "bytes", ")", "->", "RSSChannel", ":", "root", "=", "parse_xml", "(", "BytesIO", "(", "data", ")", ")", ".", "getroot", "(", ")", "return", "_parse_rss", "(", "root", ")" ]
Parse an RSS feed from a byte-string containing XML data.
[ "Parse", "an", "RSS", "feed", "from", "a", "byte", "-", "string", "containing", "XML", "data", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/rss.py#L218-L221
13,364
NicolasLM/atoma
atoma/json_feed.py
parse_json_feed_file
def parse_json_feed_file(filename: str) -> JSONFeed: """Parse a JSON feed from a local json file.""" with open(filename) as f: try: root = json.load(f) except json.decoder.JSONDecodeError: raise FeedJSONError('Not a valid JSON document') return parse_json_feed(root)
python
def parse_json_feed_file(filename: str) -> JSONFeed: """Parse a JSON feed from a local json file.""" with open(filename) as f: try: root = json.load(f) except json.decoder.JSONDecodeError: raise FeedJSONError('Not a valid JSON document') return parse_json_feed(root)
[ "def", "parse_json_feed_file", "(", "filename", ":", "str", ")", "->", "JSONFeed", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "try", ":", "root", "=", "json", ".", "load", "(", "f", ")", "except", "json", ".", "decoder", ".", "JSONDec...
Parse a JSON feed from a local json file.
[ "Parse", "a", "JSON", "feed", "from", "a", "local", "json", "file", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/json_feed.py#L205-L213
13,365
NicolasLM/atoma
atoma/json_feed.py
parse_json_feed_bytes
def parse_json_feed_bytes(data: bytes) -> JSONFeed: """Parse a JSON feed from a byte-string containing JSON data.""" try: root = json.loads(data) except json.decoder.JSONDecodeError: raise FeedJSONError('Not a valid JSON document') return parse_json_feed(root)
python
def parse_json_feed_bytes(data: bytes) -> JSONFeed: """Parse a JSON feed from a byte-string containing JSON data.""" try: root = json.loads(data) except json.decoder.JSONDecodeError: raise FeedJSONError('Not a valid JSON document') return parse_json_feed(root)
[ "def", "parse_json_feed_bytes", "(", "data", ":", "bytes", ")", "->", "JSONFeed", ":", "try", ":", "root", "=", "json", ".", "loads", "(", "data", ")", "except", "json", ".", "decoder", ".", "JSONDecodeError", ":", "raise", "FeedJSONError", "(", "'Not a va...
Parse a JSON feed from a byte-string containing JSON data.
[ "Parse", "a", "JSON", "feed", "from", "a", "byte", "-", "string", "containing", "JSON", "data", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/json_feed.py#L216-L223
13,366
NicolasLM/atoma
atoma/opml.py
parse_opml_file
def parse_opml_file(filename: str) -> OPML: """Parse an OPML document from a local XML file.""" root = parse_xml(filename).getroot() return _parse_opml(root)
python
def parse_opml_file(filename: str) -> OPML: """Parse an OPML document from a local XML file.""" root = parse_xml(filename).getroot() return _parse_opml(root)
[ "def", "parse_opml_file", "(", "filename", ":", "str", ")", "->", "OPML", ":", "root", "=", "parse_xml", "(", "filename", ")", ".", "getroot", "(", ")", "return", "_parse_opml", "(", "root", ")" ]
Parse an OPML document from a local XML file.
[ "Parse", "an", "OPML", "document", "from", "a", "local", "XML", "file", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/opml.py#L82-L85
13,367
NicolasLM/atoma
atoma/opml.py
parse_opml_bytes
def parse_opml_bytes(data: bytes) -> OPML: """Parse an OPML document from a byte-string containing XML data.""" root = parse_xml(BytesIO(data)).getroot() return _parse_opml(root)
python
def parse_opml_bytes(data: bytes) -> OPML: """Parse an OPML document from a byte-string containing XML data.""" root = parse_xml(BytesIO(data)).getroot() return _parse_opml(root)
[ "def", "parse_opml_bytes", "(", "data", ":", "bytes", ")", "->", "OPML", ":", "root", "=", "parse_xml", "(", "BytesIO", "(", "data", ")", ")", ".", "getroot", "(", ")", "return", "_parse_opml", "(", "root", ")" ]
Parse an OPML document from a byte-string containing XML data.
[ "Parse", "an", "OPML", "document", "from", "a", "byte", "-", "string", "containing", "XML", "data", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/opml.py#L88-L91
13,368
NicolasLM/atoma
atoma/opml.py
get_feed_list
def get_feed_list(opml_obj: OPML) -> List[str]: """Walk an OPML document to extract the list of feed it contains.""" rv = list() def collect(obj): for outline in obj.outlines: if outline.type == 'rss' and outline.xml_url: rv.append(outline.xml_url) if outlin...
python
def get_feed_list(opml_obj: OPML) -> List[str]: """Walk an OPML document to extract the list of feed it contains.""" rv = list() def collect(obj): for outline in obj.outlines: if outline.type == 'rss' and outline.xml_url: rv.append(outline.xml_url) if outlin...
[ "def", "get_feed_list", "(", "opml_obj", ":", "OPML", ")", "->", "List", "[", "str", "]", ":", "rv", "=", "list", "(", ")", "def", "collect", "(", "obj", ")", ":", "for", "outline", "in", "obj", ".", "outlines", ":", "if", "outline", ".", "type", ...
Walk an OPML document to extract the list of feed it contains.
[ "Walk", "an", "OPML", "document", "to", "extract", "the", "list", "of", "feed", "it", "contains", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/opml.py#L94-L107
13,369
NicolasLM/atoma
atoma/simple.py
simple_parse_file
def simple_parse_file(filename: str) -> Feed: """Parse an Atom, RSS or JSON feed from a local file.""" pairs = ( (rss.parse_rss_file, _adapt_rss_channel), (atom.parse_atom_file, _adapt_atom_feed), (json_feed.parse_json_feed_file, _adapt_json_feed) ) return _simple_parse(pairs, fi...
python
def simple_parse_file(filename: str) -> Feed: """Parse an Atom, RSS or JSON feed from a local file.""" pairs = ( (rss.parse_rss_file, _adapt_rss_channel), (atom.parse_atom_file, _adapt_atom_feed), (json_feed.parse_json_feed_file, _adapt_json_feed) ) return _simple_parse(pairs, fi...
[ "def", "simple_parse_file", "(", "filename", ":", "str", ")", "->", "Feed", ":", "pairs", "=", "(", "(", "rss", ".", "parse_rss_file", ",", "_adapt_rss_channel", ")", ",", "(", "atom", ".", "parse_atom_file", ",", "_adapt_atom_feed", ")", ",", "(", "json_f...
Parse an Atom, RSS or JSON feed from a local file.
[ "Parse", "an", "Atom", "RSS", "or", "JSON", "feed", "from", "a", "local", "file", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/simple.py#L207-L214
13,370
NicolasLM/atoma
atoma/simple.py
simple_parse_bytes
def simple_parse_bytes(data: bytes) -> Feed: """Parse an Atom, RSS or JSON feed from a byte-string containing data.""" pairs = ( (rss.parse_rss_bytes, _adapt_rss_channel), (atom.parse_atom_bytes, _adapt_atom_feed), (json_feed.parse_json_feed_bytes, _adapt_json_feed) ) return _sim...
python
def simple_parse_bytes(data: bytes) -> Feed: """Parse an Atom, RSS or JSON feed from a byte-string containing data.""" pairs = ( (rss.parse_rss_bytes, _adapt_rss_channel), (atom.parse_atom_bytes, _adapt_atom_feed), (json_feed.parse_json_feed_bytes, _adapt_json_feed) ) return _sim...
[ "def", "simple_parse_bytes", "(", "data", ":", "bytes", ")", "->", "Feed", ":", "pairs", "=", "(", "(", "rss", ".", "parse_rss_bytes", ",", "_adapt_rss_channel", ")", ",", "(", "atom", ".", "parse_atom_bytes", ",", "_adapt_atom_feed", ")", ",", "(", "json_...
Parse an Atom, RSS or JSON feed from a byte-string containing data.
[ "Parse", "an", "Atom", "RSS", "or", "JSON", "feed", "from", "a", "byte", "-", "string", "containing", "data", "." ]
16c6956112f975eb2ce774b2d5f8e9ddffde569f
https://github.com/NicolasLM/atoma/blob/16c6956112f975eb2ce774b2d5f8e9ddffde569f/atoma/simple.py#L217-L224
13,371
Atomistica/atomistica
src/python/atomistica/deformation.py
get_shear_distance
def get_shear_distance(a): """ Returns the distance a volume has moved during simple shear. Considers either Lees-Edwards boundary conditions or sheared cells. """ cx, cy, cz = a.cell if 'shear_dx' in a.info: assert abs(cx[1]) < 1e-12, 'cx[1] = {0}'.format(cx[1]) assert abs(cx[2]...
python
def get_shear_distance(a): """ Returns the distance a volume has moved during simple shear. Considers either Lees-Edwards boundary conditions or sheared cells. """ cx, cy, cz = a.cell if 'shear_dx' in a.info: assert abs(cx[1]) < 1e-12, 'cx[1] = {0}'.format(cx[1]) assert abs(cx[2]...
[ "def", "get_shear_distance", "(", "a", ")", ":", "cx", ",", "cy", ",", "cz", "=", "a", ".", "cell", "if", "'shear_dx'", "in", "a", ".", "info", ":", "assert", "abs", "(", "cx", "[", "1", "]", ")", "<", "1e-12", ",", "'cx[1] = {0}'", ".", "format"...
Returns the distance a volume has moved during simple shear. Considers either Lees-Edwards boundary conditions or sheared cells.
[ "Returns", "the", "distance", "a", "volume", "has", "moved", "during", "simple", "shear", ".", "Considers", "either", "Lees", "-", "Edwards", "boundary", "conditions", "or", "sheared", "cells", "." ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/deformation.py#L30-L50
13,372
Atomistica/atomistica
src/python/atomistica/atomic_strain.py
array_inverse
def array_inverse(A): """ Compute inverse for each matrix in a list of matrices. This is faster than calling numpy.linalg.inv for each matrix. """ A = np.ascontiguousarray(A, dtype=float) b = np.identity(A.shape[2], dtype=A.dtype) n_eq = A.shape[1] n_rhs = A.shape[2] pivots = np.zer...
python
def array_inverse(A): """ Compute inverse for each matrix in a list of matrices. This is faster than calling numpy.linalg.inv for each matrix. """ A = np.ascontiguousarray(A, dtype=float) b = np.identity(A.shape[2], dtype=A.dtype) n_eq = A.shape[1] n_rhs = A.shape[2] pivots = np.zer...
[ "def", "array_inverse", "(", "A", ")", ":", "A", "=", "np", ".", "ascontiguousarray", "(", "A", ",", "dtype", "=", "float", ")", "b", "=", "np", ".", "identity", "(", "A", ".", "shape", "[", "2", "]", ",", "dtype", "=", "A", ".", "dtype", ")", ...
Compute inverse for each matrix in a list of matrices. This is faster than calling numpy.linalg.inv for each matrix.
[ "Compute", "inverse", "for", "each", "matrix", "in", "a", "list", "of", "matrices", ".", "This", "is", "faster", "than", "calling", "numpy", ".", "linalg", ".", "inv", "for", "each", "matrix", "." ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/atomic_strain.py#L66-L86
13,373
Atomistica/atomistica
src/python/atomistica/atomic_strain.py
get_delta_plus_epsilon
def get_delta_plus_epsilon(nat, i_now, dr_now, dr_old): """ Calculate delta_ij+epsilon_ij, i.e. the deformation gradient matrix """ XIJ = get_XIJ(nat, i_now, dr_now, dr_old) YIJ = get_YIJ(nat, i_now, dr_old) YIJ_invert = array_inverse(YIJ) # Perform sum_k X_ik Y_jk^-1 epsilon = np.sum(...
python
def get_delta_plus_epsilon(nat, i_now, dr_now, dr_old): """ Calculate delta_ij+epsilon_ij, i.e. the deformation gradient matrix """ XIJ = get_XIJ(nat, i_now, dr_now, dr_old) YIJ = get_YIJ(nat, i_now, dr_old) YIJ_invert = array_inverse(YIJ) # Perform sum_k X_ik Y_jk^-1 epsilon = np.sum(...
[ "def", "get_delta_plus_epsilon", "(", "nat", ",", "i_now", ",", "dr_now", ",", "dr_old", ")", ":", "XIJ", "=", "get_XIJ", "(", "nat", ",", "i_now", ",", "dr_now", ",", "dr_old", ")", "YIJ", "=", "get_YIJ", "(", "nat", ",", "i_now", ",", "dr_old", ")"...
Calculate delta_ij+epsilon_ij, i.e. the deformation gradient matrix
[ "Calculate", "delta_ij", "+", "epsilon_ij", "i", ".", "e", ".", "the", "deformation", "gradient", "matrix" ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/atomic_strain.py#L89-L101
13,374
Atomistica/atomistica
src/python/atomistica/atomic_strain.py
get_D_square_min
def get_D_square_min(atoms_now, atoms_old, i_now, j_now, delta_plus_epsilon=None): """ Calculate the D^2_min norm of Falk and Langer """ nat = len(atoms_now) assert len(atoms_now) == len(atoms_old) pos_now = atoms_now.positions pos_old = atoms_old.positions # Compute current and old di...
python
def get_D_square_min(atoms_now, atoms_old, i_now, j_now, delta_plus_epsilon=None): """ Calculate the D^2_min norm of Falk and Langer """ nat = len(atoms_now) assert len(atoms_now) == len(atoms_old) pos_now = atoms_now.positions pos_old = atoms_old.positions # Compute current and old di...
[ "def", "get_D_square_min", "(", "atoms_now", ",", "atoms_old", ",", "i_now", ",", "j_now", ",", "delta_plus_epsilon", "=", "None", ")", ":", "nat", "=", "len", "(", "atoms_now", ")", "assert", "len", "(", "atoms_now", ")", "==", "len", "(", "atoms_old", ...
Calculate the D^2_min norm of Falk and Langer
[ "Calculate", "the", "D^2_min", "norm", "of", "Falk", "and", "Langer" ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/atomic_strain.py#L104-L144
13,375
Atomistica/atomistica
src/python/atomistica/hardware.py
dhms
def dhms(secs): """return days,hours,minutes and seconds""" dhms = [0, 0, 0, 0] dhms[0] = int(secs // 86400) s = secs % 86400 dhms[1] = int(s // 3600) s = secs % 3600 dhms[2] = int(s // 60) s = secs % 60 dhms[3] = int(s+.5) return dhms
python
def dhms(secs): """return days,hours,minutes and seconds""" dhms = [0, 0, 0, 0] dhms[0] = int(secs // 86400) s = secs % 86400 dhms[1] = int(s // 3600) s = secs % 3600 dhms[2] = int(s // 60) s = secs % 60 dhms[3] = int(s+.5) return dhms
[ "def", "dhms", "(", "secs", ")", ":", "dhms", "=", "[", "0", ",", "0", ",", "0", ",", "0", "]", "dhms", "[", "0", "]", "=", "int", "(", "secs", "//", "86400", ")", "s", "=", "secs", "%", "86400", "dhms", "[", "1", "]", "=", "int", "(", ...
return days,hours,minutes and seconds
[ "return", "days", "hours", "minutes", "and", "seconds" ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/hardware.py#L52-L62
13,376
Atomistica/atomistica
src/python/atomistica/hardware.py
hms
def hms(secs): """return hours,minutes and seconds""" hms = [0, 0, 0] hms[0] = int(secs // 3600) s = secs % 3600 hms[1] = int(s // 60) s = secs % 60 hms[2] = int(s+.5) return hms
python
def hms(secs): """return hours,minutes and seconds""" hms = [0, 0, 0] hms[0] = int(secs // 3600) s = secs % 3600 hms[1] = int(s // 60) s = secs % 60 hms[2] = int(s+.5) return hms
[ "def", "hms", "(", "secs", ")", ":", "hms", "=", "[", "0", ",", "0", ",", "0", "]", "hms", "[", "0", "]", "=", "int", "(", "secs", "//", "3600", ")", "s", "=", "secs", "%", "3600", "hms", "[", "1", "]", "=", "int", "(", "s", "//", "60",...
return hours,minutes and seconds
[ "return", "hours", "minutes", "and", "seconds" ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/hardware.py#L65-L73
13,377
Atomistica/atomistica
src/python/atomistica/analysis.py
get_enclosing_orthorhombic_box
def get_enclosing_orthorhombic_box(cell): """ Return lower and upper bounds of the orthorhombic box that encloses the parallelepiped spanned by the three cell vectors of cell. """ # Cell vectors cx, cy, cz = cell # The cell has eight corners, one is at the origin, three at cx, cy, ...
python
def get_enclosing_orthorhombic_box(cell): """ Return lower and upper bounds of the orthorhombic box that encloses the parallelepiped spanned by the three cell vectors of cell. """ # Cell vectors cx, cy, cz = cell # The cell has eight corners, one is at the origin, three at cx, cy, ...
[ "def", "get_enclosing_orthorhombic_box", "(", "cell", ")", ":", "# Cell vectors", "cx", ",", "cy", ",", "cz", "=", "cell", "# The cell has eight corners, one is at the origin, three at cx, cy, cz", "# and the last ones are...", "c1", "=", "cx", "+", "cy", "c2", "=", "cx...
Return lower and upper bounds of the orthorhombic box that encloses the parallelepiped spanned by the three cell vectors of cell.
[ "Return", "lower", "and", "upper", "bounds", "of", "the", "orthorhombic", "box", "that", "encloses", "the", "parallelepiped", "spanned", "by", "the", "three", "cell", "vectors", "of", "cell", "." ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/analysis.py#L38-L58
13,378
Atomistica/atomistica
src/python/atomistica/analysis.py
stress_invariants
def stress_invariants(s): """Receives a list of stress tensors and returns the three invariants. Return hydrostatic pressure, octahedral shear stress and J3 """ s = np.asarray(s) if s.shape == (6,): s = s.reshape(1,-1) elif s.shape == (3,3): s = s.reshape(1,-1,-1) if len(s...
python
def stress_invariants(s): """Receives a list of stress tensors and returns the three invariants. Return hydrostatic pressure, octahedral shear stress and J3 """ s = np.asarray(s) if s.shape == (6,): s = s.reshape(1,-1) elif s.shape == (3,3): s = s.reshape(1,-1,-1) if len(s...
[ "def", "stress_invariants", "(", "s", ")", ":", "s", "=", "np", ".", "asarray", "(", "s", ")", "if", "s", ".", "shape", "==", "(", "6", ",", ")", ":", "s", "=", "s", ".", "reshape", "(", "1", ",", "-", "1", ")", "elif", "s", ".", "shape", ...
Receives a list of stress tensors and returns the three invariants. Return hydrostatic pressure, octahedral shear stress and J3
[ "Receives", "a", "list", "of", "stress", "tensors", "and", "returns", "the", "three", "invariants", ".", "Return", "hydrostatic", "pressure", "octahedral", "shear", "stress", "and", "J3" ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/analysis.py#L181-L203
13,379
Atomistica/atomistica
tools/meta.py
scanmeta
def scanmeta(f): """Scan file headers for @meta ... @endmeta information and store that into a dictionary. """ print(f) if isinstance(f, str): f = io.open(f, mode='r', encoding='latin-1') done = False l = f.readline() s = None while l and s is None: i = l.find('!...
python
def scanmeta(f): """Scan file headers for @meta ... @endmeta information and store that into a dictionary. """ print(f) if isinstance(f, str): f = io.open(f, mode='r', encoding='latin-1') done = False l = f.readline() s = None while l and s is None: i = l.find('!...
[ "def", "scanmeta", "(", "f", ")", ":", "print", "(", "f", ")", "if", "isinstance", "(", "f", ",", "str", ")", ":", "f", "=", "io", ".", "open", "(", "f", ",", "mode", "=", "'r'", ",", "encoding", "=", "'latin-1'", ")", "done", "=", "False", "...
Scan file headers for @meta ... @endmeta information and store that into a dictionary.
[ "Scan", "file", "headers", "for" ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/tools/meta.py#L14-L67
13,380
Atomistica/atomistica
src/python/atomistica/snippets.py
mic
def mic(dr, cell, pbc=None): """ Apply minimum image convention to an array of distance vectors. """ # Check where distance larger than 1/2 cell. Particles have crossed # periodic boundaries then and need to be unwrapped. rec = np.linalg.inv(cell) if pbc is not None: rec *= np.array(...
python
def mic(dr, cell, pbc=None): """ Apply minimum image convention to an array of distance vectors. """ # Check where distance larger than 1/2 cell. Particles have crossed # periodic boundaries then and need to be unwrapped. rec = np.linalg.inv(cell) if pbc is not None: rec *= np.array(...
[ "def", "mic", "(", "dr", ",", "cell", ",", "pbc", "=", "None", ")", ":", "# Check where distance larger than 1/2 cell. Particles have crossed", "# periodic boundaries then and need to be unwrapped.", "rec", "=", "np", ".", "linalg", ".", "inv", "(", "cell", ")", "if",...
Apply minimum image convention to an array of distance vectors.
[ "Apply", "minimum", "image", "convention", "to", "an", "array", "of", "distance", "vectors", "." ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/snippets.py#L31-L43
13,381
Atomistica/atomistica
src/python/tools/a_run.py
s_from_dhms
def s_from_dhms(time): """return seconds from dhms""" dhms_s = { 's' : 1, 'm' : 60, 'h' : 3600, 'd' : 86400 } time = time.lower() word_list = re.findall('\d*[^\d]*',time) seconds=0 for word in word_list: if word != '': sec = 1 for t in list(dhms_s.keys()): ...
python
def s_from_dhms(time): """return seconds from dhms""" dhms_s = { 's' : 1, 'm' : 60, 'h' : 3600, 'd' : 86400 } time = time.lower() word_list = re.findall('\d*[^\d]*',time) seconds=0 for word in word_list: if word != '': sec = 1 for t in list(dhms_s.keys()): ...
[ "def", "s_from_dhms", "(", "time", ")", ":", "dhms_s", "=", "{", "'s'", ":", "1", ",", "'m'", ":", "60", ",", "'h'", ":", "3600", ",", "'d'", ":", "86400", "}", "time", "=", "time", ".", "lower", "(", ")", "word_list", "=", "re", ".", "findall"...
return seconds from dhms
[ "return", "seconds", "from", "dhms" ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/tools/a_run.py#L33-L52
13,382
Atomistica/atomistica
src/python/atomistica/join_calculators.py
JoinCalculators.get_stress
def get_stress(self, a): """Calculate stress tensor.""" s = np.zeros( 6, dtype=float ) for c in self.calcs: s += c.get_stress(a) return s
python
def get_stress(self, a): """Calculate stress tensor.""" s = np.zeros( 6, dtype=float ) for c in self.calcs: s += c.get_stress(a) return s
[ "def", "get_stress", "(", "self", ",", "a", ")", ":", "s", "=", "np", ".", "zeros", "(", "6", ",", "dtype", "=", "float", ")", "for", "c", "in", "self", ".", "calcs", ":", "s", "+=", "c", ".", "get_stress", "(", "a", ")", "return", "s" ]
Calculate stress tensor.
[ "Calculate", "stress", "tensor", "." ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/join_calculators.py#L66-L71
13,383
Atomistica/atomistica
src/python/atomistica/join_calculators.py
JoinCalculators.set_atoms
def set_atoms(self, a): """Assign an atoms object.""" for c in self.calcs: if hasattr(c, "set_atoms"): c.set_atoms(a)
python
def set_atoms(self, a): """Assign an atoms object.""" for c in self.calcs: if hasattr(c, "set_atoms"): c.set_atoms(a)
[ "def", "set_atoms", "(", "self", ",", "a", ")", ":", "for", "c", "in", "self", ".", "calcs", ":", "if", "hasattr", "(", "c", ",", "\"set_atoms\"", ")", ":", "c", ".", "set_atoms", "(", "a", ")" ]
Assign an atoms object.
[ "Assign", "an", "atoms", "object", "." ]
5ed79d776c92b91a566be22615bfb304ecc75db7
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/join_calculators.py#L79-L83
13,384
thieman/py-dag
dag/__init__.py
DAG.rename_edges
def rename_edges(self, old_task_name, new_task_name, graph=None): """ Change references to a task in existing edges. """ if not graph: graph = self.graph for node, edges in graph.items(): if node == old_task_name: graph[new_task_name] = copy(edges) ...
python
def rename_edges(self, old_task_name, new_task_name, graph=None): """ Change references to a task in existing edges. """ if not graph: graph = self.graph for node, edges in graph.items(): if node == old_task_name: graph[new_task_name] = copy(edges) ...
[ "def", "rename_edges", "(", "self", ",", "old_task_name", ",", "new_task_name", ",", "graph", "=", "None", ")", ":", "if", "not", "graph", ":", "graph", "=", "self", ".", "graph", "for", "node", ",", "edges", "in", "graph", ".", "items", "(", ")", ":...
Change references to a task in existing edges.
[ "Change", "references", "to", "a", "task", "in", "existing", "edges", "." ]
5b5eed396c930751576bdf0d45907a665aac000b
https://github.com/thieman/py-dag/blob/5b5eed396c930751576bdf0d45907a665aac000b/dag/__init__.py#L77-L90
13,385
thieman/py-dag
dag/__init__.py
DAG.predecessors
def predecessors(self, node, graph=None): """ Returns a list of all predecessors of the given node """ if graph is None: graph = self.graph return [key for key in graph if node in graph[key]]
python
def predecessors(self, node, graph=None): """ Returns a list of all predecessors of the given node """ if graph is None: graph = self.graph return [key for key in graph if node in graph[key]]
[ "def", "predecessors", "(", "self", ",", "node", ",", "graph", "=", "None", ")", ":", "if", "graph", "is", "None", ":", "graph", "=", "self", ".", "graph", "return", "[", "key", "for", "key", "in", "graph", "if", "node", "in", "graph", "[", "key", ...
Returns a list of all predecessors of the given node
[ "Returns", "a", "list", "of", "all", "predecessors", "of", "the", "given", "node" ]
5b5eed396c930751576bdf0d45907a665aac000b
https://github.com/thieman/py-dag/blob/5b5eed396c930751576bdf0d45907a665aac000b/dag/__init__.py#L92-L96
13,386
buriburisuri/sugartensor
sugartensor/sg_initializer.py
constant
def constant(name, shape, value=0, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r"""Creates a tensor variable of which initial values are `value` and shape is `shape`. Args: name: The name of new variable. shape: A tuple/list of integers or an integer. If shape is a...
python
def constant(name, shape, value=0, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r"""Creates a tensor variable of which initial values are `value` and shape is `shape`. Args: name: The name of new variable. shape: A tuple/list of integers or an integer. If shape is a...
[ "def", "constant", "(", "name", ",", "shape", ",", "value", "=", "0", ",", "dtype", "=", "tf", ".", "sg_floatx", ",", "summary", "=", "True", ",", "regularizer", "=", "None", ",", "trainable", "=", "True", ")", ":", "shape", "=", "shape", "if", "is...
r"""Creates a tensor variable of which initial values are `value` and shape is `shape`. Args: name: The name of new variable. shape: A tuple/list of integers or an integer. If shape is an integer, it is converted to a list. value: A Python scalar. All elements of the initialized variable...
[ "r", "Creates", "a", "tensor", "variable", "of", "which", "initial", "values", "are", "value", "and", "shape", "is", "shape", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_initializer.py#L10-L36
13,387
buriburisuri/sugartensor
sugartensor/sg_queue.py
sg_producer_func
def sg_producer_func(func): r"""Decorates a function `func` as sg_producer_func. Args: func: A function to decorate. """ @wraps(func) def wrapper(**kwargs): r"""Manages arguments of `tf.sg_opt`. Args: **kwargs: source: A source queue list to enqueue ...
python
def sg_producer_func(func): r"""Decorates a function `func` as sg_producer_func. Args: func: A function to decorate. """ @wraps(func) def wrapper(**kwargs): r"""Manages arguments of `tf.sg_opt`. Args: **kwargs: source: A source queue list to enqueue ...
[ "def", "sg_producer_func", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "*", "kwargs", ")", ":", "r\"\"\"Manages arguments of `tf.sg_opt`.\n\n Args:\n **kwargs:\n source: A source queue list to enqueue\n ...
r"""Decorates a function `func` as sg_producer_func. Args: func: A function to decorate.
[ "r", "Decorates", "a", "function", "func", "as", "sg_producer_func", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_queue.py#L11-L77
13,388
buriburisuri/sugartensor
sugartensor/sg_transform.py
sg_transpose
def sg_transpose(tensor, opt): r"""Permutes the dimensions according to `opt.perm`. See `tf.transpose()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: perm: A permutation of the dimensions of `tensor`. The target shape. name: If provided, replace ...
python
def sg_transpose(tensor, opt): r"""Permutes the dimensions according to `opt.perm`. See `tf.transpose()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: perm: A permutation of the dimensions of `tensor`. The target shape. name: If provided, replace ...
[ "def", "sg_transpose", "(", "tensor", ",", "opt", ")", ":", "assert", "opt", ".", "perm", "is", "not", "None", ",", "'perm is mandatory'", "return", "tf", ".", "transpose", "(", "tensor", ",", "opt", ".", "perm", ",", "name", "=", "opt", ".", "name", ...
r"""Permutes the dimensions according to `opt.perm`. See `tf.transpose()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: perm: A permutation of the dimensions of `tensor`. The target shape. name: If provided, replace current tensor's name. Returns...
[ "r", "Permutes", "the", "dimensions", "according", "to", "opt", ".", "perm", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L161-L176
13,389
buriburisuri/sugartensor
sugartensor/sg_transform.py
sg_argmin
def sg_argmin(tensor, opt): r"""Returns the indices of the minimum values along the specified axis. See `tf.argin()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis: Target axis. Default is the last one. name: If provided, replace current tenso...
python
def sg_argmin(tensor, opt): r"""Returns the indices of the minimum values along the specified axis. See `tf.argin()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis: Target axis. Default is the last one. name: If provided, replace current tenso...
[ "def", "sg_argmin", "(", "tensor", ",", "opt", ")", ":", "opt", "+=", "tf", ".", "sg_opt", "(", "axis", "=", "tensor", ".", "get_shape", "(", ")", ".", "ndims", "-", "1", ")", "return", "tf", ".", "argmin", "(", "tensor", ",", "opt", ".", "axis",...
r"""Returns the indices of the minimum values along the specified axis. See `tf.argin()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis: Target axis. Default is the last one. name: If provided, replace current tensor's name. Returns: A ...
[ "r", "Returns", "the", "indices", "of", "the", "minimum", "values", "along", "the", "specified", "axis", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L199-L214
13,390
buriburisuri/sugartensor
sugartensor/sg_transform.py
sg_concat
def sg_concat(tensor, opt): r"""Concatenates tensors along a axis. See `tf.concat()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: target: A `Tensor`. Must have the same rank as `tensor`, and all dimensions except `opt.dim` must be equal. ...
python
def sg_concat(tensor, opt): r"""Concatenates tensors along a axis. See `tf.concat()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: target: A `Tensor`. Must have the same rank as `tensor`, and all dimensions except `opt.dim` must be equal. ...
[ "def", "sg_concat", "(", "tensor", ",", "opt", ")", ":", "assert", "opt", ".", "target", "is", "not", "None", ",", "'target is mandatory.'", "opt", "+=", "tf", ".", "sg_opt", "(", "axis", "=", "tensor", ".", "get_shape", "(", ")", ".", "ndims", "-", ...
r"""Concatenates tensors along a axis. See `tf.concat()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: target: A `Tensor`. Must have the same rank as `tensor`, and all dimensions except `opt.dim` must be equal. axis : Target axis. Default is...
[ "r", "Concatenates", "tensors", "along", "a", "axis", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L218-L237
13,391
buriburisuri/sugartensor
sugartensor/sg_transform.py
sg_log
def sg_log(tensor, opt): r"""Log transform a dense tensor See `tf.log()` in tensorflow. Args: tensor: A `Tensor` ( automatically given by chain ) opt: name: If provided, replace current tensor's name. Returns: A `Tensor`. """ return tf.log(tensor + tf.sg_eps, name=...
python
def sg_log(tensor, opt): r"""Log transform a dense tensor See `tf.log()` in tensorflow. Args: tensor: A `Tensor` ( automatically given by chain ) opt: name: If provided, replace current tensor's name. Returns: A `Tensor`. """ return tf.log(tensor + tf.sg_eps, name=...
[ "def", "sg_log", "(", "tensor", ",", "opt", ")", ":", "return", "tf", ".", "log", "(", "tensor", "+", "tf", ".", "sg_eps", ",", "name", "=", "opt", ".", "name", ")" ]
r"""Log transform a dense tensor See `tf.log()` in tensorflow. Args: tensor: A `Tensor` ( automatically given by chain ) opt: name: If provided, replace current tensor's name. Returns: A `Tensor`.
[ "r", "Log", "transform", "a", "dense", "tensor" ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L281-L294
13,392
buriburisuri/sugartensor
sugartensor/sg_transform.py
sg_prod
def sg_prod(tensor, opt): r"""Computes the product of elements across axis of a tensor. See `tf.reduce_prod()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, ret...
python
def sg_prod(tensor, opt): r"""Computes the product of elements across axis of a tensor. See `tf.reduce_prod()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, ret...
[ "def", "sg_prod", "(", "tensor", ",", "opt", ")", ":", "return", "tf", ".", "reduce_prod", "(", "tensor", ",", "axis", "=", "opt", ".", "axis", ",", "keep_dims", "=", "opt", ".", "keep_dims", ",", "name", "=", "opt", ".", "name", ")" ]
r"""Computes the product of elements across axis of a tensor. See `tf.reduce_prod()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, retains reduced dimensions with l...
[ "r", "Computes", "the", "product", "of", "elements", "across", "axis", "of", "a", "tensor", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L357-L372
13,393
buriburisuri/sugartensor
sugartensor/sg_transform.py
sg_min
def sg_min(tensor, opt): r"""Computes the minimum of elements across axis of a tensor. See `tf.reduce_min()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, retai...
python
def sg_min(tensor, opt): r"""Computes the minimum of elements across axis of a tensor. See `tf.reduce_min()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, retai...
[ "def", "sg_min", "(", "tensor", ",", "opt", ")", ":", "return", "tf", ".", "reduce_min", "(", "tensor", ",", "axis", "=", "opt", ".", "axis", ",", "keep_dims", "=", "opt", ".", "keep_dims", ",", "name", "=", "opt", ".", "name", ")" ]
r"""Computes the minimum of elements across axis of a tensor. See `tf.reduce_min()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, retains reduced dimensions with le...
[ "r", "Computes", "the", "minimum", "of", "elements", "across", "axis", "of", "a", "tensor", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L376-L391
13,394
buriburisuri/sugartensor
sugartensor/sg_transform.py
sg_max
def sg_max(tensor, opt): r"""Computes the maximum of elements across axis of a tensor. See `tf.reduce_max()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, retai...
python
def sg_max(tensor, opt): r"""Computes the maximum of elements across axis of a tensor. See `tf.reduce_max()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, retai...
[ "def", "sg_max", "(", "tensor", ",", "opt", ")", ":", "return", "tf", ".", "reduce_max", "(", "tensor", ",", "axis", "=", "opt", ".", "axis", ",", "keep_dims", "=", "opt", ".", "keep_dims", ",", "name", "=", "opt", ".", "name", ")" ]
r"""Computes the maximum of elements across axis of a tensor. See `tf.reduce_max()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, retains reduced dimensions with le...
[ "r", "Computes", "the", "maximum", "of", "elements", "across", "axis", "of", "a", "tensor", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L395-L410
13,395
buriburisuri/sugartensor
sugartensor/sg_transform.py
sg_any
def sg_any(tensor, opt): r"""Computes the "logical or" of elements across axis of a tensor. See `tf.reduce_any()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, ...
python
def sg_any(tensor, opt): r"""Computes the "logical or" of elements across axis of a tensor. See `tf.reduce_any()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, ...
[ "def", "sg_any", "(", "tensor", ",", "opt", ")", ":", "return", "tf", ".", "reduce_any", "(", "tensor", ",", "axis", "=", "opt", ".", "axis", ",", "keep_dims", "=", "opt", ".", "keep_dims", ",", "name", "=", "opt", ".", "name", ")" ]
r"""Computes the "logical or" of elements across axis of a tensor. See `tf.reduce_any()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, retains reduced dimensions wi...
[ "r", "Computes", "the", "logical", "or", "of", "elements", "across", "axis", "of", "a", "tensor", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L433-L448
13,396
buriburisuri/sugartensor
sugartensor/sg_transform.py
sg_lookup
def sg_lookup(tensor, opt): r"""Looks up the `tensor`, which is the embedding matrix. Args: tensor: A tensor ( automatically given by chain ) opt: emb: A 2-D `Tensor`. An embedding matrix. name: If provided, replace current tensor's name. Returns: A `Tensor`. ...
python
def sg_lookup(tensor, opt): r"""Looks up the `tensor`, which is the embedding matrix. Args: tensor: A tensor ( automatically given by chain ) opt: emb: A 2-D `Tensor`. An embedding matrix. name: If provided, replace current tensor's name. Returns: A `Tensor`. ...
[ "def", "sg_lookup", "(", "tensor", ",", "opt", ")", ":", "assert", "opt", ".", "emb", "is", "not", "None", ",", "'emb is mandatory.'", "return", "tf", ".", "nn", ".", "embedding_lookup", "(", "opt", ".", "emb", ",", "tensor", ",", "name", "=", "opt", ...
r"""Looks up the `tensor`, which is the embedding matrix. Args: tensor: A tensor ( automatically given by chain ) opt: emb: A 2-D `Tensor`. An embedding matrix. name: If provided, replace current tensor's name. Returns: A `Tensor`.
[ "r", "Looks", "up", "the", "tensor", "which", "is", "the", "embedding", "matrix", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L533-L547
13,397
buriburisuri/sugartensor
sugartensor/sg_transform.py
sg_reverse_seq
def sg_reverse_seq(tensor, opt): r"""Reverses variable length slices. Before applying the pure tensorflow function tf.reverse_sequence, this function calculates sequence lengths by counting non-zeros. For example, ``` tensor = [[1, 2, 3, 0, 0], [4, 5, 0, 0, 0]] tensor.sg_reverse_seq...
python
def sg_reverse_seq(tensor, opt): r"""Reverses variable length slices. Before applying the pure tensorflow function tf.reverse_sequence, this function calculates sequence lengths by counting non-zeros. For example, ``` tensor = [[1, 2, 3, 0, 0], [4, 5, 0, 0, 0]] tensor.sg_reverse_seq...
[ "def", "sg_reverse_seq", "(", "tensor", ",", "opt", ")", ":", "# default sequence dimension", "opt", "+=", "tf", ".", "sg_opt", "(", "axis", "=", "1", ")", "seq_len", "=", "tf", ".", "not_equal", "(", "tensor", ",", "tf", ".", "zeros_like", "(", "tensor"...
r"""Reverses variable length slices. Before applying the pure tensorflow function tf.reverse_sequence, this function calculates sequence lengths by counting non-zeros. For example, ``` tensor = [[1, 2, 3, 0, 0], [4, 5, 0, 0, 0]] tensor.sg_reverse_seq() => [[3 2 1 0 0] [5 4 0...
[ "r", "Reverses", "variable", "length", "slices", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L551-L578
13,398
buriburisuri/sugartensor
sugartensor/sg_main.py
sg_gpus
def sg_gpus(): r""" Gets current available GPU nums Returns: A integer : total # of GPUs available """ global _gpus if _gpus is None: local_device_protos = device_lib.list_local_devices() _gpus = len([x.name for x in local_device_protos if x.device_type == 'GPU']) return...
python
def sg_gpus(): r""" Gets current available GPU nums Returns: A integer : total # of GPUs available """ global _gpus if _gpus is None: local_device_protos = device_lib.list_local_devices() _gpus = len([x.name for x in local_device_protos if x.device_type == 'GPU']) return...
[ "def", "sg_gpus", "(", ")", ":", "global", "_gpus", "if", "_gpus", "is", "None", ":", "local_device_protos", "=", "device_lib", ".", "list_local_devices", "(", ")", "_gpus", "=", "len", "(", "[", "x", ".", "name", "for", "x", "in", "local_device_protos", ...
r""" Gets current available GPU nums Returns: A integer : total # of GPUs available
[ "r", "Gets", "current", "available", "GPU", "nums" ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_main.py#L64-L76
13,399
buriburisuri/sugartensor
sugartensor/sg_main.py
sg_context
def sg_context(**kwargs): r"""Context helper for computational graph building. Makes all elements within the with Block share the parameters. For example, in the following example, the default value of parameter `bn` will be set to True in the all layers within the with block. ``` with tf.sg_c...
python
def sg_context(**kwargs): r"""Context helper for computational graph building. Makes all elements within the with Block share the parameters. For example, in the following example, the default value of parameter `bn` will be set to True in the all layers within the with block. ``` with tf.sg_c...
[ "def", "sg_context", "(", "*", "*", "kwargs", ")", ":", "global", "_context", "# set options when enter", "context_now", "=", "tf", ".", "sg_opt", "(", "kwargs", ")", "_context", "+=", "[", "context_now", "]", "# if named context", "if", "context_now", ".", "n...
r"""Context helper for computational graph building. Makes all elements within the with Block share the parameters. For example, in the following example, the default value of parameter `bn` will be set to True in the all layers within the with block. ``` with tf.sg_context(bn=True): ... ...
[ "r", "Context", "helper", "for", "computational", "graph", "building", ".", "Makes", "all", "elements", "within", "the", "with", "Block", "share", "the", "parameters", "." ]
d2c039954777c7fbe3eb0c2ae40c45c9854deb40
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_main.py#L87-L132