repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ninuxorg/nodeshot
nodeshot/community/mailing/admin.py
OutwardAdmin.send
def send(self, request, queryset): """ Send action available in change outward list """ send_outward_mails.delay(queryset) # show message in the admin messages.info(request, _('Message sent successfully'), fail_silently=True)
python
def send(self, request, queryset): """ Send action available in change outward list """ send_outward_mails.delay(queryset) # show message in the admin messages.info(request, _('Message sent successfully'), fail_silently=True)
[ "def", "send", "(", "self", ",", "request", ",", "queryset", ")", ":", "send_outward_mails", ".", "delay", "(", "queryset", ")", "# show message in the admin", "messages", ".", "info", "(", "request", ",", "_", "(", "'Message sent successfully'", ")", ",", "fa...
Send action available in change outward list
[ "Send", "action", "available", "in", "change", "outward", "list" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/admin.py#L33-L39
train
52,200
ninuxorg/nodeshot
nodeshot/community/mailing/views.py
ContactNode.post
def post(self, request, *args, **kwargs): """ Contact node owner. """ try: self.get_object(**kwargs) except Http404: return Response({'detail': _('Not Found')}, status=404) if not self.is_contactable(): return Response({'detail': _('This resource cannot be contacted')}, status=400) content_type = ContentType.objects.only('id', 'model').get(model=self.content_type) # shortcut data = request.data # init inward message message = Inward() # required fields message.content_type = content_type message.object_id = self.recipient.id message.message = data.get('message') # user info if authenticated if request.user.is_authenticated(): message.user = request.user else: message.from_name = data.get('from_name') message.from_email = data.get('from_email') # additional user info message.ip = request.META.get('REMOTE_ADDR', '') message.user_agent = request.META.get('HTTP_USER_AGENT', '') message.accept_language = request.META.get('HTTP_ACCEPT_LANGUAGE', '') try: message.full_clean() except ValidationError, e: return Response(e.message_dict, status=400) message.save() if message.status >= 1: return Response({'details': _('Message sent successfully')}, status=201) else: return Response({'details': _('Something went wrong. The email was not sent.')}, status=500)
python
def post(self, request, *args, **kwargs): """ Contact node owner. """ try: self.get_object(**kwargs) except Http404: return Response({'detail': _('Not Found')}, status=404) if not self.is_contactable(): return Response({'detail': _('This resource cannot be contacted')}, status=400) content_type = ContentType.objects.only('id', 'model').get(model=self.content_type) # shortcut data = request.data # init inward message message = Inward() # required fields message.content_type = content_type message.object_id = self.recipient.id message.message = data.get('message') # user info if authenticated if request.user.is_authenticated(): message.user = request.user else: message.from_name = data.get('from_name') message.from_email = data.get('from_email') # additional user info message.ip = request.META.get('REMOTE_ADDR', '') message.user_agent = request.META.get('HTTP_USER_AGENT', '') message.accept_language = request.META.get('HTTP_ACCEPT_LANGUAGE', '') try: message.full_clean() except ValidationError, e: return Response(e.message_dict, status=400) message.save() if message.status >= 1: return Response({'details': _('Message sent successfully')}, status=201) else: return Response({'details': _('Something went wrong. The email was not sent.')}, status=500)
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "get_object", "(", "*", "*", "kwargs", ")", "except", "Http404", ":", "return", "Response", "(", "{", "'detail'", ":", "_", ...
Contact node owner.
[ "Contact", "node", "owner", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/views.py#L51-L91
train
52,201
ninuxorg/nodeshot
nodeshot/community/profiles/views.py
ProfileList.get
def get(self, request, *args, **kwargs): """ return profile of current user if authenticated otherwise 401 """ serializer = self.serializer_reader_class if request.user.is_authenticated(): return Response(serializer(request.user, context=self.get_serializer_context()).data) else: return Response({'detail': _('Authentication credentials were not provided')}, status=401)
python
def get(self, request, *args, **kwargs): """ return profile of current user if authenticated otherwise 401 """ serializer = self.serializer_reader_class if request.user.is_authenticated(): return Response(serializer(request.user, context=self.get_serializer_context()).data) else: return Response({'detail': _('Authentication credentials were not provided')}, status=401)
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "serializer", "=", "self", ".", "serializer_reader_class", "if", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "return", "Response", "(", ...
return profile of current user if authenticated otherwise 401
[ "return", "profile", "of", "current", "user", "if", "authenticated", "otherwise", "401" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/views.py#L58-L64
train
52,202
ninuxorg/nodeshot
nodeshot/community/profiles/views.py
AccountPassword.post
def post(self, request, format=None): """ validate password change operation and return result """ serializer_class = self.get_serializer_class() serializer = serializer_class(data=request.data, instance=request.user) if serializer.is_valid(): serializer.save() return Response({'detail': _(u'Password successfully changed')}) return Response(serializer.errors, status=400)
python
def post(self, request, format=None): """ validate password change operation and return result """ serializer_class = self.get_serializer_class() serializer = serializer_class(data=request.data, instance=request.user) if serializer.is_valid(): serializer.save() return Response({'detail': _(u'Password successfully changed')}) return Response(serializer.errors, status=400)
[ "def", "post", "(", "self", ",", "request", ",", "format", "=", "None", ")", ":", "serializer_class", "=", "self", ".", "get_serializer_class", "(", ")", "serializer", "=", "serializer_class", "(", "data", "=", "request", ".", "data", ",", "instance", "=",...
validate password change operation and return result
[ "validate", "password", "change", "operation", "and", "return", "result" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/views.py#L277-L286
train
52,203
ninuxorg/nodeshot
nodeshot/interop/sync/synchronizers/base.py
HttpRetrieverMixin.retrieve_data
def retrieve_data(self): """ retrieve data from an HTTP URL """ # shortcuts for readability url = self.config.get('url') timeout = float(self.config.get('timeout', 10)) # perform HTTP request and store content self.data = requests.get(url, verify=self.verify_ssl, timeout=timeout).content
python
def retrieve_data(self): """ retrieve data from an HTTP URL """ # shortcuts for readability url = self.config.get('url') timeout = float(self.config.get('timeout', 10)) # perform HTTP request and store content self.data = requests.get(url, verify=self.verify_ssl, timeout=timeout).content
[ "def", "retrieve_data", "(", "self", ")", ":", "# shortcuts for readability", "url", "=", "self", ".", "config", ".", "get", "(", "'url'", ")", "timeout", "=", "float", "(", "self", ".", "config", ".", "get", "(", "'timeout'", ",", "10", ")", ")", "# p...
retrieve data from an HTTP URL
[ "retrieve", "data", "from", "an", "HTTP", "URL" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/base.py#L131-L137
train
52,204
ninuxorg/nodeshot
nodeshot/interop/sync/synchronizers/base.py
XMLParserMixin.get_text
def get_text(item, tag, default=False): """ returns text content of an xml tag """ try: xmlnode = item.getElementsByTagName(tag)[0].firstChild except IndexError as e: if default is not False: return default else: raise IndexError(e) if xmlnode is not None: return unicode(xmlnode.nodeValue) # empty tag else: return ''
python
def get_text(item, tag, default=False): """ returns text content of an xml tag """ try: xmlnode = item.getElementsByTagName(tag)[0].firstChild except IndexError as e: if default is not False: return default else: raise IndexError(e) if xmlnode is not None: return unicode(xmlnode.nodeValue) # empty tag else: return ''
[ "def", "get_text", "(", "item", ",", "tag", ",", "default", "=", "False", ")", ":", "try", ":", "xmlnode", "=", "item", ".", "getElementsByTagName", "(", "tag", ")", "[", "0", "]", ".", "firstChild", "except", "IndexError", "as", "e", ":", "if", "def...
returns text content of an xml tag
[ "returns", "text", "content", "of", "an", "xml", "tag" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/base.py#L148-L162
train
52,205
ninuxorg/nodeshot
nodeshot/interop/sync/synchronizers/base.py
GenericGisSynchronizer._convert_item
def _convert_item(self, item): """ take a parsed item as input and returns a python dictionary the keys will be saved into the Node model either in their respective fields or in the hstore "data" field :param item: object representing parsed item """ item = self.parse_item(item) # name is required if not item['name']: raise Exception('Expected property %s not found in item %s.' % (self.keys['name'], item)) elif len(item['name']) > 75: item['name'] = item['name'][:75] if not item['status']: item['status'] = self.default_status # get status or get default status or None try: item['status'] = Status.objects.get(slug__iexact=item['status']) except Status.DoesNotExist: try: item['status'] = Status.objects.create(name=item['status'], slug=slugify(item['status']), description=item['status'], is_default=False) except Exception as e: logger.exception(e) item['status'] = None # slugify slug item['slug'] = slugify(item['name']) if not item['address']: item['address'] = '' if not item['is_published']: item['is_published'] = '' User = get_user_model() # get user or None try: item['user'] = User.objects.get(username=item['user']) except User.DoesNotExist: item['user'] = None if not item['elev']: item['elev'] = None if not item['description']: item['description'] = '' if not item['notes']: item['notes'] = '' if item['added']: # convert dates to python datetime try: item['added'] = parser.parse(item['added']) except Exception as e: print "Exception while parsing 'added' date: %s" % e if item['updated']: try: item['updated'] = parser.parse(item['updated']) except Exception as e: print "Exception while parsing 'updated' date: %s" % e result = { "name": item['name'], "slug": item['slug'], "status": item['status'], "address": item['address'], "is_published": item['is_published'], "user": item['user'], "geometry": item['geometry'], "elev": item['elev'], "description": item['description'], "notes": item['notes'], "added": item['added'], "updated": item['updated'], "data": {} } # ensure all additional data items are strings for key, value in item['data'].items(): result["data"][key] = value return result
python
def _convert_item(self, item): """ take a parsed item as input and returns a python dictionary the keys will be saved into the Node model either in their respective fields or in the hstore "data" field :param item: object representing parsed item """ item = self.parse_item(item) # name is required if not item['name']: raise Exception('Expected property %s not found in item %s.' % (self.keys['name'], item)) elif len(item['name']) > 75: item['name'] = item['name'][:75] if not item['status']: item['status'] = self.default_status # get status or get default status or None try: item['status'] = Status.objects.get(slug__iexact=item['status']) except Status.DoesNotExist: try: item['status'] = Status.objects.create(name=item['status'], slug=slugify(item['status']), description=item['status'], is_default=False) except Exception as e: logger.exception(e) item['status'] = None # slugify slug item['slug'] = slugify(item['name']) if not item['address']: item['address'] = '' if not item['is_published']: item['is_published'] = '' User = get_user_model() # get user or None try: item['user'] = User.objects.get(username=item['user']) except User.DoesNotExist: item['user'] = None if not item['elev']: item['elev'] = None if not item['description']: item['description'] = '' if not item['notes']: item['notes'] = '' if item['added']: # convert dates to python datetime try: item['added'] = parser.parse(item['added']) except Exception as e: print "Exception while parsing 'added' date: %s" % e if item['updated']: try: item['updated'] = parser.parse(item['updated']) except Exception as e: print "Exception while parsing 'updated' date: %s" % e result = { "name": item['name'], "slug": item['slug'], "status": item['status'], "address": item['address'], "is_published": item['is_published'], "user": item['user'], "geometry": item['geometry'], "elev": item['elev'], "description": item['description'], "notes": item['notes'], "added": item['added'], "updated": item['updated'], "data": {} } # ensure all additional data items are strings for key, value in item['data'].items(): result["data"][key] = value return result
[ "def", "_convert_item", "(", "self", ",", "item", ")", ":", "item", "=", "self", ".", "parse_item", "(", "item", ")", "# name is required", "if", "not", "item", "[", "'name'", "]", ":", "raise", "Exception", "(", "'Expected property %s not found in item %s.'", ...
take a parsed item as input and returns a python dictionary the keys will be saved into the Node model either in their respective fields or in the hstore "data" field :param item: object representing parsed item
[ "take", "a", "parsed", "item", "as", "input", "and", "returns", "a", "python", "dictionary", "the", "keys", "will", "be", "saved", "into", "the", "Node", "model", "either", "in", "their", "respective", "fields", "or", "in", "the", "hstore", "data", "field"...
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/base.py#L342-L431
train
52,206
ninuxorg/nodeshot
nodeshot/core/base/mixins.py
ACLMixin.get_queryset
def get_queryset(self): """ Returns only objects which are accessible to the current user. If user is not authenticated all public objects will be returned. Model must implement AccessLevelManager! """ return self.queryset.all().accessible_to(user=self.request.user)
python
def get_queryset(self): """ Returns only objects which are accessible to the current user. If user is not authenticated all public objects will be returned. Model must implement AccessLevelManager! """ return self.queryset.all().accessible_to(user=self.request.user)
[ "def", "get_queryset", "(", "self", ")", ":", "return", "self", ".", "queryset", ".", "all", "(", ")", ".", "accessible_to", "(", "user", "=", "self", ".", "request", ".", "user", ")" ]
Returns only objects which are accessible to the current user. If user is not authenticated all public objects will be returned. Model must implement AccessLevelManager!
[ "Returns", "only", "objects", "which", "are", "accessible", "to", "the", "current", "user", ".", "If", "user", "is", "not", "authenticated", "all", "public", "objects", "will", "be", "returned", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/mixins.py#L12-L19
train
52,207
ninuxorg/nodeshot
nodeshot/core/base/mixins.py
RevisionUpdate.patch
def patch(self, request, *args, **kwargs): """ custom patch method to support django-reversion """ with reversion.create_revision(): reversion.set_user(request.user) reversion.set_comment('changed through the RESTful API from ip %s' % request.META['REMOTE_ADDR']) kwargs['partial'] = True return self.update(request, *args, **kwargs)
python
def patch(self, request, *args, **kwargs): """ custom patch method to support django-reversion """ with reversion.create_revision(): reversion.set_user(request.user) reversion.set_comment('changed through the RESTful API from ip %s' % request.META['REMOTE_ADDR']) kwargs['partial'] = True return self.update(request, *args, **kwargs)
[ "def", "patch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "reversion", ".", "create_revision", "(", ")", ":", "reversion", ".", "set_user", "(", "request", ".", "user", ")", "reversion", ".", "set_comment...
custom patch method to support django-reversion
[ "custom", "patch", "method", "to", "support", "django", "-", "reversion" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/mixins.py#L34-L40
train
52,208
ninuxorg/nodeshot
nodeshot/networking/hardware/models/device_to_model_rel.py
DeviceToModelRel.save
def save(self, *args, **kwargs): """ when creating a new record fill CPU and RAM info if available """ adding_new = False if not self.pk or (not self.cpu and not self.ram): # if self.model.cpu is not empty if self.model.cpu: self.cpu = self.model.cpu # if self.model.ram is not empty if self.model.ram: self.ram = self.model.ram # mark to add a new antenna adding_new = True # perform save super(DeviceToModelRel, self).save(*args, **kwargs) # after Device2Model object has been saved try: # does the device model have an integrated antenna? antenna_model = self.model.antennamodel except AntennaModel.DoesNotExist: # if not antenna_model is False antenna_model = False # if we are adding a new device2model and the device model has an integrated antenna if adding_new and antenna_model: # create new Antenna object antenna = Antenna( device=self.device, model=self.model.antennamodel ) # retrieve wireless interfaces and assign it to the antenna object if possible wireless_interfaces = self.device.interface_set.filter(type=2) if len(wireless_interfaces) > 0: antenna.radio = wireless_interfaces[0] # save antenna antenna.save()
python
def save(self, *args, **kwargs): """ when creating a new record fill CPU and RAM info if available """ adding_new = False if not self.pk or (not self.cpu and not self.ram): # if self.model.cpu is not empty if self.model.cpu: self.cpu = self.model.cpu # if self.model.ram is not empty if self.model.ram: self.ram = self.model.ram # mark to add a new antenna adding_new = True # perform save super(DeviceToModelRel, self).save(*args, **kwargs) # after Device2Model object has been saved try: # does the device model have an integrated antenna? antenna_model = self.model.antennamodel except AntennaModel.DoesNotExist: # if not antenna_model is False antenna_model = False # if we are adding a new device2model and the device model has an integrated antenna if adding_new and antenna_model: # create new Antenna object antenna = Antenna( device=self.device, model=self.model.antennamodel ) # retrieve wireless interfaces and assign it to the antenna object if possible wireless_interfaces = self.device.interface_set.filter(type=2) if len(wireless_interfaces) > 0: antenna.radio = wireless_interfaces[0] # save antenna antenna.save()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "adding_new", "=", "False", "if", "not", "self", ".", "pk", "or", "(", "not", "self", ".", "cpu", "and", "not", "self", ".", "ram", ")", ":", "# if self.model.cpu is n...
when creating a new record fill CPU and RAM info if available
[ "when", "creating", "a", "new", "record", "fill", "CPU", "and", "RAM", "info", "if", "available" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/hardware/models/device_to_model_rel.py#L24-L57
train
52,209
ninuxorg/nodeshot
nodeshot/community/notifications/models/notification.py
Notification.clean
def clean(self, *args, **kwargs): """ from_user and to_user must differ """ if self.from_user and self.from_user_id == self.to_user_id: raise ValidationError(_('A user cannot send a notification to herself/himself'))
python
def clean(self, *args, **kwargs): """ from_user and to_user must differ """ if self.from_user and self.from_user_id == self.to_user_id: raise ValidationError(_('A user cannot send a notification to herself/himself'))
[ "def", "clean", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "from_user", "and", "self", ".", "from_user_id", "==", "self", ".", "to_user_id", ":", "raise", "ValidationError", "(", "_", "(", "'A user cannot send a ...
from_user and to_user must differ
[ "from_user", "and", "to_user", "must", "differ" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L44-L47
train
52,210
ninuxorg/nodeshot
nodeshot/community/notifications/models/notification.py
Notification.save
def save(self, *args, **kwargs): """ custom save method to send email and push notification """ created = self.pk is None # save notification to database only if user settings allow it if self.check_user_settings(medium='web'): super(Notification, self).save(*args, **kwargs) if created: # send notifications through other mediums according to user settings self.send_notifications()
python
def save(self, *args, **kwargs): """ custom save method to send email and push notification """ created = self.pk is None # save notification to database only if user settings allow it if self.check_user_settings(medium='web'): super(Notification, self).save(*args, **kwargs) if created: # send notifications through other mediums according to user settings self.send_notifications()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "created", "=", "self", ".", "pk", "is", "None", "# save notification to database only if user settings allow it", "if", "self", ".", "check_user_settings", "(", "medium", "=", "'...
custom save method to send email and push notification
[ "custom", "save", "method", "to", "send", "email", "and", "push", "notification" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L49-L61
train
52,211
ninuxorg/nodeshot
nodeshot/community/notifications/models/notification.py
Notification.send_email
def send_email(self): """ send email notification according to user settings """ # send only if user notification setting is set to true if self.check_user_settings(): send_mail(_(self.type), self.email_message, settings.DEFAULT_FROM_EMAIL, [self.to_user.email]) return True else: # return false otherwise return False
python
def send_email(self): """ send email notification according to user settings """ # send only if user notification setting is set to true if self.check_user_settings(): send_mail(_(self.type), self.email_message, settings.DEFAULT_FROM_EMAIL, [self.to_user.email]) return True else: # return false otherwise return False
[ "def", "send_email", "(", "self", ")", ":", "# send only if user notification setting is set to true", "if", "self", ".", "check_user_settings", "(", ")", ":", "send_mail", "(", "_", "(", "self", ".", "type", ")", ",", "self", ".", "email_message", ",", "setting...
send email notification according to user settings
[ "send", "email", "notification", "according", "to", "user", "settings" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L67-L75
train
52,212
ninuxorg/nodeshot
nodeshot/community/notifications/models/notification.py
Notification.check_user_settings
def check_user_settings(self, medium='email'): """ Ensure user is ok with receiving this notification through the specified medium. Available mediums are 'web' and 'email', while 'mobile' notifications will hopefully be implemented in the future. """ # custom notifications are always sent if self.type == 'custom': return True try: user_settings = getattr(self.to_user, '%s_notification_settings' % medium) except ObjectDoesNotExist: # user has no settings specified # TODO: it would be better to create the settings with default values return False user_setting_type = getattr(user_settings.__class__, self.type).user_setting_type if user_setting_type == 'boolean': return getattr(user_settings, self.type, True) elif user_setting_type == 'distance': value = getattr(user_settings, self.type, 0) # enabled for all related objects if value is 0: return True # disabled for all related objects elif value < 0: return False # enabled for related objects comprised in specified distance range in km else: Model = self.related_object.__class__ geo_field = getattr(user_settings.__class__, self.type).geo_field geo_value = getattr(self.related_object, geo_field) km = value * 1000 queryset = Model.objects.filter(**{ "user_id": self.to_user_id, geo_field + "__distance_lte": (geo_value, km) }) # if user has related object in a distance range less than or equal to # his prefered range (specified in number of km), return True and send the notification return queryset.count() >= 1
python
def check_user_settings(self, medium='email'): """ Ensure user is ok with receiving this notification through the specified medium. Available mediums are 'web' and 'email', while 'mobile' notifications will hopefully be implemented in the future. """ # custom notifications are always sent if self.type == 'custom': return True try: user_settings = getattr(self.to_user, '%s_notification_settings' % medium) except ObjectDoesNotExist: # user has no settings specified # TODO: it would be better to create the settings with default values return False user_setting_type = getattr(user_settings.__class__, self.type).user_setting_type if user_setting_type == 'boolean': return getattr(user_settings, self.type, True) elif user_setting_type == 'distance': value = getattr(user_settings, self.type, 0) # enabled for all related objects if value is 0: return True # disabled for all related objects elif value < 0: return False # enabled for related objects comprised in specified distance range in km else: Model = self.related_object.__class__ geo_field = getattr(user_settings.__class__, self.type).geo_field geo_value = getattr(self.related_object, geo_field) km = value * 1000 queryset = Model.objects.filter(**{ "user_id": self.to_user_id, geo_field + "__distance_lte": (geo_value, km) }) # if user has related object in a distance range less than or equal to # his prefered range (specified in number of km), return True and send the notification return queryset.count() >= 1
[ "def", "check_user_settings", "(", "self", ",", "medium", "=", "'email'", ")", ":", "# custom notifications are always sent", "if", "self", ".", "type", "==", "'custom'", ":", "return", "True", "try", ":", "user_settings", "=", "getattr", "(", "self", ".", "to...
Ensure user is ok with receiving this notification through the specified medium. Available mediums are 'web' and 'email', while 'mobile' notifications will hopefully be implemented in the future.
[ "Ensure", "user", "is", "ok", "with", "receiving", "this", "notification", "through", "the", "specified", "medium", ".", "Available", "mediums", "are", "web", "and", "email", "while", "mobile", "notifications", "will", "hopefully", "be", "implemented", "in", "th...
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L81-L122
train
52,213
ninuxorg/nodeshot
nodeshot/community/notifications/models/notification.py
Notification.email_message
def email_message(self): """ compose complete email message text """ url = settings.SITE_URL hello_text = __("Hi %s," % self.to_user.get_full_name()) action_text = __("\n\nMore details here: %s") % url explain_text = __( "This is an automatic notification sent from from %s.\n" "If you want to stop receiving this notification edit your" "email notification settings here: %s") % (settings.SITE_NAME, 'TODO') return "%s\n\n%s%s\n\n%s" % (hello_text, self.text, action_text, explain_text)
python
def email_message(self): """ compose complete email message text """ url = settings.SITE_URL hello_text = __("Hi %s," % self.to_user.get_full_name()) action_text = __("\n\nMore details here: %s") % url explain_text = __( "This is an automatic notification sent from from %s.\n" "If you want to stop receiving this notification edit your" "email notification settings here: %s") % (settings.SITE_NAME, 'TODO') return "%s\n\n%s%s\n\n%s" % (hello_text, self.text, action_text, explain_text)
[ "def", "email_message", "(", "self", ")", ":", "url", "=", "settings", ".", "SITE_URL", "hello_text", "=", "__", "(", "\"Hi %s,\"", "%", "self", ".", "to_user", ".", "get_full_name", "(", ")", ")", "action_text", "=", "__", "(", "\"\\n\\nMore details here: %...
compose complete email message text
[ "compose", "complete", "email", "message", "text" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L125-L135
train
52,214
ninuxorg/nodeshot
nodeshot/community/profiles/models/emailconfirmation.py
EmailConfirmationManager.generate_key
def generate_key(self, email): """ Generate a new email confirmation key and return it. """ salt = sha1(str(random())).hexdigest()[:5] return sha1(salt + email).hexdigest()
python
def generate_key(self, email): """ Generate a new email confirmation key and return it. """ salt = sha1(str(random())).hexdigest()[:5] return sha1(salt + email).hexdigest()
[ "def", "generate_key", "(", "self", ",", "email", ")", ":", "salt", "=", "sha1", "(", "str", "(", "random", "(", ")", ")", ")", ".", "hexdigest", "(", ")", "[", ":", "5", "]", "return", "sha1", "(", "salt", "+", "email", ")", ".", "hexdigest", ...
Generate a new email confirmation key and return it.
[ "Generate", "a", "new", "email", "confirmation", "key", "and", "return", "it", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/emailconfirmation.py#L127-L132
train
52,215
ninuxorg/nodeshot
nodeshot/community/profiles/models/emailconfirmation.py
EmailConfirmationManager.create_emailconfirmation
def create_emailconfirmation(self, email_address): "Create an email confirmation obj from the given email address obj" confirmation_key = self.generate_key(email_address.email) confirmation = self.create( email_address=email_address, created_at=now(), key=confirmation_key, ) return confirmation
python
def create_emailconfirmation(self, email_address): "Create an email confirmation obj from the given email address obj" confirmation_key = self.generate_key(email_address.email) confirmation = self.create( email_address=email_address, created_at=now(), key=confirmation_key, ) return confirmation
[ "def", "create_emailconfirmation", "(", "self", ",", "email_address", ")", ":", "confirmation_key", "=", "self", ".", "generate_key", "(", "email_address", ".", "email", ")", "confirmation", "=", "self", ".", "create", "(", "email_address", "=", "email_address", ...
Create an email confirmation obj from the given email address obj
[ "Create", "an", "email", "confirmation", "obj", "from", "the", "given", "email", "address", "obj" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/emailconfirmation.py#L134-L142
train
52,216
ninuxorg/nodeshot
nodeshot/core/metrics/signals.py
user_loggedin
def user_loggedin(sender, **kwargs): """ collect metrics about user logins """ values = { 'value': 1, 'path': kwargs['request'].path, 'user_id': str(kwargs['user'].pk), 'username': kwargs['user'].username, } write('user_logins', values=values)
python
def user_loggedin(sender, **kwargs): """ collect metrics about user logins """ values = { 'value': 1, 'path': kwargs['request'].path, 'user_id': str(kwargs['user'].pk), 'username': kwargs['user'].username, } write('user_logins', values=values)
[ "def", "user_loggedin", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "values", "=", "{", "'value'", ":", "1", ",", "'path'", ":", "kwargs", "[", "'request'", "]", ".", "path", ",", "'user_id'", ":", "str", "(", "kwargs", "[", "'user'", "]", "....
collect metrics about user logins
[ "collect", "metrics", "about", "user", "logins" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/signals.py#L17-L25
train
52,217
ninuxorg/nodeshot
nodeshot/core/metrics/signals.py
user_deleted
def user_deleted(sender, **kwargs): """ collect metrics about new users signing up """ if kwargs.get('created'): write('user_variations', {'variation': 1}, tags={'action': 'created'}) write('user_count', {'total': User.objects.count()})
python
def user_deleted(sender, **kwargs): """ collect metrics about new users signing up """ if kwargs.get('created'): write('user_variations', {'variation': 1}, tags={'action': 'created'}) write('user_count', {'total': User.objects.count()})
[ "def", "user_deleted", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'created'", ")", ":", "write", "(", "'user_variations'", ",", "{", "'variation'", ":", "1", "}", ",", "tags", "=", "{", "'action'", ":", "'crea...
collect metrics about new users signing up
[ "collect", "metrics", "about", "new", "users", "signing", "up" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/signals.py#L36-L40
train
52,218
ninuxorg/nodeshot
nodeshot/community/participation/models/__init__.py
_node_rating_count
def _node_rating_count(self): """ Return node_rating_count record or create it if it does not exist usage: node = Node.objects.get(pk=1) node.rating_count """ try: return self.noderatingcount except ObjectDoesNotExist: node_rating_count = NodeRatingCount(node=self) node_rating_count.save() return node_rating_count
python
def _node_rating_count(self): """ Return node_rating_count record or create it if it does not exist usage: node = Node.objects.get(pk=1) node.rating_count """ try: return self.noderatingcount except ObjectDoesNotExist: node_rating_count = NodeRatingCount(node=self) node_rating_count.save() return node_rating_count
[ "def", "_node_rating_count", "(", "self", ")", ":", "try", ":", "return", "self", ".", "noderatingcount", "except", "ObjectDoesNotExist", ":", "node_rating_count", "=", "NodeRatingCount", "(", "node", "=", "self", ")", "node_rating_count", ".", "save", "(", ")",...
Return node_rating_count record or create it if it does not exist usage: node = Node.objects.get(pk=1) node.rating_count
[ "Return", "node_rating_count", "record", "or", "create", "it", "if", "it", "does", "not", "exist" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/__init__.py#L68-L82
train
52,219
ninuxorg/nodeshot
nodeshot/community/participation/models/__init__.py
_node_participation_settings
def _node_participation_settings(self): """ Return node_participation_settings record or create it if it does not exist usage: node = Node.objects.get(pk=1) node.participation_settings """ try: return self.node_participation_settings except ObjectDoesNotExist: node_participation_settings = NodeParticipationSettings(node=self) node_participation_settings.save() return node_participation_settings
python
def _node_participation_settings(self): """ Return node_participation_settings record or create it if it does not exist usage: node = Node.objects.get(pk=1) node.participation_settings """ try: return self.node_participation_settings except ObjectDoesNotExist: node_participation_settings = NodeParticipationSettings(node=self) node_participation_settings.save() return node_participation_settings
[ "def", "_node_participation_settings", "(", "self", ")", ":", "try", ":", "return", "self", ".", "node_participation_settings", "except", "ObjectDoesNotExist", ":", "node_participation_settings", "=", "NodeParticipationSettings", "(", "node", "=", "self", ")", "node_par...
Return node_participation_settings record or create it if it does not exist usage: node = Node.objects.get(pk=1) node.participation_settings
[ "Return", "node_participation_settings", "record", "or", "create", "it", "if", "it", "does", "not", "exist" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/__init__.py#L88-L102
train
52,220
ninuxorg/nodeshot
nodeshot/community/participation/models/__init__.py
_action_allowed
def _action_allowed(self, action): """ participation actions can be disabled on layer level, or disabled on a per node basis """ if getattr(self.layer.participation_settings, '{0}_allowed'.format(action)) is False: return False else: return getattr(self.participation_settings, '{0}_allowed'.format(action))
python
def _action_allowed(self, action): """ participation actions can be disabled on layer level, or disabled on a per node basis """ if getattr(self.layer.participation_settings, '{0}_allowed'.format(action)) is False: return False else: return getattr(self.participation_settings, '{0}_allowed'.format(action))
[ "def", "_action_allowed", "(", "self", ",", "action", ")", ":", "if", "getattr", "(", "self", ".", "layer", ".", "participation_settings", ",", "'{0}_allowed'", ".", "format", "(", "action", ")", ")", "is", "False", ":", "return", "False", "else", ":", "...
participation actions can be disabled on layer level, or disabled on a per node basis
[ "participation", "actions", "can", "be", "disabled", "on", "layer", "level", "or", "disabled", "on", "a", "per", "node", "basis" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/__init__.py#L107-L114
train
52,221
ninuxorg/nodeshot
nodeshot/community/participation/models/__init__.py
create_node_rating_counts_settings
def create_node_rating_counts_settings(sender, **kwargs): """ create node rating count and settings""" created = kwargs['created'] node = kwargs['instance'] if created: # create node_rating_count and settings # task will be executed in background unless settings.CELERY_ALWAYS_EAGER is True # if CELERY_ALWAYS_EAGER is False celery worker must be running otherwise task won't be executed create_related_object.delay(NodeRatingCount, {'node': node}) create_related_object.delay(NodeParticipationSettings, {'node': node})
python
def create_node_rating_counts_settings(sender, **kwargs): """ create node rating count and settings""" created = kwargs['created'] node = kwargs['instance'] if created: # create node_rating_count and settings # task will be executed in background unless settings.CELERY_ALWAYS_EAGER is True # if CELERY_ALWAYS_EAGER is False celery worker must be running otherwise task won't be executed create_related_object.delay(NodeRatingCount, {'node': node}) create_related_object.delay(NodeParticipationSettings, {'node': node})
[ "def", "create_node_rating_counts_settings", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "created", "=", "kwargs", "[", "'created'", "]", "node", "=", "kwargs", "[", "'instance'", "]", "if", "created", ":", "# create node_rating_count and settings", "# task ...
create node rating count and settings
[ "create", "node", "rating", "count", "and", "settings" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/__init__.py#L147-L156
train
52,222
ninuxorg/nodeshot
nodeshot/community/participation/models/__init__.py
create_layer_rating_settings
def create_layer_rating_settings(sender, **kwargs): """ create layer rating settings """ created = kwargs['created'] layer = kwargs['instance'] if created: # create layer participation settings # task will be executed in background unless settings.CELERY_ALWAYS_EAGER is True # if CELERY_ALWAYS_EAGER is False celery worker must be running otherwise task won't be executed create_related_object.delay(LayerParticipationSettings, {'layer': layer})
python
def create_layer_rating_settings(sender, **kwargs): """ create layer rating settings """ created = kwargs['created'] layer = kwargs['instance'] if created: # create layer participation settings # task will be executed in background unless settings.CELERY_ALWAYS_EAGER is True # if CELERY_ALWAYS_EAGER is False celery worker must be running otherwise task won't be executed create_related_object.delay(LayerParticipationSettings, {'layer': layer})
[ "def", "create_layer_rating_settings", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "created", "=", "kwargs", "[", "'created'", "]", "layer", "=", "kwargs", "[", "'instance'", "]", "if", "created", ":", "# create layer participation settings", "# task will be...
create layer rating settings
[ "create", "layer", "rating", "settings" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/__init__.py#L160-L168
train
52,223
ninuxorg/nodeshot
nodeshot/community/profiles/models/profile.py
Profile.needs_confirmation
def needs_confirmation(self): """ set is_active to False if needs email confirmation """ if EMAIL_CONFIRMATION: self.is_active = False self.save() return True else: return False
python
def needs_confirmation(self): """ set is_active to False if needs email confirmation """ if EMAIL_CONFIRMATION: self.is_active = False self.save() return True else: return False
[ "def", "needs_confirmation", "(", "self", ")", ":", "if", "EMAIL_CONFIRMATION", ":", "self", ".", "is_active", "=", "False", "self", ".", "save", "(", ")", "return", "True", "else", ":", "return", "False" ]
set is_active to False if needs email confirmation
[ "set", "is_active", "to", "False", "if", "needs", "email", "confirmation" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/profile.py#L124-L133
train
52,224
ninuxorg/nodeshot
nodeshot/community/profiles/models/profile.py
Profile.change_password
def change_password(self, new_password): """ Changes password and sends a signal """ self.set_password(new_password) self.save() password_changed.send(sender=self.__class__, user=self)
python
def change_password(self, new_password): """ Changes password and sends a signal """ self.set_password(new_password) self.save() password_changed.send(sender=self.__class__, user=self)
[ "def", "change_password", "(", "self", ",", "new_password", ")", ":", "self", ".", "set_password", "(", "new_password", ")", "self", ".", "save", "(", ")", "password_changed", ".", "send", "(", "sender", "=", "self", ".", "__class__", ",", "user", "=", "...
Changes password and sends a signal
[ "Changes", "password", "and", "sends", "a", "signal" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/profile.py#L135-L141
train
52,225
ninuxorg/nodeshot
nodeshot/community/notifications/models/user_settings.py
add_notifications
def add_notifications(myclass): """ Decorator which adds fields dynamically to User Notification Settings models. Each of the keys in the TEXTS dictionary are added as a field and DB column. """ for key, value in TEXTS.items(): # custom notifications cannot be disabled if 'custom' in [key, value]: continue field_type = USER_SETTING[key]['type'] if field_type == 'boolean': field = models.BooleanField(_(key), default=DEFAULT_BOOLEAN) elif field_type == 'distance': field = models.IntegerField( _(key), default=DEFAULT_DISTANCE, help_text=_('-1 (less than 0): disabled; 0: enabled for all;\ 1 (less than 0): enabled for those in the specified distance range (km)') ) field.geo_field = USER_SETTING[key]['geo_field'] field.name = field.column = field.attname = key field.user_setting_type = field_type setattr(myclass, key, field) myclass.add_to_class(key, field) return myclass
python
def add_notifications(myclass): """ Decorator which adds fields dynamically to User Notification Settings models. Each of the keys in the TEXTS dictionary are added as a field and DB column. """ for key, value in TEXTS.items(): # custom notifications cannot be disabled if 'custom' in [key, value]: continue field_type = USER_SETTING[key]['type'] if field_type == 'boolean': field = models.BooleanField(_(key), default=DEFAULT_BOOLEAN) elif field_type == 'distance': field = models.IntegerField( _(key), default=DEFAULT_DISTANCE, help_text=_('-1 (less than 0): disabled; 0: enabled for all;\ 1 (less than 0): enabled for those in the specified distance range (km)') ) field.geo_field = USER_SETTING[key]['geo_field'] field.name = field.column = field.attname = key field.user_setting_type = field_type setattr(myclass, key, field) myclass.add_to_class(key, field) return myclass
[ "def", "add_notifications", "(", "myclass", ")", ":", "for", "key", ",", "value", "in", "TEXTS", ".", "items", "(", ")", ":", "# custom notifications cannot be disabled", "if", "'custom'", "in", "[", "key", ",", "value", "]", ":", "continue", "field_type", "...
Decorator which adds fields dynamically to User Notification Settings models. Each of the keys in the TEXTS dictionary are added as a field and DB column.
[ "Decorator", "which", "adds", "fields", "dynamically", "to", "User", "Notification", "Settings", "models", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/user_settings.py#L7-L37
train
52,226
ninuxorg/nodeshot
nodeshot/community/profiles/serializers.py
LoginSerializer.validate
def validate(self, attrs): """ checks if login credentials are correct """ user = authenticate(**self.user_credentials(attrs)) if user: if user.is_active: self.instance = user else: raise serializers.ValidationError(_("This account is currently inactive.")) else: error = _("Invalid login credentials.") raise serializers.ValidationError(error) return attrs
python
def validate(self, attrs): """ checks if login credentials are correct """ user = authenticate(**self.user_credentials(attrs)) if user: if user.is_active: self.instance = user else: raise serializers.ValidationError(_("This account is currently inactive.")) else: error = _("Invalid login credentials.") raise serializers.ValidationError(error) return attrs
[ "def", "validate", "(", "self", ",", "attrs", ")", ":", "user", "=", "authenticate", "(", "*", "*", "self", ".", "user_credentials", "(", "attrs", ")", ")", "if", "user", ":", "if", "user", ".", "is_active", ":", "self", ".", "instance", "=", "user",...
checks if login credentials are correct
[ "checks", "if", "login", "credentials", "are", "correct" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L89-L101
train
52,227
ninuxorg/nodeshot
nodeshot/community/profiles/serializers.py
SocialLinkSerializer.get_details
def get_details(self, obj): """ return detail url """ return reverse('api_user_social_links_detail', args=[obj.user.username, obj.pk], request=self.context.get('request'), format=self.context.get('format'))
python
def get_details(self, obj): """ return detail url """ return reverse('api_user_social_links_detail', args=[obj.user.username, obj.pk], request=self.context.get('request'), format=self.context.get('format'))
[ "def", "get_details", "(", "self", ",", "obj", ")", ":", "return", "reverse", "(", "'api_user_social_links_detail'", ",", "args", "=", "[", "obj", ".", "user", ".", "username", ",", "obj", ".", "pk", "]", ",", "request", "=", "self", ".", "context", "....
return detail url
[ "return", "detail", "url" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L108-L113
train
52,228
ninuxorg/nodeshot
nodeshot/community/profiles/serializers.py
ProfileSerializer.get_location
def get_location(self, obj): """ return user's location """ if not obj.city and not obj.country: return None elif obj.city and obj.country: return '%s, %s' % (obj.city, obj.country) elif obj.city or obj.country: return obj.city or obj.country
python
def get_location(self, obj): """ return user's location """ if not obj.city and not obj.country: return None elif obj.city and obj.country: return '%s, %s' % (obj.city, obj.country) elif obj.city or obj.country: return obj.city or obj.country
[ "def", "get_location", "(", "self", ",", "obj", ")", ":", "if", "not", "obj", ".", "city", "and", "not", "obj", ".", "country", ":", "return", "None", "elif", "obj", ".", "city", "and", "obj", ".", "country", ":", "return", "'%s, %s'", "%", "(", "o...
return user's location
[ "return", "user", "s", "location" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L147-L154
train
52,229
ninuxorg/nodeshot
nodeshot/community/profiles/serializers.py
ChangePasswordSerializer.validate_current_password
def validate_current_password(self, value): """ current password check """ if self.instance and self.instance.has_usable_password() and not self.instance.check_password(value): raise serializers.ValidationError(_('Current password is not correct')) return value
python
def validate_current_password(self, value): """ current password check """ if self.instance and self.instance.has_usable_password() and not self.instance.check_password(value): raise serializers.ValidationError(_('Current password is not correct')) return value
[ "def", "validate_current_password", "(", "self", ",", "value", ")", ":", "if", "self", ".", "instance", "and", "self", ".", "instance", ".", "has_usable_password", "(", ")", "and", "not", "self", ".", "instance", ".", "check_password", "(", "value", ")", "...
current password check
[ "current", "password", "check" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L264-L268
train
52,230
ninuxorg/nodeshot
nodeshot/community/profiles/models/password_reset.py
PasswordResetManager.create_for_user
def create_for_user(self, user): """ create password reset for specified user """ # support passing email address too if type(user) is unicode: from .profile import Profile as User user = User.objects.get(email=user) temp_key = token_generator.make_token(user) # save it to the password reset model password_reset = PasswordReset(user=user, temp_key=temp_key) password_reset.save() # send the password reset email subject = _("Password reset email sent") message = render_to_string("profiles/email_messages/password_reset_key_message.txt", { "user": user, "uid": int_to_base36(user.id), "temp_key": temp_key, "site_url": settings.SITE_URL, "site_name": settings.SITE_NAME }) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email]) return password_reset
python
def create_for_user(self, user): """ create password reset for specified user """ # support passing email address too if type(user) is unicode: from .profile import Profile as User user = User.objects.get(email=user) temp_key = token_generator.make_token(user) # save it to the password reset model password_reset = PasswordReset(user=user, temp_key=temp_key) password_reset.save() # send the password reset email subject = _("Password reset email sent") message = render_to_string("profiles/email_messages/password_reset_key_message.txt", { "user": user, "uid": int_to_base36(user.id), "temp_key": temp_key, "site_url": settings.SITE_URL, "site_name": settings.SITE_NAME }) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email]) return password_reset
[ "def", "create_for_user", "(", "self", ",", "user", ")", ":", "# support passing email address too", "if", "type", "(", "user", ")", "is", "unicode", ":", "from", ".", "profile", "import", "Profile", "as", "User", "user", "=", "User", ".", "objects", ".", ...
create password reset for specified user
[ "create", "password", "reset", "for", "specified", "user" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/password_reset.py#L17-L41
train
52,231
ninuxorg/nodeshot
nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py
Command.handle
def handle(self, *args, **options): """ execute synchronize command """ self.options = options delete = False try: # blank line self.stdout.write('\r\n') # store verbosity level in instance attribute for later use self.verbosity = int(self.options.get('verbosity')) self.verbose('disabling signals (notififcations, websocket alerts)') pause_disconnectable_signals() self.check_status_mapping() self.retrieve_nodes() self.extract_users() self.import_admins() self.import_users() self.import_nodes() self.check_deleted_nodes() self.import_devices() self.import_interfaces() self.import_links() self.check_deleted_links() self.import_contacts() self.confirm_operation_completed() resume_disconnectable_signals() self.verbose('re-enabling signals (notififcations, websocket alerts)') except KeyboardInterrupt: self.message('\n\nOperation cancelled...') delete = True except Exception as e: tb = traceback.format_exc() delete = True # rollback database transaction transaction.rollback() self.message('Got exception:\n\n%s' % tb) error('import_old_nodeshot: %s' % e) if delete: self.delete_imported_data()
python
def handle(self, *args, **options): """ execute synchronize command """ self.options = options delete = False try: # blank line self.stdout.write('\r\n') # store verbosity level in instance attribute for later use self.verbosity = int(self.options.get('verbosity')) self.verbose('disabling signals (notififcations, websocket alerts)') pause_disconnectable_signals() self.check_status_mapping() self.retrieve_nodes() self.extract_users() self.import_admins() self.import_users() self.import_nodes() self.check_deleted_nodes() self.import_devices() self.import_interfaces() self.import_links() self.check_deleted_links() self.import_contacts() self.confirm_operation_completed() resume_disconnectable_signals() self.verbose('re-enabling signals (notififcations, websocket alerts)') except KeyboardInterrupt: self.message('\n\nOperation cancelled...') delete = True except Exception as e: tb = traceback.format_exc() delete = True # rollback database transaction transaction.rollback() self.message('Got exception:\n\n%s' % tb) error('import_old_nodeshot: %s' % e) if delete: self.delete_imported_data()
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "self", ".", "options", "=", "options", "delete", "=", "False", "try", ":", "# blank line", "self", ".", "stdout", ".", "write", "(", "'\\r\\n'", ")", "# store verbosit...
execute synchronize command
[ "execute", "synchronize", "command" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L129-L173
train
52,232
ninuxorg/nodeshot
nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py
Command.check_status_mapping
def check_status_mapping(self): """ ensure status map does not contain status values which are not present in DB """ self.verbose('checking status mapping...') if not self.status_mapping: self.message('no status mapping found') return for old_val, new_val in self.status_mapping.iteritems(): try: # look up by slug if new_val is string if isinstance(new_val, basestring): lookup = {'slug': new_val} # lookup by primary key otherwise else: lookup = {'pk': new_val} status = Status.objects.get(**lookup) self.status_mapping[old_val] = status.id except Status.DoesNotExist: raise ImproperlyConfigured('Error! Status with slug %s not found in the database' % new_val) self.verbose('status map correct')
python
def check_status_mapping(self): """ ensure status map does not contain status values which are not present in DB """ self.verbose('checking status mapping...') if not self.status_mapping: self.message('no status mapping found') return for old_val, new_val in self.status_mapping.iteritems(): try: # look up by slug if new_val is string if isinstance(new_val, basestring): lookup = {'slug': new_val} # lookup by primary key otherwise else: lookup = {'pk': new_val} status = Status.objects.get(**lookup) self.status_mapping[old_val] = status.id except Status.DoesNotExist: raise ImproperlyConfigured('Error! Status with slug %s not found in the database' % new_val) self.verbose('status map correct')
[ "def", "check_status_mapping", "(", "self", ")", ":", "self", ".", "verbose", "(", "'checking status mapping...'", ")", "if", "not", "self", ".", "status_mapping", ":", "self", ".", "message", "(", "'no status mapping found'", ")", "return", "for", "old_val", ",...
ensure status map does not contain status values which are not present in DB
[ "ensure", "status", "map", "does", "not", "contain", "status", "values", "which", "are", "not", "present", "in", "DB" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L299-L320
train
52,233
ninuxorg/nodeshot
nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py
Command.retrieve_nodes
def retrieve_nodes(self): """ retrieve nodes from old mysql DB """ self.verbose('retrieving nodes from old mysql DB...') self.old_nodes = list(OldNode.objects.all()) self.message('retrieved %d nodes' % len(self.old_nodes))
python
def retrieve_nodes(self): """ retrieve nodes from old mysql DB """ self.verbose('retrieving nodes from old mysql DB...') self.old_nodes = list(OldNode.objects.all()) self.message('retrieved %d nodes' % len(self.old_nodes))
[ "def", "retrieve_nodes", "(", "self", ")", ":", "self", ".", "verbose", "(", "'retrieving nodes from old mysql DB...'", ")", "self", ".", "old_nodes", "=", "list", "(", "OldNode", ".", "objects", ".", "all", "(", ")", ")", "self", ".", "message", "(", "'re...
retrieve nodes from old mysql DB
[ "retrieve", "nodes", "from", "old", "mysql", "DB" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L325-L330
train
52,234
ninuxorg/nodeshot
nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py
Command.extract_users
def extract_users(self): """ extract user info """ email_set = set() users_dict = {} self.verbose('going to extract user information from retrieved nodes...') for node in self.old_nodes: email_set.add(node.email) if node.email not in users_dict: users_dict[node.email] = { 'owner': node.owner } self.email_set = email_set self.users_dict = users_dict self.verbose('%d users extracted' % len(email_set))
python
def extract_users(self): """ extract user info """ email_set = set() users_dict = {} self.verbose('going to extract user information from retrieved nodes...') for node in self.old_nodes: email_set.add(node.email) if node.email not in users_dict: users_dict[node.email] = { 'owner': node.owner } self.email_set = email_set self.users_dict = users_dict self.verbose('%d users extracted' % len(email_set))
[ "def", "extract_users", "(", "self", ")", ":", "email_set", "=", "set", "(", ")", "users_dict", "=", "{", "}", "self", ".", "verbose", "(", "'going to extract user information from retrieved nodes...'", ")", "for", "node", "in", "self", ".", "old_nodes", ":", ...
extract user info
[ "extract", "user", "info" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L332-L350
train
52,235
ninuxorg/nodeshot
nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py
Command.import_admins
def import_admins(self): """ save admins to local DB """ self.message('saving admins into local DB') saved_admins = [] for olduser in OldUser.objects.all(): try: user = User.objects.get(Q(username=olduser.username) | Q(email=olduser.email)) except User.DoesNotExist: user = User() except User.MultipleObjectsReturned: continue user.username = olduser.username user.password = olduser.password user.first_name = olduser.first_name user.last_name = olduser.last_name user.email = olduser.email user.is_active = olduser.is_active user.is_staff = olduser.is_staff user.is_superuser = olduser.is_superuser user.date_joined = olduser.date_joined user.full_clean() user.save(sync_emailaddress=False) saved_admins.append(user) # mark email address as confirmed if feature is enabled if EMAIL_CONFIRMATION and EmailAddress.objects.filter(email=user.email).count() is 0: try: email_address = EmailAddress(user=user, email=user.email, verified=True, primary=True) email_address.full_clean() email_address.save() except Exception: tb = traceback.format_exc() self.message('Could not save email address for user %s, got exception:\n\n%s' % (user.username, tb)) self.message('saved %d admins into local DB' % len(saved_admins)) self.saved_admins = saved_admins
python
def import_admins(self): """ save admins to local DB """ self.message('saving admins into local DB') saved_admins = [] for olduser in OldUser.objects.all(): try: user = User.objects.get(Q(username=olduser.username) | Q(email=olduser.email)) except User.DoesNotExist: user = User() except User.MultipleObjectsReturned: continue user.username = olduser.username user.password = olduser.password user.first_name = olduser.first_name user.last_name = olduser.last_name user.email = olduser.email user.is_active = olduser.is_active user.is_staff = olduser.is_staff user.is_superuser = olduser.is_superuser user.date_joined = olduser.date_joined user.full_clean() user.save(sync_emailaddress=False) saved_admins.append(user) # mark email address as confirmed if feature is enabled if EMAIL_CONFIRMATION and EmailAddress.objects.filter(email=user.email).count() is 0: try: email_address = EmailAddress(user=user, email=user.email, verified=True, primary=True) email_address.full_clean() email_address.save() except Exception: tb = traceback.format_exc() self.message('Could not save email address for user %s, got exception:\n\n%s' % (user.username, tb)) self.message('saved %d admins into local DB' % len(saved_admins)) self.saved_admins = saved_admins
[ "def", "import_admins", "(", "self", ")", ":", "self", ".", "message", "(", "'saving admins into local DB'", ")", "saved_admins", "=", "[", "]", "for", "olduser", "in", "OldUser", ".", "objects", ".", "all", "(", ")", ":", "try", ":", "user", "=", "User"...
save admins to local DB
[ "save", "admins", "to", "local", "DB" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L352-L390
train
52,236
ninuxorg/nodeshot
nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py
Command.import_users
def import_users(self): """ save users to local DB """ self.message('saving users into local DB') saved_users = self.saved_admins # loop over all extracted unique email addresses for email in self.email_set: owner = self.users_dict[email].get('owner') # if owner is not specified, build username from email if owner.strip() == '': owner, domain = email.split('@') # replace any points with a space owner = owner.replace('.', ' ') # if owner has a space, assume he specified first and last name if ' ' in owner: owner_parts = owner.split(' ') first_name = owner_parts[0] last_name = owner_parts[1] else: first_name = owner last_name = '' # username must be slugified otherwise won't get into the DB username = slugify(owner) # check if user exists first try: # try looking by email user = User.objects.get(email=email) except User.DoesNotExist: # otherwise init new user = User() user.username = username # generate new password only for new users user.password = self.generate_random_password() user.is_active = True # we'll create one user for each unique email address we've got user.first_name = first_name.capitalize() user.last_name = last_name.capitalize() user.email = email # extract date joined from old nodes # find the oldest node of this user oldest_node = OldNode.objects.filter(email=email).order_by('added')[0] user.date_joined = oldest_node.added # be sure username is unique counter = 1 original_username = username while True: # do this check only if user is new if not user.pk and User.objects.filter(username=user.username).count() > 0: counter += 1 user.username = '%s%d' % (original_username, counter) else: break try: # validate data and save user.full_clean() user.save(sync_emailaddress=False) except Exception: # if user already exists use that instance if(User.objects.filter(email=email).count() == 1): user = User.objects.get(email=email) # otherwise report error else: tb = traceback.format_exc() self.message('Could not save user %s, got exception:\n\n%s' % (user.username, tb)) continue # if we got a user to add if user: # store id self.users_dict[email]['id'] = user.id # append to saved users saved_users.append(user) self.verbose('Saved user %s (%s) with email <%s>' % (user.username, user.get_full_name(), user.email)) # mark email address as confirmed if feature is enabled if EMAIL_CONFIRMATION and EmailAddress.objects.filter(email=user.email).count() is 0: try: email_address = EmailAddress(user=user, email=user.email, verified=True, primary=True) email_address.full_clean() email_address.save() except Exception: tb = traceback.format_exc() self.message('Could not save email address for user %s, got exception:\n\n%s' % (user.username, tb)) self.message('saved %d users into local DB' % len(saved_users)) self.saved_users = saved_users
python
def import_users(self): """ save users to local DB """ self.message('saving users into local DB') saved_users = self.saved_admins # loop over all extracted unique email addresses for email in self.email_set: owner = self.users_dict[email].get('owner') # if owner is not specified, build username from email if owner.strip() == '': owner, domain = email.split('@') # replace any points with a space owner = owner.replace('.', ' ') # if owner has a space, assume he specified first and last name if ' ' in owner: owner_parts = owner.split(' ') first_name = owner_parts[0] last_name = owner_parts[1] else: first_name = owner last_name = '' # username must be slugified otherwise won't get into the DB username = slugify(owner) # check if user exists first try: # try looking by email user = User.objects.get(email=email) except User.DoesNotExist: # otherwise init new user = User() user.username = username # generate new password only for new users user.password = self.generate_random_password() user.is_active = True # we'll create one user for each unique email address we've got user.first_name = first_name.capitalize() user.last_name = last_name.capitalize() user.email = email # extract date joined from old nodes # find the oldest node of this user oldest_node = OldNode.objects.filter(email=email).order_by('added')[0] user.date_joined = oldest_node.added # be sure username is unique counter = 1 original_username = username while True: # do this check only if user is new if not user.pk and User.objects.filter(username=user.username).count() > 0: counter += 1 user.username = '%s%d' % (original_username, counter) else: break try: # validate data and save user.full_clean() user.save(sync_emailaddress=False) except Exception: # if user already exists use that instance if(User.objects.filter(email=email).count() == 1): user = User.objects.get(email=email) # otherwise report error else: tb = traceback.format_exc() self.message('Could not save user %s, got exception:\n\n%s' % (user.username, tb)) continue # if we got a user to add if user: # store id self.users_dict[email]['id'] = user.id # append to saved users saved_users.append(user) self.verbose('Saved user %s (%s) with email <%s>' % (user.username, user.get_full_name(), user.email)) # mark email address as confirmed if feature is enabled if EMAIL_CONFIRMATION and EmailAddress.objects.filter(email=user.email).count() is 0: try: email_address = EmailAddress(user=user, email=user.email, verified=True, primary=True) email_address.full_clean() email_address.save() except Exception: tb = traceback.format_exc() self.message('Could not save email address for user %s, got exception:\n\n%s' % (user.username, tb)) self.message('saved %d users into local DB' % len(saved_users)) self.saved_users = saved_users
[ "def", "import_users", "(", "self", ")", ":", "self", ".", "message", "(", "'saving users into local DB'", ")", "saved_users", "=", "self", ".", "saved_admins", "# loop over all extracted unique email addresses", "for", "email", "in", "self", ".", "email_set", ":", ...
save users to local DB
[ "save", "users", "to", "local", "DB" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L392-L486
train
52,237
ninuxorg/nodeshot
nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py
Command.check_deleted_nodes
def check_deleted_nodes(self): """ delete imported nodes that are not present in the old database """ imported_nodes = Node.objects.filter(data__contains=['imported']) deleted_nodes = [] for node in imported_nodes: if OldNode.objects.filter(pk=node.pk).count() == 0: user = node.user deleted_nodes.append(node) node.delete() # delete user if there are no other nodes assigned to her if user.node_set.count() == 0: user.delete() if len(deleted_nodes) > 0: self.message('deleted %d imported nodes from local DB' % len(deleted_nodes)) self.deleted_nodes = deleted_nodes
python
def check_deleted_nodes(self): """ delete imported nodes that are not present in the old database """ imported_nodes = Node.objects.filter(data__contains=['imported']) deleted_nodes = [] for node in imported_nodes: if OldNode.objects.filter(pk=node.pk).count() == 0: user = node.user deleted_nodes.append(node) node.delete() # delete user if there are no other nodes assigned to her if user.node_set.count() == 0: user.delete() if len(deleted_nodes) > 0: self.message('deleted %d imported nodes from local DB' % len(deleted_nodes)) self.deleted_nodes = deleted_nodes
[ "def", "check_deleted_nodes", "(", "self", ")", ":", "imported_nodes", "=", "Node", ".", "objects", ".", "filter", "(", "data__contains", "=", "[", "'imported'", "]", ")", "deleted_nodes", "=", "[", "]", "for", "node", "in", "imported_nodes", ":", "if", "O...
delete imported nodes that are not present in the old database
[ "delete", "imported", "nodes", "that", "are", "not", "present", "in", "the", "old", "database" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L566-L582
train
52,238
ninuxorg/nodeshot
nodeshot/community/notifications/signals.py
create_settings
def create_settings(sender, **kwargs): """ create user notification settings on user creation """ created = kwargs['created'] user = kwargs['instance'] if created: UserWebNotificationSettings.objects.create(user=user) UserEmailNotificationSettings.objects.create(user=user)
python
def create_settings(sender, **kwargs): """ create user notification settings on user creation """ created = kwargs['created'] user = kwargs['instance'] if created: UserWebNotificationSettings.objects.create(user=user) UserEmailNotificationSettings.objects.create(user=user)
[ "def", "create_settings", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "created", "=", "kwargs", "[", "'created'", "]", "user", "=", "kwargs", "[", "'instance'", "]", "if", "created", ":", "UserWebNotificationSettings", ".", "objects", ".", "create", ...
create user notification settings on user creation
[ "create", "user", "notification", "settings", "on", "user", "creation" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/signals.py#L11-L17
train
52,239
ninuxorg/nodeshot
nodeshot/interop/sync/synchronizers/geojson.py
GeoJson.parse
def parse(self): """ parse geojson and ensure is collection """ try: self.parsed_data = json.loads(self.data) except UnicodeError as e: self.parsed_data = json.loads(self.data.decode('latin1')) except Exception as e: raise Exception('Error while converting response from JSON to python. %s' % e) if self.parsed_data.get('type', '') != 'FeatureCollection': raise Exception('GeoJson synchronizer expects a FeatureCollection object at root level') self.parsed_data = self.parsed_data['features']
python
def parse(self): """ parse geojson and ensure is collection """ try: self.parsed_data = json.loads(self.data) except UnicodeError as e: self.parsed_data = json.loads(self.data.decode('latin1')) except Exception as e: raise Exception('Error while converting response from JSON to python. %s' % e) if self.parsed_data.get('type', '') != 'FeatureCollection': raise Exception('GeoJson synchronizer expects a FeatureCollection object at root level') self.parsed_data = self.parsed_data['features']
[ "def", "parse", "(", "self", ")", ":", "try", ":", "self", ".", "parsed_data", "=", "json", ".", "loads", "(", "self", ".", "data", ")", "except", "UnicodeError", "as", "e", ":", "self", ".", "parsed_data", "=", "json", ".", "loads", "(", "self", "...
parse geojson and ensure is collection
[ "parse", "geojson", "and", "ensure", "is", "collection" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/geojson.py#L11-L23
train
52,240
ninuxorg/nodeshot
nodeshot/community/notifications/management/commands/purge_notifications.py
Command.retrieve_old_notifications
def retrieve_old_notifications(self): """ Retrieve notifications older than X days, where X is specified in settings """ date = ago(days=DELETE_OLD) return Notification.objects.filter(added__lte=date)
python
def retrieve_old_notifications(self): """ Retrieve notifications older than X days, where X is specified in settings """ date = ago(days=DELETE_OLD) return Notification.objects.filter(added__lte=date)
[ "def", "retrieve_old_notifications", "(", "self", ")", ":", "date", "=", "ago", "(", "days", "=", "DELETE_OLD", ")", "return", "Notification", ".", "objects", ".", "filter", "(", "added__lte", "=", "date", ")" ]
Retrieve notifications older than X days, where X is specified in settings
[ "Retrieve", "notifications", "older", "than", "X", "days", "where", "X", "is", "specified", "in", "settings" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/management/commands/purge_notifications.py#L12-L19
train
52,241
ninuxorg/nodeshot
nodeshot/interop/sync/tasks.py
push_changes_to_external_layers
def push_changes_to_external_layers(node, external_layer, operation): """ Sync other applications through their APIs by performing updates, adds or deletes. This method is designed to be performed asynchronously, avoiding blocking the user when he changes data on the local DB. :param node: the node which should be updated on the external layer. :type node: Node model instance :param operation: the operation to perform (add, change, delete) :type operation: string """ # putting the model inside prevents circular imports # subsequent imports go and look into sys.modules before reimporting the module again # so performance is not affected from nodeshot.core.nodes.models import Node # get node because for some reason the node instance object is not passed entirely, # pheraphs because objects are serialized by celery or transport/queuing mechanism if not isinstance(node, basestring): node = Node.objects.get(pk=node.pk) # import synchronizer synchronizer = import_by_path(external_layer.synchronizer_path) # create instance instance = synchronizer(external_layer.layer) # call method only if supported if hasattr(instance, operation): getattr(instance, operation)(node)
python
def push_changes_to_external_layers(node, external_layer, operation): """ Sync other applications through their APIs by performing updates, adds or deletes. This method is designed to be performed asynchronously, avoiding blocking the user when he changes data on the local DB. :param node: the node which should be updated on the external layer. :type node: Node model instance :param operation: the operation to perform (add, change, delete) :type operation: string """ # putting the model inside prevents circular imports # subsequent imports go and look into sys.modules before reimporting the module again # so performance is not affected from nodeshot.core.nodes.models import Node # get node because for some reason the node instance object is not passed entirely, # pheraphs because objects are serialized by celery or transport/queuing mechanism if not isinstance(node, basestring): node = Node.objects.get(pk=node.pk) # import synchronizer synchronizer = import_by_path(external_layer.synchronizer_path) # create instance instance = synchronizer(external_layer.layer) # call method only if supported if hasattr(instance, operation): getattr(instance, operation)(node)
[ "def", "push_changes_to_external_layers", "(", "node", ",", "external_layer", ",", "operation", ")", ":", "# putting the model inside prevents circular imports", "# subsequent imports go and look into sys.modules before reimporting the module again", "# so performance is not affected", "fr...
Sync other applications through their APIs by performing updates, adds or deletes. This method is designed to be performed asynchronously, avoiding blocking the user when he changes data on the local DB. :param node: the node which should be updated on the external layer. :type node: Node model instance :param operation: the operation to perform (add, change, delete) :type operation: string
[ "Sync", "other", "applications", "through", "their", "APIs", "by", "performing", "updates", "adds", "or", "deletes", ".", "This", "method", "is", "designed", "to", "be", "performed", "asynchronously", "avoiding", "blocking", "the", "user", "when", "he", "changes...
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/tasks.py#L18-L43
train
52,242
ninuxorg/nodeshot
nodeshot/core/websockets/tasks.py
send_message
def send_message(message, pipe='public'): """ writes message to pipe """ if pipe not in ['public', 'private']: raise ValueError('pipe argument can be only "public" or "private"') else: pipe = pipe.upper() pipe_path = PUBLIC_PIPE if pipe == 'PUBLIC' else PRIVATE_PIPE # create file if it doesn't exist, append contents pipeout = open(pipe_path, 'a') pipeout.write('%s\n' % message) pipeout.close()
python
def send_message(message, pipe='public'): """ writes message to pipe """ if pipe not in ['public', 'private']: raise ValueError('pipe argument can be only "public" or "private"') else: pipe = pipe.upper() pipe_path = PUBLIC_PIPE if pipe == 'PUBLIC' else PRIVATE_PIPE # create file if it doesn't exist, append contents pipeout = open(pipe_path, 'a') pipeout.write('%s\n' % message) pipeout.close()
[ "def", "send_message", "(", "message", ",", "pipe", "=", "'public'", ")", ":", "if", "pipe", "not", "in", "[", "'public'", ",", "'private'", "]", ":", "raise", "ValueError", "(", "'pipe argument can be only \"public\" or \"private\"'", ")", "else", ":", "pipe", ...
writes message to pipe
[ "writes", "message", "to", "pipe" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/tasks.py#L6-L21
train
52,243
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 required if not email: message = _("""your social account needs to have a verified email address in order to proceed.""") raise AuthFailed(backend, message) # Avoid hitting field max length if email and len(email) > 75: original_email = email email = '' return { 'user': UserSocialAuth.create_user(username=username, email=email, sync_emailaddress=False), 'original_email': original_email, 'is_new': True }
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 required if not email: message = _("""your social account needs to have a verified email address in order to proceed.""") raise AuthFailed(backend, message) # Avoid hitting field max length if email and len(email) > 75: original_email = email email = '' return { 'user': UserSocialAuth.create_user(username=username, email=email, sync_emailaddress=False), 'original_email': original_email, 'is_new': True }
[ "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", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/social_auth_extra/pipeline.py#L13-L37
train
52,244
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 if kwargs['is_new'] and EMAIL_CONFIRMATION: from ..models import EmailAddress # check if email exist before creating it # we might be associating an exisiting user if EmailAddress.objects.filter(email=user.email).count() < 1: EmailAddress.objects.create(user=user, email=user.email, verified=True, primary=True) if social_user: extra_data = backend.extra_data(user, uid, response, details) if kwargs.get('original_email') and 'email' not in extra_data: extra_data['email'] = kwargs.get('original_email') # update extra data if anything has changed if extra_data and social_user.extra_data != extra_data: if social_user.extra_data: social_user.extra_data.update(extra_data) else: social_user.extra_data = extra_data social_user.save() # fetch additional data from facebook on creation if backend.name == 'facebook' and kwargs['is_new']: response = json.loads(requests.get('https://graph.facebook.com/%s?access_token=%s' % (extra_data['id'], extra_data['access_token'])).content) try: user.city, user.country = response.get('hometown').get('name').split(', ') except (AttributeError, TypeError): pass try: user.birth_date = datetime.strptime(response.get('birthday'), '%m/%d/%Y').date() except (AttributeError, TypeError): pass user.save() return {'social_user': social_user}
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 if kwargs['is_new'] and EMAIL_CONFIRMATION: from ..models import EmailAddress # check if email exist before creating it # we might be associating an exisiting user if EmailAddress.objects.filter(email=user.email).count() < 1: EmailAddress.objects.create(user=user, email=user.email, verified=True, primary=True) if social_user: extra_data = backend.extra_data(user, uid, response, details) if kwargs.get('original_email') and 'email' not in extra_data: extra_data['email'] = kwargs.get('original_email') # update extra data if anything has changed if extra_data and social_user.extra_data != extra_data: if social_user.extra_data: social_user.extra_data.update(extra_data) else: social_user.extra_data = extra_data social_user.save() # fetch additional data from facebook on creation if backend.name == 'facebook' and kwargs['is_new']: response = json.loads(requests.get('https://graph.facebook.com/%s?access_token=%s' % (extra_data['id'], extra_data['access_token'])).content) try: user.city, user.country = response.get('hometown').get('name').split(', ') except (AttributeError, TypeError): pass try: user.birth_date = datetime.strptime(response.get('birthday'), '%m/%d/%Y').date() except (AttributeError, TypeError): pass user.save() return {'social_user': social_user}
[ "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", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/social_auth_extra/pipeline.py#L40-L79
train
52,245
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] elif self.content_type.name == 'layer': to = [self.to.email] # layer case is slightly special, mantainers need to be notified as well # TODO: consider making the mantainers able to switch off notifications for mantainer in self.to.mantainers.all().only('email'): to += [mantainer.email] else: to = [self.to.email] context = { 'sender_name': self.from_name, 'sender_email': self.from_email, 'message': self.message, 'site': settings.SITE_NAME, 'object_type': self.content_type.name, 'object_name': str(self.to) } message = render_to_string('mailing/inward_message.txt', context) email = EmailMessage( # subject _('Contact request from %(sender_name)s - %(site)s') % context, # message message, # from settings.DEFAULT_FROM_EMAIL, # to to, # reply-to header headers={'Reply-To': self.from_email} ) import socket # try sending email try: email.send() self.status = 1 # if error except socket.error as e: # log the error import logging log = logging.getLogger(__name__) error_msg = 'nodeshot.community.mailing.models.inward.send(): %s' % e log.error(error_msg) # set status of the instance as "error" self.status = -1
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] elif self.content_type.name == 'layer': to = [self.to.email] # layer case is slightly special, mantainers need to be notified as well # TODO: consider making the mantainers able to switch off notifications for mantainer in self.to.mantainers.all().only('email'): to += [mantainer.email] else: to = [self.to.email] context = { 'sender_name': self.from_name, 'sender_email': self.from_email, 'message': self.message, 'site': settings.SITE_NAME, 'object_type': self.content_type.name, 'object_name': str(self.to) } message = render_to_string('mailing/inward_message.txt', context) email = EmailMessage( # subject _('Contact request from %(sender_name)s - %(site)s') % context, # message message, # from settings.DEFAULT_FROM_EMAIL, # to to, # reply-to header headers={'Reply-To': self.from_email} ) import socket # try sending email try: email.send() self.status = 1 # if error except socket.error as e: # log the error import logging log = logging.getLogger(__name__) error_msg = 'nodeshot.community.mailing.models.inward.send(): %s' % e log.error(error_msg) # set status of the instance as "error" self.status = -1
[ "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...
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/inward.py#L64-L116
train
52,246
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] else: return queryset[0:n]
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] else: return queryset[0:n]
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/managers.py#L18-L28
train
52,247
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: value = ACCESS_LEVELS.get(access_level) # return queryset return self.filter(access_level__lte=value)
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: value = ACCESS_LEVELS.get(access_level) # return queryset return self.filter(access_level__lte=value)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/managers.py#L45-L54
train
52,248
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 default statuses first for status in self.__class__.objects.filter(is_default=True): status.is_default = False status.save(ignore_default_check=True) super(Status, self).save(*args, **kwargs) # in case there are no default statuses, make this one as the default one if self.__class__.objects.filter(is_default=True).count() == 0 and not ignore_default_check: self.is_default = True self.save() # update __current_status self._current_is_default = self.is_default
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 default statuses first for status in self.__class__.objects.filter(is_default=True): status.is_default = False status.save(ignore_default_check=True) super(Status, self).save(*args, **kwargs) # in case there are no default statuses, make this one as the default one if self.__class__.objects.filter(is_default=True).count() == 0 and not ignore_default_check: self.is_default = True self.save() # update __current_status self._current_is_default = self.is_default
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/status.py#L56-L73
train
52,249
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 except LayerExternal.DoesNotExist: external = False # override view get_nodes method if we have a custom one if external and self.layer.is_external and hasattr(external, 'get_nodes'): return external.get_nodes(self.__class__.__name__, request.query_params) # otherwise return the standard one else: return (self.list(request, *args, **kwargs)).data LayerNodeListMixin.get_nodes = get_nodes
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 except LayerExternal.DoesNotExist: external = False # override view get_nodes method if we have a custom one if external and self.layer.is_external and hasattr(external, 'get_nodes'): return external.get_nodes(self.__class__.__name__, request.query_params) # otherwise return the standard one else: return (self.list(request, *args, **kwargs)).data LayerNodeListMixin.get_nodes = get_nodes
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/apps.py#L7-L24
train
52,250
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_name='tasks') return app
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_name='tasks') return app
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/conf/celery.py#L26-L32
train
52,251
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 will contain django's email objects emails = [] # prepare text plain if necessary if OUTWARD_HTML: # store plain text in var html_content = self.message # set EmailClass to EmailMultiAlternatives EmailClass = EmailMultiAlternatives else: EmailClass = EmailMessage # default message is plain text message = strip_tags(self.message) # loop over recipients and fill "emails" list for recipient in recipients: msg = EmailClass( # subject self.subject, # message message, # from settings.DEFAULT_FROM_EMAIL, # to [recipient], ) if OUTWARD_HTML: msg.attach_alternative(html_content, "text/html") # prepare email object emails.append(msg) # try sending email try: # counter will count how many emails have been sent counter = 0 for email in emails: # if step reached if counter == OUTWARD_STEP: # reset counter counter = 0 # sleep time.sleep(OUTWARD_DELAY) # send email email.send() # increase counter counter += 1 # if error (connection refused, SMTP down) except socket.error as e: # log the error from logging import error error('nodeshot.core.mailing.models.outward.send(): %s' % e) # set status of the instance as "error" self.status = OUTWARD_STATUS.get('error') # change status self.status = OUTWARD_STATUS.get('sent') # save self.save()
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 will contain django's email objects emails = [] # prepare text plain if necessary if OUTWARD_HTML: # store plain text in var html_content = self.message # set EmailClass to EmailMultiAlternatives EmailClass = EmailMultiAlternatives else: EmailClass = EmailMessage # default message is plain text message = strip_tags(self.message) # loop over recipients and fill "emails" list for recipient in recipients: msg = EmailClass( # subject self.subject, # message message, # from settings.DEFAULT_FROM_EMAIL, # to [recipient], ) if OUTWARD_HTML: msg.attach_alternative(html_content, "text/html") # prepare email object emails.append(msg) # try sending email try: # counter will count how many emails have been sent counter = 0 for email in emails: # if step reached if counter == OUTWARD_STEP: # reset counter counter = 0 # sleep time.sleep(OUTWARD_DELAY) # send email email.send() # increase counter counter += 1 # if error (connection refused, SMTP down) except socket.error as e: # log the error from logging import error error('nodeshot.core.mailing.models.outward.send(): %s' % e) # set status of the instance as "error" self.status = OUTWARD_STATUS.get('error') # change status self.status = OUTWARD_STATUS.get('sent') # save self.save()
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/models/outward.py#L168-L234
train
52,252
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 """ method_name = method.func_name # add method name to additional validation method list cls._additional_validation.append(method_name) # add method to this class setattr(cls, method_name, method)
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 """ method_name = method.func_name # add method name to additional validation method list cls._additional_validation.append(method_name) # add method to this class setattr(cls, method_name, method)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/node.py#L129-L142
train
52,253
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 self.geometry else: try: # point_on_surface guarantees that the point is within the geometry return self.geometry.point_on_surface except GEOSException: # fall back on centroid which may not be within the geometry # for example, a horseshoe shaped polygon return self.geometry.centroid
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 self.geometry else: try: # point_on_surface guarantees that the point is within the geometry return self.geometry.point_on_surface except GEOSException: # fall back on centroid which may not be within the geometry # for example, a horseshoe shaped polygon return self.geometry.centroid
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/node.py#L149-L162
train
52,254
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L51-L54
train
52,255
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(NodeList, self).get_queryset().select_related('status', 'user', 'layer') # query string params search = self.request.query_params.get('search', None) layers = self.request.query_params.get('layers', None) if search is not None: search_query = ( Q(name__icontains=search) | Q(slug__icontains=search) | Q(description__icontains=search) | Q(address__icontains=search) ) # add instructions for search to queryset queryset = queryset.filter(search_query) if layers is not None: # look for nodes that are assigned to the specified layers queryset = queryset.filter(Q(layer__slug__in=layers.split(','))) return queryset
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(NodeList, self).get_queryset().select_related('status', 'user', 'layer') # query string params search = self.request.query_params.get('search', None) layers = self.request.query_params.get('layers', None) if search is not None: search_query = ( Q(name__icontains=search) | Q(slug__icontains=search) | Q(description__icontains=search) | Q(address__icontains=search) ) # add instructions for search to queryset queryset = queryset.filter(search_query) if layers is not None: # look for nodes that are assigned to the specified layers queryset = queryset.filter(Q(layer__slug__in=layers.split(','))) return queryset
[ "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", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L56-L79
train
52,256
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 else '' notification_text = TEXTS[notification_type] % additional # loop users, notification settings check is done in Notification model for user in users: n = Notification( to_user=user, type=notification_type, text=notification_text ) # attach related object if present if related_object: n.related_object = related_object # create notification and send according to user settings n.save()
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 else '' notification_text = TEXTS[notification_type] % additional # loop users, notification settings check is done in Notification model for user in users: n = Notification( to_user=user, type=notification_type, text=notification_text ) # attach related object if present if related_object: n.related_object = related_object # create notification and send according to user settings n.save()
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/tasks.py#L19-L42
train
52,257
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/interfaces/ethernet.py#L21-L24
train
52,258
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 else: is_urlconf_module = False # if url is really a urlmodule if is_urlconf_module: # loop over urls of that module for url in urlmodule.urlconf_module.urlpatterns: # TODO: configurable skip url in settings # skip api-docs url if url.name in ['django.swagger.resources.view']: continue # try adding url to list of urls to show try: endpoints.append({ 'name': url.name.replace('api_', ''), 'url': reverse(url.name, request=request, format=format) }) # urls of object details will fail silently (eg: /nodes/<slug>/) except NoReverseMatch: pass return Response(endpoints)
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 else: is_urlconf_module = False # if url is really a urlmodule if is_urlconf_module: # loop over urls of that module for url in urlmodule.urlconf_module.urlpatterns: # TODO: configurable skip url in settings # skip api-docs url if url.name in ['django.swagger.resources.view']: continue # try adding url to list of urls to show try: endpoints.append({ 'name': url.name.replace('api_', ''), 'url': reverse(url.name, request=request, format=format) }) # urls of object details will fail silently (eg: /nodes/<slug>/) except NoReverseMatch: pass return Response(endpoints)
[ "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", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/api/views.py#L11-L40
train
52,259
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/comment.py#L26-L30
train
52,260
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_settings.comments_allowed is False: raise ValidationError("Comments not allowed for this node") # ensure comments for this layer are allowed if 'nodeshot.core.layers' in settings.INSTALLED_APPS: layer = node.layer if layer.participation_settings.comments_allowed is False: raise ValidationError("Comments not allowed for this layer")
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_settings.comments_allowed is False: raise ValidationError("Comments not allowed for this node") # ensure comments for this layer are allowed if 'nodeshot.core.layers' in settings.INSTALLED_APPS: layer = node.layer if layer.participation_settings.comments_allowed is False: raise ValidationError("Comments not allowed for this layer")
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/comment.py#L32-L46
train
52,261
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.objects.published().external() # check if there is any layer to exclude if options['exclude']: # convert comma separated string in python list, ignore spaces exclude_list = options['exclude'].replace(' ', '').split(',') # retrieve all layers except the ones specified in exclude list return all_layers.exclude(slug__in=exclude_list) else: # nothing to exclude, retrieve all layers self.verbose('no layer specified, will retrieve all layers!') return all_layers # otherwise loop over args and retrieve each specified layer for layer_slug in args: queryset = queryset | Q(slug=layer_slug) # verify existence try: # retrieve layer layer = Layer.objects.get(slug=layer_slug) # raise exception if layer is not external if not layer.is_external: raise CommandError('Layer "%s" is not an external layer\n\r' % layer_slug) # raise exception if layer is not published if not layer.is_published: raise CommandError('Layer "%s" is not published. Why are you trying to work on an unpublished layer?\n\r' % layer_slug) # raise exception if one of the layer looked for doesn't exist except Layer.DoesNotExist: raise CommandError('Layer "%s" does not exist\n\r' % layer_slug) # return published external layers return Layer.objects.published().external().select_related().filter(queryset)
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.objects.published().external() # check if there is any layer to exclude if options['exclude']: # convert comma separated string in python list, ignore spaces exclude_list = options['exclude'].replace(' ', '').split(',') # retrieve all layers except the ones specified in exclude list return all_layers.exclude(slug__in=exclude_list) else: # nothing to exclude, retrieve all layers self.verbose('no layer specified, will retrieve all layers!') return all_layers # otherwise loop over args and retrieve each specified layer for layer_slug in args: queryset = queryset | Q(slug=layer_slug) # verify existence try: # retrieve layer layer = Layer.objects.get(slug=layer_slug) # raise exception if layer is not external if not layer.is_external: raise CommandError('Layer "%s" is not an external layer\n\r' % layer_slug) # raise exception if layer is not published if not layer.is_published: raise CommandError('Layer "%s" is not published. Why are you trying to work on an unpublished layer?\n\r' % layer_slug) # raise exception if one of the layer looked for doesn't exist except Layer.DoesNotExist: raise CommandError('Layer "%s" does not exist\n\r' % layer_slug) # return published external layers return Layer.objects.published().external().select_related().filter(queryset)
[ "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", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/management/commands/sync.py#L30-L70
train
52,262
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, **options) if len(layers) < 1: self.stdout.write('no layers to process\n\r') return else: self.verbose('going to process %d layers...' % len(layers)) # loop over for layer in layers: # retrieve interop class if available try: synchronizer_path = layer.external.synchronizer_path except (ObjectDoesNotExist, AttributeError): self.stdout.write('External Layer %s does not have a synchronizer class specified\n\r' % layer.name) continue # if no synchronizer_path jump to next layer if synchronizer_path == 'None': self.stdout.write('External Layer %s does not have a synchronizer class specified\n\r' % layer.name) continue if layer.external.config is None: self.stdout.write('Layer %s does not have a config yet\n\r' % layer.name) continue # retrieve class synchronizer = import_by_path(synchronizer_path) self.stdout.write('imported module %s\r\n' % synchronizer.__name__) # try running try: instance = synchronizer(layer, verbosity=self.verbosity) self.stdout.write('Processing layer "%s"\r\n' % layer.slug) messages = instance.sync() except ImproperlyConfigured as e: self.stdout.write('Validation error: %s\r\n' % e) continue except Exception as e: self.stdout.write('Got Exception: %s\r\n' % e) exception(e) continue for message in messages: self.stdout.write('%s\n\r' % message) self.stdout.write('\r\n')
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, **options) if len(layers) < 1: self.stdout.write('no layers to process\n\r') return else: self.verbose('going to process %d layers...' % len(layers)) # loop over for layer in layers: # retrieve interop class if available try: synchronizer_path = layer.external.synchronizer_path except (ObjectDoesNotExist, AttributeError): self.stdout.write('External Layer %s does not have a synchronizer class specified\n\r' % layer.name) continue # if no synchronizer_path jump to next layer if synchronizer_path == 'None': self.stdout.write('External Layer %s does not have a synchronizer class specified\n\r' % layer.name) continue if layer.external.config is None: self.stdout.write('Layer %s does not have a config yet\n\r' % layer.name) continue # retrieve class synchronizer = import_by_path(synchronizer_path) self.stdout.write('imported module %s\r\n' % synchronizer.__name__) # try running try: instance = synchronizer(layer, verbosity=self.verbosity) self.stdout.write('Processing layer "%s"\r\n' % layer.slug) messages = instance.sync() except ImproperlyConfigured as e: self.stdout.write('Validation error: %s\r\n' % e) continue except Exception as e: self.stdout.write('Got Exception: %s\r\n' % e) exception(e) continue for message in messages: self.stdout.write('%s\n\r' % message) self.stdout.write('\r\n')
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/management/commands/sync.py#L76-L129
train
52,263
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_path is None: return False push_changes_to_external_layers.delay(node=node, external_layer=node.layer.external, operation=operation)
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_path is None: return False push_changes_to_external_layers.delay(node=node, external_layer=node.layer.external, operation=operation)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/node_external.py#L36-L44
train
52,264
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, 'external') and node.external.external_id: push_changes_to_external_layers.delay( node=node.external.external_id, external_layer=node.layer.external, operation='delete' )
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, 'external') and node.external.external_id: push_changes_to_external_layers.delay( node=node.external.external_id, external_layer=node.layer.external, operation='delete' )
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/node_external.py#L48-L60
train
52,265
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_vote.delete() super(Vote, self).save(*args, **kwargs)
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_vote.delete() super(Vote, self).save(*args, **kwargs)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/vote.py#L36-L45
train
52,266
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/vote.py#L47-L52
train
52,267
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("Voting not allowed for this node") if 'nodeshot.core.layers' in settings.INSTALLED_APPS: layer = self.node.layer # ensure voting for this layer is allowed if layer.participation_settings.voting_allowed is not True: raise ValidationError("Voting not allowed for this layer")
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("Voting not allowed for this node") if 'nodeshot.core.layers' in settings.INSTALLED_APPS: layer = self.node.layer # ensure voting for this layer is allowed if layer.participation_settings.voting_allowed is not True: raise ValidationError("Voting not allowed for this layer")
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/vote.py#L54-L68
train
52,268
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 = super(DeviceList, self).get_queryset()#.select_related('layer', 'status', 'user') # retrieve value of querystring parameter "search" search = self.request.query_params.get('search', None) if search is not None: search_query = ( Q(name__icontains=search) | Q(description__icontains=search) ) # add instructions for search to queryset queryset = queryset.filter(search_query) return queryset
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 = super(DeviceList, self).get_queryset()#.select_related('layer', 'status', 'user') # retrieve value of querystring parameter "search" search = self.request.query_params.get('search', None) if search is not None: search_query = ( Q(name__icontains=search) | Q(description__icontains=search) ) # add instructions for search to queryset queryset = queryset.filter(search_query) return queryset
[ "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", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L35-L55
train
52,269
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 eventual auto_update if 'auto_update' in kwargs: kwargs.pop('auto_update') super(BaseDate, self).save(*args, **kwargs)
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 eventual auto_update if 'auto_update' in kwargs: kwargs.pop('auto_update') super(BaseDate, self).save(*args, **kwargs)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/models.py#L64-L77
train
52,270
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, self).save()
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, self).save()
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/models.py#L161-L168
train
52,271
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: dependencies = [dependencies] elif type(dependencies) != list: raise TypeError('dependencies argument must be of type list or string') for dependency in dependencies: if dependency not in settings.INSTALLED_APPS: raise DependencyError('%s depends on %s, which should be in settings.INSTALLED_APPS' % (module, dependency))
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: dependencies = [dependencies] elif type(dependencies) != list: raise TypeError('dependencies argument must be of type list or string') for dependency in dependencies: if dependency not in settings.INSTALLED_APPS: raise DependencyError('%s depends on %s, which should be in settings.INSTALLED_APPS' % (module, dependency))
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/utils.py#L38-L52
train
52,272
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: return ugettext(key)
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: return ugettext(key)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/utils.py#L75-L84
train
52,273
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L56-L63
train
52,274
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L65-L68
train
52,275
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/views.py#L75-L80
train
52,276
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", "." ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/ip.py#L36-L43
train
52,277
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/db.py#L24-L30
train
52,278
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/db.py#L66-L72
train
52,279
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: return Response({'detail': e.content}, status=e.code) return Response(list(results.get_points(metric.name))) # post else: if not request.data: return Response({'detail': 'expected values in POST data or JSON payload'}, status=400) data = request.data.copy() # try converting strings to floats when sending form-data if request.content_type != 'application/json': for key, value in data.items(): try: data[key] = float(value) if '.' in value else int(value) except ValueError: pass # write metric.write(data) return Response({'detail': 'ok'})
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: return Response({'detail': e.content}, status=e.code) return Response(list(results.get_points(metric.name))) # post else: if not request.data: return Response({'detail': 'expected values in POST data or JSON payload'}, status=400) data = request.data.copy() # try converting strings to floats when sending form-data if request.content_type != 'application/json': for key, value in data.items(): try: data[key] = float(value) if '.' in value else int(value) except ValueError: pass # write metric.write(data) return Response({'detail': 'ok'})
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/views.py#L12-L39
train
52,280
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: # generate a random uuid if it's an unauthenticated client self.channel = 'public' user_id = uuid.uuid1().hex else: self.channel = 'private' self.id = user_id self.channels[self.channel][self.id] = self print 'Client connected to the %s channel.' % self.channel
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: # generate a random uuid if it's an unauthenticated client self.channel = 'public' user_id = uuid.uuid1().hex else: self.channel = 'private' self.id = user_id self.channels[self.channel][self.id] = self print 'Client connected to the %s channel.' % self.channel
[ "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"...
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L21-L36
train
52,281
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L43-L48
train
52,282
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 self.channels['private'] print 'client with id %s not found' % user_id return False client.send_message(message) print 'message sent to client #%s' % user_id return True
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 self.channels['private'] print 'client with id %s not found' % user_id return False client.send_message(message) print 'message sent to client #%s' % user_id return True
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L51-L66
train
52,283
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L69-L73
train
52,284
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) # welcome message self.send_message("Welcome to nodeshot websocket server.") # new client connected message client_count = len(self.get_clients().keys()) new_client_message = 'New client connected, now we have %d %s!' % (client_count, 'client' if client_count <= 1 else 'clients') # broadcast new client connected message to all connected clients self.broadcast(new_client_message) print self.channels['private']
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) # welcome message self.send_message("Welcome to nodeshot websocket server.") # new client connected message client_count = len(self.get_clients().keys()) new_client_message = 'New client connected, now we have %d %s!' % (client_count, 'client' if client_count <= 1 else 'clients') # broadcast new client connected message to all connected clients self.broadcast(new_client_message) print self.channels['private']
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L75-L91
train
52,285
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 client_count <= 1 else 'clients') self.broadcast(new_client_message)
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 client_count <= 1 else 'clients') self.broadcast(new_client_message)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/handlers.py#L99-L106
train
52,286
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 databases: db.create_database(settings.INFLUXDB_DATABASE) print('Created inlfuxdb database {0}'.format(settings.INFLUXDB_DATABASE))
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 databases: db.create_database(settings.INFLUXDB_DATABASE) print('Created inlfuxdb database {0}'.format(settings.INFLUXDB_DATABASE))
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/utils.py#L55-L64
train
52,287
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: old_rating.delete() super(Rating, self).save(*args, **kwargs)
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: old_rating.delete() super(Rating, self).save(*args, **kwargs)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/rating.py#L34-L43
train
52,288
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 ratings are deleted the value will be None! if node_rating_count.rating_avg is None: # set to 0 otherwise we'll get an exception node_rating_count.rating_avg = 0 node_rating_count.save()
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 ratings are deleted the value will be None! if node_rating_count.rating_avg is None: # set to 0 otherwise we'll get an exception node_rating_count.rating_avg = 0 node_rating_count.save()
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/rating.py#L45-L56
train
52,289
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: raise ValidationError("Rating not allowed for this layer") if node.participation_settings.rating_allowed is not True: raise ValidationError("Rating not allowed for this node")
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: raise ValidationError("Rating not allowed for this layer") if node.participation_settings.rating_allowed is not True: raise ValidationError("Rating not allowed for this node")
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/rating.py#L58-L68
train
52,290
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(*args, **kwargs) # this operation must be performed after the parent save if created: self.update_count()
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(*args, **kwargs) # this operation must be performed after the parent save if created: self.update_count()
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/base.py#L17-L27
train
52,291
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/base.py#L29-L32
train
52,292
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__()) logger.exception(msg) print('{0}: {1}\n' 'see networking.log for more information\n'.format(msg, e.__class__))
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__()) logger.exception(msg) print('{0}: {1}\n' 'see networking.log for more information\n'.format(msg, e.__class__))
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/utils.py#L20-L32
train
52,293
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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L94-L104
train
52,294
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 arguments = self._build_netengine_arguments() self.__netengine = NetengineBackend(**arguments) # return netengine instance return self.__netengine
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 arguments = self._build_netengine_arguments() self.__netengine = NetengineBackend(**arguments) # return netengine instance return self.__netengine
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L107-L121
train
52,295
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 following python exception: "%s"') % e)
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 following python exception: "%s"') % e)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L123-L129
train
52,296
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 {} # default to empty dict of no config required_keys_set = set(self.REQUIRED_CONFIG_KEYS) config_keys_set = set(self.config.keys()) missing_required_keys = required_keys_set - config_keys_set unrecognized_keys = config_keys_set - required_keys_set # if any missing required key raise ValidationError if len(missing_required_keys) > 0: # converts list in comma separated string missing_keys_string = ', '.join(missing_required_keys) # django error raise ValidationError(_('Missing required config keys: "%s"') % missing_keys_string) elif len(unrecognized_keys) > 0: # converts list in comma separated string unrecognized_keys_string = ', '.join(unrecognized_keys) # django error raise ValidationError(_('Unrecognized config keys: "%s"') % unrecognized_keys_string)
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 {} # default to empty dict of no config required_keys_set = set(self.REQUIRED_CONFIG_KEYS) config_keys_set = set(self.config.keys()) missing_required_keys = required_keys_set - config_keys_set unrecognized_keys = config_keys_set - required_keys_set # if any missing required key raise ValidationError if len(missing_required_keys) > 0: # converts list in comma separated string missing_keys_string = ', '.join(missing_required_keys) # django error raise ValidationError(_('Missing required config keys: "%s"') % missing_keys_string) elif len(unrecognized_keys) > 0: # converts list in comma separated string unrecognized_keys_string = ', '.join(unrecognized_keys) # django error raise ValidationError(_('Unrecognized config keys: "%s"') % unrecognized_keys_string)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L131-L156
train
52,297
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.netengine_dict = self.netengine.to_dict() # loop over interfaces and check mac address for interface in self.netengine_dict['interfaces']: # avoid checking twice for the same interface (often ifconfig returns duplicates) if interface['mac_address'] in duplicates: continue # check in DB if Interface.objects.filter(mac__iexact=interface['mac_address']).count() > 0: duplicates.append(interface['mac_address']) # if we have duplicates raise validation error if len(duplicates) > 0: mac_address_string = ', '.join(duplicates) raise ValidationError(_('interfaces with the following mac addresses already exist: %s') % mac_address_string)
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.netengine_dict = self.netengine.to_dict() # loop over interfaces and check mac address for interface in self.netengine_dict['interfaces']: # avoid checking twice for the same interface (often ifconfig returns duplicates) if interface['mac_address'] in duplicates: continue # check in DB if Interface.objects.filter(mac__iexact=interface['mac_address']).count() > 0: duplicates.append(interface['mac_address']) # if we have duplicates raise validation error if len(duplicates) > 0: mac_address_string = ', '.join(duplicates) raise ValidationError(_('interfaces with the following mac addresses already exist: %s') % mac_address_string)
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L169-L190
train
52,298
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() argspec = inspect.getargspec(backend_class.__init__) # store args args = argspec.args # remove known arguments for argument_name in ['self', 'host', 'port']: args.remove(argument_name) if required: # list of default values default_values = list(argspec.defaults) # always remove last default value, which is port number default_values = default_values[0:-1] # remove an amount of arguments equals to number of default values, starting from right args = args[0:len(args)-len(default_values)] return args
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() argspec = inspect.getargspec(backend_class.__init__) # store args args = argspec.args # remove known arguments for argument_name in ['self', 'host', 'port']: args.remove(argument_name) if required: # list of default values default_values = list(argspec.defaults) # always remove last default value, which is port number default_values = default_values[0:-1] # remove an amount of arguments equals to number of default values, starting from right args = args[0:len(args)-len(default_values)] return args
[ "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" ]
2466f0a55f522b2696026f196436ce7ba3f1e5c6
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/connectors/models/device_connector.py#L192-L216
train
52,299