repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
ninuxorg/nodeshot
nodeshot/community/profiles/social_auth_extra/pipeline.py
create_user
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """ Creates user. Depends on get_username pipeline. """ if user: return {'user': user} if not username: return None email = details.get('email') original_email = None # email is requir...
python
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """ Creates user. Depends on get_username pipeline. """ if user: return {'user': user} if not username: return None email = details.get('email') original_email = None # email is requir...
[ "def", "create_user", "(", "backend", ",", "details", ",", "response", ",", "uid", ",", "username", ",", "user", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "user", ":", "return", "{", "'user'", ":", "user", "}", "if", ...
Creates user. Depends on get_username pipeline.
[ "Creates", "user", ".", "Depends", "on", "get_username", "pipeline", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/social_auth_extra/pipeline.py#L13-L37
ninuxorg/nodeshot
nodeshot/community/profiles/social_auth_extra/pipeline.py
load_extra_data
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """ Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or UserSocialAuth.get_social_auth(backend.name, uid) # create verified email address...
python
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """ Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or UserSocialAuth.get_social_auth(backend.name, uid) # create verified email address...
[ "def", "load_extra_data", "(", "backend", ",", "details", ",", "response", ",", "uid", ",", "user", ",", "social_user", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "social_user", "=", "social_user", "or", "UserSocialAuth", ".", "get...
Load extra data from provider and store it on current UserSocialAuth extra_data field.
[ "Load", "extra", "data", "from", "provider", "and", "store", "it", "on", "current", "UserSocialAuth", "extra_data", "field", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/social_auth_extra/pipeline.py#L40-L79
ninuxorg/nodeshot
nodeshot/community/mailing/models/inward.py
Inward.clean
def clean(self, *args, **kwargs): """ custom validation """ if not self.user and (not self.from_name or not self.from_email): raise ValidationError(_('If sender is not specified from_name and from_email must be filled in.')) # fill name and email if self.user: sel...
python
def clean(self, *args, **kwargs): """ custom validation """ if not self.user and (not self.from_name or not self.from_email): raise ValidationError(_('If sender is not specified from_name and from_email must be filled in.')) # fill name and email if self.user: sel...
[ "def", "clean", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "user", "and", "(", "not", "self", ".", "from_name", "or", "not", "self", ".", "from_email", ")", ":", "raise", "ValidationError", "(", "_",...
custom validation
[ "custom", "validation" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/inward.py#L55-L62
ninuxorg/nodeshot
nodeshot/community/mailing/models/inward.py
Inward.send
def send(self): """ Sends the email to the recipient If the sending fails will set the status of the instance to "error" and will log the error according to your project's django-logging configuration """ if self.content_type.name == 'node': to = [self.to.user.email] ...
python
def send(self): """ Sends the email to the recipient If the sending fails will set the status of the instance to "error" and will log the error according to your project's django-logging configuration """ if self.content_type.name == 'node': to = [self.to.user.email] ...
[ "def", "send", "(", "self", ")", ":", "if", "self", ".", "content_type", ".", "name", "==", "'node'", ":", "to", "=", "[", "self", ".", "to", ".", "user", ".", "email", "]", "elif", "self", ".", "content_type", ".", "name", "==", "'layer'", ":", ...
Sends the email to the recipient If the sending fails will set the status of the instance to "error" and will log the error according to your project's django-logging configuration
[ "Sends", "the", "email", "to", "the", "recipient", "If", "the", "sending", "fails", "will", "set", "the", "status", "of", "the", "instance", "to", "error", "and", "will", "log", "the", "error", "according", "to", "your", "project", "s", "django", "-", "l...
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/inward.py#L64-L116
ninuxorg/nodeshot
nodeshot/community/mailing/models/inward.py
Inward.save
def save(self, *args, **kwargs): """ Custom save method """ # fill name and email if self.user: self.from_name = self.user.get_full_name() self.from_email = self.user.email # if not sent yet if int(self.status) < 1: # tries sen...
python
def save(self, *args, **kwargs): """ Custom save method """ # fill name and email if self.user: self.from_name = self.user.get_full_name() self.from_email = self.user.email # if not sent yet if int(self.status) < 1: # tries sen...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# fill name and email", "if", "self", ".", "user", ":", "self", ".", "from_name", "=", "self", ".", "user", ".", "get_full_name", "(", ")", "self", ".", "from_email", "...
Custom save method
[ "Custom", "save", "method" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/inward.py#L118-L134
ninuxorg/nodeshot
nodeshot/core/base/managers.py
BaseUtilityMixin.slice
def slice(self, order_by='pk', n=None): """ return n objects according to specified ordering """ if n is not None and n < 0: raise ValueError('slice parameter cannot be negative') queryset = self.order_by(order_by) if n is None: return queryset[0...
python
def slice(self, order_by='pk', n=None): """ return n objects according to specified ordering """ if n is not None and n < 0: raise ValueError('slice parameter cannot be negative') queryset = self.order_by(order_by) if n is None: return queryset[0...
[ "def", "slice", "(", "self", ",", "order_by", "=", "'pk'", ",", "n", "=", "None", ")", ":", "if", "n", "is", "not", "None", "and", "n", "<", "0", ":", "raise", "ValueError", "(", "'slice parameter cannot be negative'", ")", "queryset", "=", "self", "."...
return n objects according to specified ordering
[ "return", "n", "objects", "according", "to", "specified", "ordering" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/managers.py#L18-L28
ninuxorg/nodeshot
nodeshot/core/base/managers.py
ACLMixin.access_level_up_to
def access_level_up_to(self, access_level): """ returns all items that have an access level equal or lower than the one specified """ # if access_level is number if isinstance(access_level, int): value = access_level # else if is string get the numeric value else: ...
python
def access_level_up_to(self, access_level): """ returns all items that have an access level equal or lower than the one specified """ # if access_level is number if isinstance(access_level, int): value = access_level # else if is string get the numeric value else: ...
[ "def", "access_level_up_to", "(", "self", ",", "access_level", ")", ":", "# if access_level is number", "if", "isinstance", "(", "access_level", ",", "int", ")", ":", "value", "=", "access_level", "# else if is string get the numeric value", "else", ":", "value", "=",...
returns all items that have an access level equal or lower than the one specified
[ "returns", "all", "items", "that", "have", "an", "access", "level", "equal", "or", "lower", "than", "the", "one", "specified" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/managers.py#L45-L54
ninuxorg/nodeshot
nodeshot/core/base/managers.py
ACLMixin.accessible_to
def accessible_to(self, user): """ returns all the items that are accessible to the specified user if user is not authenticated will return public items :param user: an user instance """ if user.is_superuser: try: queryset = self.get_q...
python
def accessible_to(self, user): """ returns all the items that are accessible to the specified user if user is not authenticated will return public items :param user: an user instance """ if user.is_superuser: try: queryset = self.get_q...
[ "def", "accessible_to", "(", "self", ",", "user", ")", ":", "if", "user", ".", "is_superuser", ":", "try", ":", "queryset", "=", "self", ".", "get_queryset", "(", ")", "except", "AttributeError", ":", "queryset", "=", "self", "elif", "user", ".", "is_aut...
returns all the items that are accessible to the specified user if user is not authenticated will return public items :param user: an user instance
[ "returns", "all", "the", "items", "that", "are", "accessible", "to", "the", "specified", "user", "if", "user", "is", "not", "authenticated", "will", "return", "public", "items", ":", "param", "user", ":", "an", "user", "instance" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/managers.py#L56-L74
ninuxorg/nodeshot
nodeshot/core/nodes/models/status.py
Status.save
def save(self, *args, **kwargs): """ intercepts changes to is_default """ ignore_default_check = kwargs.pop('ignore_default_check', False) # if making this status the default one if self.is_default != self._current_is_default and self.is_default is True: # uncheck other defau...
python
def save(self, *args, **kwargs): """ intercepts changes to is_default """ ignore_default_check = kwargs.pop('ignore_default_check', False) # if making this status the default one if self.is_default != self._current_is_default and self.is_default is True: # uncheck other defau...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ignore_default_check", "=", "kwargs", ".", "pop", "(", "'ignore_default_check'", ",", "False", ")", "# if making this status the default one", "if", "self", ".", "is_default", "!...
intercepts changes to is_default
[ "intercepts", "changes", "to", "is_default" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/status.py#L56-L73
ninuxorg/nodeshot
nodeshot/networking/links/views.py
NodeLinkList.initial
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only links of current node """ super(NodeLinkList, self).initial(request, *args, **kwargs) # ensu...
python
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only links of current node """ super(NodeLinkList, self).initial(request, *args, **kwargs) # ensu...
[ "def", "initial", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "NodeLinkList", ",", "self", ")", ".", "initial", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# ensure node exists"...
Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only links of current node
[ "Custom", "initial", "method", ":", "*", "ensure", "node", "exists", "and", "store", "it", "in", "an", "instance", "attribute", "*", "change", "queryset", "to", "return", "only", "links", "of", "current", "node" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/views.py#L73-L93
ninuxorg/nodeshot
nodeshot/interop/sync/apps.py
AppConfig.ready
def ready(self): """ patch LayerNodesList view to support external layers """ from .models import LayerExternal from nodeshot.core.layers.views import LayerNodeListMixin def get_nodes(self, request, *args, **kwargs): try: external = self.layer.external ...
python
def ready(self): """ patch LayerNodesList view to support external layers """ from .models import LayerExternal from nodeshot.core.layers.views import LayerNodeListMixin def get_nodes(self, request, *args, **kwargs): try: external = self.layer.external ...
[ "def", "ready", "(", "self", ")", ":", "from", ".", "models", "import", "LayerExternal", "from", "nodeshot", ".", "core", ".", "layers", ".", "views", "import", "LayerNodeListMixin", "def", "get_nodes", "(", "self", ",", "request", ",", "*", "args", ",", ...
patch LayerNodesList view to support external layers
[ "patch", "LayerNodesList", "view", "to", "support", "external", "layers" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/apps.py#L7-L24
ninuxorg/nodeshot
nodeshot/conf/celery.py
init_celery
def init_celery(project_name): """ init celery app without the need of redundant code """ os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % project_name) app = Celery(project_name) app.config_from_object('django.conf:settings') app.autodiscover_tasks(settings.INSTALLED_APPS, related_na...
python
def init_celery(project_name): """ init celery app without the need of redundant code """ os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % project_name) app = Celery(project_name) app.config_from_object('django.conf:settings') app.autodiscover_tasks(settings.INSTALLED_APPS, related_na...
[ "def", "init_celery", "(", "project_name", ")", ":", "os", ".", "environ", ".", "setdefault", "(", "'DJANGO_SETTINGS_MODULE'", ",", "'%s.settings'", "%", "project_name", ")", "app", "=", "Celery", "(", "project_name", ")", "app", ".", "config_from_object", "(", ...
init celery app without the need of redundant code
[ "init", "celery", "app", "without", "the", "need", "of", "redundant", "code" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/conf/celery.py#L26-L32
ninuxorg/nodeshot
nodeshot/community/mailing/models/outward.py
Outward.get_recipients
def get_recipients(self): """ Determine recipients depending on selected filtering which can be either: * group based * layer based * user based Choosing "group" and "layer" filtering together has the effect of sending the message only to users for wh...
python
def get_recipients(self): """ Determine recipients depending on selected filtering which can be either: * group based * layer based * user based Choosing "group" and "layer" filtering together has the effect of sending the message only to users for wh...
[ "def", "get_recipients", "(", "self", ")", ":", "# user model", "User", "=", "get_user_model", "(", ")", "# prepare email list", "emails", "=", "[", "]", "# the following code is a bit ugly. Considering the titanic amount of work required to build all", "# the cools functionaliti...
Determine recipients depending on selected filtering which can be either: * group based * layer based * user based Choosing "group" and "layer" filtering together has the effect of sending the message only to users for which the following conditions are both true: ...
[ "Determine", "recipients", "depending", "on", "selected", "filtering", "which", "can", "be", "either", ":", "*", "group", "based", "*", "layer", "based", "*", "user", "based" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/outward.py#L67-L166
ninuxorg/nodeshot
nodeshot/community/mailing/models/outward.py
Outward.send
def send(self): """ Sends the email to the recipients """ # if it has already been sent don't send again if self.status is OUTWARD_STATUS.get('sent'): return False # determine recipients recipients = self.get_recipients() # init empty list that...
python
def send(self): """ Sends the email to the recipients """ # if it has already been sent don't send again if self.status is OUTWARD_STATUS.get('sent'): return False # determine recipients recipients = self.get_recipients() # init empty list that...
[ "def", "send", "(", "self", ")", ":", "# if it has already been sent don't send again", "if", "self", ".", "status", "is", "OUTWARD_STATUS", ".", "get", "(", "'sent'", ")", ":", "return", "False", "# determine recipients", "recipients", "=", "self", ".", "get_reci...
Sends the email to the recipients
[ "Sends", "the", "email", "to", "the", "recipients" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/outward.py#L168-L234
ninuxorg/nodeshot
nodeshot/community/mailing/models/outward.py
Outward.save
def save(self, *args, **kwargs): """ Custom save method """ # change status to scheduled if necessary if self.is_scheduled and self.status is not OUTWARD_STATUS.get('scheduled'): self.status = OUTWARD_STATUS.get('scheduled') # call super.save() super(...
python
def save(self, *args, **kwargs): """ Custom save method """ # change status to scheduled if necessary if self.is_scheduled and self.status is not OUTWARD_STATUS.get('scheduled'): self.status = OUTWARD_STATUS.get('scheduled') # call super.save() super(...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# change status to scheduled if necessary", "if", "self", ".", "is_scheduled", "and", "self", ".", "status", "is", "not", "OUTWARD_STATUS", ".", "get", "(", "'scheduled'", ")",...
Custom save method
[ "Custom", "save", "method" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/outward.py#L236-L245
ninuxorg/nodeshot
nodeshot/community/mailing/models/outward.py
Outward.clean
def clean(self, *args, **kwargs): """ Custom validation """ if self.is_scheduled is 1 and (self.scheduled_date == '' or self.scheduled_date is None or self.scheduled_time == '' or self.scheduled_time is None): raise ValidationError(_('If...
python
def clean(self, *args, **kwargs): """ Custom validation """ if self.is_scheduled is 1 and (self.scheduled_date == '' or self.scheduled_date is None or self.scheduled_time == '' or self.scheduled_time is None): raise ValidationError(_('If...
[ "def", "clean", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "is_scheduled", "is", "1", "and", "(", "self", ".", "scheduled_date", "==", "''", "or", "self", ".", "scheduled_date", "is", "None", "or", "self", ...
Custom validation
[ "Custom", "validation" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/outward.py#L247-L264
ninuxorg/nodeshot
nodeshot/core/nodes/models/node.py
Node.save
def save(self, *args, **kwargs): """ Custom save method does the following things: * converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point) * intercepts changes to status and fires node_status_changed signal * set defau...
python
def save(self, *args, **kwargs): """ Custom save method does the following things: * converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point) * intercepts changes to status and fires node_status_changed signal * set defau...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# geometry collection check", "if", "isinstance", "(", "self", ".", "geometry", ",", "GeometryCollection", ")", "and", "0", "<", "len", "(", "self", ".", "geometry", ")", ...
Custom save method does the following things: * converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point) * intercepts changes to status and fires node_status_changed signal * set default status
[ "Custom", "save", "method", "does", "the", "following", "things", ":", "*", "converts", "geometry", "collections", "of", "just", "1", "item", "to", "that", "item", "(", "eg", ":", "a", "collection", "of", "1", "Point", "becomes", "a", "Point", ")", "*", ...
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/node.py#L88-L116
ninuxorg/nodeshot
nodeshot/core/nodes/models/node.py
Node.add_validation_method
def add_validation_method(cls, method): """ Extend validation of Node by adding a function to the _additional_validation list. The additional validation function will be called by the clean method :method function: function to be added to _additional_validation """ metho...
python
def add_validation_method(cls, method): """ Extend validation of Node by adding a function to the _additional_validation list. The additional validation function will be called by the clean method :method function: function to be added to _additional_validation """ metho...
[ "def", "add_validation_method", "(", "cls", ",", "method", ")", ":", "method_name", "=", "method", ".", "func_name", "# add method name to additional validation method list", "cls", ".", "_additional_validation", ".", "append", "(", "method_name", ")", "# add method to th...
Extend validation of Node by adding a function to the _additional_validation list. The additional validation function will be called by the clean method :method function: function to be added to _additional_validation
[ "Extend", "validation", "of", "Node", "by", "adding", "a", "function", "to", "the", "_additional_validation", "list", ".", "The", "additional", "validation", "function", "will", "be", "called", "by", "the", "clean", "method" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/node.py#L129-L142
ninuxorg/nodeshot
nodeshot/core/nodes/models/node.py
Node.point
def point(self): """ returns location of node. If node geometry is not a point a center point will be returned """ if not self.geometry: raise ValueError('geometry attribute must be set before trying to get point property') if self.geometry.geom_type == 'Point': return s...
python
def point(self): """ returns location of node. If node geometry is not a point a center point will be returned """ if not self.geometry: raise ValueError('geometry attribute must be set before trying to get point property') if self.geometry.geom_type == 'Point': return s...
[ "def", "point", "(", "self", ")", ":", "if", "not", "self", ".", "geometry", ":", "raise", "ValueError", "(", "'geometry attribute must be set before trying to get point property'", ")", "if", "self", ".", "geometry", ".", "geom_type", "==", "'Point'", ":", "retur...
returns location of node. If node geometry is not a point a center point will be returned
[ "returns", "location", "of", "node", ".", "If", "node", "geometry", "is", "not", "a", "point", "a", "center", "point", "will", "be", "returned" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/node.py#L149-L162
ninuxorg/nodeshot
nodeshot/core/nodes/views.py
elevation_profile
def elevation_profile(request, format=None): """ Proxy to google elevation API but returns GeoJSON (unless "original" parameter is passed, in which case the original response is returned). For input parameters read: https://developers.google.com/maps/documentation/elevation/ """ if format i...
python
def elevation_profile(request, format=None): """ Proxy to google elevation API but returns GeoJSON (unless "original" parameter is passed, in which case the original response is returned). For input parameters read: https://developers.google.com/maps/documentation/elevation/ """ if format i...
[ "def", "elevation_profile", "(", "request", ",", "format", "=", "None", ")", ":", "if", "format", "is", "None", ":", "format", "=", "'json'", "path", "=", "request", ".", "query_params", ".", "get", "(", "'path'", ")", "if", "not", "path", ":", "return...
Proxy to google elevation API but returns GeoJSON (unless "original" parameter is passed, in which case the original response is returned). For input parameters read: https://developers.google.com/maps/documentation/elevation/
[ "Proxy", "to", "google", "elevation", "API", "but", "returns", "GeoJSON", "(", "unless", "original", "parameter", "is", "passed", "in", "which", "case", "the", "original", "response", "is", "returned", ")", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L246-L263
ninuxorg/nodeshot
nodeshot/core/nodes/views.py
NodeList.perform_create
def perform_create(self, serializer): """ determine user when node is added """ if serializer.instance is None: serializer.save(user=self.request.user)
python
def perform_create(self, serializer): """ determine user when node is added """ if serializer.instance is None: serializer.save(user=self.request.user)
[ "def", "perform_create", "(", "self", ",", "serializer", ")", ":", "if", "serializer", ".", "instance", "is", "None", ":", "serializer", ".", "save", "(", "user", "=", "self", ".", "request", ".", "user", ")" ]
determine user when node is added
[ "determine", "user", "when", "node", "is", "added" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L51-L54
ninuxorg/nodeshot
nodeshot/core/nodes/views.py
NodeList.get_queryset
def get_queryset(self): """ Optionally restricts the returned nodes by filtering against a `search` query parameter in the URL. """ # retrieve all nodes which are published and accessible to current user # and use joins to retrieve related fields queryset = super(...
python
def get_queryset(self): """ Optionally restricts the returned nodes by filtering against a `search` query parameter in the URL. """ # retrieve all nodes which are published and accessible to current user # and use joins to retrieve related fields queryset = super(...
[ "def", "get_queryset", "(", "self", ")", ":", "# retrieve all nodes which are published and accessible to current user", "# and use joins to retrieve related fields", "queryset", "=", "super", "(", "NodeList", ",", "self", ")", ".", "get_queryset", "(", ")", ".", "select_re...
Optionally restricts the returned nodes by filtering against a `search` query parameter in the URL.
[ "Optionally", "restricts", "the", "returned", "nodes", "by", "filtering", "against", "a", "search", "query", "parameter", "in", "the", "URL", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L56-L79
ninuxorg/nodeshot
nodeshot/core/nodes/views.py
NodeImageList.initial
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only images of current node """ super(NodeImageList, self).initial(request, *args, **kwargs) # en...
python
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only images of current node """ super(NodeImageList, self).initial(request, *args, **kwargs) # en...
[ "def", "initial", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "NodeImageList", ",", "self", ")", ".", "initial", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# ensure node exists...
Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only images of current node
[ "Custom", "initial", "method", ":", "*", "ensure", "node", "exists", "and", "store", "it", "in", "an", "instance", "attribute", "*", "change", "queryset", "to", "return", "only", "images", "of", "current", "node" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L163-L176
ninuxorg/nodeshot
nodeshot/community/notifications/tasks.py
create_notifications
def create_notifications(users, notification_model, notification_type, related_object): """ create notifications in a background job to avoid slowing down users """ # shortcuts for readability Notification = notification_model # text additional = related_object.__dict__ if related_object el...
python
def create_notifications(users, notification_model, notification_type, related_object): """ create notifications in a background job to avoid slowing down users """ # shortcuts for readability Notification = notification_model # text additional = related_object.__dict__ if related_object el...
[ "def", "create_notifications", "(", "users", ",", "notification_model", ",", "notification_type", ",", "related_object", ")", ":", "# shortcuts for readability", "Notification", "=", "notification_model", "# text", "additional", "=", "related_object", ".", "__dict__", "if...
create notifications in a background job to avoid slowing down users
[ "create", "notifications", "in", "a", "background", "job", "to", "avoid", "slowing", "down", "users" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/tasks.py#L19-L42
ninuxorg/nodeshot
nodeshot/networking/net/models/interfaces/ethernet.py
Ethernet.save
def save(self, *args, **kwargs): """ automatically set Interface.type to ethernet """ self.type = INTERFACE_TYPES.get('ethernet') super(Ethernet, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): """ automatically set Interface.type to ethernet """ self.type = INTERFACE_TYPES.get('ethernet') super(Ethernet, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "type", "=", "INTERFACE_TYPES", ".", "get", "(", "'ethernet'", ")", "super", "(", "Ethernet", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*",...
automatically set Interface.type to ethernet
[ "automatically", "set", "Interface", ".", "type", "to", "ethernet" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/interfaces/ethernet.py#L21-L24
ninuxorg/nodeshot
nodeshot/core/api/views.py
root_endpoint
def root_endpoint(request, format=None): """ List of all the available resources of this RESTful API. """ endpoints = [] # loop over url modules for urlmodule in urlpatterns: # is it a urlconf module? if hasattr(urlmodule, 'urlconf_module'): is_urlconf_module = True ...
python
def root_endpoint(request, format=None): """ List of all the available resources of this RESTful API. """ endpoints = [] # loop over url modules for urlmodule in urlpatterns: # is it a urlconf module? if hasattr(urlmodule, 'urlconf_module'): is_urlconf_module = True ...
[ "def", "root_endpoint", "(", "request", ",", "format", "=", "None", ")", ":", "endpoints", "=", "[", "]", "# loop over url modules", "for", "urlmodule", "in", "urlpatterns", ":", "# is it a urlconf module?", "if", "hasattr", "(", "urlmodule", ",", "'urlconf_module...
List of all the available resources of this RESTful API.
[ "List", "of", "all", "the", "available", "resources", "of", "this", "RESTful", "API", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/api/views.py#L11-L40
ninuxorg/nodeshot
nodeshot/networking/net/models/interface.py
Interface.save
def save(self, *args, **kwargs): """ Custom save method does the following: * save shortcuts if HSTORE is enabled """ if 'node' not in self.shortcuts: self.shortcuts['node'] = self.device.node if 'user' not in self.shortcuts and self.device.node.user: ...
python
def save(self, *args, **kwargs): """ Custom save method does the following: * save shortcuts if HSTORE is enabled """ if 'node' not in self.shortcuts: self.shortcuts['node'] = self.device.node if 'user' not in self.shortcuts and self.device.node.user: ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'node'", "not", "in", "self", ".", "shortcuts", ":", "self", ".", "shortcuts", "[", "'node'", "]", "=", "self", ".", "device", ".", "node", "if", "'user'", "n...
Custom save method does the following: * save shortcuts if HSTORE is enabled
[ "Custom", "save", "method", "does", "the", "following", ":", "*", "save", "shortcuts", "if", "HSTORE", "is", "enabled" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/interface.py#L38-L52
ninuxorg/nodeshot
nodeshot/networking/net/models/interface.py
Interface.ip_addresses
def ip_addresses(self, value): """ :param value: a list of ip addresses """ if not isinstance(value, list): raise ValueError('ip_addresses value must be a list') # in soem cases self.data might be none, so let's instantiate an empty dict if self.data is None: self...
python
def ip_addresses(self, value): """ :param value: a list of ip addresses """ if not isinstance(value, list): raise ValueError('ip_addresses value must be a list') # in soem cases self.data might be none, so let's instantiate an empty dict if self.data is None: self...
[ "def", "ip_addresses", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "raise", "ValueError", "(", "'ip_addresses value must be a list'", ")", "# in soem cases self.data might be none, so let's instantiate an empty dict...
:param value: a list of ip addresses
[ ":", "param", "value", ":", "a", "list", "of", "ip", "addresses" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/interface.py#L94-L102
ninuxorg/nodeshot
nodeshot/community/participation/models/comment.py
Comment.update_count
def update_count(self): """ updates comment count """ node_rating_count = self.node.rating_count node_rating_count.comment_count = self.node.comment_set.count() node_rating_count.save()
python
def update_count(self): """ updates comment count """ node_rating_count = self.node.rating_count node_rating_count.comment_count = self.node.comment_set.count() node_rating_count.save()
[ "def", "update_count", "(", "self", ")", ":", "node_rating_count", "=", "self", ".", "node", ".", "rating_count", "node_rating_count", ".", "comment_count", "=", "self", ".", "node", ".", "comment_set", ".", "count", "(", ")", "node_rating_count", ".", "save",...
updates comment count
[ "updates", "comment", "count" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/comment.py#L26-L30
ninuxorg/nodeshot
nodeshot/community/participation/models/comment.py
Comment.clean
def clean(self, *args, **kwargs): """ Check if comments can be inserted for parent node or parent layer """ # check done only for new nodes! if not self.pk: node = self.node # ensure comments for this node are allowed if node.participation_sett...
python
def clean(self, *args, **kwargs): """ Check if comments can be inserted for parent node or parent layer """ # check done only for new nodes! if not self.pk: node = self.node # ensure comments for this node are allowed if node.participation_sett...
[ "def", "clean", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# check done only for new nodes!", "if", "not", "self", ".", "pk", ":", "node", "=", "self", ".", "node", "# ensure comments for this node are allowed", "if", "node", ".", "pa...
Check if comments can be inserted for parent node or parent layer
[ "Check", "if", "comments", "can", "be", "inserted", "for", "parent", "node", "or", "parent", "layer" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/comment.py#L32-L46
ninuxorg/nodeshot
nodeshot/interop/sync/management/commands/sync.py
Command.retrieve_layers
def retrieve_layers(self, *args, **options): """ Retrieve specified layers or all external layers if no layer specified. """ # init empty Q object queryset = Q() # if no layer specified if len(args) < 1: # cache queryset all_layers = Layer...
python
def retrieve_layers(self, *args, **options): """ Retrieve specified layers or all external layers if no layer specified. """ # init empty Q object queryset = Q() # if no layer specified if len(args) < 1: # cache queryset all_layers = Layer...
[ "def", "retrieve_layers", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "# init empty Q object", "queryset", "=", "Q", "(", ")", "# if no layer specified", "if", "len", "(", "args", ")", "<", "1", ":", "# cache queryset", "all_layers", ...
Retrieve specified layers or all external layers if no layer specified.
[ "Retrieve", "specified", "layers", "or", "all", "external", "layers", "if", "no", "layer", "specified", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/management/commands/sync.py#L30-L70
ninuxorg/nodeshot
nodeshot/interop/sync/management/commands/sync.py
Command.handle
def handle(self, *args, **options): """ execute sync command """ # store verbosity level in instance attribute for later use self.verbosity = int(options.get('verbosity')) # blank line self.stdout.write('\r\n') # retrieve layers layers = self.retrieve_layers(*args...
python
def handle(self, *args, **options): """ execute sync command """ # store verbosity level in instance attribute for later use self.verbosity = int(options.get('verbosity')) # blank line self.stdout.write('\r\n') # retrieve layers layers = self.retrieve_layers(*args...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "# store verbosity level in instance attribute for later use", "self", ".", "verbosity", "=", "int", "(", "options", ".", "get", "(", "'verbosity'", ")", ")", "# blank line", "...
execute sync command
[ "execute", "sync", "command" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/management/commands/sync.py#L76-L129
ninuxorg/nodeshot
nodeshot/interop/sync/models/node_external.py
save_external_nodes
def save_external_nodes(sender, **kwargs): """ sync by creating nodes in external layers when needed """ node = kwargs['instance'] operation = 'add' if kwargs['created'] is True else 'change' if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_p...
python
def save_external_nodes(sender, **kwargs): """ sync by creating nodes in external layers when needed """ node = kwargs['instance'] operation = 'add' if kwargs['created'] is True else 'change' if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_p...
[ "def", "save_external_nodes", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "node", "=", "kwargs", "[", "'instance'", "]", "operation", "=", "'add'", "if", "kwargs", "[", "'created'", "]", "is", "True", "else", "'change'", "if", "node", ".", "layer",...
sync by creating nodes in external layers when needed
[ "sync", "by", "creating", "nodes", "in", "external", "layers", "when", "needed" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/node_external.py#L36-L44
ninuxorg/nodeshot
nodeshot/interop/sync/models/node_external.py
delete_external_nodes
def delete_external_nodes(sender, **kwargs): """ sync by deleting nodes from external layers when needed """ node = kwargs['instance'] if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None: return False if hasattr(node, 'exte...
python
def delete_external_nodes(sender, **kwargs): """ sync by deleting nodes from external layers when needed """ node = kwargs['instance'] if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None: return False if hasattr(node, 'exte...
[ "def", "delete_external_nodes", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "node", "=", "kwargs", "[", "'instance'", "]", "if", "node", ".", "layer", ".", "is_external", "is", "False", "or", "not", "hasattr", "(", "node", ".", "layer", ",", "'ex...
sync by deleting nodes from external layers when needed
[ "sync", "by", "deleting", "nodes", "from", "external", "layers", "when", "needed" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/node_external.py#L48-L60
ninuxorg/nodeshot
nodeshot/community/participation/models/vote.py
Vote.save
def save(self, *args, **kwargs): """ ensure users cannot vote the same node multiple times but let users change their votes """ if not self.pk: old_votes = Vote.objects.filter(user=self.user, node=self.node) for old_vote in old_votes: old_v...
python
def save(self, *args, **kwargs): """ ensure users cannot vote the same node multiple times but let users change their votes """ if not self.pk: old_votes = Vote.objects.filter(user=self.user, node=self.node) for old_vote in old_votes: old_v...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "pk", ":", "old_votes", "=", "Vote", ".", "objects", ".", "filter", "(", "user", "=", "self", ".", "user", ",", "node", "=", "self", ".",...
ensure users cannot vote the same node multiple times but let users change their votes
[ "ensure", "users", "cannot", "vote", "the", "same", "node", "multiple", "times", "but", "let", "users", "change", "their", "votes" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/vote.py#L36-L45
ninuxorg/nodeshot
nodeshot/community/participation/models/vote.py
Vote.update_count
def update_count(self): """ updates likes and dislikes count """ node_rating_count = self.node.rating_count node_rating_count.likes = self.node.vote_set.filter(vote=1).count() node_rating_count.dislikes = self.node.vote_set.filter(vote=-1).count() node_rating_count.save()
python
def update_count(self): """ updates likes and dislikes count """ node_rating_count = self.node.rating_count node_rating_count.likes = self.node.vote_set.filter(vote=1).count() node_rating_count.dislikes = self.node.vote_set.filter(vote=-1).count() node_rating_count.save()
[ "def", "update_count", "(", "self", ")", ":", "node_rating_count", "=", "self", ".", "node", ".", "rating_count", "node_rating_count", ".", "likes", "=", "self", ".", "node", ".", "vote_set", ".", "filter", "(", "vote", "=", "1", ")", ".", "count", "(", ...
updates likes and dislikes count
[ "updates", "likes", "and", "dislikes", "count" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/vote.py#L47-L52
ninuxorg/nodeshot
nodeshot/community/participation/models/vote.py
Vote.clean
def clean(self, *args, **kwargs): """ Check if votes can be inserted for parent node or parent layer """ if not self.pk: # ensure voting for this node is allowed if self.node.participation_settings.voting_allowed is not True: raise ValidationError(...
python
def clean(self, *args, **kwargs): """ Check if votes can be inserted for parent node or parent layer """ if not self.pk: # ensure voting for this node is allowed if self.node.participation_settings.voting_allowed is not True: raise ValidationError(...
[ "def", "clean", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "pk", ":", "# ensure voting for this node is allowed", "if", "self", ".", "node", ".", "participation_settings", ".", "voting_allowed", "is", "not", ...
Check if votes can be inserted for parent node or parent layer
[ "Check", "if", "votes", "can", "be", "inserted", "for", "parent", "node", "or", "parent", "layer" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/vote.py#L54-L68
ninuxorg/nodeshot
nodeshot/networking/net/views.py
whois_list
def whois_list(request, format=None): """ Retrieve basic whois information related to a layer2 or layer3 network address. """ results = [] # layer3 results for ip in Ip.objects.select_related().all(): interface = ip.interface user = interface.device.node.user device = int...
python
def whois_list(request, format=None): """ Retrieve basic whois information related to a layer2 or layer3 network address. """ results = [] # layer3 results for ip in Ip.objects.select_related().all(): interface = ip.interface user = interface.device.node.user device = int...
[ "def", "whois_list", "(", "request", ",", "format", "=", "None", ")", ":", "results", "=", "[", "]", "# layer3 results", "for", "ip", "in", "Ip", ".", "objects", ".", "select_related", "(", ")", ".", "all", "(", ")", ":", "interface", "=", "ip", ".",...
Retrieve basic whois information related to a layer2 or layer3 network address.
[ "Retrieve", "basic", "whois", "information", "related", "to", "a", "layer2", "or", "layer3", "network", "address", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L335-L365
ninuxorg/nodeshot
nodeshot/networking/net/views.py
whois_detail
def whois_detail(request, address, format=None): """ Retrieve basic whois information related to a layer2 or layer3 network address. """ address_obj = None try: address_obj = IPAddress(address) except AddrFormatError: try: address_obj = EUI(address) except Add...
python
def whois_detail(request, address, format=None): """ Retrieve basic whois information related to a layer2 or layer3 network address. """ address_obj = None try: address_obj = IPAddress(address) except AddrFormatError: try: address_obj = EUI(address) except Add...
[ "def", "whois_detail", "(", "request", ",", "address", ",", "format", "=", "None", ")", ":", "address_obj", "=", "None", "try", ":", "address_obj", "=", "IPAddress", "(", "address", ")", "except", "AddrFormatError", ":", "try", ":", "address_obj", "=", "EU...
Retrieve basic whois information related to a layer2 or layer3 network address.
[ "Retrieve", "basic", "whois", "information", "related", "to", "a", "layer2", "or", "layer3", "network", "address", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L369-L405
ninuxorg/nodeshot
nodeshot/networking/net/views.py
DeviceList.get_queryset
def get_queryset(self): """ Optionally restricts the returned devices by filtering against a `search` query parameter in the URL. """ # retrieve all devices which are published and accessible to current user # and use joins to retrieve related fields queryset = su...
python
def get_queryset(self): """ Optionally restricts the returned devices by filtering against a `search` query parameter in the URL. """ # retrieve all devices which are published and accessible to current user # and use joins to retrieve related fields queryset = su...
[ "def", "get_queryset", "(", "self", ")", ":", "# retrieve all devices which are published and accessible to current user", "# and use joins to retrieve related fields", "queryset", "=", "super", "(", "DeviceList", ",", "self", ")", ".", "get_queryset", "(", ")", "#.select_rel...
Optionally restricts the returned devices by filtering against a `search` query parameter in the URL.
[ "Optionally", "restricts", "the", "returned", "devices", "by", "filtering", "against", "a", "search", "query", "parameter", "in", "the", "URL", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L35-L55
ninuxorg/nodeshot
nodeshot/networking/net/views.py
NodeDeviceList.initial
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only devices of current node """ super(NodeDeviceList, self).initial(request, *args, **kwargs) #...
python
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only devices of current node """ super(NodeDeviceList, self).initial(request, *args, **kwargs) #...
[ "def", "initial", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "NodeDeviceList", ",", "self", ")", ".", "initial", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# ensure node exist...
Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only devices of current node
[ "Custom", "initial", "method", ":", "*", "ensure", "node", "exists", "and", "store", "it", "in", "an", "instance", "attribute", "*", "change", "queryset", "to", "return", "only", "devices", "of", "current", "node" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L101-L123
ninuxorg/nodeshot
nodeshot/networking/net/views.py
BaseInterfaceList.initial
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure device exists and store it in an instance attribute * change queryset to return only devices of current node """ super(BaseInterfaceList, self).initial(request, *args, **kwargs) ...
python
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure device exists and store it in an instance attribute * change queryset to return only devices of current node """ super(BaseInterfaceList, self).initial(request, *args, **kwargs) ...
[ "def", "initial", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "BaseInterfaceList", ",", "self", ")", ".", "initial", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# ensure device ...
Custom initial method: * ensure device exists and store it in an instance attribute * change queryset to return only devices of current node
[ "Custom", "initial", "method", ":", "*", "ensure", "device", "exists", "and", "store", "it", "in", "an", "instance", "attribute", "*", "change", "queryset", "to", "return", "only", "devices", "of", "current", "node" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L145-L165
ninuxorg/nodeshot
nodeshot/networking/net/views.py
InterfaceIpList.initial
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure interface exists and store it in an instance attribute * change queryset to return only devices of current node """ super(InterfaceIpList, self).initial(request, *args, **kwargs) ...
python
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure interface exists and store it in an instance attribute * change queryset to return only devices of current node """ super(InterfaceIpList, self).initial(request, *args, **kwargs) ...
[ "def", "initial", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "InterfaceIpList", ",", "self", ")", ".", "initial", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# ensure interface...
Custom initial method: * ensure interface exists and store it in an instance attribute * change queryset to return only devices of current node
[ "Custom", "initial", "method", ":", "*", "ensure", "interface", "exists", "and", "store", "it", "in", "an", "instance", "attribute", "*", "change", "queryset", "to", "return", "only", "devices", "of", "current", "node" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L279-L299
ninuxorg/nodeshot
nodeshot/community/profiles/html_views.py
group_and_bridge
def group_and_bridge(kwargs): """ Given kwargs from the view (with view specific keys popped) pull out the bridge and fetch group from database. """ bridge = kwargs.pop("bridge", None) if bridge: try: group = bridge.get_group(**kwargs) except ObjectDoesNotExist: ...
python
def group_and_bridge(kwargs): """ Given kwargs from the view (with view specific keys popped) pull out the bridge and fetch group from database. """ bridge = kwargs.pop("bridge", None) if bridge: try: group = bridge.get_group(**kwargs) except ObjectDoesNotExist: ...
[ "def", "group_and_bridge", "(", "kwargs", ")", ":", "bridge", "=", "kwargs", ".", "pop", "(", "\"bridge\"", ",", "None", ")", "if", "bridge", ":", "try", ":", "group", "=", "bridge", ".", "get_group", "(", "*", "*", "kwargs", ")", "except", "ObjectDoes...
Given kwargs from the view (with view specific keys popped) pull out the bridge and fetch group from database.
[ "Given", "kwargs", "from", "the", "view", "(", "with", "view", "specific", "keys", "popped", ")", "pull", "out", "the", "bridge", "and", "fetch", "group", "from", "database", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/html_views.py#L17-L33
ninuxorg/nodeshot
nodeshot/core/base/models.py
BaseDate.save
def save(self, *args, **kwargs): """ automatically update updated date field """ # auto fill updated field with current time unless explicitly disabled auto_update = kwargs.get('auto_update', True) if auto_update: self.updated = now() # remove eventua...
python
def save(self, *args, **kwargs): """ automatically update updated date field """ # auto fill updated field with current time unless explicitly disabled auto_update = kwargs.get('auto_update', True) if auto_update: self.updated = now() # remove eventua...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# auto fill updated field with current time unless explicitly disabled", "auto_update", "=", "kwargs", ".", "get", "(", "'auto_update'", ",", "True", ")", "if", "auto_update", ":", ...
automatically update updated date field
[ "automatically", "update", "updated", "date", "field" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/models.py#L64-L77
ninuxorg/nodeshot
nodeshot/core/base/models.py
BaseOrdered.save
def save(self, *args, **kwargs): """ if order left blank """ if self.order == '' or self.order is None: try: self.order = self.get_auto_order_queryset().order_by("-order")[0].order + 1 except IndexError: self.order = 0 super(BaseOrdered, se...
python
def save(self, *args, **kwargs): """ if order left blank """ if self.order == '' or self.order is None: try: self.order = self.get_auto_order_queryset().order_by("-order")[0].order + 1 except IndexError: self.order = 0 super(BaseOrdered, se...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "order", "==", "''", "or", "self", ".", "order", "is", "None", ":", "try", ":", "self", ".", "order", "=", "self", ".", "get_auto_order_queryset", ...
if order left blank
[ "if", "order", "left", "blank" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/models.py#L161-L168
ninuxorg/nodeshot
nodeshot/core/base/utils.py
check_dependencies
def check_dependencies(dependencies, module): """ Ensure dependencies of a module are listed in settings.INSTALLED_APPS :dependencies string | list: list of dependencies to check :module string: string representing the path to the current app """ if type(dependencies) == str: dependenci...
python
def check_dependencies(dependencies, module): """ Ensure dependencies of a module are listed in settings.INSTALLED_APPS :dependencies string | list: list of dependencies to check :module string: string representing the path to the current app """ if type(dependencies) == str: dependenci...
[ "def", "check_dependencies", "(", "dependencies", ",", "module", ")", ":", "if", "type", "(", "dependencies", ")", "==", "str", ":", "dependencies", "=", "[", "dependencies", "]", "elif", "type", "(", "dependencies", ")", "!=", "list", ":", "raise", "TypeE...
Ensure dependencies of a module are listed in settings.INSTALLED_APPS :dependencies string | list: list of dependencies to check :module string: string representing the path to the current app
[ "Ensure", "dependencies", "of", "a", "module", "are", "listed", "in", "settings", ".", "INSTALLED_APPS" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/utils.py#L38-L52
ninuxorg/nodeshot
nodeshot/core/base/utils.py
choicify
def choicify(dictionary): """ Converts a readable python dictionary into a django model/form choice structure (list of tuples) ordered based on the values of each key :param dictionary: the dictionary to convert """ # get order of the fields ordered_fields = sorted(dictionary, key=dictionar...
python
def choicify(dictionary): """ Converts a readable python dictionary into a django model/form choice structure (list of tuples) ordered based on the values of each key :param dictionary: the dictionary to convert """ # get order of the fields ordered_fields = sorted(dictionary, key=dictionar...
[ "def", "choicify", "(", "dictionary", ")", ":", "# get order of the fields", "ordered_fields", "=", "sorted", "(", "dictionary", ",", "key", "=", "dictionary", ".", "get", ")", "choices", "=", "[", "]", "# loop over each field", "for", "field", "in", "ordered_fi...
Converts a readable python dictionary into a django model/form choice structure (list of tuples) ordered based on the values of each key :param dictionary: the dictionary to convert
[ "Converts", "a", "readable", "python", "dictionary", "into", "a", "django", "model", "/", "form", "choice", "structure", "(", "list", "of", "tuples", ")", "ordered", "based", "on", "the", "values", "of", "each", "key" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/utils.py#L55-L72
ninuxorg/nodeshot
nodeshot/core/base/utils.py
get_key_by_value
def get_key_by_value(dictionary, search_value): """ searchs a value in a dicionary and returns the key of the first occurrence :param dictionary: dictionary to search in :param search_value: value to search for """ for key, value in dictionary.iteritems(): if value == search_value: ...
python
def get_key_by_value(dictionary, search_value): """ searchs a value in a dicionary and returns the key of the first occurrence :param dictionary: dictionary to search in :param search_value: value to search for """ for key, value in dictionary.iteritems(): if value == search_value: ...
[ "def", "get_key_by_value", "(", "dictionary", ",", "search_value", ")", ":", "for", "key", ",", "value", "in", "dictionary", ".", "iteritems", "(", ")", ":", "if", "value", "==", "search_value", ":", "return", "ugettext", "(", "key", ")" ]
searchs a value in a dicionary and returns the key of the first occurrence :param dictionary: dictionary to search in :param search_value: value to search for
[ "searchs", "a", "value", "in", "a", "dicionary", "and", "returns", "the", "key", "of", "the", "first", "occurrence" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/utils.py#L75-L84
ninuxorg/nodeshot
nodeshot/core/layers/views.py
LayerNodeListMixin.get_layer
def get_layer(self): """ retrieve layer from DB """ if self.layer: return try: self.layer = Layer.objects.get(slug=self.kwargs['slug']) except Layer.DoesNotExist: raise Http404(_('Layer not found'))
python
def get_layer(self): """ retrieve layer from DB """ if self.layer: return try: self.layer = Layer.objects.get(slug=self.kwargs['slug']) except Layer.DoesNotExist: raise Http404(_('Layer not found'))
[ "def", "get_layer", "(", "self", ")", ":", "if", "self", ".", "layer", ":", "return", "try", ":", "self", ".", "layer", "=", "Layer", ".", "objects", ".", "get", "(", "slug", "=", "self", ".", "kwargs", "[", "'slug'", "]", ")", "except", "Layer", ...
retrieve layer from DB
[ "retrieve", "layer", "from", "DB" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L56-L63
ninuxorg/nodeshot
nodeshot/core/layers/views.py
LayerNodeListMixin.get_queryset
def get_queryset(self): """ extend parent class queryset by filtering nodes of the specified layer """ self.get_layer() return super(LayerNodeListMixin, self).get_queryset().filter(layer_id=self.layer.id)
python
def get_queryset(self): """ extend parent class queryset by filtering nodes of the specified layer """ self.get_layer() return super(LayerNodeListMixin, self).get_queryset().filter(layer_id=self.layer.id)
[ "def", "get_queryset", "(", "self", ")", ":", "self", ".", "get_layer", "(", ")", "return", "super", "(", "LayerNodeListMixin", ",", "self", ")", ".", "get_queryset", "(", ")", ".", "filter", "(", "layer_id", "=", "self", ".", "layer", ".", "id", ")" ]
extend parent class queryset by filtering nodes of the specified layer
[ "extend", "parent", "class", "queryset", "by", "filtering", "nodes", "of", "the", "specified", "layer" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L65-L68
ninuxorg/nodeshot
nodeshot/core/layers/views.py
LayerNodeListMixin.get_nodes
def get_nodes(self, request, *args, **kwargs): """ this method might be overridden by other modules (eg: nodeshot.interop.sync) """ # ListSerializerMixin.list returns a serializer object return (self.list(request, *args, **kwargs)).data
python
def get_nodes(self, request, *args, **kwargs): """ this method might be overridden by other modules (eg: nodeshot.interop.sync) """ # ListSerializerMixin.list returns a serializer object return (self.list(request, *args, **kwargs)).data
[ "def", "get_nodes", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# ListSerializerMixin.list returns a serializer object", "return", "(", "self", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", "...
this method might be overridden by other modules (eg: nodeshot.interop.sync)
[ "this", "method", "might", "be", "overridden", "by", "other", "modules", "(", "eg", ":", "nodeshot", ".", "interop", ".", "sync", ")" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L70-L73
ninuxorg/nodeshot
nodeshot/core/layers/views.py
LayerNodeListMixin.get
def get(self, request, *args, **kwargs): """ Retrieve list of nodes of the specified layer """ self.get_layer() # get nodes of layer nodes = self.get_nodes(request, *args, **kwargs) return Response(nodes)
python
def get(self, request, *args, **kwargs): """ Retrieve list of nodes of the specified layer """ self.get_layer() # get nodes of layer nodes = self.get_nodes(request, *args, **kwargs) return Response(nodes)
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "get_layer", "(", ")", "# get nodes of layer", "nodes", "=", "self", ".", "get_nodes", "(", "request", ",", "*", "args", ",", "*", "*", "kw...
Retrieve list of nodes of the specified layer
[ "Retrieve", "list", "of", "nodes", "of", "the", "specified", "layer" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L75-L80
ninuxorg/nodeshot
nodeshot/networking/net/models/ip.py
Ip.save
def save(self, *args, **kwargs): """ Determines ip protocol version automatically. Stores address in interface shortcuts for convenience. """ self.protocol = 'ipv%d' % self.address.version # save super(Ip, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): """ Determines ip protocol version automatically. Stores address in interface shortcuts for convenience. """ self.protocol = 'ipv%d' % self.address.version # save super(Ip, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "protocol", "=", "'ipv%d'", "%", "self", ".", "address", ".", "version", "# save", "super", "(", "Ip", ",", "self", ")", ".", "save", "(", "*", "args", ...
Determines ip protocol version automatically. Stores address in interface shortcuts for convenience.
[ "Determines", "ip", "protocol", "version", "automatically", ".", "Stores", "address", "in", "interface", "shortcuts", "for", "convenience", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/ip.py#L36-L43
ninuxorg/nodeshot
nodeshot/interop/oldimporter/db.py
DefaultRouter.allow_relation
def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed between nodeshot2 objects only """ if obj1._meta.app_label != 'oldimporter' and obj2._meta.app_label != 'oldimporter': return True return None
python
def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed between nodeshot2 objects only """ if obj1._meta.app_label != 'oldimporter' and obj2._meta.app_label != 'oldimporter': return True return None
[ "def", "allow_relation", "(", "self", ",", "obj1", ",", "obj2", ",", "*", "*", "hints", ")", ":", "if", "obj1", ".", "_meta", ".", "app_label", "!=", "'oldimporter'", "and", "obj2", ".", "_meta", ".", "app_label", "!=", "'oldimporter'", ":", "return", ...
Relations between objects are allowed between nodeshot2 objects only
[ "Relations", "between", "objects", "are", "allowed", "between", "nodeshot2", "objects", "only" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/db.py#L24-L30
ninuxorg/nodeshot
nodeshot/interop/oldimporter/db.py
OldNodeshotRouter.allow_migrate
def allow_migrate(self, db, model): """ Make sure the old_nodeshot app only appears in the 'old_nodeshot' database """ if db != 'old_nodeshot' or model._meta.app_label != 'oldimporter': return False return True
python
def allow_migrate(self, db, model): """ Make sure the old_nodeshot app only appears in the 'old_nodeshot' database """ if db != 'old_nodeshot' or model._meta.app_label != 'oldimporter': return False return True
[ "def", "allow_migrate", "(", "self", ",", "db", ",", "model", ")", ":", "if", "db", "!=", "'old_nodeshot'", "or", "model", ".", "_meta", ".", "app_label", "!=", "'oldimporter'", ":", "return", "False", "return", "True" ]
Make sure the old_nodeshot app only appears in the 'old_nodeshot' database
[ "Make", "sure", "the", "old_nodeshot", "app", "only", "appears", "in", "the", "old_nodeshot", "database" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/db.py#L66-L72
ninuxorg/nodeshot
nodeshot/community/profiles/forms.py
ResetPasswordForm.clean_email
def clean_email(self): """ ensure email is in the database """ if EMAIL_CONFIRMATION: from .models import EmailAddress condition = EmailAddress.objects.filter( email__iexact=self.cleaned_data["email"], verified=True ).count() == 0 ...
python
def clean_email(self): """ ensure email is in the database """ if EMAIL_CONFIRMATION: from .models import EmailAddress condition = EmailAddress.objects.filter( email__iexact=self.cleaned_data["email"], verified=True ).count() == 0 ...
[ "def", "clean_email", "(", "self", ")", ":", "if", "EMAIL_CONFIRMATION", ":", "from", ".", "models", "import", "EmailAddress", "condition", "=", "EmailAddress", ".", "objects", ".", "filter", "(", "email__iexact", "=", "self", ".", "cleaned_data", "[", "\"emai...
ensure email is in the database
[ "ensure", "email", "is", "in", "the", "database" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/forms.py#L23-L41
ninuxorg/nodeshot
nodeshot/core/metrics/views.py
metric_details
def metric_details(request, pk, format=None): """ Get or write metric values """ metric = get_object_or_404(Metric, pk=pk) # get if request.method == 'GET': try: results = metric.select(q=request.query_params.get('q', metric.query)) except InfluxDBClientError as e: ...
python
def metric_details(request, pk, format=None): """ Get or write metric values """ metric = get_object_or_404(Metric, pk=pk) # get if request.method == 'GET': try: results = metric.select(q=request.query_params.get('q', metric.query)) except InfluxDBClientError as e: ...
[ "def", "metric_details", "(", "request", ",", "pk", ",", "format", "=", "None", ")", ":", "metric", "=", "get_object_or_404", "(", "Metric", ",", "pk", "=", "pk", ")", "# get", "if", "request", ".", "method", "==", "'GET'", ":", "try", ":", "results", ...
Get or write metric values
[ "Get", "or", "write", "metric", "values" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/views.py#L12-L39
ninuxorg/nodeshot
nodeshot/core/websockets/handlers.py
WebSocketHandler.add_client
def add_client(self, user_id=None): """ Adds current instance to public or private channel. If user_id is specified it will be added to the private channel, If user_id is not specified it will be added to the public one instead. """ if user_id is None: # gener...
python
def add_client(self, user_id=None): """ Adds current instance to public or private channel. If user_id is specified it will be added to the private channel, If user_id is not specified it will be added to the public one instead. """ if user_id is None: # gener...
[ "def", "add_client", "(", "self", ",", "user_id", "=", "None", ")", ":", "if", "user_id", "is", "None", ":", "# generate a random uuid if it's an unauthenticated client", "self", ".", "channel", "=", "'public'", "user_id", "=", "uuid", ".", "uuid1", "(", ")", ...
Adds current instance to public or private channel. If user_id is specified it will be added to the private channel, If user_id is not specified it will be added to the public one instead.
[ "Adds", "current", "instance", "to", "public", "or", "private", "channel", ".", "If", "user_id", "is", "specified", "it", "will", "be", "added", "to", "the", "private", "channel", "If", "user_id", "is", "not", "specified", "it", "will", "be", "added", "to"...
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L21-L36
ninuxorg/nodeshot
nodeshot/core/websockets/handlers.py
WebSocketHandler.broadcast
def broadcast(cls, message): """ broadcast message to all connected clients """ clients = cls.get_clients() # loop over every client and send message for id, client in clients.iteritems(): client.send_message(message)
python
def broadcast(cls, message): """ broadcast message to all connected clients """ clients = cls.get_clients() # loop over every client and send message for id, client in clients.iteritems(): client.send_message(message)
[ "def", "broadcast", "(", "cls", ",", "message", ")", ":", "clients", "=", "cls", ".", "get_clients", "(", ")", "# loop over every client and send message", "for", "id", ",", "client", "in", "clients", ".", "iteritems", "(", ")", ":", "client", ".", "send_mes...
broadcast message to all connected clients
[ "broadcast", "message", "to", "all", "connected", "clients" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L43-L48
ninuxorg/nodeshot
nodeshot/core/websockets/handlers.py
WebSocketHandler.send_private_message
def send_private_message(self, user_id, message): """ Send a message to a specific client. Returns True if successful, False otherwise """ try: client = self.channels['private'][str(user_id)] except KeyError: print '====debug====' print...
python
def send_private_message(self, user_id, message): """ Send a message to a specific client. Returns True if successful, False otherwise """ try: client = self.channels['private'][str(user_id)] except KeyError: print '====debug====' print...
[ "def", "send_private_message", "(", "self", ",", "user_id", ",", "message", ")", ":", "try", ":", "client", "=", "self", ".", "channels", "[", "'private'", "]", "[", "str", "(", "user_id", ")", "]", "except", "KeyError", ":", "print", "'====debug===='", ...
Send a message to a specific client. Returns True if successful, False otherwise
[ "Send", "a", "message", "to", "a", "specific", "client", ".", "Returns", "True", "if", "successful", "False", "otherwise" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L51-L66
ninuxorg/nodeshot
nodeshot/core/websockets/handlers.py
WebSocketHandler.get_clients
def get_clients(self): """ return a merge of public and private clients """ public = self.channels['public'] private = self.channels['private'] return dict(public.items() + private.items())
python
def get_clients(self): """ return a merge of public and private clients """ public = self.channels['public'] private = self.channels['private'] return dict(public.items() + private.items())
[ "def", "get_clients", "(", "self", ")", ":", "public", "=", "self", ".", "channels", "[", "'public'", "]", "private", "=", "self", ".", "channels", "[", "'private'", "]", "return", "dict", "(", "public", ".", "items", "(", ")", "+", "private", ".", "...
return a merge of public and private clients
[ "return", "a", "merge", "of", "public", "and", "private", "clients" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L69-L73
ninuxorg/nodeshot
nodeshot/core/websockets/handlers.py
WebSocketHandler.open
def open(self): """ method which is called every time a new client connects """ print 'Connection opened.' # retrieve user_id if specified user_id = self.get_argument("user_id", None) # add client to list of connected clients self.add_client(user_id) # we...
python
def open(self): """ method which is called every time a new client connects """ print 'Connection opened.' # retrieve user_id if specified user_id = self.get_argument("user_id", None) # add client to list of connected clients self.add_client(user_id) # we...
[ "def", "open", "(", "self", ")", ":", "print", "'Connection opened.'", "# retrieve user_id if specified", "user_id", "=", "self", ".", "get_argument", "(", "\"user_id\"", ",", "None", ")", "# add client to list of connected clients", "self", ".", "add_client", "(", "u...
method which is called every time a new client connects
[ "method", "which", "is", "called", "every", "time", "a", "new", "client", "connects" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L75-L91
ninuxorg/nodeshot
nodeshot/core/websockets/handlers.py
WebSocketHandler.on_close
def on_close(self): """ method which is called every time a client disconnects """ print 'Connection closed.' self.remove_client() client_count = len(self.get_clients().keys()) new_client_message = '1 client disconnected, now we have %d %s!' % (client_count, 'client' if ...
python
def on_close(self): """ method which is called every time a client disconnects """ print 'Connection closed.' self.remove_client() client_count = len(self.get_clients().keys()) new_client_message = '1 client disconnected, now we have %d %s!' % (client_count, 'client' if ...
[ "def", "on_close", "(", "self", ")", ":", "print", "'Connection closed.'", "self", ".", "remove_client", "(", ")", "client_count", "=", "len", "(", "self", ".", "get_clients", "(", ")", ".", "keys", "(", ")", ")", "new_client_message", "=", "'1 client discon...
method which is called every time a client disconnects
[ "method", "which", "is", "called", "every", "time", "a", "client", "disconnects" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L99-L106
ninuxorg/nodeshot
nodeshot/core/metrics/utils.py
get_db
def get_db(): """Returns an ``InfluxDBClient`` instance.""" return client.InfluxDBClient( settings.INFLUXDB_HOST, settings.INFLUXDB_PORT, settings.INFLUXDB_USER, settings.INFLUXDB_PASSWORD, settings.INFLUXDB_DATABASE, )
python
def get_db(): """Returns an ``InfluxDBClient`` instance.""" return client.InfluxDBClient( settings.INFLUXDB_HOST, settings.INFLUXDB_PORT, settings.INFLUXDB_USER, settings.INFLUXDB_PASSWORD, settings.INFLUXDB_DATABASE, )
[ "def", "get_db", "(", ")", ":", "return", "client", ".", "InfluxDBClient", "(", "settings", ".", "INFLUXDB_HOST", ",", "settings", ".", "INFLUXDB_PORT", ",", "settings", ".", "INFLUXDB_USER", ",", "settings", ".", "INFLUXDB_PASSWORD", ",", "settings", ".", "IN...
Returns an ``InfluxDBClient`` instance.
[ "Returns", "an", "InfluxDBClient", "instance", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L8-L16
ninuxorg/nodeshot
nodeshot/core/metrics/utils.py
query
def query(query, params={}, epoch=None, expected_response_code=200, database=None): """Wrapper around ``InfluxDBClient.query()``.""" db = get_db() database = database or settings.INFLUXDB_DATABASE return db.query(query, params, epoch, expected_response_code, database=database)
python
def query(query, params={}, epoch=None, expected_response_code=200, database=None): """Wrapper around ``InfluxDBClient.query()``.""" db = get_db() database = database or settings.INFLUXDB_DATABASE return db.query(query, params, epoch, expected_response_code, database=database)
[ "def", "query", "(", "query", ",", "params", "=", "{", "}", ",", "epoch", "=", "None", ",", "expected_response_code", "=", "200", ",", "database", "=", "None", ")", ":", "db", "=", "get_db", "(", ")", "database", "=", "database", "or", "settings", "....
Wrapper around ``InfluxDBClient.query()``.
[ "Wrapper", "around", "InfluxDBClient", ".", "query", "()", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L19-L24
ninuxorg/nodeshot
nodeshot/core/metrics/utils.py
write_async
def write_async(name, values, tags={}, timestamp=None, database=None): """ write metrics """ thread = Thread(target=write, args=(name, values, tags, timestamp, database)) thread.start()
python
def write_async(name, values, tags={}, timestamp=None, database=None): """ write metrics """ thread = Thread(target=write, args=(name, values, tags, timestamp, database)) thread.start()
[ "def", "write_async", "(", "name", ",", "values", ",", "tags", "=", "{", "}", ",", "timestamp", "=", "None", ",", "database", "=", "None", ")", ":", "thread", "=", "Thread", "(", "target", "=", "write", ",", "args", "=", "(", "name", ",", "values",...
write metrics
[ "write", "metrics" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L27-L31
ninuxorg/nodeshot
nodeshot/core/metrics/utils.py
write
def write(name, values, tags={}, timestamp=None, database=None): """ Method to be called via threading module. """ point = { 'measurement': name, 'tags': tags, 'fields': values } if isinstance(timestamp, datetime): timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%SZ') ...
python
def write(name, values, tags={}, timestamp=None, database=None): """ Method to be called via threading module. """ point = { 'measurement': name, 'tags': tags, 'fields': values } if isinstance(timestamp, datetime): timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%SZ') ...
[ "def", "write", "(", "name", ",", "values", ",", "tags", "=", "{", "}", ",", "timestamp", "=", "None", ",", "database", "=", "None", ")", ":", "point", "=", "{", "'measurement'", ":", "name", ",", "'tags'", ":", "tags", ",", "'fields'", ":", "value...
Method to be called via threading module.
[ "Method", "to", "be", "called", "via", "threading", "module", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L34-L52
ninuxorg/nodeshot
nodeshot/core/metrics/utils.py
create_database
def create_database(): """ creates database if necessary """ db = get_db() response = db.query('SHOW DATABASES') items = list(response.get_points('databases')) databases = [database['name'] for database in items] # if database does not exists, create it if settings.INFLUXDB_DATABASE not in d...
python
def create_database(): """ creates database if necessary """ db = get_db() response = db.query('SHOW DATABASES') items = list(response.get_points('databases')) databases = [database['name'] for database in items] # if database does not exists, create it if settings.INFLUXDB_DATABASE not in d...
[ "def", "create_database", "(", ")", ":", "db", "=", "get_db", "(", ")", "response", "=", "db", ".", "query", "(", "'SHOW DATABASES'", ")", "items", "=", "list", "(", "response", ".", "get_points", "(", "'databases'", ")", ")", "databases", "=", "[", "d...
creates database if necessary
[ "creates", "database", "if", "necessary" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L55-L64
ninuxorg/nodeshot
nodeshot/community/participation/models/rating.py
Rating.save
def save(self, *args, **kwargs): """ ensure users cannot rate the same node multiple times but let users change their rating """ if not self.pk: old_ratings = Rating.objects.filter(user=self.user, node=self.node) for old_rating in old_ratings: ...
python
def save(self, *args, **kwargs): """ ensure users cannot rate the same node multiple times but let users change their rating """ if not self.pk: old_ratings = Rating.objects.filter(user=self.user, node=self.node) for old_rating in old_ratings: ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "pk", ":", "old_ratings", "=", "Rating", ".", "objects", ".", "filter", "(", "user", "=", "self", ".", "user", ",", "node", "=", "self", ...
ensure users cannot rate the same node multiple times but let users change their rating
[ "ensure", "users", "cannot", "rate", "the", "same", "node", "multiple", "times", "but", "let", "users", "change", "their", "rating" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/rating.py#L34-L43
ninuxorg/nodeshot
nodeshot/community/participation/models/rating.py
Rating.update_count
def update_count(self): """ updates rating count and rating average """ node_rating_count = self.node.rating_count node_rating_count.rating_count = self.node.rating_set.count() node_rating_count.rating_avg = self.node.rating_set.aggregate(rate=Avg('value'))['rate'] # if all rati...
python
def update_count(self): """ updates rating count and rating average """ node_rating_count = self.node.rating_count node_rating_count.rating_count = self.node.rating_set.count() node_rating_count.rating_avg = self.node.rating_set.aggregate(rate=Avg('value'))['rate'] # if all rati...
[ "def", "update_count", "(", "self", ")", ":", "node_rating_count", "=", "self", ".", "node", ".", "rating_count", "node_rating_count", ".", "rating_count", "=", "self", ".", "node", ".", "rating_set", ".", "count", "(", ")", "node_rating_count", ".", "rating_a...
updates rating count and rating average
[ "updates", "rating", "count", "and", "rating", "average" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/rating.py#L45-L56
ninuxorg/nodeshot
nodeshot/community/participation/models/rating.py
Rating.clean
def clean(self, *args, **kwargs): """ Check if rating can be inserted for parent node or parent layer """ if not self.pk: node = self.node layer = Layer.objects.get(pk=node.layer_id) if layer.participation_settings.rating_allowed is not True: ...
python
def clean(self, *args, **kwargs): """ Check if rating can be inserted for parent node or parent layer """ if not self.pk: node = self.node layer = Layer.objects.get(pk=node.layer_id) if layer.participation_settings.rating_allowed is not True: ...
[ "def", "clean", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "pk", ":", "node", "=", "self", ".", "node", "layer", "=", "Layer", ".", "objects", ".", "get", "(", "pk", "=", "node", ".", "layer_id",...
Check if rating can be inserted for parent node or parent layer
[ "Check", "if", "rating", "can", "be", "inserted", "for", "parent", "node", "or", "parent", "layer" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/rating.py#L58-L68
ninuxorg/nodeshot
nodeshot/community/participation/models/base.py
UpdateCountsMixin.save
def save(self, *args, **kwargs): """ custom save method to update counts """ # the following lines determines if the comment is being created or not # in case the comment exists the pk attribute is an int created = type(self.pk) is not int super(UpdateCountsMixin, self).save(*ar...
python
def save(self, *args, **kwargs): """ custom save method to update counts """ # the following lines determines if the comment is being created or not # in case the comment exists the pk attribute is an int created = type(self.pk) is not int super(UpdateCountsMixin, self).save(*ar...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# the following lines determines if the comment is being created or not", "# in case the comment exists the pk attribute is an int", "created", "=", "type", "(", "self", ".", "pk", ")", "i...
custom save method to update counts
[ "custom", "save", "method", "to", "update", "counts" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/base.py#L17-L27
ninuxorg/nodeshot
nodeshot/community/participation/models/base.py
UpdateCountsMixin.delete
def delete(self, *args, **kwargs): """ custom delete method to update counts """ super(UpdateCountsMixin, self).delete(*args, **kwargs) self.update_count()
python
def delete(self, *args, **kwargs): """ custom delete method to update counts """ super(UpdateCountsMixin, self).delete(*args, **kwargs) self.update_count()
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "UpdateCountsMixin", ",", "self", ")", ".", "delete", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "update_count", "(", ")" ]
custom delete method to update counts
[ "custom", "delete", "method", "to", "update", "counts" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/base.py#L29-L32
ninuxorg/nodeshot
nodeshot/networking/links/utils.py
update_topology
def update_topology(): """ updates all the topology sends logs to the "nodeshot.networking" logger """ for topology in Topology.objects.all(): try: topology.update() except Exception as e: msg = 'Failed to update {}'.format(topology.__repr__()) log...
python
def update_topology(): """ updates all the topology sends logs to the "nodeshot.networking" logger """ for topology in Topology.objects.all(): try: topology.update() except Exception as e: msg = 'Failed to update {}'.format(topology.__repr__()) log...
[ "def", "update_topology", "(", ")", ":", "for", "topology", "in", "Topology", ".", "objects", ".", "all", "(", ")", ":", "try", ":", "topology", ".", "update", "(", ")", "except", "Exception", "as", "e", ":", "msg", "=", "'Failed to update {}'", ".", "...
updates all the topology sends logs to the "nodeshot.networking" logger
[ "updates", "all", "the", "topology", "sends", "logs", "to", "the", "nodeshot", ".", "networking", "logger" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/utils.py#L20-L32
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector.save
def save(self, *args, **kwargs): """ Custom save does the following: * strip trailing whitespace from host attribute * create device and all other related objects * store connection config in DB if store attribute is True """ self.host = self.host.stri...
python
def save(self, *args, **kwargs): """ Custom save does the following: * strip trailing whitespace from host attribute * create device and all other related objects * store connection config in DB if store attribute is True """ self.host = self.host.stri...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "host", "=", "self", ".", "host", ".", "strip", "(", ")", "if", "not", "self", ".", "id", ":", "self", ".", "device", "=", "self", ".", "__create_devi...
Custom save does the following: * strip trailing whitespace from host attribute * create device and all other related objects * store connection config in DB if store attribute is True
[ "Custom", "save", "does", "the", "following", ":", "*", "strip", "trailing", "whitespace", "from", "host", "attribute", "*", "create", "device", "and", "all", "other", "related", "objects", "*", "store", "connection", "config", "in", "DB", "if", "store", "at...
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L63-L76
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector.clean
def clean(self, *args, **kwargs): """ validation """ self._validate_backend() self._validate_config() self._validate_netengine() self._validate_duplicates()
python
def clean(self, *args, **kwargs): """ validation """ self._validate_backend() self._validate_config() self._validate_netengine() self._validate_duplicates()
[ "def", "clean", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_validate_backend", "(", ")", "self", ".", "_validate_config", "(", ")", "self", ".", "_validate_netengine", "(", ")", "self", ".", "_validate_duplicates", "(...
validation
[ "validation" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L78-L83
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector.backend_class
def backend_class(self): """ returns python netengine backend class, importing it if needed """ if not self.backend: return None if not self.__backend_class: self.__backend_class = self._get_netengine_backend() return self.__backend_class
python
def backend_class(self): """ returns python netengine backend class, importing it if needed """ if not self.backend: return None if not self.__backend_class: self.__backend_class = self._get_netengine_backend() return self.__backend_class
[ "def", "backend_class", "(", "self", ")", ":", "if", "not", "self", ".", "backend", ":", "return", "None", "if", "not", "self", ".", "__backend_class", ":", "self", ".", "__backend_class", "=", "self", ".", "_get_netengine_backend", "(", ")", "return", "se...
returns python netengine backend class, importing it if needed
[ "returns", "python", "netengine", "backend", "class", "importing", "it", "if", "needed" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L94-L104
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector.netengine
def netengine(self): """ access netengine instance """ # return None if no backend chosen yet if not self.backend: return None # init instance of the netengine backend if not already done if not self.__netengine: NetengineBackend = self.backend_class ...
python
def netengine(self): """ access netengine instance """ # return None if no backend chosen yet if not self.backend: return None # init instance of the netengine backend if not already done if not self.__netengine: NetengineBackend = self.backend_class ...
[ "def", "netengine", "(", "self", ")", ":", "# return None if no backend chosen yet", "if", "not", "self", ".", "backend", ":", "return", "None", "# init instance of the netengine backend if not already done", "if", "not", "self", ".", "__netengine", ":", "NetengineBackend...
access netengine instance
[ "access", "netengine", "instance" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L107-L121
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector._validate_backend
def _validate_backend(self): """ ensure backend string representation is correct """ try: self.backend_class # if we get an import error the specified path is wrong except (ImportError, AttributeError) as e: raise ValidationError(_('No valid backend found, got the...
python
def _validate_backend(self): """ ensure backend string representation is correct """ try: self.backend_class # if we get an import error the specified path is wrong except (ImportError, AttributeError) as e: raise ValidationError(_('No valid backend found, got the...
[ "def", "_validate_backend", "(", "self", ")", ":", "try", ":", "self", ".", "backend_class", "# if we get an import error the specified path is wrong", "except", "(", "ImportError", ",", "AttributeError", ")", "as", "e", ":", "raise", "ValidationError", "(", "_", "(...
ensure backend string representation is correct
[ "ensure", "backend", "string", "representation", "is", "correct" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L123-L129
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector._validate_config
def _validate_config(self): """ ensure REQUIRED_CONFIG_KEYS are filled """ # exit if no backend specified if not self.backend: return # exit if no required config keys if len(self.REQUIRED_CONFIG_KEYS) < 1: return self.config = self.config or {} ...
python
def _validate_config(self): """ ensure REQUIRED_CONFIG_KEYS are filled """ # exit if no backend specified if not self.backend: return # exit if no required config keys if len(self.REQUIRED_CONFIG_KEYS) < 1: return self.config = self.config or {} ...
[ "def", "_validate_config", "(", "self", ")", ":", "# exit if no backend specified", "if", "not", "self", ".", "backend", ":", "return", "# exit if no required config keys", "if", "len", "(", "self", ".", "REQUIRED_CONFIG_KEYS", ")", "<", "1", ":", "return", "self"...
ensure REQUIRED_CONFIG_KEYS are filled
[ "ensure", "REQUIRED_CONFIG_KEYS", "are", "filled" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L131-L156
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector._validate_netengine
def _validate_netengine(self): """ call netengine validate() method verifies connection parameters are correct """ if self.backend: try: self.netengine.validate() except NetEngineError as e: raise ValidationError(e)
python
def _validate_netengine(self): """ call netengine validate() method verifies connection parameters are correct """ if self.backend: try: self.netengine.validate() except NetEngineError as e: raise ValidationError(e)
[ "def", "_validate_netengine", "(", "self", ")", ":", "if", "self", ".", "backend", ":", "try", ":", "self", ".", "netengine", ".", "validate", "(", ")", "except", "NetEngineError", "as", "e", ":", "raise", "ValidationError", "(", "e", ")" ]
call netengine validate() method verifies connection parameters are correct
[ "call", "netengine", "validate", "()", "method", "verifies", "connection", "parameters", "are", "correct" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L158-L167
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector._validate_duplicates
def _validate_duplicates(self): """ Ensure we're not creating a device that already exists Runs only when the DeviceConnector object is created, not when is updated """ # if connector is being created right now if not self.id: duplicates = [] self....
python
def _validate_duplicates(self): """ Ensure we're not creating a device that already exists Runs only when the DeviceConnector object is created, not when is updated """ # if connector is being created right now if not self.id: duplicates = [] self....
[ "def", "_validate_duplicates", "(", "self", ")", ":", "# if connector is being created right now", "if", "not", "self", ".", "id", ":", "duplicates", "=", "[", "]", "self", ".", "netengine_dict", "=", "self", ".", "netengine", ".", "to_dict", "(", ")", "# loop...
Ensure we're not creating a device that already exists Runs only when the DeviceConnector object is created, not when is updated
[ "Ensure", "we", "re", "not", "creating", "a", "device", "that", "already", "exists", "Runs", "only", "when", "the", "DeviceConnector", "object", "is", "created", "not", "when", "is", "updated" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L169-L190
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector._get_netengine_arguments
def _get_netengine_arguments(self, required=False): """ returns list of available config params returns list of required config params if required is True for internal use only """ # inspect netengine class backend_class = self._get_netengine_backend() arg...
python
def _get_netengine_arguments(self, required=False): """ returns list of available config params returns list of required config params if required is True for internal use only """ # inspect netengine class backend_class = self._get_netengine_backend() arg...
[ "def", "_get_netengine_arguments", "(", "self", ",", "required", "=", "False", ")", ":", "# inspect netengine class", "backend_class", "=", "self", ".", "_get_netengine_backend", "(", ")", "argspec", "=", "inspect", ".", "getargspec", "(", "backend_class", ".", "_...
returns list of available config params returns list of required config params if required is True for internal use only
[ "returns", "list", "of", "available", "config", "params", "returns", "list", "of", "required", "config", "params", "if", "required", "is", "True", "for", "internal", "use", "only" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L192-L216
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector._get_netengine_backend
def _get_netengine_backend(self): """ returns the netengine backend specified in self.backend for internal use only """ # extract backend class name, eg: AirOS or OpenWRT backend_class_name = self.backend.split('.')[-1] # convert to lowercase to get the path ...
python
def _get_netengine_backend(self): """ returns the netengine backend specified in self.backend for internal use only """ # extract backend class name, eg: AirOS or OpenWRT backend_class_name = self.backend.split('.')[-1] # convert to lowercase to get the path ...
[ "def", "_get_netengine_backend", "(", "self", ")", ":", "# extract backend class name, eg: AirOS or OpenWRT", "backend_class_name", "=", "self", ".", "backend", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "# convert to lowercase to get the path", "backend_path", ...
returns the netengine backend specified in self.backend for internal use only
[ "returns", "the", "netengine", "backend", "specified", "in", "self", ".", "backend", "for", "internal", "use", "only" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L218-L232
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector._build_netengine_arguments
def _build_netengine_arguments(self): """ returns a python dictionary representing arguments that will be passed to a netengine backend for internal use only """ arguments = { "host": self.host } if self.config is not None: for key...
python
def _build_netengine_arguments(self): """ returns a python dictionary representing arguments that will be passed to a netengine backend for internal use only """ arguments = { "host": self.host } if self.config is not None: for key...
[ "def", "_build_netengine_arguments", "(", "self", ")", ":", "arguments", "=", "{", "\"host\"", ":", "self", ".", "host", "}", "if", "self", ".", "config", "is", "not", "None", ":", "for", "key", ",", "value", "in", "self", ".", "config", ".", "iteritem...
returns a python dictionary representing arguments that will be passed to a netengine backend for internal use only
[ "returns", "a", "python", "dictionary", "representing", "arguments", "that", "will", "be", "passed", "to", "a", "netengine", "backend", "for", "internal", "use", "only" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L234-L251
ninuxorg/nodeshot
nodeshot/networking/connectors/models/device_connector.py
DeviceConnector.__create_device
def __create_device(self): """ creates device, internal use only """ # retrieve netengine dictionary from memory or from network device_dict = getattr(self, 'netengine_dict', self.netengine.to_dict()) device = Device() device.node_id = self.node_id device....
python
def __create_device(self): """ creates device, internal use only """ # retrieve netengine dictionary from memory or from network device_dict = getattr(self, 'netengine_dict', self.netengine.to_dict()) device = Device() device.node_id = self.node_id device....
[ "def", "__create_device", "(", "self", ")", ":", "# retrieve netengine dictionary from memory or from network", "device_dict", "=", "getattr", "(", "self", ",", "'netengine_dict'", ",", "self", ".", "netengine", ".", "to_dict", "(", ")", ")", "device", "=", "Device"...
creates device, internal use only
[ "creates", "device", "internal", "use", "only" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L259-L383
ninuxorg/nodeshot
nodeshot/core/base/cache.py
cache_by_group
def cache_by_group(view_instance, view_method, request, args, kwargs): """ Cache view response by media type and user group. The cache_key is constructed this way: "{view_name:path.group.media_type}" EG: "MenuList:/api/v1/menu/.public.application/json" Possible groups are: * public *...
python
def cache_by_group(view_instance, view_method, request, args, kwargs): """ Cache view response by media type and user group. The cache_key is constructed this way: "{view_name:path.group.media_type}" EG: "MenuList:/api/v1/menu/.public.application/json" Possible groups are: * public *...
[ "def", "cache_by_group", "(", "view_instance", ",", "view_method", ",", "request", ",", "args", ",", "kwargs", ")", ":", "if", "request", ".", "user", ".", "is_anonymous", "(", ")", ":", "group", "=", "'public'", "elif", "request", ".", "user", ".", "is_...
Cache view response by media type and user group. The cache_key is constructed this way: "{view_name:path.group.media_type}" EG: "MenuList:/api/v1/menu/.public.application/json" Possible groups are: * public * superuser * the rest are retrieved from DB (registered, community, trusted...
[ "Cache", "view", "response", "by", "media", "type", "and", "user", "group", ".", "The", "cache_key", "is", "constructed", "this", "way", ":", "{", "view_name", ":", "path", ".", "group", ".", "media_type", "}", "EG", ":", "MenuList", ":", "/", "api", "...
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/cache.py#L16-L43
bcwaldon/warlock
warlock/core.py
model_factory
def model_factory(schema, resolver=None, base_class=model.Model, name=None): """Generate a model class based on the provided JSON Schema :param schema: dict representing valid JSON schema :param name: A name to give the class, if `name` is not in `schema` """ schema = copy.deepcopy(schema) reso...
python
def model_factory(schema, resolver=None, base_class=model.Model, name=None): """Generate a model class based on the provided JSON Schema :param schema: dict representing valid JSON schema :param name: A name to give the class, if `name` is not in `schema` """ schema = copy.deepcopy(schema) reso...
[ "def", "model_factory", "(", "schema", ",", "resolver", "=", "None", ",", "base_class", "=", "model", ".", "Model", ",", "name", "=", "None", ")", ":", "schema", "=", "copy", ".", "deepcopy", "(", "schema", ")", "resolver", "=", "resolver", "class", "M...
Generate a model class based on the provided JSON Schema :param schema: dict representing valid JSON schema :param name: A name to give the class, if `name` is not in `schema`
[ "Generate", "a", "model", "class", "based", "on", "the", "provided", "JSON", "Schema" ]
train
https://github.com/bcwaldon/warlock/blob/19b2b3e103ddd753bb5da5b5d96f801c267dad3b/warlock/core.py#L22-L44
bcwaldon/warlock
warlock/model.py
Model.patch
def patch(self): """Return a jsonpatch object representing the delta""" original = self.__dict__['__original__'] return jsonpatch.make_patch(original, dict(self)).to_string()
python
def patch(self): """Return a jsonpatch object representing the delta""" original = self.__dict__['__original__'] return jsonpatch.make_patch(original, dict(self)).to_string()
[ "def", "patch", "(", "self", ")", ":", "original", "=", "self", ".", "__dict__", "[", "'__original__'", "]", "return", "jsonpatch", ".", "make_patch", "(", "original", ",", "dict", "(", "self", ")", ")", ".", "to_string", "(", ")" ]
Return a jsonpatch object representing the delta
[ "Return", "a", "jsonpatch", "object", "representing", "the", "delta" ]
train
https://github.com/bcwaldon/warlock/blob/19b2b3e103ddd753bb5da5b5d96f801c267dad3b/warlock/model.py#L125-L128
bcwaldon/warlock
warlock/model.py
Model.changes
def changes(self): """Dumber version of 'patch' method""" deprecation_msg = 'Model.changes will be removed in warlock v2' warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2) return copy.deepcopy(self.__dict__['changes'])
python
def changes(self): """Dumber version of 'patch' method""" deprecation_msg = 'Model.changes will be removed in warlock v2' warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2) return copy.deepcopy(self.__dict__['changes'])
[ "def", "changes", "(", "self", ")", ":", "deprecation_msg", "=", "'Model.changes will be removed in warlock v2'", "warnings", ".", "warn", "(", "deprecation_msg", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "return", "copy", ".", "deepcopy", "(", ...
Dumber version of 'patch' method
[ "Dumber", "version", "of", "patch", "method" ]
train
https://github.com/bcwaldon/warlock/blob/19b2b3e103ddd753bb5da5b5d96f801c267dad3b/warlock/model.py#L131-L135
bcwaldon/warlock
warlock/model.py
Model.validate
def validate(self, obj): """Apply a JSON schema to an object""" try: if self.resolver is not None: jsonschema.validate(obj, self.schema, resolver=self.resolver) else: jsonschema.validate(obj, self.schema) except jsonschema.ValidationError a...
python
def validate(self, obj): """Apply a JSON schema to an object""" try: if self.resolver is not None: jsonschema.validate(obj, self.schema, resolver=self.resolver) else: jsonschema.validate(obj, self.schema) except jsonschema.ValidationError a...
[ "def", "validate", "(", "self", ",", "obj", ")", ":", "try", ":", "if", "self", ".", "resolver", "is", "not", "None", ":", "jsonschema", ".", "validate", "(", "obj", ",", "self", ".", "schema", ",", "resolver", "=", "self", ".", "resolver", ")", "e...
Apply a JSON schema to an object
[ "Apply", "a", "JSON", "schema", "to", "an", "object" ]
train
https://github.com/bcwaldon/warlock/blob/19b2b3e103ddd753bb5da5b5d96f801c267dad3b/warlock/model.py#L137-L145
sashs/filebytes
filebytes/mach_o.py
MachO.isSupportedContent
def isSupportedContent(cls, fileContent): """Returns if the files are valid for this filetype""" magic = bytearray(fileContent)[:4] return magic == p('>I', 0xfeedface) or magic == p('>I', 0xfeedfacf) or magic == p('<I', 0xfeedface) or magic == p('<I', 0xfeedfacf)
python
def isSupportedContent(cls, fileContent): """Returns if the files are valid for this filetype""" magic = bytearray(fileContent)[:4] return magic == p('>I', 0xfeedface) or magic == p('>I', 0xfeedfacf) or magic == p('<I', 0xfeedface) or magic == p('<I', 0xfeedfacf)
[ "def", "isSupportedContent", "(", "cls", ",", "fileContent", ")", ":", "magic", "=", "bytearray", "(", "fileContent", ")", "[", ":", "4", "]", "return", "magic", "==", "p", "(", "'>I'", ",", "0xfeedface", ")", "or", "magic", "==", "p", "(", "'>I'", "...
Returns if the files are valid for this filetype
[ "Returns", "if", "the", "files", "are", "valid", "for", "this", "filetype" ]
train
https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/mach_o.py#L476-L479
sashs/filebytes
filebytes/oat.py
OAT._parseOatHeader
def _parseOatHeader(self, data): """Returns the OatHeader""" header = OatHeader.from_buffer(data) if header.magic != b'oat\n': raise BinaryError('No valid OAT file') key_value_store_bytes = (c_ubyte * header.keyValueStoreSize).from_buffer(data, sizeof(OatHeader)) key...
python
def _parseOatHeader(self, data): """Returns the OatHeader""" header = OatHeader.from_buffer(data) if header.magic != b'oat\n': raise BinaryError('No valid OAT file') key_value_store_bytes = (c_ubyte * header.keyValueStoreSize).from_buffer(data, sizeof(OatHeader)) key...
[ "def", "_parseOatHeader", "(", "self", ",", "data", ")", ":", "header", "=", "OatHeader", ".", "from_buffer", "(", "data", ")", "if", "header", ".", "magic", "!=", "b'oat\\n'", ":", "raise", "BinaryError", "(", "'No valid OAT file'", ")", "key_value_store_byte...
Returns the OatHeader
[ "Returns", "the", "OatHeader" ]
train
https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/oat.py#L169-L178
sashs/filebytes
filebytes/oat.py
OAT.__parseKeyValueStore
def __parseKeyValueStore(self, data): """Returns a dictionary filled with the keys and values of the key value store""" offset = 0 key_value_store = {} while offset != len(data): key = get_str(data, offset) offset += len(key)+1 value = get_str(data, o...
python
def __parseKeyValueStore(self, data): """Returns a dictionary filled with the keys and values of the key value store""" offset = 0 key_value_store = {} while offset != len(data): key = get_str(data, offset) offset += len(key)+1 value = get_str(data, o...
[ "def", "__parseKeyValueStore", "(", "self", ",", "data", ")", ":", "offset", "=", "0", "key_value_store", "=", "{", "}", "while", "offset", "!=", "len", "(", "data", ")", ":", "key", "=", "get_str", "(", "data", ",", "offset", ")", "offset", "+=", "l...
Returns a dictionary filled with the keys and values of the key value store
[ "Returns", "a", "dictionary", "filled", "with", "the", "keys", "and", "values", "of", "the", "key", "value", "store" ]
train
https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/oat.py#L180-L193
sashs/filebytes
filebytes/pe.py
to_raw_address
def to_raw_address(addr, section): """Converts the addr from a rva to a pointer to raw data in the file""" return addr - section.header.VirtualAddress + section.header.PointerToRawData
python
def to_raw_address(addr, section): """Converts the addr from a rva to a pointer to raw data in the file""" return addr - section.header.VirtualAddress + section.header.PointerToRawData
[ "def", "to_raw_address", "(", "addr", ",", "section", ")", ":", "return", "addr", "-", "section", ".", "header", ".", "VirtualAddress", "+", "section", ".", "header", ".", "PointerToRawData" ]
Converts the addr from a rva to a pointer to raw data in the file
[ "Converts", "the", "addr", "from", "a", "rva", "to", "a", "pointer", "to", "raw", "data", "in", "the", "file" ]
train
https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L356-L358
sashs/filebytes
filebytes/pe.py
PE._getSuitableClasses
def _getSuitableClasses(self, data, imageDosHeader): """Returns the class which holds the suitable classes for the loaded file""" classes = None machine = IMAGE_FILE_MACHINE[c_ushort.from_buffer(data,imageDosHeader.header.e_lfanew+4).value] if machine == IMAGE_FILE_MACHINE.I386: ...
python
def _getSuitableClasses(self, data, imageDosHeader): """Returns the class which holds the suitable classes for the loaded file""" classes = None machine = IMAGE_FILE_MACHINE[c_ushort.from_buffer(data,imageDosHeader.header.e_lfanew+4).value] if machine == IMAGE_FILE_MACHINE.I386: ...
[ "def", "_getSuitableClasses", "(", "self", ",", "data", ",", "imageDosHeader", ")", ":", "classes", "=", "None", "machine", "=", "IMAGE_FILE_MACHINE", "[", "c_ushort", ".", "from_buffer", "(", "data", ",", "imageDosHeader", ".", "header", ".", "e_lfanew", "+",...
Returns the class which holds the suitable classes for the loaded file
[ "Returns", "the", "class", "which", "holds", "the", "suitable", "classes", "for", "the", "loaded", "file" ]
train
https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L486-L496
sashs/filebytes
filebytes/pe.py
PE._parseImageDosHeader
def _parseImageDosHeader(self, data): """Returns the ImageDosHeader""" ioh = IMAGE_DOS_HEADER.from_buffer(data) if ioh.e_magic != b'MZ': raise BinaryError('No valid PE/COFF file') return ImageDosHeaderData(header=ioh)
python
def _parseImageDosHeader(self, data): """Returns the ImageDosHeader""" ioh = IMAGE_DOS_HEADER.from_buffer(data) if ioh.e_magic != b'MZ': raise BinaryError('No valid PE/COFF file') return ImageDosHeaderData(header=ioh)
[ "def", "_parseImageDosHeader", "(", "self", ",", "data", ")", ":", "ioh", "=", "IMAGE_DOS_HEADER", ".", "from_buffer", "(", "data", ")", "if", "ioh", ".", "e_magic", "!=", "b'MZ'", ":", "raise", "BinaryError", "(", "'No valid PE/COFF file'", ")", "return", "...
Returns the ImageDosHeader
[ "Returns", "the", "ImageDosHeader" ]
train
https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L498-L504
sashs/filebytes
filebytes/pe.py
PE._parseImageNtHeaders
def _parseImageNtHeaders(self, data, imageDosHeader): """Returns the ImageNtHeaders""" inth = self._classes.IMAGE_NT_HEADERS.from_buffer(data, imageDosHeader.header.e_lfanew) if inth.Signature != b'PE': raise BinaryError('No valid PE/COFF file') return ImageNtHeaderData(hea...
python
def _parseImageNtHeaders(self, data, imageDosHeader): """Returns the ImageNtHeaders""" inth = self._classes.IMAGE_NT_HEADERS.from_buffer(data, imageDosHeader.header.e_lfanew) if inth.Signature != b'PE': raise BinaryError('No valid PE/COFF file') return ImageNtHeaderData(hea...
[ "def", "_parseImageNtHeaders", "(", "self", ",", "data", ",", "imageDosHeader", ")", ":", "inth", "=", "self", ".", "_classes", ".", "IMAGE_NT_HEADERS", ".", "from_buffer", "(", "data", ",", "imageDosHeader", ".", "header", ".", "e_lfanew", ")", "if", "inth"...
Returns the ImageNtHeaders
[ "Returns", "the", "ImageNtHeaders" ]
train
https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L506-L513
sashs/filebytes
filebytes/pe.py
PE._parseSections
def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False): """Parses the sections in the memory and returns a list of them""" sections = [] optional_header_offset = imageDosHeader.header.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER) offset = optional_header_offs...
python
def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False): """Parses the sections in the memory and returns a list of them""" sections = [] optional_header_offset = imageDosHeader.header.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER) offset = optional_header_offs...
[ "def", "_parseSections", "(", "self", ",", "data", ",", "imageDosHeader", ",", "imageNtHeaders", ",", "parse_header_only", "=", "False", ")", ":", "sections", "=", "[", "]", "optional_header_offset", "=", "imageDosHeader", ".", "header", ".", "e_lfanew", "+", ...
Parses the sections in the memory and returns a list of them
[ "Parses", "the", "sections", "in", "the", "memory", "and", "returns", "a", "list", "of", "them" ]
train
https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L515-L539