repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
ninuxorg/nodeshot
nodeshot/interop/open311/views.py
ServiceDefinitionList.get
def get(self, request, *args, **kwargs): """ return list of open 311 services """ # init django rest framework specific stuff serializer_class = self.get_serializer_class() context = self.get_serializer_context() # init empty list services = [] # loop over each service for service_type in SERVICES.keys(): # initialize serializers for layer services.append( serializer_class( object(), context=context, service_type=service_type ).data ) return Response(services)
python
def get(self, request, *args, **kwargs): """ return list of open 311 services """ # init django rest framework specific stuff serializer_class = self.get_serializer_class() context = self.get_serializer_context() # init empty list services = [] # loop over each service for service_type in SERVICES.keys(): # initialize serializers for layer services.append( serializer_class( object(), context=context, service_type=service_type ).data ) return Response(services)
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# init django rest framework specific stuff", "serializer_class", "=", "self", ".", "get_serializer_class", "(", ")", "context", "=", "self", ".", "get_serializer_context", "(", ")", "# init empty list", "services", "=", "[", "]", "# loop over each service", "for", "service_type", "in", "SERVICES", ".", "keys", "(", ")", ":", "# initialize serializers for layer", "services", ".", "append", "(", "serializer_class", "(", "object", "(", ")", ",", "context", "=", "context", ",", "service_type", "=", "service_type", ")", ".", "data", ")", "return", "Response", "(", "services", ")" ]
return list of open 311 services
[ "return", "list", "of", "open", "311", "services" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/open311/views.py#L40-L60
ninuxorg/nodeshot
nodeshot/interop/open311/views.py
ServiceRequestList.get_serializer
def get_serializer(self, instance=None, data=None, many=False, partial=False): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializers = { 'node': NodeRequestListSerializer, 'vote': VoteRequestListSerializer, 'comment': CommentRequestListSerializer, 'rate': RatingRequestListSerializer, } context = self.get_serializer_context() service_code = context['request'].query_params.get('service_code', 'node') if service_code not in serializers.keys(): serializer_class = self.get_serializer_class() else: serializer_class = serializers[service_code] return serializer_class(instance, many=many, partial=partial, context=context)
python
def get_serializer(self, instance=None, data=None, many=False, partial=False): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializers = { 'node': NodeRequestListSerializer, 'vote': VoteRequestListSerializer, 'comment': CommentRequestListSerializer, 'rate': RatingRequestListSerializer, } context = self.get_serializer_context() service_code = context['request'].query_params.get('service_code', 'node') if service_code not in serializers.keys(): serializer_class = self.get_serializer_class() else: serializer_class = serializers[service_code] return serializer_class(instance, many=many, partial=partial, context=context)
[ "def", "get_serializer", "(", "self", ",", "instance", "=", "None", ",", "data", "=", "None", ",", "many", "=", "False", ",", "partial", "=", "False", ")", ":", "serializers", "=", "{", "'node'", ":", "NodeRequestListSerializer", ",", "'vote'", ":", "VoteRequestListSerializer", ",", "'comment'", ":", "CommentRequestListSerializer", ",", "'rate'", ":", "RatingRequestListSerializer", ",", "}", "context", "=", "self", ".", "get_serializer_context", "(", ")", "service_code", "=", "context", "[", "'request'", "]", ".", "query_params", ".", "get", "(", "'service_code'", ",", "'node'", ")", "if", "service_code", "not", "in", "serializers", ".", "keys", "(", ")", ":", "serializer_class", "=", "self", ".", "get_serializer_class", "(", ")", "else", ":", "serializer_class", "=", "serializers", "[", "service_code", "]", "return", "serializer_class", "(", "instance", ",", "many", "=", "many", ",", "partial", "=", "partial", ",", "context", "=", "context", ")" ]
Return the serializer instance that should be used for validating and deserializing input, and for serializing output.
[ "Return", "the", "serializer", "instance", "that", "should", "be", "used", "for", "validating", "and", "deserializing", "input", "and", "for", "serializing", "output", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/open311/views.py#L141-L161
ninuxorg/nodeshot
nodeshot/interop/open311/views.py
ServiceRequestList.get
def get(self, request, *args, **kwargs): """ Retrieve list of service requests """ if 'service_code' not in request.GET.keys(): return Response({ 'detail': _('A service code must be inserted') }, status=404) service_code = request.GET['service_code'] if service_code not in SERVICES.keys(): return Response({ 'detail': _('Service not found') }, status=404) start_date = None end_date = None status = None layer = None STATUSES = {} for status_type in ('open', 'closed'): STATUSES[status_type] = [k for k, v in STATUS.items() if v == status_type] if 'start_date' in request.GET.keys(): start_date = request.GET['start_date'] if iso8601_REGEXP.match(start_date) is None: return Response({ 'detail': _('Invalid date inserted') }, status=404) if 'end_date' in request.GET.keys(): end_date = request.GET['end_date'] if iso8601_REGEXP.match(end_date) is None: return Response({ 'detail': _('Invalid date inserted') }, status=404) if 'status' in request.GET.keys(): if request.GET['status'] not in ('open','closed'): return Response({ 'detail': _('Invalid status inserted') }, status=404) status = request.GET['status'] if 'layer' in request.GET.keys(): layer = request.GET['layer'] node_layer = get_object_or_404(Layer, slug=layer) service_model = MODELS[service_code] if service_code in ('vote', 'comment', 'rate'): self.queryset = service_model.objects.none() else: self.queryset = service_model.objects.all() # Filter by layer if layer is not None: self.queryset = self.queryset.filter(layer = node_layer) # Check of date parameters if start_date is not None and end_date is not None: self.queryset = self.queryset.filter(added__gte = start_date).filter(added__lte = end_date) if start_date is not None and end_date is None: self.queryset = self.queryset.filter(added__gte = start_date) if start_date is None and end_date is not None: self.queryset = self.queryset.filter(added__lte = end_date) # Check of status parameter if status is not None: q_list = [Q(status__slug__exact = s) for s in STATUSES[status]] self.queryset = self.queryset.filter(reduce(operator.or_, q_list)) return self.list(request, *args, **kwargs)
python
def get(self, request, *args, **kwargs): """ Retrieve list of service requests """ if 'service_code' not in request.GET.keys(): return Response({ 'detail': _('A service code must be inserted') }, status=404) service_code = request.GET['service_code'] if service_code not in SERVICES.keys(): return Response({ 'detail': _('Service not found') }, status=404) start_date = None end_date = None status = None layer = None STATUSES = {} for status_type in ('open', 'closed'): STATUSES[status_type] = [k for k, v in STATUS.items() if v == status_type] if 'start_date' in request.GET.keys(): start_date = request.GET['start_date'] if iso8601_REGEXP.match(start_date) is None: return Response({ 'detail': _('Invalid date inserted') }, status=404) if 'end_date' in request.GET.keys(): end_date = request.GET['end_date'] if iso8601_REGEXP.match(end_date) is None: return Response({ 'detail': _('Invalid date inserted') }, status=404) if 'status' in request.GET.keys(): if request.GET['status'] not in ('open','closed'): return Response({ 'detail': _('Invalid status inserted') }, status=404) status = request.GET['status'] if 'layer' in request.GET.keys(): layer = request.GET['layer'] node_layer = get_object_or_404(Layer, slug=layer) service_model = MODELS[service_code] if service_code in ('vote', 'comment', 'rate'): self.queryset = service_model.objects.none() else: self.queryset = service_model.objects.all() # Filter by layer if layer is not None: self.queryset = self.queryset.filter(layer = node_layer) # Check of date parameters if start_date is not None and end_date is not None: self.queryset = self.queryset.filter(added__gte = start_date).filter(added__lte = end_date) if start_date is not None and end_date is None: self.queryset = self.queryset.filter(added__gte = start_date) if start_date is None and end_date is not None: self.queryset = self.queryset.filter(added__lte = end_date) # Check of status parameter if status is not None: q_list = [Q(status__slug__exact = s) for s in STATUSES[status]] self.queryset = self.queryset.filter(reduce(operator.or_, q_list)) return self.list(request, *args, **kwargs)
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'service_code'", "not", "in", "request", ".", "GET", ".", "keys", "(", ")", ":", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "'A service code must be inserted'", ")", "}", ",", "status", "=", "404", ")", "service_code", "=", "request", ".", "GET", "[", "'service_code'", "]", "if", "service_code", "not", "in", "SERVICES", ".", "keys", "(", ")", ":", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "'Service not found'", ")", "}", ",", "status", "=", "404", ")", "start_date", "=", "None", "end_date", "=", "None", "status", "=", "None", "layer", "=", "None", "STATUSES", "=", "{", "}", "for", "status_type", "in", "(", "'open'", ",", "'closed'", ")", ":", "STATUSES", "[", "status_type", "]", "=", "[", "k", "for", "k", ",", "v", "in", "STATUS", ".", "items", "(", ")", "if", "v", "==", "status_type", "]", "if", "'start_date'", "in", "request", ".", "GET", ".", "keys", "(", ")", ":", "start_date", "=", "request", ".", "GET", "[", "'start_date'", "]", "if", "iso8601_REGEXP", ".", "match", "(", "start_date", ")", "is", "None", ":", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "'Invalid date inserted'", ")", "}", ",", "status", "=", "404", ")", "if", "'end_date'", "in", "request", ".", "GET", ".", "keys", "(", ")", ":", "end_date", "=", "request", ".", "GET", "[", "'end_date'", "]", "if", "iso8601_REGEXP", ".", "match", "(", "end_date", ")", "is", "None", ":", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "'Invalid date inserted'", ")", "}", ",", "status", "=", "404", ")", "if", "'status'", "in", "request", ".", "GET", ".", "keys", "(", ")", ":", "if", "request", ".", "GET", "[", "'status'", "]", "not", "in", "(", "'open'", ",", "'closed'", ")", ":", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "'Invalid status inserted'", ")", "}", ",", "status", "=", "404", ")", "status", "=", "request", ".", "GET", "[", "'status'", "]", "if", "'layer'", "in", "request", ".", "GET", ".", "keys", "(", ")", ":", "layer", "=", "request", ".", "GET", "[", "'layer'", "]", "node_layer", "=", "get_object_or_404", "(", "Layer", ",", "slug", "=", "layer", ")", "service_model", "=", "MODELS", "[", "service_code", "]", "if", "service_code", "in", "(", "'vote'", ",", "'comment'", ",", "'rate'", ")", ":", "self", ".", "queryset", "=", "service_model", ".", "objects", ".", "none", "(", ")", "else", ":", "self", ".", "queryset", "=", "service_model", ".", "objects", ".", "all", "(", ")", "# Filter by layer", "if", "layer", "is", "not", "None", ":", "self", ".", "queryset", "=", "self", ".", "queryset", ".", "filter", "(", "layer", "=", "node_layer", ")", "# Check of date parameters", "if", "start_date", "is", "not", "None", "and", "end_date", "is", "not", "None", ":", "self", ".", "queryset", "=", "self", ".", "queryset", ".", "filter", "(", "added__gte", "=", "start_date", ")", ".", "filter", "(", "added__lte", "=", "end_date", ")", "if", "start_date", "is", "not", "None", "and", "end_date", "is", "None", ":", "self", ".", "queryset", "=", "self", ".", "queryset", ".", "filter", "(", "added__gte", "=", "start_date", ")", "if", "start_date", "is", "None", "and", "end_date", "is", "not", "None", ":", "self", ".", "queryset", "=", "self", ".", "queryset", ".", "filter", "(", "added__lte", "=", "end_date", ")", "# Check of status parameter", "if", "status", "is", "not", "None", ":", "q_list", "=", "[", "Q", "(", "status__slug__exact", "=", "s", ")", "for", "s", "in", "STATUSES", "[", "status", "]", "]", "self", ".", "queryset", "=", "self", ".", "queryset", ".", "filter", "(", "reduce", "(", "operator", ".", "or_", ",", "q_list", ")", ")", "return", "self", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Retrieve list of service requests
[ "Retrieve", "list", "of", "service", "requests" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/open311/views.py#L169-L231
ninuxorg/nodeshot
nodeshot/interop/open311/views.py
ServiceRequestList.post
def post(self, request, *args, **kwargs): """ Post a service request (requires authentication) """ service_code = request.data['service_code'] if service_code not in SERVICES.keys(): return Response({ 'detail': _('Service not found') }, status=404) serializers = { 'node': NodeRequestSerializer, 'vote': VoteRequestSerializer, 'comment': CommentRequestSerializer, 'rate': RatingRequestSerializer, } # init right serializer kwargs['service_code'] = service_code kwargs['serializer'] = serializers[service_code] user=self.get_custom_data() request.UPDATED = request.data.copy() request.UPDATED['user'] = user['user'] if service_code == 'node': for checkPOSTdata in ('layer','name','lat','long'): # Check if mandatory parameters key exists if checkPOSTdata not in request.data.keys(): return Response({ 'detail': _('Mandatory parameter not found') }, status=400) else: # Check if mandatory parameters values have been inserted if not request.data[checkPOSTdata] : return Response({ 'detail': _('Mandatory parameter not found') }, status=400) # Get layer id layer = Layer.objects.get(slug=request.UPDATED['layer']) request.UPDATED['layer'] = layer.id # Transform coords in wkt geometry lat = float(request.UPDATED['lat']) long = float(request.UPDATED['long']) point = Point((long, lat)) request.UPDATED['geometry'] = point.wkt request.UPDATED['slug'] = slugify(request.UPDATED['name']) return self.create(request, *args, **kwargs)
python
def post(self, request, *args, **kwargs): """ Post a service request (requires authentication) """ service_code = request.data['service_code'] if service_code not in SERVICES.keys(): return Response({ 'detail': _('Service not found') }, status=404) serializers = { 'node': NodeRequestSerializer, 'vote': VoteRequestSerializer, 'comment': CommentRequestSerializer, 'rate': RatingRequestSerializer, } # init right serializer kwargs['service_code'] = service_code kwargs['serializer'] = serializers[service_code] user=self.get_custom_data() request.UPDATED = request.data.copy() request.UPDATED['user'] = user['user'] if service_code == 'node': for checkPOSTdata in ('layer','name','lat','long'): # Check if mandatory parameters key exists if checkPOSTdata not in request.data.keys(): return Response({ 'detail': _('Mandatory parameter not found') }, status=400) else: # Check if mandatory parameters values have been inserted if not request.data[checkPOSTdata] : return Response({ 'detail': _('Mandatory parameter not found') }, status=400) # Get layer id layer = Layer.objects.get(slug=request.UPDATED['layer']) request.UPDATED['layer'] = layer.id # Transform coords in wkt geometry lat = float(request.UPDATED['lat']) long = float(request.UPDATED['long']) point = Point((long, lat)) request.UPDATED['geometry'] = point.wkt request.UPDATED['slug'] = slugify(request.UPDATED['name']) return self.create(request, *args, **kwargs)
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "service_code", "=", "request", ".", "data", "[", "'service_code'", "]", "if", "service_code", "not", "in", "SERVICES", ".", "keys", "(", ")", ":", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "'Service not found'", ")", "}", ",", "status", "=", "404", ")", "serializers", "=", "{", "'node'", ":", "NodeRequestSerializer", ",", "'vote'", ":", "VoteRequestSerializer", ",", "'comment'", ":", "CommentRequestSerializer", ",", "'rate'", ":", "RatingRequestSerializer", ",", "}", "# init right serializer", "kwargs", "[", "'service_code'", "]", "=", "service_code", "kwargs", "[", "'serializer'", "]", "=", "serializers", "[", "service_code", "]", "user", "=", "self", ".", "get_custom_data", "(", ")", "request", ".", "UPDATED", "=", "request", ".", "data", ".", "copy", "(", ")", "request", ".", "UPDATED", "[", "'user'", "]", "=", "user", "[", "'user'", "]", "if", "service_code", "==", "'node'", ":", "for", "checkPOSTdata", "in", "(", "'layer'", ",", "'name'", ",", "'lat'", ",", "'long'", ")", ":", "# Check if mandatory parameters key exists", "if", "checkPOSTdata", "not", "in", "request", ".", "data", ".", "keys", "(", ")", ":", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "'Mandatory parameter not found'", ")", "}", ",", "status", "=", "400", ")", "else", ":", "# Check if mandatory parameters values have been inserted", "if", "not", "request", ".", "data", "[", "checkPOSTdata", "]", ":", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "'Mandatory parameter not found'", ")", "}", ",", "status", "=", "400", ")", "# Get layer id", "layer", "=", "Layer", ".", "objects", ".", "get", "(", "slug", "=", "request", ".", "UPDATED", "[", "'layer'", "]", ")", "request", ".", "UPDATED", "[", "'layer'", "]", "=", "layer", ".", "id", "# Transform coords in wkt geometry", "lat", "=", "float", "(", "request", ".", "UPDATED", "[", "'lat'", "]", ")", "long", "=", "float", "(", "request", ".", "UPDATED", "[", "'long'", "]", ")", "point", "=", "Point", "(", "(", "long", ",", "lat", ")", ")", "request", ".", "UPDATED", "[", "'geometry'", "]", "=", "point", ".", "wkt", "request", ".", "UPDATED", "[", "'slug'", "]", "=", "slugify", "(", "request", ".", "UPDATED", "[", "'name'", "]", ")", "return", "self", ".", "create", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Post a service request (requires authentication)
[ "Post", "a", "service", "request", "(", "requires", "authentication", ")" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/open311/views.py#L233-L274
ninuxorg/nodeshot
nodeshot/community/participation/apps.py
AppConfig.ready
def ready(self): """ Add user info to ExtensibleNodeSerializer """ from nodeshot.core.nodes.base import ExtensibleNodeSerializer from .models import Vote from .serializers import (CommentRelationSerializer, ParticipationSerializer) ExtensibleNodeSerializer.add_relationship( 'comments', serializer=CommentRelationSerializer, many=True, queryset=lambda obj, request: obj.comment_set.all() ) ExtensibleNodeSerializer.add_relationship( 'counts', serializer=ParticipationSerializer, queryset=lambda obj, request: obj.noderatingcount ) ExtensibleNodeSerializer.add_relationship( 'votes_url', view_name='api_node_votes', lookup_field='slug' ) ExtensibleNodeSerializer.add_relationship( 'ratings_url', view_name='api_node_ratings', lookup_field='slug' ) ExtensibleNodeSerializer.add_relationship( 'comments_url', view_name='api_node_comments', lookup_field='slug' ) def voted(obj, request): """ Determines if current logged-in user has already voted on a node returns 1 if user has already liked returns -1 if user has already disliked returns False if user hasn't voted or if not authenticated """ if request.user.is_authenticated(): v = Vote.objects.filter(node_id=obj.id, user_id=request.user.id) if len(v) > 0: return v[0].vote # hasn't voted yet or not authenticated return False ExtensibleNodeSerializer.add_relationship( 'voted', function=voted ) ExtensibleNodeSerializer.add_relationship( 'voting_allowed', function=lambda obj, request: obj.voting_allowed ) ExtensibleNodeSerializer.add_relationship( 'rating_allowed', function=lambda obj, request: obj.rating_allowed ) ExtensibleNodeSerializer.add_relationship( 'comments_allowed', function=lambda obj, request: obj.comments_allowed )
python
def ready(self): """ Add user info to ExtensibleNodeSerializer """ from nodeshot.core.nodes.base import ExtensibleNodeSerializer from .models import Vote from .serializers import (CommentRelationSerializer, ParticipationSerializer) ExtensibleNodeSerializer.add_relationship( 'comments', serializer=CommentRelationSerializer, many=True, queryset=lambda obj, request: obj.comment_set.all() ) ExtensibleNodeSerializer.add_relationship( 'counts', serializer=ParticipationSerializer, queryset=lambda obj, request: obj.noderatingcount ) ExtensibleNodeSerializer.add_relationship( 'votes_url', view_name='api_node_votes', lookup_field='slug' ) ExtensibleNodeSerializer.add_relationship( 'ratings_url', view_name='api_node_ratings', lookup_field='slug' ) ExtensibleNodeSerializer.add_relationship( 'comments_url', view_name='api_node_comments', lookup_field='slug' ) def voted(obj, request): """ Determines if current logged-in user has already voted on a node returns 1 if user has already liked returns -1 if user has already disliked returns False if user hasn't voted or if not authenticated """ if request.user.is_authenticated(): v = Vote.objects.filter(node_id=obj.id, user_id=request.user.id) if len(v) > 0: return v[0].vote # hasn't voted yet or not authenticated return False ExtensibleNodeSerializer.add_relationship( 'voted', function=voted ) ExtensibleNodeSerializer.add_relationship( 'voting_allowed', function=lambda obj, request: obj.voting_allowed ) ExtensibleNodeSerializer.add_relationship( 'rating_allowed', function=lambda obj, request: obj.rating_allowed ) ExtensibleNodeSerializer.add_relationship( 'comments_allowed', function=lambda obj, request: obj.comments_allowed )
[ "def", "ready", "(", "self", ")", ":", "from", "nodeshot", ".", "core", ".", "nodes", ".", "base", "import", "ExtensibleNodeSerializer", "from", ".", "models", "import", "Vote", "from", ".", "serializers", "import", "(", "CommentRelationSerializer", ",", "ParticipationSerializer", ")", "ExtensibleNodeSerializer", ".", "add_relationship", "(", "'comments'", ",", "serializer", "=", "CommentRelationSerializer", ",", "many", "=", "True", ",", "queryset", "=", "lambda", "obj", ",", "request", ":", "obj", ".", "comment_set", ".", "all", "(", ")", ")", "ExtensibleNodeSerializer", ".", "add_relationship", "(", "'counts'", ",", "serializer", "=", "ParticipationSerializer", ",", "queryset", "=", "lambda", "obj", ",", "request", ":", "obj", ".", "noderatingcount", ")", "ExtensibleNodeSerializer", ".", "add_relationship", "(", "'votes_url'", ",", "view_name", "=", "'api_node_votes'", ",", "lookup_field", "=", "'slug'", ")", "ExtensibleNodeSerializer", ".", "add_relationship", "(", "'ratings_url'", ",", "view_name", "=", "'api_node_ratings'", ",", "lookup_field", "=", "'slug'", ")", "ExtensibleNodeSerializer", ".", "add_relationship", "(", "'comments_url'", ",", "view_name", "=", "'api_node_comments'", ",", "lookup_field", "=", "'slug'", ")", "def", "voted", "(", "obj", ",", "request", ")", ":", "\"\"\"\n Determines if current logged-in user has already voted on a node\n returns 1 if user has already liked\n returns -1 if user has already disliked\n returns False if user hasn't voted or if not authenticated\n \"\"\"", "if", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "v", "=", "Vote", ".", "objects", ".", "filter", "(", "node_id", "=", "obj", ".", "id", ",", "user_id", "=", "request", ".", "user", ".", "id", ")", "if", "len", "(", "v", ")", ">", "0", ":", "return", "v", "[", "0", "]", ".", "vote", "# hasn't voted yet or not authenticated", "return", "False", "ExtensibleNodeSerializer", ".", "add_relationship", "(", "'voted'", ",", "function", "=", "voted", ")", "ExtensibleNodeSerializer", ".", "add_relationship", "(", "'voting_allowed'", ",", "function", "=", "lambda", "obj", ",", "request", ":", "obj", ".", "voting_allowed", ")", "ExtensibleNodeSerializer", ".", "add_relationship", "(", "'rating_allowed'", ",", "function", "=", "lambda", "obj", ",", "request", ":", "obj", ".", "rating_allowed", ")", "ExtensibleNodeSerializer", ".", "add_relationship", "(", "'comments_allowed'", ",", "function", "=", "lambda", "obj", ",", "request", ":", "obj", ".", "comments_allowed", ")" ]
Add user info to ExtensibleNodeSerializer
[ "Add", "user", "info", "to", "ExtensibleNodeSerializer" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/apps.py#L7-L77
ninuxorg/nodeshot
nodeshot/community/notifications/registrars/nodes.py
node_created_handler
def node_created_handler(sender, **kwargs): """ send notification when a new node is created according to users's settings """ if kwargs['created']: obj = kwargs['instance'] queryset = exclude_owner_of_node(obj) create_notifications.delay(**{ "users": queryset, "notification_model": Notification, "notification_type": "node_created", "related_object": obj })
python
def node_created_handler(sender, **kwargs): """ send notification when a new node is created according to users's settings """ if kwargs['created']: obj = kwargs['instance'] queryset = exclude_owner_of_node(obj) create_notifications.delay(**{ "users": queryset, "notification_model": Notification, "notification_type": "node_created", "related_object": obj })
[ "def", "node_created_handler", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", "[", "'created'", "]", ":", "obj", "=", "kwargs", "[", "'instance'", "]", "queryset", "=", "exclude_owner_of_node", "(", "obj", ")", "create_notifications", ".", "delay", "(", "*", "*", "{", "\"users\"", ":", "queryset", ",", "\"notification_model\"", ":", "Notification", ",", "\"notification_type\"", ":", "\"node_created\"", ",", "\"related_object\"", ":", "obj", "}", ")" ]
send notification when a new node is created according to users's settings
[ "send", "notification", "when", "a", "new", "node", "is", "created", "according", "to", "users", "s", "settings" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/registrars/nodes.py#L26-L36
ninuxorg/nodeshot
nodeshot/community/notifications/registrars/nodes.py
node_status_changed_handler
def node_status_changed_handler(**kwargs): """ send notification when the status of a node changes according to users's settings """ obj = kwargs['instance'] obj.old_status = kwargs['old_status'].name obj.new_status = kwargs['new_status'].name queryset = exclude_owner_of_node(obj) create_notifications.delay(**{ "users": queryset, "notification_model": Notification, "notification_type": "node_status_changed", "related_object": obj }) # if node has owner send a different notification to him if obj.user is not None: create_notifications.delay(**{ "users": [obj.user], "notification_model": Notification, "notification_type": "node_own_status_changed", "related_object": obj })
python
def node_status_changed_handler(**kwargs): """ send notification when the status of a node changes according to users's settings """ obj = kwargs['instance'] obj.old_status = kwargs['old_status'].name obj.new_status = kwargs['new_status'].name queryset = exclude_owner_of_node(obj) create_notifications.delay(**{ "users": queryset, "notification_model": Notification, "notification_type": "node_status_changed", "related_object": obj }) # if node has owner send a different notification to him if obj.user is not None: create_notifications.delay(**{ "users": [obj.user], "notification_model": Notification, "notification_type": "node_own_status_changed", "related_object": obj })
[ "def", "node_status_changed_handler", "(", "*", "*", "kwargs", ")", ":", "obj", "=", "kwargs", "[", "'instance'", "]", "obj", ".", "old_status", "=", "kwargs", "[", "'old_status'", "]", ".", "name", "obj", ".", "new_status", "=", "kwargs", "[", "'new_status'", "]", ".", "name", "queryset", "=", "exclude_owner_of_node", "(", "obj", ")", "create_notifications", ".", "delay", "(", "*", "*", "{", "\"users\"", ":", "queryset", ",", "\"notification_model\"", ":", "Notification", ",", "\"notification_type\"", ":", "\"node_status_changed\"", ",", "\"related_object\"", ":", "obj", "}", ")", "# if node has owner send a different notification to him", "if", "obj", ".", "user", "is", "not", "None", ":", "create_notifications", ".", "delay", "(", "*", "*", "{", "\"users\"", ":", "[", "obj", ".", "user", "]", ",", "\"notification_model\"", ":", "Notification", ",", "\"notification_type\"", ":", "\"node_own_status_changed\"", ",", "\"related_object\"", ":", "obj", "}", ")" ]
send notification when the status of a node changes according to users's settings
[ "send", "notification", "when", "the", "status", "of", "a", "node", "changes", "according", "to", "users", "s", "settings" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/registrars/nodes.py#L42-L62
ninuxorg/nodeshot
nodeshot/networking/links/models/topology.py
Topology.diff
def diff(self): """ shortcut to netdiff.diff """ latest = self.latest current = NetJsonParser(self.json()) return diff(current, latest)
python
def diff(self): """ shortcut to netdiff.diff """ latest = self.latest current = NetJsonParser(self.json()) return diff(current, latest)
[ "def", "diff", "(", "self", ")", ":", "latest", "=", "self", ".", "latest", "current", "=", "NetJsonParser", "(", "self", ".", "json", "(", ")", ")", "return", "diff", "(", "current", ",", "latest", ")" ]
shortcut to netdiff.diff
[ "shortcut", "to", "netdiff", ".", "diff" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/models/topology.py#L51-L55
ninuxorg/nodeshot
nodeshot/networking/links/models/topology.py
Topology.json
def json(self): """ returns a dict that represents a NetJSON NetworkGraph object """ nodes = [] links = [] for link in self.link_set.all(): if self.is_layer2: source = link.interface_a.mac destination = link.interface_b.mac else: source = str(link.interface_a.ip_set.first().address) destination = str(link.interface_b.ip_set.first().address) nodes.append({ 'id': source }) nodes.append({ 'id': destination }) links.append(OrderedDict(( ('source', source), ('target', destination), ('cost', link.metric_value) ))) return OrderedDict(( ('type', 'NetworkGraph'), ('protocol', self.parser.protocol), ('version', self.parser.version), ('metric', self.parser.metric), ('nodes', nodes), ('links', links) ))
python
def json(self): """ returns a dict that represents a NetJSON NetworkGraph object """ nodes = [] links = [] for link in self.link_set.all(): if self.is_layer2: source = link.interface_a.mac destination = link.interface_b.mac else: source = str(link.interface_a.ip_set.first().address) destination = str(link.interface_b.ip_set.first().address) nodes.append({ 'id': source }) nodes.append({ 'id': destination }) links.append(OrderedDict(( ('source', source), ('target', destination), ('cost', link.metric_value) ))) return OrderedDict(( ('type', 'NetworkGraph'), ('protocol', self.parser.protocol), ('version', self.parser.version), ('metric', self.parser.metric), ('nodes', nodes), ('links', links) ))
[ "def", "json", "(", "self", ")", ":", "nodes", "=", "[", "]", "links", "=", "[", "]", "for", "link", "in", "self", ".", "link_set", ".", "all", "(", ")", ":", "if", "self", ".", "is_layer2", ":", "source", "=", "link", ".", "interface_a", ".", "mac", "destination", "=", "link", ".", "interface_b", ".", "mac", "else", ":", "source", "=", "str", "(", "link", ".", "interface_a", ".", "ip_set", ".", "first", "(", ")", ".", "address", ")", "destination", "=", "str", "(", "link", ".", "interface_b", ".", "ip_set", ".", "first", "(", ")", ".", "address", ")", "nodes", ".", "append", "(", "{", "'id'", ":", "source", "}", ")", "nodes", ".", "append", "(", "{", "'id'", ":", "destination", "}", ")", "links", ".", "append", "(", "OrderedDict", "(", "(", "(", "'source'", ",", "source", ")", ",", "(", "'target'", ",", "destination", ")", ",", "(", "'cost'", ",", "link", ".", "metric_value", ")", ")", ")", ")", "return", "OrderedDict", "(", "(", "(", "'type'", ",", "'NetworkGraph'", ")", ",", "(", "'protocol'", ",", "self", ".", "parser", ".", "protocol", ")", ",", "(", "'version'", ",", "self", ".", "parser", ".", "version", ")", ",", "(", "'metric'", ",", "self", ".", "parser", ".", "metric", ")", ",", "(", "'nodes'", ",", "nodes", ")", ",", "(", "'links'", ",", "links", ")", ")", ")" ]
returns a dict that represents a NetJSON NetworkGraph object
[ "returns", "a", "dict", "that", "represents", "a", "NetJSON", "NetworkGraph", "object" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/models/topology.py#L57-L88
ninuxorg/nodeshot
nodeshot/networking/links/models/topology.py
Topology.update
def update(self): """ Updates topology Links are not deleted straightaway but set as "disconnected" """ from .link import Link # avoid circular dependency diff = self.diff() status = { 'added': 'active', 'removed': 'disconnected', 'changed': 'active' } for section in ['added', 'removed', 'changed']: # section might be empty if not diff[section]: continue for link_dict in diff[section]['links']: try: link = Link.get_or_create(source=link_dict['source'], target=link_dict['target'], cost=link_dict['cost'], topology=self) except (LinkDataNotFound, ValidationError) as e: msg = 'Exception while updating {0}'.format(self.__repr__()) logger.exception(msg) print('{0}\n{1}\n'.format(msg, e)) continue link.ensure(status=status[section], cost=link_dict['cost'])
python
def update(self): """ Updates topology Links are not deleted straightaway but set as "disconnected" """ from .link import Link # avoid circular dependency diff = self.diff() status = { 'added': 'active', 'removed': 'disconnected', 'changed': 'active' } for section in ['added', 'removed', 'changed']: # section might be empty if not diff[section]: continue for link_dict in diff[section]['links']: try: link = Link.get_or_create(source=link_dict['source'], target=link_dict['target'], cost=link_dict['cost'], topology=self) except (LinkDataNotFound, ValidationError) as e: msg = 'Exception while updating {0}'.format(self.__repr__()) logger.exception(msg) print('{0}\n{1}\n'.format(msg, e)) continue link.ensure(status=status[section], cost=link_dict['cost'])
[ "def", "update", "(", "self", ")", ":", "from", ".", "link", "import", "Link", "# avoid circular dependency", "diff", "=", "self", ".", "diff", "(", ")", "status", "=", "{", "'added'", ":", "'active'", ",", "'removed'", ":", "'disconnected'", ",", "'changed'", ":", "'active'", "}", "for", "section", "in", "[", "'added'", ",", "'removed'", ",", "'changed'", "]", ":", "# section might be empty", "if", "not", "diff", "[", "section", "]", ":", "continue", "for", "link_dict", "in", "diff", "[", "section", "]", "[", "'links'", "]", ":", "try", ":", "link", "=", "Link", ".", "get_or_create", "(", "source", "=", "link_dict", "[", "'source'", "]", ",", "target", "=", "link_dict", "[", "'target'", "]", ",", "cost", "=", "link_dict", "[", "'cost'", "]", ",", "topology", "=", "self", ")", "except", "(", "LinkDataNotFound", ",", "ValidationError", ")", "as", "e", ":", "msg", "=", "'Exception while updating {0}'", ".", "format", "(", "self", ".", "__repr__", "(", ")", ")", "logger", ".", "exception", "(", "msg", ")", "print", "(", "'{0}\\n{1}\\n'", ".", "format", "(", "msg", ",", "e", ")", ")", "continue", "link", ".", "ensure", "(", "status", "=", "status", "[", "section", "]", ",", "cost", "=", "link_dict", "[", "'cost'", "]", ")" ]
Updates topology Links are not deleted straightaway but set as "disconnected"
[ "Updates", "topology", "Links", "are", "not", "deleted", "straightaway", "but", "set", "as", "disconnected" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/models/topology.py#L90-L120
ninuxorg/nodeshot
nodeshot/interop/sync/models/layer_external.py
LayerExternal.clean
def clean(self, *args, **kwargs): """ Call self.synchronizer.clean method """ if self.synchronizer_path != 'None' and self.config: # call synchronizer custom clean try: self.synchronizer.load_config(self.config) self.synchronizer.clean() except ImproperlyConfigured as e: raise ValidationError(e.message)
python
def clean(self, *args, **kwargs): """ Call self.synchronizer.clean method """ if self.synchronizer_path != 'None' and self.config: # call synchronizer custom clean try: self.synchronizer.load_config(self.config) self.synchronizer.clean() except ImproperlyConfigured as e: raise ValidationError(e.message)
[ "def", "clean", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "synchronizer_path", "!=", "'None'", "and", "self", ".", "config", ":", "# call synchronizer custom clean", "try", ":", "self", ".", "synchronizer", ".", "load_config", "(", "self", ".", "config", ")", "self", ".", "synchronizer", ".", "clean", "(", ")", "except", "ImproperlyConfigured", "as", "e", ":", "raise", "ValidationError", "(", "e", ".", "message", ")" ]
Call self.synchronizer.clean method
[ "Call", "self", ".", "synchronizer", ".", "clean", "method" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/layer_external.py#L72-L82
ninuxorg/nodeshot
nodeshot/interop/sync/models/layer_external.py
LayerExternal.save
def save(self, *args, **kwargs): """ call synchronizer "after_external_layer_saved" method for any additional operation that must be executed after save """ after_save = kwargs.pop('after_save', True) super(LayerExternal, self).save(*args, **kwargs) # call after_external_layer_saved method of synchronizer if after_save: try: synchronizer = self.synchronizer except ImproperlyConfigured: pass else: if synchronizer: synchronizer.after_external_layer_saved(self.config) # reload schema self._reload_schema()
python
def save(self, *args, **kwargs): """ call synchronizer "after_external_layer_saved" method for any additional operation that must be executed after save """ after_save = kwargs.pop('after_save', True) super(LayerExternal, self).save(*args, **kwargs) # call after_external_layer_saved method of synchronizer if after_save: try: synchronizer = self.synchronizer except ImproperlyConfigured: pass else: if synchronizer: synchronizer.after_external_layer_saved(self.config) # reload schema self._reload_schema()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "after_save", "=", "kwargs", ".", "pop", "(", "'after_save'", ",", "True", ")", "super", "(", "LayerExternal", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# call after_external_layer_saved method of synchronizer", "if", "after_save", ":", "try", ":", "synchronizer", "=", "self", ".", "synchronizer", "except", "ImproperlyConfigured", ":", "pass", "else", ":", "if", "synchronizer", ":", "synchronizer", ".", "after_external_layer_saved", "(", "self", ".", "config", ")", "# reload schema", "self", ".", "_reload_schema", "(", ")" ]
call synchronizer "after_external_layer_saved" method for any additional operation that must be executed after save
[ "call", "synchronizer", "after_external_layer_saved", "method", "for", "any", "additional", "operation", "that", "must", "be", "executed", "after", "save" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/layer_external.py#L84-L101
ninuxorg/nodeshot
nodeshot/interop/sync/models/layer_external.py
LayerExternal.synchronizer
def synchronizer(self): """ access synchronizer """ if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer: return False # ensure data is up to date if (self._synchronizer is not None and self._synchronizer_class.__name__ not in self.synchronizer_path): self._synchronizer = None self._synchronizer_class = None # init synchronizer only if necessary if not self._synchronizer: self._synchronizer = (self.synchronizer_class)(self.layer) return self._synchronizer
python
def synchronizer(self): """ access synchronizer """ if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer: return False # ensure data is up to date if (self._synchronizer is not None and self._synchronizer_class.__name__ not in self.synchronizer_path): self._synchronizer = None self._synchronizer_class = None # init synchronizer only if necessary if not self._synchronizer: self._synchronizer = (self.synchronizer_class)(self.layer) return self._synchronizer
[ "def", "synchronizer", "(", "self", ")", ":", "if", "not", "self", ".", "synchronizer_path", "or", "self", ".", "synchronizer_path", "==", "'None'", "or", "not", "self", ".", "layer", ":", "return", "False", "# ensure data is up to date", "if", "(", "self", ".", "_synchronizer", "is", "not", "None", "and", "self", ".", "_synchronizer_class", ".", "__name__", "not", "in", "self", ".", "synchronizer_path", ")", ":", "self", ".", "_synchronizer", "=", "None", "self", ".", "_synchronizer_class", "=", "None", "# init synchronizer only if necessary", "if", "not", "self", ".", "_synchronizer", ":", "self", ".", "_synchronizer", "=", "(", "self", ".", "synchronizer_class", ")", "(", "self", ".", "layer", ")", "return", "self", ".", "_synchronizer" ]
access synchronizer
[ "access", "synchronizer" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/layer_external.py#L104-L115
ninuxorg/nodeshot
nodeshot/interop/sync/models/layer_external.py
LayerExternal.synchronizer_class
def synchronizer_class(self): """ returns synchronizer class """ if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer: return False # ensure data is up to date if (self._synchronizer_class is not None and self._synchronizer_class.__name__ not in self.synchronizer_path): self._synchronizer = None self._synchronizer_class = None # import synchronizer class only if not imported already if not self._synchronizer_class: self._synchronizer_class = import_by_path(self.synchronizer_path) return self._synchronizer_class
python
def synchronizer_class(self): """ returns synchronizer class """ if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer: return False # ensure data is up to date if (self._synchronizer_class is not None and self._synchronizer_class.__name__ not in self.synchronizer_path): self._synchronizer = None self._synchronizer_class = None # import synchronizer class only if not imported already if not self._synchronizer_class: self._synchronizer_class = import_by_path(self.synchronizer_path) return self._synchronizer_class
[ "def", "synchronizer_class", "(", "self", ")", ":", "if", "not", "self", ".", "synchronizer_path", "or", "self", ".", "synchronizer_path", "==", "'None'", "or", "not", "self", ".", "layer", ":", "return", "False", "# ensure data is up to date", "if", "(", "self", ".", "_synchronizer_class", "is", "not", "None", "and", "self", ".", "_synchronizer_class", ".", "__name__", "not", "in", "self", ".", "synchronizer_path", ")", ":", "self", ".", "_synchronizer", "=", "None", "self", ".", "_synchronizer_class", "=", "None", "# import synchronizer class only if not imported already", "if", "not", "self", ".", "_synchronizer_class", ":", "self", ".", "_synchronizer_class", "=", "import_by_path", "(", "self", ".", "synchronizer_path", ")", "return", "self", ".", "_synchronizer_class" ]
returns synchronizer class
[ "returns", "synchronizer", "class" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/layer_external.py#L118-L129
ninuxorg/nodeshot
nodeshot/core/nodes/serializers.py
NodeSerializer.get_can_edit
def get_can_edit(self, obj): """ returns true if user has permission to edit, false otherwise """ view = self.context.get('view') request = copy(self.context.get('request')) request._method = 'PUT' try: view.check_object_permissions(request, obj) except (PermissionDenied, NotAuthenticated): return False else: return True
python
def get_can_edit(self, obj): """ returns true if user has permission to edit, false otherwise """ view = self.context.get('view') request = copy(self.context.get('request')) request._method = 'PUT' try: view.check_object_permissions(request, obj) except (PermissionDenied, NotAuthenticated): return False else: return True
[ "def", "get_can_edit", "(", "self", ",", "obj", ")", ":", "view", "=", "self", ".", "context", ".", "get", "(", "'view'", ")", "request", "=", "copy", "(", "self", ".", "context", ".", "get", "(", "'request'", ")", ")", "request", ".", "_method", "=", "'PUT'", "try", ":", "view", ".", "check_object_permissions", "(", "request", ",", "obj", ")", "except", "(", "PermissionDenied", ",", "NotAuthenticated", ")", ":", "return", "False", "else", ":", "return", "True" ]
returns true if user has permission to edit, false otherwise
[ "returns", "true", "if", "user", "has", "permission", "to", "edit", "false", "otherwise" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/serializers.py#L28-L38
ninuxorg/nodeshot
nodeshot/core/nodes/serializers.py
ImageSerializer.get_details
def get_details(self, obj): """ returns uri of API image resource """ args = { 'slug': obj.node.slug, 'pk': obj.pk } return reverse('api_node_image_detail', kwargs=args, request=self.context.get('request', None))
python
def get_details(self, obj): """ returns uri of API image resource """ args = { 'slug': obj.node.slug, 'pk': obj.pk } return reverse('api_node_image_detail', kwargs=args, request=self.context.get('request', None))
[ "def", "get_details", "(", "self", ",", "obj", ")", ":", "args", "=", "{", "'slug'", ":", "obj", ".", "node", ".", "slug", ",", "'pk'", ":", "obj", ".", "pk", "}", "return", "reverse", "(", "'api_node_image_detail'", ",", "kwargs", "=", "args", ",", "request", "=", "self", ".", "context", ".", "get", "(", "'request'", ",", "None", ")", ")" ]
returns uri of API image resource
[ "returns", "uri", "of", "API", "image", "resource" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/serializers.py#L91-L99
ninuxorg/nodeshot
nodeshot/interop/sync/synchronizers/georss.py
GeoRss.parse
def parse(self): """ parse data """ super(GeoRss, self).parse() # support RSS and ATOM tag_name = 'item' if '<item>' in self.data else 'entry' self.parsed_data = self.parsed_data.getElementsByTagName(tag_name)
python
def parse(self): """ parse data """ super(GeoRss, self).parse() # support RSS and ATOM tag_name = 'item' if '<item>' in self.data else 'entry' self.parsed_data = self.parsed_data.getElementsByTagName(tag_name)
[ "def", "parse", "(", "self", ")", ":", "super", "(", "GeoRss", ",", "self", ")", ".", "parse", "(", ")", "# support RSS and ATOM", "tag_name", "=", "'item'", "if", "'<item>'", "in", "self", ".", "data", "else", "'entry'", "self", ".", "parsed_data", "=", "self", ".", "parsed_data", ".", "getElementsByTagName", "(", "tag_name", ")" ]
parse data
[ "parse", "data" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/georss.py#L162-L169
ninuxorg/nodeshot
nodeshot/community/profiles/permissions.py
IsProfileOwner.has_permission
def has_permission(self, request, view): """ applies to social-link-list """ if request.method == 'POST': user = Profile.objects.only('id', 'username').get(username=view.kwargs['username']) return request.user.id == user.id return True
python
def has_permission(self, request, view): """ applies to social-link-list """ if request.method == 'POST': user = Profile.objects.only('id', 'username').get(username=view.kwargs['username']) return request.user.id == user.id return True
[ "def", "has_permission", "(", "self", ",", "request", ",", "view", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "user", "=", "Profile", ".", "objects", ".", "only", "(", "'id'", ",", "'username'", ")", ".", "get", "(", "username", "=", "view", ".", "kwargs", "[", "'username'", "]", ")", "return", "request", ".", "user", ".", "id", "==", "user", ".", "id", "return", "True" ]
applies to social-link-list
[ "applies", "to", "social", "-", "link", "-", "list" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/permissions.py#L33-L39
ninuxorg/nodeshot
nodeshot/core/nodes/models/image.py
Image.delete
def delete(self, *args, **kwargs): """ delete image when an image record is deleted """ try: os.remove(self.file.file.name) # image does not exist except (OSError, IOError): pass super(Image, self).delete(*args, **kwargs)
python
def delete(self, *args, **kwargs): """ delete image when an image record is deleted """ try: os.remove(self.file.file.name) # image does not exist except (OSError, IOError): pass super(Image, self).delete(*args, **kwargs)
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "os", ".", "remove", "(", "self", ".", "file", ".", "file", ".", "name", ")", "# image does not exist", "except", "(", "OSError", ",", "IOError", ")", ":", "pass", "super", "(", "Image", ",", "self", ")", ".", "delete", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
delete image when an image record is deleted
[ "delete", "image", "when", "an", "image", "record", "is", "deleted" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/image.py#L33-L40
ninuxorg/nodeshot
nodeshot/interop/oldimporter/models.py
OldLink.get_quality
def get_quality(self, type='etx'): """ used to determine color of links""" if type == 'etx': if 0 < self.etx < 1.5: quality = 1 elif self.etx < 3: quality = 2 else: quality = 3 elif type == 'dbm': if -83 < self.dbm < 0: quality = 1 elif self.dbm > -88: quality = 2 else: quality = 3 return quality
python
def get_quality(self, type='etx'): """ used to determine color of links""" if type == 'etx': if 0 < self.etx < 1.5: quality = 1 elif self.etx < 3: quality = 2 else: quality = 3 elif type == 'dbm': if -83 < self.dbm < 0: quality = 1 elif self.dbm > -88: quality = 2 else: quality = 3 return quality
[ "def", "get_quality", "(", "self", ",", "type", "=", "'etx'", ")", ":", "if", "type", "==", "'etx'", ":", "if", "0", "<", "self", ".", "etx", "<", "1.5", ":", "quality", "=", "1", "elif", "self", ".", "etx", "<", "3", ":", "quality", "=", "2", "else", ":", "quality", "=", "3", "elif", "type", "==", "'dbm'", ":", "if", "-", "83", "<", "self", ".", "dbm", "<", "0", ":", "quality", "=", "1", "elif", "self", ".", "dbm", ">", "-", "88", ":", "quality", "=", "2", "else", ":", "quality", "=", "3", "return", "quality" ]
used to determine color of links
[ "used", "to", "determine", "color", "of", "links" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/models.py#L157-L173
ninuxorg/nodeshot
nodeshot/core/layers/models/layer.py
new_nodes_allowed_for_layer
def new_nodes_allowed_for_layer(self): """ ensure new nodes are allowed for this layer """ if not self.pk and self.layer and not self.layer.new_nodes_allowed: raise ValidationError(_('New nodes are not allowed for this layer'))
python
def new_nodes_allowed_for_layer(self): """ ensure new nodes are allowed for this layer """ if not self.pk and self.layer and not self.layer.new_nodes_allowed: raise ValidationError(_('New nodes are not allowed for this layer'))
[ "def", "new_nodes_allowed_for_layer", "(", "self", ")", ":", "if", "not", "self", ".", "pk", "and", "self", ".", "layer", "and", "not", "self", ".", "layer", ".", "new_nodes_allowed", ":", "raise", "ValidationError", "(", "_", "(", "'New nodes are not allowed for this layer'", ")", ")" ]
ensure new nodes are allowed for this layer
[ "ensure", "new", "nodes", "are", "allowed", "for", "this", "layer" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/models/layer.py#L138-L143
ninuxorg/nodeshot
nodeshot/core/layers/models/layer.py
nodes_minimum_distance_validation
def nodes_minimum_distance_validation(self): """ if minimum distance is specified, ensure node is not too close to other nodes; """ if self.layer and self.layer.nodes_minimum_distance: minimum_distance = self.layer.nodes_minimum_distance # TODO - lower priority: do this check only when coordinates are changing near_nodes = Node.objects.exclude(pk=self.id).filter(geometry__distance_lte=(self.geometry, D(m=minimum_distance))).count() if near_nodes > 0: raise ValidationError(_('Distance between nodes cannot be less than %s meters') % minimum_distance)
python
def nodes_minimum_distance_validation(self): """ if minimum distance is specified, ensure node is not too close to other nodes; """ if self.layer and self.layer.nodes_minimum_distance: minimum_distance = self.layer.nodes_minimum_distance # TODO - lower priority: do this check only when coordinates are changing near_nodes = Node.objects.exclude(pk=self.id).filter(geometry__distance_lte=(self.geometry, D(m=minimum_distance))).count() if near_nodes > 0: raise ValidationError(_('Distance between nodes cannot be less than %s meters') % minimum_distance)
[ "def", "nodes_minimum_distance_validation", "(", "self", ")", ":", "if", "self", ".", "layer", "and", "self", ".", "layer", ".", "nodes_minimum_distance", ":", "minimum_distance", "=", "self", ".", "layer", ".", "nodes_minimum_distance", "# TODO - lower priority: do this check only when coordinates are changing", "near_nodes", "=", "Node", ".", "objects", ".", "exclude", "(", "pk", "=", "self", ".", "id", ")", ".", "filter", "(", "geometry__distance_lte", "=", "(", "self", ".", "geometry", ",", "D", "(", "m", "=", "minimum_distance", ")", ")", ")", ".", "count", "(", ")", "if", "near_nodes", ">", "0", ":", "raise", "ValidationError", "(", "_", "(", "'Distance between nodes cannot be less than %s meters'", ")", "%", "minimum_distance", ")" ]
if minimum distance is specified, ensure node is not too close to other nodes;
[ "if", "minimum", "distance", "is", "specified", "ensure", "node", "is", "not", "too", "close", "to", "other", "nodes", ";" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/models/layer.py#L146-L155
ninuxorg/nodeshot
nodeshot/core/layers/models/layer.py
node_contained_in_layer_area_validation
def node_contained_in_layer_area_validation(self): """ if layer defines an area, ensure node coordinates are contained in the area """ # if area is a polygon ensure it contains the node if self.layer and isinstance(self.layer.area, Polygon) and not self.layer.area.contains(self.geometry): raise ValidationError(_('Node must be inside layer area'))
python
def node_contained_in_layer_area_validation(self): """ if layer defines an area, ensure node coordinates are contained in the area """ # if area is a polygon ensure it contains the node if self.layer and isinstance(self.layer.area, Polygon) and not self.layer.area.contains(self.geometry): raise ValidationError(_('Node must be inside layer area'))
[ "def", "node_contained_in_layer_area_validation", "(", "self", ")", ":", "# if area is a polygon ensure it contains the node", "if", "self", ".", "layer", "and", "isinstance", "(", "self", ".", "layer", ".", "area", ",", "Polygon", ")", "and", "not", "self", ".", "layer", ".", "area", ".", "contains", "(", "self", ".", "geometry", ")", ":", "raise", "ValidationError", "(", "_", "(", "'Node must be inside layer area'", ")", ")" ]
if layer defines an area, ensure node coordinates are contained in the area
[ "if", "layer", "defines", "an", "area", "ensure", "node", "coordinates", "are", "contained", "in", "the", "area" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/models/layer.py#L158-L164
ninuxorg/nodeshot
nodeshot/core/layers/models/layer.py
Layer.save
def save(self, *args, **kwargs): """ intercepts changes to is_published and fires layer_is_published_changed signal """ super(Layer, self).save(*args, **kwargs) # if is_published of an existing layer changes if self.pk and self.is_published != self._current_is_published: # send django signal layer_is_published_changed.send( sender=self.__class__, instance=self, old_is_published=self._current_is_published, new_is_published=self.is_published ) # unpublish nodes self.update_nodes_published() # update _current_is_published self._current_is_published = self.is_published
python
def save(self, *args, **kwargs): """ intercepts changes to is_published and fires layer_is_published_changed signal """ super(Layer, self).save(*args, **kwargs) # if is_published of an existing layer changes if self.pk and self.is_published != self._current_is_published: # send django signal layer_is_published_changed.send( sender=self.__class__, instance=self, old_is_published=self._current_is_published, new_is_published=self.is_published ) # unpublish nodes self.update_nodes_published() # update _current_is_published self._current_is_published = self.is_published
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Layer", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# if is_published of an existing layer changes", "if", "self", ".", "pk", "and", "self", ".", "is_published", "!=", "self", ".", "_current_is_published", ":", "# send django signal", "layer_is_published_changed", ".", "send", "(", "sender", "=", "self", ".", "__class__", ",", "instance", "=", "self", ",", "old_is_published", "=", "self", ".", "_current_is_published", ",", "new_is_published", "=", "self", ".", "is_published", ")", "# unpublish nodes", "self", ".", "update_nodes_published", "(", ")", "# update _current_is_published", "self", ".", "_current_is_published", "=", "self", ".", "is_published" ]
intercepts changes to is_published and fires layer_is_published_changed signal
[ "intercepts", "changes", "to", "is_published", "and", "fires", "layer_is_published_changed", "signal" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/models/layer.py#L72-L91
ninuxorg/nodeshot
nodeshot/core/layers/models/layer.py
Layer.update_nodes_published
def update_nodes_published(self): """ publish or unpublish nodes of current layer """ if self.pk: self.node_set.all().update(is_published=self.is_published)
python
def update_nodes_published(self): """ publish or unpublish nodes of current layer """ if self.pk: self.node_set.all().update(is_published=self.is_published)
[ "def", "update_nodes_published", "(", "self", ")", ":", "if", "self", ".", "pk", ":", "self", ".", "node_set", ".", "all", "(", ")", ".", "update", "(", "is_published", "=", "self", ".", "is_published", ")" ]
publish or unpublish nodes of current layer
[ "publish", "or", "unpublish", "nodes", "of", "current", "layer" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/models/layer.py#L114-L117
ninuxorg/nodeshot
nodeshot/community/notifications/views.py
NotificationList.get
def get(self, request, format=None): """ get HTTP method """ action = request.query_params.get('action', 'unread') # action can be only "unread" (default), "count" and "all" action = action if action == 'count' or action == 'all' else 'unread' # mark as read parameter, defaults to true mark_as_read = request.query_params.get('read', 'true') == 'true' # queryset notifications = self.get_queryset().filter(to_user=request.user) # pass to specific action return getattr(self, 'get_%s' % action)(request, notifications, mark_as_read)
python
def get(self, request, format=None): """ get HTTP method """ action = request.query_params.get('action', 'unread') # action can be only "unread" (default), "count" and "all" action = action if action == 'count' or action == 'all' else 'unread' # mark as read parameter, defaults to true mark_as_read = request.query_params.get('read', 'true') == 'true' # queryset notifications = self.get_queryset().filter(to_user=request.user) # pass to specific action return getattr(self, 'get_%s' % action)(request, notifications, mark_as_read)
[ "def", "get", "(", "self", ",", "request", ",", "format", "=", "None", ")", ":", "action", "=", "request", ".", "query_params", ".", "get", "(", "'action'", ",", "'unread'", ")", "# action can be only \"unread\" (default), \"count\" and \"all\"", "action", "=", "action", "if", "action", "==", "'count'", "or", "action", "==", "'all'", "else", "'unread'", "# mark as read parameter, defaults to true", "mark_as_read", "=", "request", ".", "query_params", ".", "get", "(", "'read'", ",", "'true'", ")", "==", "'true'", "# queryset", "notifications", "=", "self", ".", "get_queryset", "(", ")", ".", "filter", "(", "to_user", "=", "request", ".", "user", ")", "# pass to specific action", "return", "getattr", "(", "self", ",", "'get_%s'", "%", "action", ")", "(", "request", ",", "notifications", ",", "mark_as_read", ")" ]
get HTTP method
[ "get", "HTTP", "method" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/views.py#L36-L46
ninuxorg/nodeshot
nodeshot/community/notifications/views.py
NotificationList.get_unread
def get_unread(self, request, notifications, mark_as_read): """ return unread notifications and mark as read (unless read=false param is passed) """ notifications = notifications.filter(is_read=False) serializer = UnreadNotificationSerializer(list(notifications), # evaluate queryset many=True, context=self.get_serializer_context()) # retrieve unread notifications as read (default behaviour) if mark_as_read: notifications.update(is_read=True) return Response(serializer.data)
python
def get_unread(self, request, notifications, mark_as_read): """ return unread notifications and mark as read (unless read=false param is passed) """ notifications = notifications.filter(is_read=False) serializer = UnreadNotificationSerializer(list(notifications), # evaluate queryset many=True, context=self.get_serializer_context()) # retrieve unread notifications as read (default behaviour) if mark_as_read: notifications.update(is_read=True) return Response(serializer.data)
[ "def", "get_unread", "(", "self", ",", "request", ",", "notifications", ",", "mark_as_read", ")", ":", "notifications", "=", "notifications", ".", "filter", "(", "is_read", "=", "False", ")", "serializer", "=", "UnreadNotificationSerializer", "(", "list", "(", "notifications", ")", ",", "# evaluate queryset", "many", "=", "True", ",", "context", "=", "self", ".", "get_serializer_context", "(", ")", ")", "# retrieve unread notifications as read (default behaviour)", "if", "mark_as_read", ":", "notifications", ".", "update", "(", "is_read", "=", "True", ")", "return", "Response", "(", "serializer", ".", "data", ")" ]
return unread notifications and mark as read (unless read=false param is passed)
[ "return", "unread", "notifications", "and", "mark", "as", "read", "(", "unless", "read", "=", "false", "param", "is", "passed", ")" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/views.py#L48-L60
ninuxorg/nodeshot
nodeshot/community/notifications/views.py
NotificationList.get_count
def get_count(self, request, notifications, mark_as_read=False): """ return count of unread notification """ return Response({'count': notifications.filter(is_read=False).count()})
python
def get_count(self, request, notifications, mark_as_read=False): """ return count of unread notification """ return Response({'count': notifications.filter(is_read=False).count()})
[ "def", "get_count", "(", "self", ",", "request", ",", "notifications", ",", "mark_as_read", "=", "False", ")", ":", "return", "Response", "(", "{", "'count'", ":", "notifications", ".", "filter", "(", "is_read", "=", "False", ")", ".", "count", "(", ")", "}", ")" ]
return count of unread notification
[ "return", "count", "of", "unread", "notification" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/views.py#L62-L64
ninuxorg/nodeshot
nodeshot/community/notifications/views.py
NotificationList.get_all
def get_all(self, request, notifications, mark_as_read=False): """ return all notifications with pagination """ return self.list(request, notifications)
python
def get_all(self, request, notifications, mark_as_read=False): """ return all notifications with pagination """ return self.list(request, notifications)
[ "def", "get_all", "(", "self", ",", "request", ",", "notifications", ",", "mark_as_read", "=", "False", ")", ":", "return", "self", ".", "list", "(", "request", ",", "notifications", ")" ]
return all notifications with pagination
[ "return", "all", "notifications", "with", "pagination" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/views.py#L66-L68
ninuxorg/nodeshot
nodeshot/community/notifications/views.py
EmailNotificationSettings.get_object
def get_object(self, queryset=None): """ get privacy settings of current user """ try: obj = self.get_queryset() except self.model.DoesNotExist: raise Http404() self.check_object_permissions(self.request, obj) return obj
python
def get_object(self, queryset=None): """ get privacy settings of current user """ try: obj = self.get_queryset() except self.model.DoesNotExist: raise Http404() self.check_object_permissions(self.request, obj) return obj
[ "def", "get_object", "(", "self", ",", "queryset", "=", "None", ")", ":", "try", ":", "obj", "=", "self", ".", "get_queryset", "(", ")", "except", "self", ".", "model", ".", "DoesNotExist", ":", "raise", "Http404", "(", ")", "self", ".", "check_object_permissions", "(", "self", ".", "request", ",", "obj", ")", "return", "obj" ]
get privacy settings of current user
[ "get", "privacy", "settings", "of", "current", "user" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/views.py#L108-L115
ninuxorg/nodeshot
nodeshot/networking/links/models/link.py
Link.clean
def clean(self, *args, **kwargs): """ Custom validation 1. interface_a and interface_b mandatory except for planned links 2. planned links should have at least node_a and node_b filled in 3. dbm and noise fields can be filled only for radio links 4. interface_a and interface_b must differ 5. interface a and b type must match """ if self.status != LINK_STATUS.get('planned'): if self.interface_a is None or self.interface_b is None: raise ValidationError(_('fields "from interface" and "to interface" are mandatory in this case')) if (self.interface_a_id == self.interface_b_id) or (self.interface_a == self.interface_b): msg = _('link cannot have same "from interface" and "to interface: %s"') % self.interface_a raise ValidationError(msg) if self.status == LINK_STATUS.get('planned') and (self.node_a is None or self.node_b is None): raise ValidationError(_('fields "from node" and "to node" are mandatory for planned links')) if self.type != LINK_TYPES.get('radio') and (self.dbm is not None or self.noise is not None): raise ValidationError(_('Only links of type "radio" can contain "dbm" and "noise" information'))
python
def clean(self, *args, **kwargs): """ Custom validation 1. interface_a and interface_b mandatory except for planned links 2. planned links should have at least node_a and node_b filled in 3. dbm and noise fields can be filled only for radio links 4. interface_a and interface_b must differ 5. interface a and b type must match """ if self.status != LINK_STATUS.get('planned'): if self.interface_a is None or self.interface_b is None: raise ValidationError(_('fields "from interface" and "to interface" are mandatory in this case')) if (self.interface_a_id == self.interface_b_id) or (self.interface_a == self.interface_b): msg = _('link cannot have same "from interface" and "to interface: %s"') % self.interface_a raise ValidationError(msg) if self.status == LINK_STATUS.get('planned') and (self.node_a is None or self.node_b is None): raise ValidationError(_('fields "from node" and "to node" are mandatory for planned links')) if self.type != LINK_TYPES.get('radio') and (self.dbm is not None or self.noise is not None): raise ValidationError(_('Only links of type "radio" can contain "dbm" and "noise" information'))
[ "def", "clean", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "status", "!=", "LINK_STATUS", ".", "get", "(", "'planned'", ")", ":", "if", "self", ".", "interface_a", "is", "None", "or", "self", ".", "interface_b", "is", "None", ":", "raise", "ValidationError", "(", "_", "(", "'fields \"from interface\" and \"to interface\" are mandatory in this case'", ")", ")", "if", "(", "self", ".", "interface_a_id", "==", "self", ".", "interface_b_id", ")", "or", "(", "self", ".", "interface_a", "==", "self", ".", "interface_b", ")", ":", "msg", "=", "_", "(", "'link cannot have same \"from interface\" and \"to interface: %s\"'", ")", "%", "self", ".", "interface_a", "raise", "ValidationError", "(", "msg", ")", "if", "self", ".", "status", "==", "LINK_STATUS", ".", "get", "(", "'planned'", ")", "and", "(", "self", ".", "node_a", "is", "None", "or", "self", ".", "node_b", "is", "None", ")", ":", "raise", "ValidationError", "(", "_", "(", "'fields \"from node\" and \"to node\" are mandatory for planned links'", ")", ")", "if", "self", ".", "type", "!=", "LINK_TYPES", ".", "get", "(", "'radio'", ")", "and", "(", "self", ".", "dbm", "is", "not", "None", "or", "self", ".", "noise", "is", "not", "None", ")", ":", "raise", "ValidationError", "(", "_", "(", "'Only links of type \"radio\" can contain \"dbm\" and \"noise\" information'", ")", ")" ]
Custom validation 1. interface_a and interface_b mandatory except for planned links 2. planned links should have at least node_a and node_b filled in 3. dbm and noise fields can be filled only for radio links 4. interface_a and interface_b must differ 5. interface a and b type must match
[ "Custom", "validation", "1", ".", "interface_a", "and", "interface_b", "mandatory", "except", "for", "planned", "links", "2", ".", "planned", "links", "should", "have", "at", "least", "node_a", "and", "node_b", "filled", "in", "3", ".", "dbm", "and", "noise", "fields", "can", "be", "filled", "only", "for", "radio", "links", "4", ".", "interface_a", "and", "interface_b", "must", "differ", "5", ".", "interface", "a", "and", "b", "type", "must", "match" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/models/link.py#L89-L110
ninuxorg/nodeshot
nodeshot/networking/links/models/link.py
Link.save
def save(self, *args, **kwargs): """ Custom save does the following: * determine link type if not specified * automatically fill 'node_a' and 'node_b' fields if necessary * draw line between two nodes * fill shortcut properties node_a_name and node_b_name """ if not self.type: if self.interface_a.type == INTERFACE_TYPES.get('wireless'): self.type = LINK_TYPES.get('radio') elif self.interface_a.type == INTERFACE_TYPES.get('ethernet'): self.type = LINK_TYPES.get('ethernet') else: self.type = LINK_TYPES.get('virtual') if self.interface_a_id: self.interface_a = Interface.objects.get(pk=self.interface_a_id) if self.interface_b_id: self.interface_b = Interface.objects.get(pk=self.interface_b_id) # fill in node_a and node_b if self.node_a is None and self.interface_a is not None: self.node_a = self.interface_a.node if self.node_b is None and self.interface_b is not None: self.node_b = self.interface_b.node # fill layer from node_a if self.layer is None: self.layer = self.node_a.layer # draw linestring if not self.line: self.line = LineString(self.node_a.point, self.node_b.point) # fill properties if self.data.get('node_a_name', None) is None: self.data['node_a_name'] = self.node_a.name self.data['node_b_name'] = self.node_b.name if self.data.get('node_a_slug', None) is None or self.data.get('node_b_slug', None) is None: self.data['node_a_slug'] = self.node_a.slug self.data['node_b_slug'] = self.node_b.slug if self.interface_a and self.data.get('interface_a_mac', None) is None: self.data['interface_a_mac'] = self.interface_a.mac if self.interface_b and self.data.get('interface_b_mac', None) is None: self.data['interface_b_mac'] = self.interface_b.mac if self.data.get('layer_slug') != self.layer.slug: self.data['layer_slug'] = self.layer.slug super(Link, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): """ Custom save does the following: * determine link type if not specified * automatically fill 'node_a' and 'node_b' fields if necessary * draw line between two nodes * fill shortcut properties node_a_name and node_b_name """ if not self.type: if self.interface_a.type == INTERFACE_TYPES.get('wireless'): self.type = LINK_TYPES.get('radio') elif self.interface_a.type == INTERFACE_TYPES.get('ethernet'): self.type = LINK_TYPES.get('ethernet') else: self.type = LINK_TYPES.get('virtual') if self.interface_a_id: self.interface_a = Interface.objects.get(pk=self.interface_a_id) if self.interface_b_id: self.interface_b = Interface.objects.get(pk=self.interface_b_id) # fill in node_a and node_b if self.node_a is None and self.interface_a is not None: self.node_a = self.interface_a.node if self.node_b is None and self.interface_b is not None: self.node_b = self.interface_b.node # fill layer from node_a if self.layer is None: self.layer = self.node_a.layer # draw linestring if not self.line: self.line = LineString(self.node_a.point, self.node_b.point) # fill properties if self.data.get('node_a_name', None) is None: self.data['node_a_name'] = self.node_a.name self.data['node_b_name'] = self.node_b.name if self.data.get('node_a_slug', None) is None or self.data.get('node_b_slug', None) is None: self.data['node_a_slug'] = self.node_a.slug self.data['node_b_slug'] = self.node_b.slug if self.interface_a and self.data.get('interface_a_mac', None) is None: self.data['interface_a_mac'] = self.interface_a.mac if self.interface_b and self.data.get('interface_b_mac', None) is None: self.data['interface_b_mac'] = self.interface_b.mac if self.data.get('layer_slug') != self.layer.slug: self.data['layer_slug'] = self.layer.slug super(Link, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "type", ":", "if", "self", ".", "interface_a", ".", "type", "==", "INTERFACE_TYPES", ".", "get", "(", "'wireless'", ")", ":", "self", ".", "type", "=", "LINK_TYPES", ".", "get", "(", "'radio'", ")", "elif", "self", ".", "interface_a", ".", "type", "==", "INTERFACE_TYPES", ".", "get", "(", "'ethernet'", ")", ":", "self", ".", "type", "=", "LINK_TYPES", ".", "get", "(", "'ethernet'", ")", "else", ":", "self", ".", "type", "=", "LINK_TYPES", ".", "get", "(", "'virtual'", ")", "if", "self", ".", "interface_a_id", ":", "self", ".", "interface_a", "=", "Interface", ".", "objects", ".", "get", "(", "pk", "=", "self", ".", "interface_a_id", ")", "if", "self", ".", "interface_b_id", ":", "self", ".", "interface_b", "=", "Interface", ".", "objects", ".", "get", "(", "pk", "=", "self", ".", "interface_b_id", ")", "# fill in node_a and node_b", "if", "self", ".", "node_a", "is", "None", "and", "self", ".", "interface_a", "is", "not", "None", ":", "self", ".", "node_a", "=", "self", ".", "interface_a", ".", "node", "if", "self", ".", "node_b", "is", "None", "and", "self", ".", "interface_b", "is", "not", "None", ":", "self", ".", "node_b", "=", "self", ".", "interface_b", ".", "node", "# fill layer from node_a", "if", "self", ".", "layer", "is", "None", ":", "self", ".", "layer", "=", "self", ".", "node_a", ".", "layer", "# draw linestring", "if", "not", "self", ".", "line", ":", "self", ".", "line", "=", "LineString", "(", "self", ".", "node_a", ".", "point", ",", "self", ".", "node_b", ".", "point", ")", "# fill properties", "if", "self", ".", "data", ".", "get", "(", "'node_a_name'", ",", "None", ")", "is", "None", ":", "self", ".", "data", "[", "'node_a_name'", "]", "=", "self", ".", "node_a", ".", "name", "self", ".", "data", "[", "'node_b_name'", "]", "=", "self", ".", "node_b", ".", "name", "if", "self", ".", "data", ".", "get", "(", "'node_a_slug'", ",", "None", ")", "is", "None", "or", "self", ".", "data", ".", "get", "(", "'node_b_slug'", ",", "None", ")", "is", "None", ":", "self", ".", "data", "[", "'node_a_slug'", "]", "=", "self", ".", "node_a", ".", "slug", "self", ".", "data", "[", "'node_b_slug'", "]", "=", "self", ".", "node_b", ".", "slug", "if", "self", ".", "interface_a", "and", "self", ".", "data", ".", "get", "(", "'interface_a_mac'", ",", "None", ")", "is", "None", ":", "self", ".", "data", "[", "'interface_a_mac'", "]", "=", "self", ".", "interface_a", ".", "mac", "if", "self", ".", "interface_b", "and", "self", ".", "data", ".", "get", "(", "'interface_b_mac'", ",", "None", ")", "is", "None", ":", "self", ".", "data", "[", "'interface_b_mac'", "]", "=", "self", ".", "interface_b", ".", "mac", "if", "self", ".", "data", ".", "get", "(", "'layer_slug'", ")", "!=", "self", ".", "layer", ".", "slug", ":", "self", ".", "data", "[", "'layer_slug'", "]", "=", "self", ".", "layer", ".", "slug", "super", "(", "Link", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Custom save does the following: * determine link type if not specified * automatically fill 'node_a' and 'node_b' fields if necessary * draw line between two nodes * fill shortcut properties node_a_name and node_b_name
[ "Custom", "save", "does", "the", "following", ":", "*", "determine", "link", "type", "if", "not", "specified", "*", "automatically", "fill", "node_a", "and", "node_b", "fields", "if", "necessary", "*", "draw", "line", "between", "two", "nodes", "*", "fill", "shortcut", "properties", "node_a_name", "and", "node_b_name" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/models/link.py#L112-L165
ninuxorg/nodeshot
nodeshot/networking/links/models/link.py
Link.get_link
def get_link(cls, source, target, topology=None): """ Find link between source and target, (or vice versa, order is irrelevant). :param source: ip or mac addresses :param target: ip or mac addresses :param topology: optional topology relation :returns: Link object :raises: LinkNotFound """ a = source b = target # ensure parameters are coherent if not (valid_ipv4(a) and valid_ipv4(b)) and not (valid_ipv6(a) and valid_ipv6(b)) and not (valid_mac(a) and valid_mac(b)): raise ValueError('Expecting valid ipv4, ipv6 or mac address') # get interfaces a = cls._get_link_interface(a) b = cls._get_link_interface(b) # raise LinkDataNotFound if an interface is not found not_found = [] if a is None: not_found.append(source) if b is None: not_found.append(target) if not_found: msg = 'the following interfaces could not be found: {0}'.format(', '.join(not_found)) raise LinkDataNotFound(msg) # find link with interfaces # inverse order is also ok q = (Q(interface_a=a, interface_b=b) | Q(interface_a=b, interface_b=a)) # add topology to lookup if topology: q = q & Q(topology=topology) link = Link.objects.filter(q).first() if link is None: raise LinkNotFound('Link matching query does not exist', interface_a=a, interface_b=b, topology=topology) return link
python
def get_link(cls, source, target, topology=None): """ Find link between source and target, (or vice versa, order is irrelevant). :param source: ip or mac addresses :param target: ip or mac addresses :param topology: optional topology relation :returns: Link object :raises: LinkNotFound """ a = source b = target # ensure parameters are coherent if not (valid_ipv4(a) and valid_ipv4(b)) and not (valid_ipv6(a) and valid_ipv6(b)) and not (valid_mac(a) and valid_mac(b)): raise ValueError('Expecting valid ipv4, ipv6 or mac address') # get interfaces a = cls._get_link_interface(a) b = cls._get_link_interface(b) # raise LinkDataNotFound if an interface is not found not_found = [] if a is None: not_found.append(source) if b is None: not_found.append(target) if not_found: msg = 'the following interfaces could not be found: {0}'.format(', '.join(not_found)) raise LinkDataNotFound(msg) # find link with interfaces # inverse order is also ok q = (Q(interface_a=a, interface_b=b) | Q(interface_a=b, interface_b=a)) # add topology to lookup if topology: q = q & Q(topology=topology) link = Link.objects.filter(q).first() if link is None: raise LinkNotFound('Link matching query does not exist', interface_a=a, interface_b=b, topology=topology) return link
[ "def", "get_link", "(", "cls", ",", "source", ",", "target", ",", "topology", "=", "None", ")", ":", "a", "=", "source", "b", "=", "target", "# ensure parameters are coherent", "if", "not", "(", "valid_ipv4", "(", "a", ")", "and", "valid_ipv4", "(", "b", ")", ")", "and", "not", "(", "valid_ipv6", "(", "a", ")", "and", "valid_ipv6", "(", "b", ")", ")", "and", "not", "(", "valid_mac", "(", "a", ")", "and", "valid_mac", "(", "b", ")", ")", ":", "raise", "ValueError", "(", "'Expecting valid ipv4, ipv6 or mac address'", ")", "# get interfaces", "a", "=", "cls", ".", "_get_link_interface", "(", "a", ")", "b", "=", "cls", ".", "_get_link_interface", "(", "b", ")", "# raise LinkDataNotFound if an interface is not found", "not_found", "=", "[", "]", "if", "a", "is", "None", ":", "not_found", ".", "append", "(", "source", ")", "if", "b", "is", "None", ":", "not_found", ".", "append", "(", "target", ")", "if", "not_found", ":", "msg", "=", "'the following interfaces could not be found: {0}'", ".", "format", "(", "', '", ".", "join", "(", "not_found", ")", ")", "raise", "LinkDataNotFound", "(", "msg", ")", "# find link with interfaces", "# inverse order is also ok", "q", "=", "(", "Q", "(", "interface_a", "=", "a", ",", "interface_b", "=", "b", ")", "|", "Q", "(", "interface_a", "=", "b", ",", "interface_b", "=", "a", ")", ")", "# add topology to lookup", "if", "topology", ":", "q", "=", "q", "&", "Q", "(", "topology", "=", "topology", ")", "link", "=", "Link", ".", "objects", ".", "filter", "(", "q", ")", ".", "first", "(", ")", "if", "link", "is", "None", ":", "raise", "LinkNotFound", "(", "'Link matching query does not exist'", ",", "interface_a", "=", "a", ",", "interface_b", "=", "b", ",", "topology", "=", "topology", ")", "return", "link" ]
Find link between source and target, (or vice versa, order is irrelevant). :param source: ip or mac addresses :param target: ip or mac addresses :param topology: optional topology relation :returns: Link object :raises: LinkNotFound
[ "Find", "link", "between", "source", "and", "target", "(", "or", "vice", "versa", "order", "is", "irrelevant", ")", ".", ":", "param", "source", ":", "ip", "or", "mac", "addresses", ":", "param", "target", ":", "ip", "or", "mac", "addresses", ":", "param", "topology", ":", "optional", "topology", "relation", ":", "returns", ":", "Link", "object", ":", "raises", ":", "LinkNotFound" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/models/link.py#L168-L206
ninuxorg/nodeshot
nodeshot/networking/links/models/link.py
Link.get_or_create
def get_or_create(cls, source, target, cost, topology=None): """ Tries to find a link with get_link, creates a new link if link not found. """ try: return cls.get_link(source, target, topology) except LinkNotFound as e: pass # create link link = Link(interface_a=e.interface_a, interface_b=e.interface_b, status=LINK_STATUS['active'], metric_value=cost, topology=topology) link.full_clean() link.save() return link
python
def get_or_create(cls, source, target, cost, topology=None): """ Tries to find a link with get_link, creates a new link if link not found. """ try: return cls.get_link(source, target, topology) except LinkNotFound as e: pass # create link link = Link(interface_a=e.interface_a, interface_b=e.interface_b, status=LINK_STATUS['active'], metric_value=cost, topology=topology) link.full_clean() link.save() return link
[ "def", "get_or_create", "(", "cls", ",", "source", ",", "target", ",", "cost", ",", "topology", "=", "None", ")", ":", "try", ":", "return", "cls", ".", "get_link", "(", "source", ",", "target", ",", "topology", ")", "except", "LinkNotFound", "as", "e", ":", "pass", "# create link", "link", "=", "Link", "(", "interface_a", "=", "e", ".", "interface_a", ",", "interface_b", "=", "e", ".", "interface_b", ",", "status", "=", "LINK_STATUS", "[", "'active'", "]", ",", "metric_value", "=", "cost", ",", "topology", "=", "topology", ")", "link", ".", "full_clean", "(", ")", "link", ".", "save", "(", ")", "return", "link" ]
Tries to find a link with get_link, creates a new link if link not found.
[ "Tries", "to", "find", "a", "link", "with", "get_link", "creates", "a", "new", "link", "if", "link", "not", "found", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/models/link.py#L222-L238
ninuxorg/nodeshot
nodeshot/networking/links/models/link.py
Link.ensure
def ensure(self, status, cost): """ ensure link properties correspond to the specified ones perform save operation only if necessary """ changed = False status_id = LINK_STATUS[status] if self.status != status_id: self.status = status_id changed = True if self.metric_value != cost: self.metric_value = cost changed = True if changed: self.save()
python
def ensure(self, status, cost): """ ensure link properties correspond to the specified ones perform save operation only if necessary """ changed = False status_id = LINK_STATUS[status] if self.status != status_id: self.status = status_id changed = True if self.metric_value != cost: self.metric_value = cost changed = True if changed: self.save()
[ "def", "ensure", "(", "self", ",", "status", ",", "cost", ")", ":", "changed", "=", "False", "status_id", "=", "LINK_STATUS", "[", "status", "]", "if", "self", ".", "status", "!=", "status_id", ":", "self", ".", "status", "=", "status_id", "changed", "=", "True", "if", "self", ".", "metric_value", "!=", "cost", ":", "self", ".", "metric_value", "=", "cost", "changed", "=", "True", "if", "changed", ":", "self", ".", "save", "(", ")" ]
ensure link properties correspond to the specified ones perform save operation only if necessary
[ "ensure", "link", "properties", "correspond", "to", "the", "specified", "ones", "perform", "save", "operation", "only", "if", "necessary" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/models/link.py#L280-L294
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'", ")", ",", "fail_silently", "=", "True", ")" ]
Send action available in change outward list
[ "Send", "action", "available", "in", "change", "outward", "list" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/admin.py#L33-L39
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'", ":", "_", "(", "'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", ")" ]
Contact node owner.
[ "Contact", "node", "owner", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/mailing/views.py#L51-L91
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", "(", "serializer", "(", "request", ".", "user", ",", "context", "=", "self", ".", "get_serializer_context", "(", ")", ")", ".", "data", ")", "else", ":", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "'Authentication credentials were not provided'", ")", "}", ",", "status", "=", "401", ")" ]
return profile of current user if authenticated otherwise 401
[ "return", "profile", "of", "current", "user", "if", "authenticated", "otherwise", "401" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/views.py#L58-L64
ninuxorg/nodeshot
nodeshot/community/profiles/views.py
AccountLogin.post
def post(self, request, format=None): """ authenticate """ serializer = self.serializer_class(data=request.data) if serializer.is_valid(): login(request, serializer.instance) if request.data.get('remember'): # TODO: remember configurable request.session.set_expiry(60 * 60 * 24 * 7 * 3) else: request.session.set_expiry(0) return Response({ 'detail': _(u'Logged in successfully'), 'user': ProfileOwnSerializer(serializer.instance, context={'request': request}).data }) return Response(serializer.errors, status=400)
python
def post(self, request, format=None): """ authenticate """ serializer = self.serializer_class(data=request.data) if serializer.is_valid(): login(request, serializer.instance) if request.data.get('remember'): # TODO: remember configurable request.session.set_expiry(60 * 60 * 24 * 7 * 3) else: request.session.set_expiry(0) return Response({ 'detail': _(u'Logged in successfully'), 'user': ProfileOwnSerializer(serializer.instance, context={'request': request}).data }) return Response(serializer.errors, status=400)
[ "def", "post", "(", "self", ",", "request", ",", "format", "=", "None", ")", ":", "serializer", "=", "self", ".", "serializer_class", "(", "data", "=", "request", ".", "data", ")", "if", "serializer", ".", "is_valid", "(", ")", ":", "login", "(", "request", ",", "serializer", ".", "instance", ")", "if", "request", ".", "data", ".", "get", "(", "'remember'", ")", ":", "# TODO: remember configurable", "request", ".", "session", ".", "set_expiry", "(", "60", "*", "60", "*", "24", "*", "7", "*", "3", ")", "else", ":", "request", ".", "session", ".", "set_expiry", "(", "0", ")", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "u'Logged in successfully'", ")", ",", "'user'", ":", "ProfileOwnSerializer", "(", "serializer", ".", "instance", ",", "context", "=", "{", "'request'", ":", "request", "}", ")", ".", "data", "}", ")", "return", "Response", "(", "serializer", ".", "errors", ",", "status", "=", "400", ")" ]
authenticate
[ "authenticate" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/views.py#L208-L226
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", "=", "request", ".", "user", ")", "if", "serializer", ".", "is_valid", "(", ")", ":", "serializer", ".", "save", "(", ")", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "u'Password successfully changed'", ")", "}", ")", "return", "Response", "(", "serializer", ".", "errors", ",", "status", "=", "400", ")" ]
validate password change operation and return result
[ "validate", "password", "change", "operation", "and", "return", "result" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/views.py#L277-L286
ninuxorg/nodeshot
nodeshot/interop/sync/synchronizers/base.py
BaseSynchronizer.sync
def sync(self): """ This is the method that does everything automatically (at least attempts to). Steps: 0. Call "before_start" method (which might be implemented by children classes) 1. Retrieve data from external source 2. Parse the data 3. Save the data locally 4. Call "after_complete" method (which might be implemented by children classes) """ self.before_start() self.retrieve_data() self.parse() # TRICK: disable new_nodes_allowed_for_layer validation try: Node._additional_validation.remove('new_nodes_allowed_for_layer') except ValueError as e: print "WARNING! got exception: %s" % e # avoid sending zillions of notifications pause_disconnectable_signals() self.save() # Re-enable new_nodes_allowed_for_layer validation try: Node._additional_validation.insert(0, 'new_nodes_allowed_for_layer') except ValueError as e: print "WARNING! got exception: %s" % e # reconnect signals resume_disconnectable_signals() self.after_complete() # return message as a list because more than one messages might be returned return [self.message]
python
def sync(self): """ This is the method that does everything automatically (at least attempts to). Steps: 0. Call "before_start" method (which might be implemented by children classes) 1. Retrieve data from external source 2. Parse the data 3. Save the data locally 4. Call "after_complete" method (which might be implemented by children classes) """ self.before_start() self.retrieve_data() self.parse() # TRICK: disable new_nodes_allowed_for_layer validation try: Node._additional_validation.remove('new_nodes_allowed_for_layer') except ValueError as e: print "WARNING! got exception: %s" % e # avoid sending zillions of notifications pause_disconnectable_signals() self.save() # Re-enable new_nodes_allowed_for_layer validation try: Node._additional_validation.insert(0, 'new_nodes_allowed_for_layer') except ValueError as e: print "WARNING! got exception: %s" % e # reconnect signals resume_disconnectable_signals() self.after_complete() # return message as a list because more than one messages might be returned return [self.message]
[ "def", "sync", "(", "self", ")", ":", "self", ".", "before_start", "(", ")", "self", ".", "retrieve_data", "(", ")", "self", ".", "parse", "(", ")", "# TRICK: disable new_nodes_allowed_for_layer validation", "try", ":", "Node", ".", "_additional_validation", ".", "remove", "(", "'new_nodes_allowed_for_layer'", ")", "except", "ValueError", "as", "e", ":", "print", "\"WARNING! got exception: %s\"", "%", "e", "# avoid sending zillions of notifications", "pause_disconnectable_signals", "(", ")", "self", ".", "save", "(", ")", "# Re-enable new_nodes_allowed_for_layer validation", "try", ":", "Node", ".", "_additional_validation", ".", "insert", "(", "0", ",", "'new_nodes_allowed_for_layer'", ")", "except", "ValueError", "as", "e", ":", "print", "\"WARNING! got exception: %s\"", "%", "e", "# reconnect signals", "resume_disconnectable_signals", "(", ")", "self", ".", "after_complete", "(", ")", "# return message as a list because more than one messages might be returned", "return", "[", "self", ".", "message", "]" ]
This is the method that does everything automatically (at least attempts to). Steps: 0. Call "before_start" method (which might be implemented by children classes) 1. Retrieve data from external source 2. Parse the data 3. Save the data locally 4. Call "after_complete" method (which might be implemented by children classes)
[ "This", "is", "the", "method", "that", "does", "everything", "automatically", "(", "at", "least", "attempts", "to", ")", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/base.py#L73-L109
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", ")", ")", "# perform HTTP request and store content", "self", ".", "data", "=", "requests", ".", "get", "(", "url", ",", "verify", "=", "self", ".", "verify_ssl", ",", "timeout", "=", "timeout", ")", ".", "content" ]
retrieve data from an HTTP URL
[ "retrieve", "data", "from", "an", "HTTP", "URL" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/base.py#L131-L137
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", "default", "is", "not", "False", ":", "return", "default", "else", ":", "raise", "IndexError", "(", "e", ")", "if", "xmlnode", "is", "not", "None", ":", "return", "unicode", "(", "xmlnode", ".", "nodeValue", ")", "# empty tag", "else", ":", "return", "''" ]
returns text content of an xml tag
[ "returns", "text", "content", "of", "an", "xml", "tag" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/base.py#L148-L162
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.'", "%", "(", "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" ]
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" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/base.py#L342-L431
ninuxorg/nodeshot
nodeshot/interop/sync/synchronizers/base.py
GenericGisSynchronizer.save
def save(self): """ save data into DB: 1. save new (missing) data 2. update only when needed 3. delete old data 4. generate report that will be printed constraints: * ensure new nodes do not take a name/slug which is already used * validate through django before saving * use good defaults """ self.key_mapping() # retrieve all items items = self.parsed_data # init empty lists added_nodes = [] changed_nodes = [] unmodified_nodes = [] # retrieve a list of all the slugs of this layer layer_nodes_slug_list = Node.objects.filter(layer=self.layer).values_list('slug', flat=True) # keep a list of all the nodes of other layers other_layers_slug_list = Node.objects.exclude(layer=self.layer).values_list('slug', flat=True) # init empty list of slug of external nodes that will be needed to perform delete operations processed_slug_list = [] deleted_nodes_count = 0 # loop over every item for item in items: item = self._convert_item(item) number = 1 original_name = item['name'] needed_different_name = False while True: # items might have the same name... so we add a number.. if item['slug'] in processed_slug_list or item['slug'] in other_layers_slug_list: needed_different_name = True number = number + 1 item['name'] = "%s - %d" % (original_name, number) item['slug'] = slugify(item['name']) else: if needed_different_name: self.verbose('needed a different name for %s, trying "%s"' % (original_name, item['name'])) break # default values added = False changed = False try: # edit existing node node = Node.objects.get(slug=item['slug'], layer=self.layer) except Node.DoesNotExist: # add a new node node = Node() node.layer = self.layer added = True # loop over fields and store data only if necessary for field in Node._meta.fields: # geometry is a special case, skip if field.name == 'geometry': continue # skip if field is not present in values if field.name not in item.keys(): continue # shortcut for value value = item[field.name] # if value is different than what we have if value is not None and getattr(node, field.name) != value: # set value setattr(node, field.name, value) # indicates that a DB query is necessary changed = True if added or (node.geometry.equals(item['geometry']) is False and node.geometry.equals_exact(item['geometry']) is False): node.geometry = item['geometry'] changed = True node.data = node.data or {} # store any additional key/value in HStore data field for key, value in item['data'].items(): if node.data[key] != value: node.data[key] = value changed = True # perform save or update only if necessary if added or changed: try: node.full_clean() if None not in [node.added, node.updated]: node.save(auto_update=False) else: node.save() except Exception as e: raise Exception('error while processing "%s": %s' % (node.name, e)) if added: added_nodes.append(node) self.verbose('new node saved with name "%s"' % node.name) elif changed: changed_nodes.append(node) self.verbose('node "%s" updated' % node.name) else: unmodified_nodes.append(node) self.verbose('node "%s" unmodified' % node.name) # fill node list container processed_slug_list.append(node.slug) # delete old nodes for local_node in layer_nodes_slug_list: # if local node not found in external nodes if local_node not in processed_slug_list: # retrieve from DB and delete node = Node.objects.get(slug=local_node) # store node name to print it later node_name = node.name node.delete() # then increment count that will be included in message deleted_nodes_count = deleted_nodes_count + 1 self.verbose('node "%s" deleted' % node_name) # message that will be returned self.message = """ %s nodes added %s nodes changed %s nodes deleted %s nodes unmodified %s total external records processed %s total local nodes for this layer """ % ( len(added_nodes), len(changed_nodes), deleted_nodes_count, len(unmodified_nodes), len(items), Node.objects.filter(layer=self.layer).count() )
python
def save(self): """ save data into DB: 1. save new (missing) data 2. update only when needed 3. delete old data 4. generate report that will be printed constraints: * ensure new nodes do not take a name/slug which is already used * validate through django before saving * use good defaults """ self.key_mapping() # retrieve all items items = self.parsed_data # init empty lists added_nodes = [] changed_nodes = [] unmodified_nodes = [] # retrieve a list of all the slugs of this layer layer_nodes_slug_list = Node.objects.filter(layer=self.layer).values_list('slug', flat=True) # keep a list of all the nodes of other layers other_layers_slug_list = Node.objects.exclude(layer=self.layer).values_list('slug', flat=True) # init empty list of slug of external nodes that will be needed to perform delete operations processed_slug_list = [] deleted_nodes_count = 0 # loop over every item for item in items: item = self._convert_item(item) number = 1 original_name = item['name'] needed_different_name = False while True: # items might have the same name... so we add a number.. if item['slug'] in processed_slug_list or item['slug'] in other_layers_slug_list: needed_different_name = True number = number + 1 item['name'] = "%s - %d" % (original_name, number) item['slug'] = slugify(item['name']) else: if needed_different_name: self.verbose('needed a different name for %s, trying "%s"' % (original_name, item['name'])) break # default values added = False changed = False try: # edit existing node node = Node.objects.get(slug=item['slug'], layer=self.layer) except Node.DoesNotExist: # add a new node node = Node() node.layer = self.layer added = True # loop over fields and store data only if necessary for field in Node._meta.fields: # geometry is a special case, skip if field.name == 'geometry': continue # skip if field is not present in values if field.name not in item.keys(): continue # shortcut for value value = item[field.name] # if value is different than what we have if value is not None and getattr(node, field.name) != value: # set value setattr(node, field.name, value) # indicates that a DB query is necessary changed = True if added or (node.geometry.equals(item['geometry']) is False and node.geometry.equals_exact(item['geometry']) is False): node.geometry = item['geometry'] changed = True node.data = node.data or {} # store any additional key/value in HStore data field for key, value in item['data'].items(): if node.data[key] != value: node.data[key] = value changed = True # perform save or update only if necessary if added or changed: try: node.full_clean() if None not in [node.added, node.updated]: node.save(auto_update=False) else: node.save() except Exception as e: raise Exception('error while processing "%s": %s' % (node.name, e)) if added: added_nodes.append(node) self.verbose('new node saved with name "%s"' % node.name) elif changed: changed_nodes.append(node) self.verbose('node "%s" updated' % node.name) else: unmodified_nodes.append(node) self.verbose('node "%s" unmodified' % node.name) # fill node list container processed_slug_list.append(node.slug) # delete old nodes for local_node in layer_nodes_slug_list: # if local node not found in external nodes if local_node not in processed_slug_list: # retrieve from DB and delete node = Node.objects.get(slug=local_node) # store node name to print it later node_name = node.name node.delete() # then increment count that will be included in message deleted_nodes_count = deleted_nodes_count + 1 self.verbose('node "%s" deleted' % node_name) # message that will be returned self.message = """ %s nodes added %s nodes changed %s nodes deleted %s nodes unmodified %s total external records processed %s total local nodes for this layer """ % ( len(added_nodes), len(changed_nodes), deleted_nodes_count, len(unmodified_nodes), len(items), Node.objects.filter(layer=self.layer).count() )
[ "def", "save", "(", "self", ")", ":", "self", ".", "key_mapping", "(", ")", "# retrieve all items", "items", "=", "self", ".", "parsed_data", "# init empty lists", "added_nodes", "=", "[", "]", "changed_nodes", "=", "[", "]", "unmodified_nodes", "=", "[", "]", "# retrieve a list of all the slugs of this layer", "layer_nodes_slug_list", "=", "Node", ".", "objects", ".", "filter", "(", "layer", "=", "self", ".", "layer", ")", ".", "values_list", "(", "'slug'", ",", "flat", "=", "True", ")", "# keep a list of all the nodes of other layers", "other_layers_slug_list", "=", "Node", ".", "objects", ".", "exclude", "(", "layer", "=", "self", ".", "layer", ")", ".", "values_list", "(", "'slug'", ",", "flat", "=", "True", ")", "# init empty list of slug of external nodes that will be needed to perform delete operations", "processed_slug_list", "=", "[", "]", "deleted_nodes_count", "=", "0", "# loop over every item", "for", "item", "in", "items", ":", "item", "=", "self", ".", "_convert_item", "(", "item", ")", "number", "=", "1", "original_name", "=", "item", "[", "'name'", "]", "needed_different_name", "=", "False", "while", "True", ":", "# items might have the same name... so we add a number..", "if", "item", "[", "'slug'", "]", "in", "processed_slug_list", "or", "item", "[", "'slug'", "]", "in", "other_layers_slug_list", ":", "needed_different_name", "=", "True", "number", "=", "number", "+", "1", "item", "[", "'name'", "]", "=", "\"%s - %d\"", "%", "(", "original_name", ",", "number", ")", "item", "[", "'slug'", "]", "=", "slugify", "(", "item", "[", "'name'", "]", ")", "else", ":", "if", "needed_different_name", ":", "self", ".", "verbose", "(", "'needed a different name for %s, trying \"%s\"'", "%", "(", "original_name", ",", "item", "[", "'name'", "]", ")", ")", "break", "# default values", "added", "=", "False", "changed", "=", "False", "try", ":", "# edit existing node", "node", "=", "Node", ".", "objects", ".", "get", "(", "slug", "=", "item", "[", "'slug'", "]", ",", "layer", "=", "self", ".", "layer", ")", "except", "Node", ".", "DoesNotExist", ":", "# add a new node", "node", "=", "Node", "(", ")", "node", ".", "layer", "=", "self", ".", "layer", "added", "=", "True", "# loop over fields and store data only if necessary", "for", "field", "in", "Node", ".", "_meta", ".", "fields", ":", "# geometry is a special case, skip", "if", "field", ".", "name", "==", "'geometry'", ":", "continue", "# skip if field is not present in values", "if", "field", ".", "name", "not", "in", "item", ".", "keys", "(", ")", ":", "continue", "# shortcut for value", "value", "=", "item", "[", "field", ".", "name", "]", "# if value is different than what we have", "if", "value", "is", "not", "None", "and", "getattr", "(", "node", ",", "field", ".", "name", ")", "!=", "value", ":", "# set value", "setattr", "(", "node", ",", "field", ".", "name", ",", "value", ")", "# indicates that a DB query is necessary", "changed", "=", "True", "if", "added", "or", "(", "node", ".", "geometry", ".", "equals", "(", "item", "[", "'geometry'", "]", ")", "is", "False", "and", "node", ".", "geometry", ".", "equals_exact", "(", "item", "[", "'geometry'", "]", ")", "is", "False", ")", ":", "node", ".", "geometry", "=", "item", "[", "'geometry'", "]", "changed", "=", "True", "node", ".", "data", "=", "node", ".", "data", "or", "{", "}", "# store any additional key/value in HStore data field", "for", "key", ",", "value", "in", "item", "[", "'data'", "]", ".", "items", "(", ")", ":", "if", "node", ".", "data", "[", "key", "]", "!=", "value", ":", "node", ".", "data", "[", "key", "]", "=", "value", "changed", "=", "True", "# perform save or update only if necessary", "if", "added", "or", "changed", ":", "try", ":", "node", ".", "full_clean", "(", ")", "if", "None", "not", "in", "[", "node", ".", "added", ",", "node", ".", "updated", "]", ":", "node", ".", "save", "(", "auto_update", "=", "False", ")", "else", ":", "node", ".", "save", "(", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "'error while processing \"%s\": %s'", "%", "(", "node", ".", "name", ",", "e", ")", ")", "if", "added", ":", "added_nodes", ".", "append", "(", "node", ")", "self", ".", "verbose", "(", "'new node saved with name \"%s\"'", "%", "node", ".", "name", ")", "elif", "changed", ":", "changed_nodes", ".", "append", "(", "node", ")", "self", ".", "verbose", "(", "'node \"%s\" updated'", "%", "node", ".", "name", ")", "else", ":", "unmodified_nodes", ".", "append", "(", "node", ")", "self", ".", "verbose", "(", "'node \"%s\" unmodified'", "%", "node", ".", "name", ")", "# fill node list container", "processed_slug_list", ".", "append", "(", "node", ".", "slug", ")", "# delete old nodes", "for", "local_node", "in", "layer_nodes_slug_list", ":", "# if local node not found in external nodes", "if", "local_node", "not", "in", "processed_slug_list", ":", "# retrieve from DB and delete", "node", "=", "Node", ".", "objects", ".", "get", "(", "slug", "=", "local_node", ")", "# store node name to print it later", "node_name", "=", "node", ".", "name", "node", ".", "delete", "(", ")", "# then increment count that will be included in message", "deleted_nodes_count", "=", "deleted_nodes_count", "+", "1", "self", ".", "verbose", "(", "'node \"%s\" deleted'", "%", "node_name", ")", "# message that will be returned", "self", ".", "message", "=", "\"\"\"\n %s nodes added\n %s nodes changed\n %s nodes deleted\n %s nodes unmodified\n %s total external records processed\n %s total local nodes for this layer\n \"\"\"", "%", "(", "len", "(", "added_nodes", ")", ",", "len", "(", "changed_nodes", ")", ",", "deleted_nodes_count", ",", "len", "(", "unmodified_nodes", ")", ",", "len", "(", "items", ")", ",", "Node", ".", "objects", ".", "filter", "(", "layer", "=", "self", ".", "layer", ")", ".", "count", "(", ")", ")" ]
save data into DB: 1. save new (missing) data 2. update only when needed 3. delete old data 4. generate report that will be printed constraints: * ensure new nodes do not take a name/slug which is already used * validate through django before saving * use good defaults
[ "save", "data", "into", "DB", ":" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/base.py#L449-L596
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", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/mixins.py#L12-L19
ninuxorg/nodeshot
nodeshot/core/base/mixins.py
RevisionUpdate.put
def put(self, request, *args, **kwargs): """ custom put 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']) return self.update(request, *args, **kwargs)
python
def put(self, request, *args, **kwargs): """ custom put 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']) return self.update(request, *args, **kwargs)
[ "def", "put", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "reversion", ".", "create_revision", "(", ")", ":", "reversion", ".", "set_user", "(", "request", ".", "user", ")", "reversion", ".", "set_comment", "(", "'changed through the RESTful API from ip %s'", "%", "request", ".", "META", "[", "'REMOTE_ADDR'", "]", ")", "return", "self", ".", "update", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
custom put method to support django-reversion
[ "custom", "put", "method", "to", "support", "django", "-", "reversion" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/mixins.py#L27-L32
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", "(", "'changed through the RESTful API from ip %s'", "%", "request", ".", "META", "[", "'REMOTE_ADDR'", "]", ")", "kwargs", "[", "'partial'", "]", "=", "True", "return", "self", ".", "update", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
custom patch method to support django-reversion
[ "custom", "patch", "method", "to", "support", "django", "-", "reversion" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/mixins.py#L34-L40
ninuxorg/nodeshot
nodeshot/core/base/mixins.py
RevisionCreate.post
def post(self, request, *args, **kwargs): """ custom put method to support django-reversion """ with reversion.create_revision(): reversion.set_user(request.user) reversion.set_comment('created through the RESTful API from ip %s' % request.META['REMOTE_ADDR']) return self.create(request, *args, **kwargs)
python
def post(self, request, *args, **kwargs): """ custom put method to support django-reversion """ with reversion.create_revision(): reversion.set_user(request.user) reversion.set_comment('created through the RESTful API from ip %s' % request.META['REMOTE_ADDR']) return self.create(request, *args, **kwargs)
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "reversion", ".", "create_revision", "(", ")", ":", "reversion", ".", "set_user", "(", "request", ".", "user", ")", "reversion", ".", "set_comment", "(", "'created through the RESTful API from ip %s'", "%", "request", ".", "META", "[", "'REMOTE_ADDR'", "]", ")", "return", "self", ".", "create", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
custom put method to support django-reversion
[ "custom", "put", "method", "to", "support", "django", "-", "reversion" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/mixins.py#L48-L53
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 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", "(", ")" ]
when creating a new record fill CPU and RAM info if available
[ "when", "creating", "a", "new", "record", "fill", "CPU", "and", "RAM", "info", "if", "available" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/hardware/models/device_to_model_rel.py#L24-L57
ninuxorg/nodeshot
nodeshot/core/websockets/registrars/nodes.py
disconnect
def disconnect(): """ disconnect signals """ post_save.disconnect(node_created_handler, sender=Node) node_status_changed.disconnect(node_status_changed_handler) pre_delete.disconnect(node_deleted_handler, sender=Node)
python
def disconnect(): """ disconnect signals """ post_save.disconnect(node_created_handler, sender=Node) node_status_changed.disconnect(node_status_changed_handler) pre_delete.disconnect(node_deleted_handler, sender=Node)
[ "def", "disconnect", "(", ")", ":", "post_save", ".", "disconnect", "(", "node_created_handler", ",", "sender", "=", "Node", ")", "node_status_changed", ".", "disconnect", "(", "node_status_changed_handler", ")", "pre_delete", ".", "disconnect", "(", "node_deleted_handler", ",", "sender", "=", "Node", ")" ]
disconnect signals
[ "disconnect", "signals" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/registrars/nodes.py#L42-L46
ninuxorg/nodeshot
nodeshot/core/websockets/registrars/nodes.py
reconnect
def reconnect(): """ reconnect signals """ post_save.connect(node_created_handler, sender=Node) node_status_changed.connect(node_status_changed_handler) pre_delete.connect(node_deleted_handler, sender=Node)
python
def reconnect(): """ reconnect signals """ post_save.connect(node_created_handler, sender=Node) node_status_changed.connect(node_status_changed_handler) pre_delete.connect(node_deleted_handler, sender=Node)
[ "def", "reconnect", "(", ")", ":", "post_save", ".", "connect", "(", "node_created_handler", ",", "sender", "=", "Node", ")", "node_status_changed", ".", "connect", "(", "node_status_changed_handler", ")", "pre_delete", ".", "connect", "(", "node_deleted_handler", ",", "sender", "=", "Node", ")" ]
reconnect signals
[ "reconnect", "signals" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/registrars/nodes.py#L49-L53
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 notification to herself/himself'", ")", ")" ]
from_user and to_user must differ
[ "from_user", "and", "to_user", "must", "differ" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L44-L47
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", "=", "'web'", ")", ":", "super", "(", "Notification", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "created", ":", "# send notifications through other mediums according to user settings", "self", ".", "send_notifications", "(", ")" ]
custom save method to send email and push notification
[ "custom", "save", "method", "to", "send", "email", "and", "push", "notification" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L49-L61
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", ",", "settings", ".", "DEFAULT_FROM_EMAIL", ",", "[", "self", ".", "to_user", ".", "email", "]", ")", "return", "True", "else", ":", "# return false otherwise", "return", "False" ]
send email notification according to user settings
[ "send", "email", "notification", "according", "to", "user", "settings" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L67-L75
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_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" ]
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", "the", "future", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L81-L122
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: %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", ")" ]
compose complete email message text
[ "compose", "complete", "email", "message", "text" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L125-L135
ninuxorg/nodeshot
nodeshot/interop/sync/synchronizers/openwisp.py
OpenWisp.parse
def parse(self): """ parse data """ super(OpenWisp, self).parse() self.parsed_data = self.parsed_data.getElementsByTagName('item')
python
def parse(self): """ parse data """ super(OpenWisp, self).parse() self.parsed_data = self.parsed_data.getElementsByTagName('item')
[ "def", "parse", "(", "self", ")", ":", "super", "(", "OpenWisp", ",", "self", ")", ".", "parse", "(", ")", "self", ".", "parsed_data", "=", "self", ".", "parsed_data", ".", "getElementsByTagName", "(", "'item'", ")" ]
parse data
[ "parse", "data" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/openwisp.py#L10-L13
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", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/emailconfirmation.py#L127-L132
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", ",", "created_at", "=", "now", "(", ")", ",", "key", "=", "confirmation_key", ",", ")", "return", "confirmation" ]
Create an email confirmation obj from the given email address obj
[ "Create", "an", "email", "confirmation", "obj", "from", "the", "given", "email", "address", "obj" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/emailconfirmation.py#L134-L142
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'", "]", ".", "pk", ")", ",", "'username'", ":", "kwargs", "[", "'user'", "]", ".", "username", ",", "}", "write", "(", "'user_logins'", ",", "values", "=", "values", ")" ]
collect metrics about user logins
[ "collect", "metrics", "about", "user", "logins" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/signals.py#L17-L25
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'", ":", "'created'", "}", ")", "write", "(", "'user_count'", ",", "{", "'total'", ":", "User", ".", "objects", ".", "count", "(", ")", "}", ")" ]
collect metrics about new users signing up
[ "collect", "metrics", "about", "new", "users", "signing", "up" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/signals.py#L36-L40
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" ]
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" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/__init__.py#L68-L82
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_participation_settings", ".", "save", "(", ")", "return", "node_participation_settings" ]
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" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/__init__.py#L88-L102
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", ":", "return", "getattr", "(", "self", ".", "participation_settings", ",", "'{0}_allowed'", ".", "format", "(", "action", ")", ")" ]
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" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/__init__.py#L107-L114
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 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", "}", ")" ]
create node rating count and settings
[ "create", "node", "rating", "count", "and", "settings" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/__init__.py#L147-L156
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 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", "}", ")" ]
create layer rating settings
[ "create", "layer", "rating", "settings" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/__init__.py#L160-L168
ninuxorg/nodeshot
nodeshot/community/profiles/models/profile.py
Profile.save
def save(self, *args, **kwargs): """ performs actions on create: * ensure instance has usable password * set default group * keep in sync with email address model """ created = self.pk is None sync_emailaddress = kwargs.pop('sync_emailaddress', True) # ensure usable password if created and self.has_usable_password() is False: self.set_password(self.password) # save super(Profile, self).save(*args, **kwargs) # add user to default group if created and self.groups.count() < 1: # TODO: make default group configurable in settings try: default_group = Group.objects.get(name='registered') self.groups.add(default_group) except Group.DoesNotExist: pass # keep in sync with EmailAddress model if (EMAIL_CONFIRMATION and sync_emailaddress and self.email # noqa and self.email_set.filter(email=self.email).count() < 1): # noqa self.email_set.add_email(self, email=self.email) self.email_set.last().set_as_primary()
python
def save(self, *args, **kwargs): """ performs actions on create: * ensure instance has usable password * set default group * keep in sync with email address model """ created = self.pk is None sync_emailaddress = kwargs.pop('sync_emailaddress', True) # ensure usable password if created and self.has_usable_password() is False: self.set_password(self.password) # save super(Profile, self).save(*args, **kwargs) # add user to default group if created and self.groups.count() < 1: # TODO: make default group configurable in settings try: default_group = Group.objects.get(name='registered') self.groups.add(default_group) except Group.DoesNotExist: pass # keep in sync with EmailAddress model if (EMAIL_CONFIRMATION and sync_emailaddress and self.email # noqa and self.email_set.filter(email=self.email).count() < 1): # noqa self.email_set.add_email(self, email=self.email) self.email_set.last().set_as_primary()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "created", "=", "self", ".", "pk", "is", "None", "sync_emailaddress", "=", "kwargs", ".", "pop", "(", "'sync_emailaddress'", ",", "True", ")", "# ensure usable password", "if", "created", "and", "self", ".", "has_usable_password", "(", ")", "is", "False", ":", "self", ".", "set_password", "(", "self", ".", "password", ")", "# save", "super", "(", "Profile", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# add user to default group", "if", "created", "and", "self", ".", "groups", ".", "count", "(", ")", "<", "1", ":", "# TODO: make default group configurable in settings", "try", ":", "default_group", "=", "Group", ".", "objects", ".", "get", "(", "name", "=", "'registered'", ")", "self", ".", "groups", ".", "add", "(", "default_group", ")", "except", "Group", ".", "DoesNotExist", ":", "pass", "# keep in sync with EmailAddress model", "if", "(", "EMAIL_CONFIRMATION", "and", "sync_emailaddress", "and", "self", ".", "email", "# noqa", "and", "self", ".", "email_set", ".", "filter", "(", "email", "=", "self", ".", "email", ")", ".", "count", "(", ")", "<", "1", ")", ":", "# noqa", "self", ".", "email_set", ".", "add_email", "(", "self", ",", "email", "=", "self", ".", "email", ")", "self", ".", "email_set", ".", "last", "(", ")", ".", "set_as_primary", "(", ")" ]
performs actions on create: * ensure instance has usable password * set default group * keep in sync with email address model
[ "performs", "actions", "on", "create", ":", "*", "ensure", "instance", "has", "usable", "password", "*", "set", "default", "group", "*", "keep", "in", "sync", "with", "email", "address", "model" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/profile.py#L78-L105
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" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/profile.py#L124-L133
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", "=", "self", ")" ]
Changes password and sends a signal
[ "Changes", "password", "and", "sends", "a", "signal" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/profile.py#L135-L141
ninuxorg/nodeshot
nodeshot/community/participation/views.py
NodeRelationViewMixin.initial
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only comments of current node """ super(NodeRelationViewMixin, self).initial(request, *args, **kwargs) self.node = get_object_or_404(Node, **{'slug': self.kwargs['slug']}) self.queryset = self.model.objects.filter(node_id=self.node.id)
python
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only comments of current node """ super(NodeRelationViewMixin, self).initial(request, *args, **kwargs) self.node = get_object_or_404(Node, **{'slug': self.kwargs['slug']}) self.queryset = self.model.objects.filter(node_id=self.node.id)
[ "def", "initial", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "NodeRelationViewMixin", ",", "self", ")", ".", "initial", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "node", "=", "get_object_or_404", "(", "Node", ",", "*", "*", "{", "'slug'", ":", "self", ".", "kwargs", "[", "'slug'", "]", "}", ")", "self", ".", "queryset", "=", "self", ".", "model", ".", "objects", ".", "filter", "(", "node_id", "=", "self", ".", "node", ".", "id", ")" ]
Custom initial method: * ensure node exists and store it in an instance attribute * change queryset to return only comments of current node
[ "Custom", "initial", "method", ":", "*", "ensure", "node", "exists", "and", "store", "it", "in", "an", "instance", "attribute", "*", "change", "queryset", "to", "return", "only", "comments", "of", "current", "node" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/views.py#L15-L23
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", "=", "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;\\\n 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" ]
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", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/user_settings.py#L7-L37
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", "else", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(", "\"This account is currently inactive.\"", ")", ")", "else", ":", "error", "=", "_", "(", "\"Invalid login credentials.\"", ")", "raise", "serializers", ".", "ValidationError", "(", "error", ")", "return", "attrs" ]
checks if login credentials are correct
[ "checks", "if", "login", "credentials", "are", "correct" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L89-L101
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", ".", "get", "(", "'request'", ")", ",", "format", "=", "self", ".", "context", ".", "get", "(", "'format'", ")", ")" ]
return detail url
[ "return", "detail", "url" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L108-L113
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'", "%", "(", "obj", ".", "city", ",", "obj", ".", "country", ")", "elif", "obj", ".", "city", "or", "obj", ".", "country", ":", "return", "obj", ".", "city", "or", "obj", ".", "country" ]
return user's location
[ "return", "user", "s", "location" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L147-L154
ninuxorg/nodeshot
nodeshot/community/profiles/serializers.py
ProfileCreateSerializer.validate_password_confirmation
def validate_password_confirmation(self, value): """ password_confirmation check """ if value != self.initial_data['password']: raise serializers.ValidationError(_('Password confirmation mismatch')) return value
python
def validate_password_confirmation(self, value): """ password_confirmation check """ if value != self.initial_data['password']: raise serializers.ValidationError(_('Password confirmation mismatch')) return value
[ "def", "validate_password_confirmation", "(", "self", ",", "value", ")", ":", "if", "value", "!=", "self", ".", "initial_data", "[", "'password'", "]", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(", "'Password confirmation mismatch'", ")", ")", "return", "value" ]
password_confirmation check
[ "password_confirmation", "check" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L201-L205
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", ")", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(", "'Current password is not correct'", ")", ")", "return", "value" ]
current password check
[ "current", "password", "check" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L264-L268
ninuxorg/nodeshot
nodeshot/community/profiles/serializers.py
ChangePasswordSerializer.validate_password2
def validate_password2(self, value): """ password_confirmation check """ if value != self.initial_data['password1']: raise serializers.ValidationError(_('Password confirmation mismatch')) return value
python
def validate_password2(self, value): """ password_confirmation check """ if value != self.initial_data['password1']: raise serializers.ValidationError(_('Password confirmation mismatch')) return value
[ "def", "validate_password2", "(", "self", ",", "value", ")", ":", "if", "value", "!=", "self", ".", "initial_data", "[", "'password1'", "]", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(", "'Password confirmation mismatch'", ")", ")", "return", "value" ]
password_confirmation check
[ "password_confirmation", "check" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L270-L274
ninuxorg/nodeshot
nodeshot/community/profiles/serializers.py
ResetPasswordSerializer.validate_email
def validate_email(self, value): """ ensure email is in the database """ if EMAIL_CONFIRMATION: queryset = EmailAddress.objects.filter(email__iexact=value, verified=True) else: queryset = User.objects.get(email__iexact=value, is_active=True).count() == 0 if queryset.count() < 1: raise serializers.ValidationError(_("Email address not found")) return queryset.first().email
python
def validate_email(self, value): """ ensure email is in the database """ if EMAIL_CONFIRMATION: queryset = EmailAddress.objects.filter(email__iexact=value, verified=True) else: queryset = User.objects.get(email__iexact=value, is_active=True).count() == 0 if queryset.count() < 1: raise serializers.ValidationError(_("Email address not found")) return queryset.first().email
[ "def", "validate_email", "(", "self", ",", "value", ")", ":", "if", "EMAIL_CONFIRMATION", ":", "queryset", "=", "EmailAddress", ".", "objects", ".", "filter", "(", "email__iexact", "=", "value", ",", "verified", "=", "True", ")", "else", ":", "queryset", "=", "User", ".", "objects", ".", "get", "(", "email__iexact", "=", "value", ",", "is_active", "=", "True", ")", ".", "count", "(", ")", "==", "0", "if", "queryset", ".", "count", "(", ")", "<", "1", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(", "\"Email address not found\"", ")", ")", "return", "queryset", ".", "first", "(", ")", ".", "email" ]
ensure email is in the database
[ "ensure", "email", "is", "in", "the", "database" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L285-L293
ninuxorg/nodeshot
nodeshot/community/profiles/serializers.py
ResetPasswordKeySerializer.update
def update(self, instance, validated_data): """ change password """ instance.user.set_password(validated_data["password1"]) instance.user.full_clean() instance.user.save() # mark password reset object as reset instance.reset = True instance.full_clean() instance.save() return instance
python
def update(self, instance, validated_data): """ change password """ instance.user.set_password(validated_data["password1"]) instance.user.full_clean() instance.user.save() # mark password reset object as reset instance.reset = True instance.full_clean() instance.save() return instance
[ "def", "update", "(", "self", ",", "instance", ",", "validated_data", ")", ":", "instance", ".", "user", ".", "set_password", "(", "validated_data", "[", "\"password1\"", "]", ")", "instance", ".", "user", ".", "full_clean", "(", ")", "instance", ".", "user", ".", "save", "(", ")", "# mark password reset object as reset", "instance", ".", "reset", "=", "True", "instance", ".", "full_clean", "(", ")", "instance", ".", "save", "(", ")", "return", "instance" ]
change password
[ "change", "password" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/serializers.py#L312-L321
ninuxorg/nodeshot
nodeshot/networking/net/models/device.py
Device.save
def save(self, *args, **kwargs): """ Custom save method does the following: * automatically inherit node coordinates and elevation * save shortcuts if HSTORE is enabled """ custom_checks = kwargs.pop('custom_checks', True) super(Device, self).save(*args, **kwargs) if custom_checks is False: return changed = False if not self.location: self.location = self.node.point changed = True if not self.elev and self.node.elev: self.elev = self.node.elev changed = True original_user = self.shortcuts.get('user') if self.node.user: self.shortcuts['user'] = self.node.user if original_user != self.shortcuts.get('user'): changed = True if 'nodeshot.core.layers' in settings.INSTALLED_APPS: original_layer = self.shortcuts.get('layer') self.shortcuts['layer'] = self.node.layer if original_layer != self.shortcuts.get('layer'): changed = True if changed: self.save(custom_checks=False)
python
def save(self, *args, **kwargs): """ Custom save method does the following: * automatically inherit node coordinates and elevation * save shortcuts if HSTORE is enabled """ custom_checks = kwargs.pop('custom_checks', True) super(Device, self).save(*args, **kwargs) if custom_checks is False: return changed = False if not self.location: self.location = self.node.point changed = True if not self.elev and self.node.elev: self.elev = self.node.elev changed = True original_user = self.shortcuts.get('user') if self.node.user: self.shortcuts['user'] = self.node.user if original_user != self.shortcuts.get('user'): changed = True if 'nodeshot.core.layers' in settings.INSTALLED_APPS: original_layer = self.shortcuts.get('layer') self.shortcuts['layer'] = self.node.layer if original_layer != self.shortcuts.get('layer'): changed = True if changed: self.save(custom_checks=False)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "custom_checks", "=", "kwargs", ".", "pop", "(", "'custom_checks'", ",", "True", ")", "super", "(", "Device", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "custom_checks", "is", "False", ":", "return", "changed", "=", "False", "if", "not", "self", ".", "location", ":", "self", ".", "location", "=", "self", ".", "node", ".", "point", "changed", "=", "True", "if", "not", "self", ".", "elev", "and", "self", ".", "node", ".", "elev", ":", "self", ".", "elev", "=", "self", ".", "node", ".", "elev", "changed", "=", "True", "original_user", "=", "self", ".", "shortcuts", ".", "get", "(", "'user'", ")", "if", "self", ".", "node", ".", "user", ":", "self", ".", "shortcuts", "[", "'user'", "]", "=", "self", ".", "node", ".", "user", "if", "original_user", "!=", "self", ".", "shortcuts", ".", "get", "(", "'user'", ")", ":", "changed", "=", "True", "if", "'nodeshot.core.layers'", "in", "settings", ".", "INSTALLED_APPS", ":", "original_layer", "=", "self", ".", "shortcuts", ".", "get", "(", "'layer'", ")", "self", ".", "shortcuts", "[", "'layer'", "]", "=", "self", ".", "node", ".", "layer", "if", "original_layer", "!=", "self", ".", "shortcuts", ".", "get", "(", "'layer'", ")", ":", "changed", "=", "True", "if", "changed", ":", "self", ".", "save", "(", "custom_checks", "=", "False", ")" ]
Custom save method does the following: * automatically inherit node coordinates and elevation * save shortcuts if HSTORE is enabled
[ "Custom", "save", "method", "does", "the", "following", ":", "*", "automatically", "inherit", "node", "coordinates", "and", "elevation", "*", "save", "shortcuts", "if", "HSTORE", "is", "enabled" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/device.py#L60-L99
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", ".", "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" ]
create password reset for specified user
[ "create", "password", "reset", "for", "specified", "user" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/models/password_reset.py#L17-L41
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 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", "(", ")" ]
execute synchronize command
[ "execute", "synchronize", "command" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L129-L173
ninuxorg/nodeshot
nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py
Command.prompt_layer_selection
def prompt_layer_selection(self, node, layers): """Ask user what to do when an old node is contained in more than one layer. Possible answers are: * use default layer (default answer if pressing enter) * choose layer * discard node """ valid = { "default": "default", "def": "default", "discard": "discard", "dis": "discard", } question = """Cannot automatically determine layer for node "%s" because there \ are %d layers available in that area, what do you want to do?\n\n""" % (node.name, len(layers)) available_layers = "" for layer in layers: available_layers += "%d (%s)\n" % (layer.id, layer.name) valid[str(layer.id)] = layer.id prompt = """\ choose (enter the number of) one of the following layers: %s "default" use default layer (if no default layer specified in settings node will be discarded) "discard" discard node (default action is to use default layer)\n\n""" % available_layers sys.stdout.write(question + prompt) while True: if self.options.get('noinput') is True: answer = 'default' break answer = raw_input().lower() if answer == '': answer = "default" if answer in valid: answer = valid[answer] break else: sys.stdout.write("Please respond with one of the valid answers\n") sys.stdout.write("\n") return answer
python
def prompt_layer_selection(self, node, layers): """Ask user what to do when an old node is contained in more than one layer. Possible answers are: * use default layer (default answer if pressing enter) * choose layer * discard node """ valid = { "default": "default", "def": "default", "discard": "discard", "dis": "discard", } question = """Cannot automatically determine layer for node "%s" because there \ are %d layers available in that area, what do you want to do?\n\n""" % (node.name, len(layers)) available_layers = "" for layer in layers: available_layers += "%d (%s)\n" % (layer.id, layer.name) valid[str(layer.id)] = layer.id prompt = """\ choose (enter the number of) one of the following layers: %s "default" use default layer (if no default layer specified in settings node will be discarded) "discard" discard node (default action is to use default layer)\n\n""" % available_layers sys.stdout.write(question + prompt) while True: if self.options.get('noinput') is True: answer = 'default' break answer = raw_input().lower() if answer == '': answer = "default" if answer in valid: answer = valid[answer] break else: sys.stdout.write("Please respond with one of the valid answers\n") sys.stdout.write("\n") return answer
[ "def", "prompt_layer_selection", "(", "self", ",", "node", ",", "layers", ")", ":", "valid", "=", "{", "\"default\"", ":", "\"default\"", ",", "\"def\"", ":", "\"default\"", ",", "\"discard\"", ":", "\"discard\"", ",", "\"dis\"", ":", "\"discard\"", ",", "}", "question", "=", "\"\"\"Cannot automatically determine layer for node \"%s\" because there \\\nare %d layers available in that area, what do you want to do?\\n\\n\"\"\"", "%", "(", "node", ".", "name", ",", "len", "(", "layers", ")", ")", "available_layers", "=", "\"\"", "for", "layer", "in", "layers", ":", "available_layers", "+=", "\"%d (%s)\\n\"", "%", "(", "layer", ".", "id", ",", "layer", ".", "name", ")", "valid", "[", "str", "(", "layer", ".", "id", ")", "]", "=", "layer", ".", "id", "prompt", "=", "\"\"\"\\\nchoose (enter the number of) one of the following layers:\n%s\n\"default\" use default layer (if no default layer specified in settings node will be discarded)\n\"discard\" discard node\n\n(default action is to use default layer)\\n\\n\"\"\"", "%", "available_layers", "sys", ".", "stdout", ".", "write", "(", "question", "+", "prompt", ")", "while", "True", ":", "if", "self", ".", "options", ".", "get", "(", "'noinput'", ")", "is", "True", ":", "answer", "=", "'default'", "break", "answer", "=", "raw_input", "(", ")", ".", "lower", "(", ")", "if", "answer", "==", "''", ":", "answer", "=", "\"default\"", "if", "answer", "in", "valid", ":", "answer", "=", "valid", "[", "answer", "]", "break", "else", ":", "sys", ".", "stdout", ".", "write", "(", "\"Please respond with one of the valid answers\\n\"", ")", "sys", ".", "stdout", ".", "write", "(", "\"\\n\"", ")", "return", "answer" ]
Ask user what to do when an old node is contained in more than one layer. Possible answers are: * use default layer (default answer if pressing enter) * choose layer * discard node
[ "Ask", "user", "what", "to", "do", "when", "an", "old", "node", "is", "contained", "in", "more", "than", "one", "layer", ".", "Possible", "answers", "are", ":", "*", "use", "default", "layer", "(", "default", "answer", "if", "pressing", "enter", ")", "*", "choose", "layer", "*", "discard", "node" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L246-L293
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", ",", "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'", ")" ]
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" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L299-L320
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", "(", "'retrieved %d nodes'", "%", "len", "(", "self", ".", "old_nodes", ")", ")" ]
retrieve nodes from old mysql DB
[ "retrieve", "nodes", "from", "old", "mysql", "DB" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L325-L330
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", ":", "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", ")", ")" ]
extract user info
[ "extract", "user", "info" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L332-L350
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", ".", "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" ]
save admins to local DB
[ "save", "admins", "to", "local", "DB" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L352-L390
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", ":", "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" ]
save users to local DB
[ "save", "users", "to", "local", "DB" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L392-L486
ninuxorg/nodeshot
nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py
Command.import_nodes
def import_nodes(self): """ import nodes into local DB """ self.message('saving nodes into local DB...') saved_nodes = [] # loop over all old node and create new nodes for old_node in self.old_nodes: # if this old node is unconfirmed skip to next cycle if old_node.status == 'u': continue try: node = Node.objects.get(pk=old_node.id) except Node.DoesNotExist: node = Node(id=old_node.id) node.data = {} node.user_id = self.users_dict[old_node.email]['id'] node.name = old_node.name node.slug = old_node.slug node.geometry = Point(old_node.lng, old_node.lat) node.elev = old_node.alt node.description = old_node.description node.notes = old_node.notes node.added = old_node.added node.updated = old_node.updated node.data['imported'] = 'true' intersecting_layers = node.intersecting_layers # if more than one intersecting layer if len(intersecting_layers) > 1: # prompt user answer = self.prompt_layer_selection(node, intersecting_layers) if isinstance(answer, int): node.layer_id = answer elif answer == 'default' and self.default_layer is not False: node.layer_id = self.default_layer else: self.message('Node %s discarded' % node.name) continue # if one intersecting layer select that elif 2 > len(intersecting_layers) > 0: node.layer = intersecting_layers[0] # if no intersecting layers else: if self.default_layer is False: # discard node if no default layer specified self.message("""Node %s discarded because is not contained in any specified layer and no default layer specified""" % node.name) continue else: node.layer_id = self.default_layer if old_node.postal_code: # additional info node.data['postal_code'] = old_node.postal_code # is it a hotspot? if old_node.status in ['h', 'ah']: node.data['is_hotspot'] = 'true' # determine status according to settings if self.status_mapping: node.status_id = self.get_status(old_node.status) try: node.full_clean() node.save(auto_update=False) saved_nodes.append(node) self.verbose('Saved node %s in layer %s with status %s' % (node.name, node.layer, node.status.name)) except Exception: tb = traceback.format_exc() self.message('Could not save node %s, got exception:\n\n%s' % (node.name, tb)) self.message('saved %d nodes into local DB' % len(saved_nodes)) self.saved_nodes = saved_nodes
python
def import_nodes(self): """ import nodes into local DB """ self.message('saving nodes into local DB...') saved_nodes = [] # loop over all old node and create new nodes for old_node in self.old_nodes: # if this old node is unconfirmed skip to next cycle if old_node.status == 'u': continue try: node = Node.objects.get(pk=old_node.id) except Node.DoesNotExist: node = Node(id=old_node.id) node.data = {} node.user_id = self.users_dict[old_node.email]['id'] node.name = old_node.name node.slug = old_node.slug node.geometry = Point(old_node.lng, old_node.lat) node.elev = old_node.alt node.description = old_node.description node.notes = old_node.notes node.added = old_node.added node.updated = old_node.updated node.data['imported'] = 'true' intersecting_layers = node.intersecting_layers # if more than one intersecting layer if len(intersecting_layers) > 1: # prompt user answer = self.prompt_layer_selection(node, intersecting_layers) if isinstance(answer, int): node.layer_id = answer elif answer == 'default' and self.default_layer is not False: node.layer_id = self.default_layer else: self.message('Node %s discarded' % node.name) continue # if one intersecting layer select that elif 2 > len(intersecting_layers) > 0: node.layer = intersecting_layers[0] # if no intersecting layers else: if self.default_layer is False: # discard node if no default layer specified self.message("""Node %s discarded because is not contained in any specified layer and no default layer specified""" % node.name) continue else: node.layer_id = self.default_layer if old_node.postal_code: # additional info node.data['postal_code'] = old_node.postal_code # is it a hotspot? if old_node.status in ['h', 'ah']: node.data['is_hotspot'] = 'true' # determine status according to settings if self.status_mapping: node.status_id = self.get_status(old_node.status) try: node.full_clean() node.save(auto_update=False) saved_nodes.append(node) self.verbose('Saved node %s in layer %s with status %s' % (node.name, node.layer, node.status.name)) except Exception: tb = traceback.format_exc() self.message('Could not save node %s, got exception:\n\n%s' % (node.name, tb)) self.message('saved %d nodes into local DB' % len(saved_nodes)) self.saved_nodes = saved_nodes
[ "def", "import_nodes", "(", "self", ")", ":", "self", ".", "message", "(", "'saving nodes into local DB...'", ")", "saved_nodes", "=", "[", "]", "# loop over all old node and create new nodes", "for", "old_node", "in", "self", ".", "old_nodes", ":", "# if this old node is unconfirmed skip to next cycle", "if", "old_node", ".", "status", "==", "'u'", ":", "continue", "try", ":", "node", "=", "Node", ".", "objects", ".", "get", "(", "pk", "=", "old_node", ".", "id", ")", "except", "Node", ".", "DoesNotExist", ":", "node", "=", "Node", "(", "id", "=", "old_node", ".", "id", ")", "node", ".", "data", "=", "{", "}", "node", ".", "user_id", "=", "self", ".", "users_dict", "[", "old_node", ".", "email", "]", "[", "'id'", "]", "node", ".", "name", "=", "old_node", ".", "name", "node", ".", "slug", "=", "old_node", ".", "slug", "node", ".", "geometry", "=", "Point", "(", "old_node", ".", "lng", ",", "old_node", ".", "lat", ")", "node", ".", "elev", "=", "old_node", ".", "alt", "node", ".", "description", "=", "old_node", ".", "description", "node", ".", "notes", "=", "old_node", ".", "notes", "node", ".", "added", "=", "old_node", ".", "added", "node", ".", "updated", "=", "old_node", ".", "updated", "node", ".", "data", "[", "'imported'", "]", "=", "'true'", "intersecting_layers", "=", "node", ".", "intersecting_layers", "# if more than one intersecting layer", "if", "len", "(", "intersecting_layers", ")", ">", "1", ":", "# prompt user", "answer", "=", "self", ".", "prompt_layer_selection", "(", "node", ",", "intersecting_layers", ")", "if", "isinstance", "(", "answer", ",", "int", ")", ":", "node", ".", "layer_id", "=", "answer", "elif", "answer", "==", "'default'", "and", "self", ".", "default_layer", "is", "not", "False", ":", "node", ".", "layer_id", "=", "self", ".", "default_layer", "else", ":", "self", ".", "message", "(", "'Node %s discarded'", "%", "node", ".", "name", ")", "continue", "# if one intersecting layer select that", "elif", "2", ">", "len", "(", "intersecting_layers", ")", ">", "0", ":", "node", ".", "layer", "=", "intersecting_layers", "[", "0", "]", "# if no intersecting layers", "else", ":", "if", "self", ".", "default_layer", "is", "False", ":", "# discard node if no default layer specified", "self", ".", "message", "(", "\"\"\"Node %s discarded because is not contained\n in any specified layer and no default layer specified\"\"\"", "%", "node", ".", "name", ")", "continue", "else", ":", "node", ".", "layer_id", "=", "self", ".", "default_layer", "if", "old_node", ".", "postal_code", ":", "# additional info", "node", ".", "data", "[", "'postal_code'", "]", "=", "old_node", ".", "postal_code", "# is it a hotspot?", "if", "old_node", ".", "status", "in", "[", "'h'", ",", "'ah'", "]", ":", "node", ".", "data", "[", "'is_hotspot'", "]", "=", "'true'", "# determine status according to settings", "if", "self", ".", "status_mapping", ":", "node", ".", "status_id", "=", "self", ".", "get_status", "(", "old_node", ".", "status", ")", "try", ":", "node", ".", "full_clean", "(", ")", "node", ".", "save", "(", "auto_update", "=", "False", ")", "saved_nodes", ".", "append", "(", "node", ")", "self", ".", "verbose", "(", "'Saved node %s in layer %s with status %s'", "%", "(", "node", ".", "name", ",", "node", ".", "layer", ",", "node", ".", "status", ".", "name", ")", ")", "except", "Exception", ":", "tb", "=", "traceback", ".", "format_exc", "(", ")", "self", ".", "message", "(", "'Could not save node %s, got exception:\\n\\n%s'", "%", "(", "node", ".", "name", ",", "tb", ")", ")", "self", ".", "message", "(", "'saved %d nodes into local DB'", "%", "len", "(", "saved_nodes", ")", ")", "self", ".", "saved_nodes", "=", "saved_nodes" ]
import nodes into local DB
[ "import", "nodes", "into", "local", "DB" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L488-L564
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", "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" ]
delete imported nodes that are not present in the old database
[ "delete", "imported", "nodes", "that", "are", "not", "present", "in", "the", "old", "database" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/management/commands/import_old_nodeshot.py#L566-L582
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", "(", "user", "=", "user", ")", "UserEmailNotificationSettings", ".", "objects", ".", "create", "(", "user", "=", "user", ")" ]
create user notification settings on user creation
[ "create", "user", "notification", "settings", "on", "user", "creation" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/signals.py#L11-L17
ninuxorg/nodeshot
nodeshot/community/profiles/apps.py
AppConfig.ready
def ready(self): """ Add user info to ExtensibleNodeSerializer """ from nodeshot.core.nodes.base import ExtensibleNodeSerializer from .serializers import ProfileRelationSerializer ExtensibleNodeSerializer.add_relationship( name='user', serializer=ProfileRelationSerializer, queryset=lambda obj, request: obj.user )
python
def ready(self): """ Add user info to ExtensibleNodeSerializer """ from nodeshot.core.nodes.base import ExtensibleNodeSerializer from .serializers import ProfileRelationSerializer ExtensibleNodeSerializer.add_relationship( name='user', serializer=ProfileRelationSerializer, queryset=lambda obj, request: obj.user )
[ "def", "ready", "(", "self", ")", ":", "from", "nodeshot", ".", "core", ".", "nodes", ".", "base", "import", "ExtensibleNodeSerializer", "from", ".", "serializers", "import", "ProfileRelationSerializer", "ExtensibleNodeSerializer", ".", "add_relationship", "(", "name", "=", "'user'", ",", "serializer", "=", "ProfileRelationSerializer", ",", "queryset", "=", "lambda", "obj", ",", "request", ":", "obj", ".", "user", ")" ]
Add user info to ExtensibleNodeSerializer
[ "Add", "user", "info", "to", "ExtensibleNodeSerializer" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/profiles/apps.py#L7-L16
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", ".", "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'", "]" ]
parse geojson and ensure is collection
[ "parse", "geojson", "and", "ensure", "is", "collection" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/geojson.py#L11-L23
ninuxorg/nodeshot
nodeshot/core/base/serializers.py
DynamicRelationshipsMixin.add_relationship
def add_relationship(_class, name, view_name=None, lookup_field=None, serializer=None, many=False, queryset=None, function=None): """ adds a relationship to serializer :param name: relationship name (dictionary key) :type name: str :param view_name: view name as specified in urls.py :type view_name: str :param lookup_field: lookup field, usually slug or id/pk :type lookup_field: str :param serializer: Serializer class to use for relationship :type serializer: Serializer :param many: indicates if it's a list or a single element, defaults to False :type many: bool :param queryset: queryset string representation to use for the serializer :type queryset: QuerySet :param function: function that returns the value to display (dict, list or str) :type function: function(obj, request) :returns: None """ if view_name is not None and lookup_field is not None: _class._relationships[name] = { 'type': 'link', 'view_name': view_name, 'lookup_field': lookup_field } elif serializer is not None and queryset is not None: _class._relationships[name] = { 'type': 'serializer', 'serializer': serializer, 'many': many, 'queryset': queryset } elif function is not None: _class._relationships[name] = { 'type': 'function', 'function': function } else: raise ValueError('missing arguments, either pass view_name and lookup_field or serializer and queryset')
python
def add_relationship(_class, name, view_name=None, lookup_field=None, serializer=None, many=False, queryset=None, function=None): """ adds a relationship to serializer :param name: relationship name (dictionary key) :type name: str :param view_name: view name as specified in urls.py :type view_name: str :param lookup_field: lookup field, usually slug or id/pk :type lookup_field: str :param serializer: Serializer class to use for relationship :type serializer: Serializer :param many: indicates if it's a list or a single element, defaults to False :type many: bool :param queryset: queryset string representation to use for the serializer :type queryset: QuerySet :param function: function that returns the value to display (dict, list or str) :type function: function(obj, request) :returns: None """ if view_name is not None and lookup_field is not None: _class._relationships[name] = { 'type': 'link', 'view_name': view_name, 'lookup_field': lookup_field } elif serializer is not None and queryset is not None: _class._relationships[name] = { 'type': 'serializer', 'serializer': serializer, 'many': many, 'queryset': queryset } elif function is not None: _class._relationships[name] = { 'type': 'function', 'function': function } else: raise ValueError('missing arguments, either pass view_name and lookup_field or serializer and queryset')
[ "def", "add_relationship", "(", "_class", ",", "name", ",", "view_name", "=", "None", ",", "lookup_field", "=", "None", ",", "serializer", "=", "None", ",", "many", "=", "False", ",", "queryset", "=", "None", ",", "function", "=", "None", ")", ":", "if", "view_name", "is", "not", "None", "and", "lookup_field", "is", "not", "None", ":", "_class", ".", "_relationships", "[", "name", "]", "=", "{", "'type'", ":", "'link'", ",", "'view_name'", ":", "view_name", ",", "'lookup_field'", ":", "lookup_field", "}", "elif", "serializer", "is", "not", "None", "and", "queryset", "is", "not", "None", ":", "_class", ".", "_relationships", "[", "name", "]", "=", "{", "'type'", ":", "'serializer'", ",", "'serializer'", ":", "serializer", ",", "'many'", ":", "many", ",", "'queryset'", ":", "queryset", "}", "elif", "function", "is", "not", "None", ":", "_class", ".", "_relationships", "[", "name", "]", "=", "{", "'type'", ":", "'function'", ",", "'function'", ":", "function", "}", "else", ":", "raise", "ValueError", "(", "'missing arguments, either pass view_name and lookup_field or serializer and queryset'", ")" ]
adds a relationship to serializer :param name: relationship name (dictionary key) :type name: str :param view_name: view name as specified in urls.py :type view_name: str :param lookup_field: lookup field, usually slug or id/pk :type lookup_field: str :param serializer: Serializer class to use for relationship :type serializer: Serializer :param many: indicates if it's a list or a single element, defaults to False :type many: bool :param queryset: queryset string representation to use for the serializer :type queryset: QuerySet :param function: function that returns the value to display (dict, list or str) :type function: function(obj, request) :returns: None
[ "adds", "a", "relationship", "to", "serializer", ":", "param", "name", ":", "relationship", "name", "(", "dictionary", "key", ")", ":", "type", "name", ":", "str", ":", "param", "view_name", ":", "view", "name", "as", "specified", "in", "urls", ".", "py", ":", "type", "view_name", ":", "str", ":", "param", "lookup_field", ":", "lookup", "field", "usually", "slug", "or", "id", "/", "pk", ":", "type", "lookup_field", ":", "str", ":", "param", "serializer", ":", "Serializer", "class", "to", "use", "for", "relationship", ":", "type", "serializer", ":", "Serializer", ":", "param", "many", ":", "indicates", "if", "it", "s", "a", "list", "or", "a", "single", "element", "defaults", "to", "False", ":", "type", "many", ":", "bool", ":", "param", "queryset", ":", "queryset", "string", "representation", "to", "use", "for", "the", "serializer", ":", "type", "queryset", ":", "QuerySet", ":", "param", "function", ":", "function", "that", "returns", "the", "value", "to", "display", "(", "dict", "list", "or", "str", ")", ":", "type", "function", ":", "function", "(", "obj", "request", ")", ":", "returns", ":", "None" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/base/serializers.py#L44-L84
ninuxorg/nodeshot
nodeshot/interop/sync/synchronizers/cnml.py
Cnml.parse
def parse(self): """ parse data """ url = self.config.get('url') self.cnml = CNMLParser(url) self.parsed_data = self.cnml.getNodes()
python
def parse(self): """ parse data """ url = self.config.get('url') self.cnml = CNMLParser(url) self.parsed_data = self.cnml.getNodes()
[ "def", "parse", "(", "self", ")", ":", "url", "=", "self", ".", "config", ".", "get", "(", "'url'", ")", "self", ".", "cnml", "=", "CNMLParser", "(", "url", ")", "self", ".", "parsed_data", "=", "self", ".", "cnml", ".", "getNodes", "(", ")" ]
parse data
[ "parse", "data" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/synchronizers/cnml.py#L130-L134
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" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/management/commands/purge_notifications.py#L12-L19
ninuxorg/nodeshot
nodeshot/community/notifications/management/commands/purge_notifications.py
Command.handle
def handle(self, *args, **options): """ Purge notifications """ # retrieve layers notifications = self.retrieve_old_notifications() count = len(notifications) if count > 0: self.output('found %d notifications to purge...' % count) notifications.delete() self.output('%d notifications deleted successfully.' % count) else: self.output('there are no old notifications to purge')
python
def handle(self, *args, **options): """ Purge notifications """ # retrieve layers notifications = self.retrieve_old_notifications() count = len(notifications) if count > 0: self.output('found %d notifications to purge...' % count) notifications.delete() self.output('%d notifications deleted successfully.' % count) else: self.output('there are no old notifications to purge')
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "# retrieve layers", "notifications", "=", "self", ".", "retrieve_old_notifications", "(", ")", "count", "=", "len", "(", "notifications", ")", "if", "count", ">", "0", ":", "self", ".", "output", "(", "'found %d notifications to purge...'", "%", "count", ")", "notifications", ".", "delete", "(", ")", "self", ".", "output", "(", "'%d notifications deleted successfully.'", "%", "count", ")", "else", ":", "self", ".", "output", "(", "'there are no old notifications to purge'", ")" ]
Purge notifications
[ "Purge", "notifications" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/management/commands/purge_notifications.py#L24-L35
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", "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", ")" ]
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", "data", "on", "the", "local", "DB", "." ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/tasks.py#L18-L43
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", "=", "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", "(", ")" ]
writes message to pipe
[ "writes", "message", "to", "pipe" ]
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/websockets/tasks.py#L6-L21