code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
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
... | def check_status_mapping(self) | ensure status map does not contain status values which are not present in DB | 3.35864 | 3.240715 | 1.036388 |
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) | retrieve nodes from old mysql DB | 8.205236 | 4.641504 | 1.767797 |
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] = {
... | def extract_users(self) | extract user info | 3.741407 | 3.664858 | 1.020888 |
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()
... | def import_admins(self) | save admins to local DB | 2.286693 | 2.195739 | 1.041423 |
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
... | def import_users(self) | save users to local DB | 3.221411 | 3.172864 | 1.015301 |
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
... | def import_nodes(self) | import nodes into local DB | 3.108961 | 3.028079 | 1.026711 |
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()
... | def check_deleted_nodes(self) | delete imported nodes that are not present in the old database | 3.583715 | 3.306991 | 1.083679 |
created = kwargs['created']
user = kwargs['instance']
if created:
UserWebNotificationSettings.objects.create(user=user)
UserEmailNotificationSettings.objects.create(user=user) | def create_settings(sender, **kwargs) | create user notification settings on user creation | 3.422609 | 2.969461 | 1.152603 |
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) | Add user info to ExtensibleNodeSerializer | 16.486746 | 9.535081 | 1.729062 |
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.pa... | def parse(self) | parse geojson and ensure is collection | 3.841197 | 3.432462 | 1.119079 |
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:
... | 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 seria... | 1.806326 | 1.885834 | 0.95784 |
url = self.config.get('url')
self.cnml = CNMLParser(url)
self.parsed_data = self.cnml.getNodes() | def parse(self) | parse data | 8.979204 | 8.364343 | 1.07351 |
date = ago(days=DELETE_OLD)
return Notification.objects.filter(added__lte=date) | def retrieve_old_notifications(self) | Retrieve notifications older than X days, where X is specified in settings | 16.494448 | 15.554443 | 1.060433 |
# 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.'... | def handle(self, *args, **options) | Purge notifications | 5.320824 | 4.502632 | 1.181714 |
# 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 entir... | 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 instanc... | 14.348478 | 13.506611 | 1.06233 |
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')
... | def send_message(message, pipe='public') | writes message to pipe | 3.840806 | 3.67043 | 1.046419 |
if user:
return {'user': user}
if not username:
return None
email = details.get('email')
original_email = None
# email is required
if not email:
message = _()
raise AuthFailed(backend, message)
# Avoid hitting field max length
if email and len(email) ... | def create_user(backend, details, response, uid, username, user=None, *args, **kwargs) | Creates user. Depends on get_username pipeline. | 5.032526 | 4.96313 | 1.013982 |
social_user = social_user or UserSocialAuth.get_social_auth(backend.name, uid)
# create verified email address
if kwargs['is_new'] and EMAIL_CONFIRMATION:
from ..models import EmailAddress
# check if email exist before creating it
# we might be associating an exisiting user
... | def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs) | Load extra data from provider and store it on current UserSocialAuth extra_data field. | 2.70757 | 2.688199 | 1.007206 |
if not self.user and (not self.from_name or not self.from_email):
raise ValidationError(_('If sender is not specified from_name and from_email must be filled in.'))
# fill name and email
if self.user:
self.from_name = self.user.get_full_name()
self.fr... | def clean(self, *args, **kwargs) | custom validation | 3.664059 | 3.354231 | 1.092369 |
if self.content_type.name == 'node':
to = [self.to.user.email]
elif self.content_type.name == 'layer':
to = [self.to.email]
# layer case is slightly special, mantainers need to be notified as well
# TODO: consider making the mantainers able to swi... | def send(self) | Sends the email to the recipient
If the sending fails will set the status of the instance to "error" and will log the error according to your project's django-logging configuration | 3.7077 | 3.408768 | 1.087695 |
# fill name and email
if self.user:
self.from_name = self.user.get_full_name()
self.from_email = self.user.email
# if not sent yet
if int(self.status) < 1:
# tries sending email (will modify self.status!)
self.send()
# sa... | def save(self, *args, **kwargs) | Custom save method | 6.78609 | 6.687168 | 1.014793 |
if n is not None and n < 0:
raise ValueError('slice parameter cannot be negative')
queryset = self.order_by(order_by)
if n is None:
return queryset[0]
else:
return queryset[0:n] | def slice(self, order_by='pk', n=None) | return n objects according to specified ordering | 2.893334 | 2.726259 | 1.061284 |
# if access_level is number
if isinstance(access_level, int):
value = access_level
# else if is string get the numeric value
else:
value = ACCESS_LEVELS.get(access_level)
# return queryset
return self.filter(access_level__lte=value) | def access_level_up_to(self, access_level) | returns all items that have an access level equal or lower than the one specified | 4.333052 | 4.090631 | 1.059263 |
if user.is_superuser:
try:
queryset = self.get_queryset()
except AttributeError:
queryset = self
elif user.is_authenticated():
# get user group (higher id)
group = user.groups.all().order_by('-id')[0]
qu... | def accessible_to(self, user) | returns all the items that are accessible to the specified user
if user is not authenticated will return public items
:param user: an user instance | 3.300762 | 3.280191 | 1.006271 |
ignore_default_check = kwargs.pop('ignore_default_check', False)
# if making this status the default one
if self.is_default != self._current_is_default and self.is_default is True:
# uncheck other default statuses first
for status in self.__class__.objects.filter... | def save(self, *args, **kwargs) | intercepts changes to is_default | 3.279775 | 2.973148 | 1.103132 |
super(NodeLinkList, self).initial(request, *args, **kwargs)
# ensure node exists
try:
self.node = Node.objects.published()\
.accessible_to(request.user)\
.get(slug=self.kwargs.get('slug', None))
... | def initial(self, request, *args, **kwargs) | Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only links of current node | 2.872078 | 2.4259 | 1.183923 |
from .models import LayerExternal
from nodeshot.core.layers.views import LayerNodeListMixin
def get_nodes(self, request, *args, **kwargs):
try:
external = self.layer.external
except LayerExternal.DoesNotExist:
external = False
... | def ready(self) | patch LayerNodesList view to support external layers | 6.266705 | 5.428883 | 1.154327 |
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % project_name)
app = Celery(project_name)
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(settings.INSTALLED_APPS, related_name='tasks')
return app | def init_celery(project_name) | init celery app without the need of redundant code | 1.719078 | 1.68162 | 1.022275 |
# user model
User = get_user_model()
# prepare email list
emails = []
# the following code is a bit ugly. Considering the titanic amount of work required to build all
# the cools functionalities that I have in my mind, I can't be bothered to waste time on makin... | def get_recipients(self) | Determine recipients depending on selected filtering which can be either:
* group based
* layer based
* user based
Choosing "group" and "layer" filtering together has the effect of sending the message
only to users for which the following conditions are both true:
... | 4.524715 | 4.425767 | 1.022357 |
# if it has already been sent don't send again
if self.status is OUTWARD_STATUS.get('sent'):
return False
# determine recipients
recipients = self.get_recipients()
# init empty list that will contain django's email objects
emails = []
# prepa... | def send(self) | Sends the email to the recipients | 4.297388 | 4.184361 | 1.027012 |
# change status to scheduled if necessary
if self.is_scheduled and self.status is not OUTWARD_STATUS.get('scheduled'):
self.status = OUTWARD_STATUS.get('scheduled')
# call super.save()
super(Outward, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | Custom save method | 5.672607 | 5.311802 | 1.067925 |
if self.is_scheduled is 1 and (self.scheduled_date == '' or self.scheduled_date is None
or self.scheduled_time == '' or self.scheduled_time is None):
raise ValidationError(_('If message is scheduled both fields "scheduled date" and "scheduled time" mus... | def clean(self, *args, **kwargs) | Custom validation | 3.214923 | 3.167774 | 1.014884 |
# geometry collection check
if isinstance(self.geometry, GeometryCollection) and 0 < len(self.geometry) < 2:
self.geometry = self.geometry[0]
# if no status specified
if not self.status and not self.status_id:
try:
self.status = Status.obj... | def save(self, *args, **kwargs) | Custom save method does the following things:
* converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point)
* intercepts changes to status and fires node_status_changed signal
* set default status | 2.818239 | 2.497827 | 1.128276 |
method_name = method.func_name
# add method name to additional validation method list
cls._additional_validation.append(method_name)
# add method to this class
setattr(cls, method_name, method) | def add_validation_method(cls, method) | Extend validation of Node by adding a function to the _additional_validation list.
The additional validation function will be called by the clean method
:method function: function to be added to _additional_validation | 4.173083 | 4.428688 | 0.942284 |
if not self.geometry:
raise ValueError('geometry attribute must be set before trying to get point property')
if self.geometry.geom_type == 'Point':
return self.geometry
else:
try:
# point_on_surface guarantees that the point is within ... | def point(self) | returns location of node. If node geometry is not a point a center point will be returned | 5.509874 | 5.101321 | 1.080088 |
if format is None:
format = 'json'
path = request.query_params.get('path')
if not path:
return Response({'detail': _('missing required path argument')}, status=400)
return Response(elevation(path,
api_key=ELEVATION_API_KEY,
... | def elevation_profile(request, format=None) | Proxy to google elevation API but returns GeoJSON
(unless "original" parameter is passed, in which case the original response is returned).
For input parameters read:
https://developers.google.com/maps/documentation/elevation/ | 4.235862 | 5.236207 | 0.808956 |
if serializer.instance is None:
serializer.save(user=self.request.user) | def perform_create(self, serializer) | determine user when node is added | 4.488118 | 3.407367 | 1.317181 |
# retrieve all nodes which are published and accessible to current user
# and use joins to retrieve related fields
queryset = super(NodeList, self).get_queryset().select_related('status', 'user', 'layer')
# query string params
search = self.request.query_params.get('sear... | def get_queryset(self) | Optionally restricts the returned nodes
by filtering against a `search` query parameter in the URL. | 3.200959 | 3.035941 | 1.054355 |
super(NodeImageList, self).initial(request, *args, **kwargs)
# ensure node exists
self.node = get_queryset_or_404(
Node.objects.published().accessible_to(request.user),
{'slug': self.kwargs['slug']}
)
# check permissions on node (for image creatio... | def initial(self, request, *args, **kwargs) | Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only images of current node | 4.698424 | 3.794054 | 1.238365 |
# shortcuts for readability
Notification = notification_model
# text
additional = related_object.__dict__ if related_object else ''
notification_text = TEXTS[notification_type] % additional
# loop users, notification settings check is done in Notification model
for user in users:
... | def create_notifications(users, notification_model, notification_type, related_object) | create notifications in a background job to avoid slowing down users | 5.935535 | 5.96255 | 0.995469 |
self.type = INTERFACE_TYPES.get('ethernet')
super(Ethernet, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | automatically set Interface.type to ethernet | 7.361075 | 3.540063 | 2.079363 |
endpoints = []
# loop over url modules
for urlmodule in urlpatterns:
# is it a urlconf module?
if hasattr(urlmodule, 'urlconf_module'):
is_urlconf_module = True
else:
is_urlconf_module = False
# if url is really a urlmodule
if is_urlconf_m... | def root_endpoint(request, format=None) | List of all the available resources of this RESTful API. | 5.032058 | 5.030651 | 1.00028 |
if 'node' not in self.shortcuts:
self.shortcuts['node'] = self.device.node
if 'user' not in self.shortcuts and self.device.node.user:
self.shortcuts['user'] = self.device.node.user
if 'layer' not in self.shortcuts and 'nodeshot.core.layers' in settings.INSTALLE... | def save(self, *args, **kwargs) | Custom save method does the following:
* save shortcuts if HSTORE is enabled | 3.557258 | 3.607317 | 0.986123 |
if not isinstance(value, list):
raise ValueError('ip_addresses value must be a list')
# in soem cases self.data might be none, so let's instantiate an empty dict
if self.data is None:
self.data = {}
# update field
self.data['ip_addresses'] = ', '.... | def ip_addresses(self, value) | :param value: a list of ip addresses | 4.879389 | 4.574215 | 1.066716 |
node_rating_count = self.node.rating_count
node_rating_count.comment_count = self.node.comment_set.count()
node_rating_count.save() | def update_count(self) | updates comment count | 4.992652 | 3.925138 | 1.271969 |
# check done only for new nodes!
if not self.pk:
node = self.node
# ensure comments for this node are allowed
if node.participation_settings.comments_allowed is False:
raise ValidationError("Comments not allowed for this node")
# e... | def clean(self, *args, **kwargs) | Check if comments can be inserted for parent node or parent layer | 6.054921 | 4.900224 | 1.235642 |
# init empty Q object
queryset = Q()
# if no layer specified
if len(args) < 1:
# cache queryset
all_layers = Layer.objects.published().external()
# check if there is any layer to exclude
if options['exclude']:
# co... | def retrieve_layers(self, *args, **options) | Retrieve specified layers or all external layers if no layer specified. | 3.686198 | 3.511105 | 1.049868 |
# store verbosity level in instance attribute for later use
self.verbosity = int(options.get('verbosity'))
# blank line
self.stdout.write('\r\n')
# retrieve layers
layers = self.retrieve_layers(*args, **options)
if len(layers) < 1:
self.stdou... | def handle(self, *args, **options) | execute sync command | 3.142216 | 3.10815 | 1.010961 |
node = kwargs['instance']
operation = 'add' if kwargs['created'] is True else 'change'
if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None:
return False
push_changes_to_external_layers.delay(node=node, external_layer=n... | def save_external_nodes(sender, **kwargs) | sync by creating nodes in external layers when needed | 5.115775 | 4.451803 | 1.149147 |
node = kwargs['instance']
if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None:
return False
if hasattr(node, 'external') and node.external.external_id:
push_changes_to_external_layers.delay(
node=node.e... | def delete_external_nodes(sender, **kwargs) | sync by deleting nodes from external layers when needed | 4.74897 | 4.161583 | 1.141145 |
if not self.pk:
old_votes = Vote.objects.filter(user=self.user, node=self.node)
for old_vote in old_votes:
old_vote.delete()
super(Vote, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | ensure users cannot vote the same node multiple times
but let users change their votes | 2.536526 | 1.992915 | 1.272772 |
node_rating_count = self.node.rating_count
node_rating_count.likes = self.node.vote_set.filter(vote=1).count()
node_rating_count.dislikes = self.node.vote_set.filter(vote=-1).count()
node_rating_count.save() | def update_count(self) | updates likes and dislikes count | 2.946942 | 2.455296 | 1.200239 |
if not self.pk:
# ensure voting for this node is allowed
if self.node.participation_settings.voting_allowed is not True:
raise ValidationError("Voting not allowed for this node")
if 'nodeshot.core.layers' in settings.INSTALLED_APPS:
l... | def clean(self, *args, **kwargs) | Check if votes can be inserted for parent node or parent layer | 4.958282 | 3.922417 | 1.264088 |
results = []
# layer3 results
for ip in Ip.objects.select_related().all():
interface = ip.interface
user = interface.device.node.user
device = interface.device
results.append({
'address': str(ip.address),
'user': user.username,
'name':... | def whois_list(request, format=None) | Retrieve basic whois information related to a layer2 or layer3 network address. | 2.252947 | 2.185394 | 1.030911 |
address_obj = None
try:
address_obj = IPAddress(address)
except AddrFormatError:
try:
address_obj = EUI(address)
except AddrFormatError:
pass
if not address_obj:
return Response({'detail': 'invalid address'}, status=400)
elif isinstance(ad... | def whois_detail(request, address, format=None) | Retrieve basic whois information related to a layer2 or layer3 network address. | 2.203442 | 2.207736 | 0.998055 |
# retrieve all devices which are published and accessible to current user
# and use joins to retrieve related fields
queryset = super(DeviceList, self).get_queryset()#.select_related('layer', 'status', 'user')
# retrieve value of querystring parameter "search"
search = ... | def get_queryset(self) | Optionally restricts the returned devices
by filtering against a `search` query parameter in the URL. | 4.733218 | 4.29972 | 1.10082 |
super(NodeDeviceList, self).initial(request, *args, **kwargs)
# ensure node exists
try:
self.node = Node.objects.published()\
.accessible_to(request.user)\
.get(slug=self.kwargs.get('slug', None))
except Node.DoesNotEx... | def initial(self, request, *args, **kwargs) | Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only devices of current node | 3.151554 | 2.596406 | 1.213814 |
super(BaseInterfaceList, self).initial(request, *args, **kwargs)
# ensure device exists
try:
self.device = Device.objects.accessible_to(request.user)\
.get(pk=self.kwargs.get('pk', None))
except Device.DoesNotExist:
raise Http404(... | def initial(self, request, *args, **kwargs) | Custom initial method:
* ensure device exists and store it in an instance attribute
* change queryset to return only devices of current node | 3.344815 | 2.854939 | 1.171589 |
super(InterfaceIpList, self).initial(request, *args, **kwargs)
# ensure interface exists
try:
self.interface = Interface.objects.accessible_to(request.user)\
.get(pk=self.kwargs.get('pk', None))
except Interface.DoesNotExist:
rais... | def initial(self, request, *args, **kwargs) | Custom initial method:
* ensure interface exists and store it in an instance attribute
* change queryset to return only devices of current node | 3.423181 | 2.967981 | 1.15337 |
bridge = kwargs.pop("bridge", None)
if bridge:
try:
group = bridge.get_group(**kwargs)
except ObjectDoesNotExist:
raise Http404
else:
group = None
return group, bridge | def group_and_bridge(kwargs) | Given kwargs from the view (with view specific keys popped) pull out the
bridge and fetch group from database. | 3.739675 | 2.837725 | 1.317843 |
# auto fill updated field with current time unless explicitly disabled
auto_update = kwargs.get('auto_update', True)
if auto_update:
self.updated = now()
# remove eventual auto_update
if 'auto_update' in kwargs:
kwargs.pop('auto_update')
... | def save(self, *args, **kwargs) | automatically update updated date field | 4.473015 | 3.819446 | 1.171116 |
if self.order == '' or self.order is None:
try:
self.order = self.get_auto_order_queryset().order_by("-order")[0].order + 1
except IndexError:
self.order = 0
super(BaseOrdered, self).save() | def save(self, *args, **kwargs) | if order left blank | 4.456069 | 3.808363 | 1.170075 |
if type(dependencies) == str:
dependencies = [dependencies]
elif type(dependencies) != list:
raise TypeError('dependencies argument must be of type list or string')
for dependency in dependencies:
if dependency not in settings.INSTALLED_APPS:
raise DependencyError('... | def check_dependencies(dependencies, module) | Ensure dependencies of a module are listed in settings.INSTALLED_APPS
:dependencies string | list: list of dependencies to check
:module string: string representing the path to the current app | 2.92474 | 2.626066 | 1.113734 |
# get order of the fields
ordered_fields = sorted(dictionary, key=dictionary.get)
choices = []
# loop over each field
for field in ordered_fields:
# build tuple (value, i18n_key)
row = (dictionary[field], _(field.replace('_', ' ')))
# append tuple to choices
choi... | def choicify(dictionary) | Converts a readable python dictionary into a django model/form
choice structure (list of tuples) ordered based on the values of each key
:param dictionary: the dictionary to convert | 4.415159 | 4.425815 | 0.997592 |
for key, value in dictionary.iteritems():
if value == search_value:
return ugettext(key) | def get_key_by_value(dictionary, search_value) | searchs a value in a dicionary and returns the key of the first occurrence
:param dictionary: dictionary to search in
:param search_value: value to search for | 4.155626 | 6.087907 | 0.682603 |
if self.layer:
return
try:
self.layer = Layer.objects.get(slug=self.kwargs['slug'])
except Layer.DoesNotExist:
raise Http404(_('Layer not found')) | def get_layer(self) | retrieve layer from DB | 3.204364 | 2.646399 | 1.210839 |
self.get_layer()
return super(LayerNodeListMixin, self).get_queryset().filter(layer_id=self.layer.id) | def get_queryset(self) | extend parent class queryset by filtering nodes of the specified layer | 7.395131 | 4.180753 | 1.768852 |
# ListSerializerMixin.list returns a serializer object
return (self.list(request, *args, **kwargs)).data | def get_nodes(self, request, *args, **kwargs) | this method might be overridden by other modules (eg: nodeshot.interop.sync) | 14.292968 | 13.629486 | 1.04868 |
self.get_layer()
# get nodes of layer
nodes = self.get_nodes(request, *args, **kwargs)
return Response(nodes) | def get(self, request, *args, **kwargs) | Retrieve list of nodes of the specified layer | 6.892978 | 4.374345 | 1.575774 |
self.protocol = 'ipv%d' % self.address.version
# save
super(Ip, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | Determines ip protocol version automatically.
Stores address in interface shortcuts for convenience. | 8.568329 | 5.371745 | 1.595074 |
if obj1._meta.app_label != 'oldimporter' and obj2._meta.app_label != 'oldimporter':
return True
return None | def allow_relation(self, obj1, obj2, **hints) | Relations between objects are allowed between nodeshot2 objects only | 4.288389 | 4.978775 | 0.861334 |
if db != 'old_nodeshot' or model._meta.app_label != 'oldimporter':
return False
return True | def allow_migrate(self, db, model) | Make sure the old_nodeshot app only appears in the 'old_nodeshot' database | 17.373857 | 5.348876 | 3.248133 |
if EMAIL_CONFIRMATION:
from .models import EmailAddress
condition = EmailAddress.objects.filter(
email__iexact=self.cleaned_data["email"],
verified=True
).count() == 0
else:
condition = User.objects.get(
... | def clean_email(self) | ensure email is in the database | 3.035648 | 2.77409 | 1.094286 |
metric = get_object_or_404(Metric, pk=pk)
# get
if request.method == 'GET':
try:
results = metric.select(q=request.query_params.get('q', metric.query))
except InfluxDBClientError as e:
return Response({'detail': e.content}, status=e.code)
return Response(... | def metric_details(request, pk, format=None) | Get or write metric values | 3.245516 | 3.137028 | 1.034583 |
if user_id is None:
# generate a random uuid if it's an unauthenticated client
self.channel = 'public'
user_id = uuid.uuid1().hex
else:
self.channel = 'private'
self.id = user_id
self.channels[self.channel][self.id] = self... | def add_client(self, user_id=None) | Adds current instance to public or private channel.
If user_id is specified it will be added to the private channel,
If user_id is not specified it will be added to the public one instead. | 4.317723 | 4.192179 | 1.029947 |
clients = cls.get_clients()
# loop over every client and send message
for id, client in clients.iteritems():
client.send_message(message) | def broadcast(cls, message) | broadcast message to all connected clients | 5.31431 | 4.355698 | 1.220082 |
try:
client = self.channels['private'][str(user_id)]
except KeyError:
print '====debug===='
print self.channels['private']
print 'client with id %s not found' % user_id
return False
client.send_message(message)
... | def send_private_message(self, user_id, message) | Send a message to a specific client.
Returns True if successful, False otherwise | 4.188015 | 4.01649 | 1.042705 |
public = self.channels['public']
private = self.channels['private']
return dict(public.items() + private.items()) | def get_clients(self) | return a merge of public and private clients | 6.34655 | 3.472469 | 1.827676 |
print 'Connection opened.'
# retrieve user_id if specified
user_id = self.get_argument("user_id", None)
# add client to list of connected clients
self.add_client(user_id)
# welcome message
self.send_message("Welcome to nodeshot websocket server."... | def open(self) | method which is called every time a new client connects | 5.353669 | 5.045327 | 1.061114 |
print 'Connection closed.'
self.remove_client()
client_count = len(self.get_clients().keys())
new_client_message = '1 client disconnected, now we have %d %s!' % (client_count, 'client' if client_count <= 1 else 'clients')
self.broadcast(new_client_message) | def on_close(self) | method which is called every time a client disconnects | 5.024785 | 4.722952 | 1.063908 |
return client.InfluxDBClient(
settings.INFLUXDB_HOST,
settings.INFLUXDB_PORT,
settings.INFLUXDB_USER,
settings.INFLUXDB_PASSWORD,
settings.INFLUXDB_DATABASE,
) | def get_db() | Returns an ``InfluxDBClient`` instance. | 2.256458 | 1.909533 | 1.18168 |
db = get_db()
database = database or settings.INFLUXDB_DATABASE
return db.query(query, params, epoch, expected_response_code, database=database) | def query(query, params={}, epoch=None,
expected_response_code=200, database=None) | Wrapper around ``InfluxDBClient.query()``. | 3.544832 | 2.883937 | 1.229164 |
thread = Thread(target=write,
args=(name, values, tags, timestamp, database))
thread.start() | def write_async(name, values, tags={}, timestamp=None, database=None) | write metrics | 3.216115 | 3.084713 | 1.042598 |
point = {
'measurement': name,
'tags': tags,
'fields': values
}
if isinstance(timestamp, datetime):
timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')
if timestamp:
point['time'] = timestamp
try:
get_db().write({'points': [point]},
... | def write(name, values, tags={}, timestamp=None, database=None) | Method to be called via threading module. | 2.779645 | 2.759929 | 1.007144 |
db = get_db()
response = db.query('SHOW DATABASES')
items = list(response.get_points('databases'))
databases = [database['name'] for database in items]
# if database does not exists, create it
if settings.INFLUXDB_DATABASE not in databases:
db.create_database(settings.INFLUXDB_DATAB... | def create_database() | creates database if necessary | 3.55328 | 3.500702 | 1.015019 |
if not self.pk:
old_ratings = Rating.objects.filter(user=self.user, node=self.node)
for old_rating in old_ratings:
old_rating.delete()
super(Rating, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | ensure users cannot rate the same node multiple times
but let users change their rating | 2.587109 | 2.003815 | 1.291092 |
node_rating_count = self.node.rating_count
node_rating_count.rating_count = self.node.rating_set.count()
node_rating_count.rating_avg = self.node.rating_set.aggregate(rate=Avg('value'))['rate']
# if all ratings are deleted the value will be None!
if node_rating_count.ra... | def update_count(self) | updates rating count and rating average | 3.837784 | 3.430673 | 1.118668 |
if not self.pk:
node = self.node
layer = Layer.objects.get(pk=node.layer_id)
if layer.participation_settings.rating_allowed is not True:
raise ValidationError("Rating not allowed for this layer")
if node.participation_settings.rating_allow... | def clean(self, *args, **kwargs) | Check if rating can be inserted for parent node or parent layer | 4.436036 | 3.216736 | 1.379049 |
# the following lines determines if the comment is being created or not
# in case the comment exists the pk attribute is an int
created = type(self.pk) is not int
super(UpdateCountsMixin, self).save(*args, **kwargs)
# this operation must be performed after the parent s... | def save(self, *args, **kwargs) | custom save method to update counts | 10.500647 | 8.834895 | 1.188542 |
super(UpdateCountsMixin, self).delete(*args, **kwargs)
self.update_count() | def delete(self, *args, **kwargs) | custom delete method to update counts | 7.242816 | 3.994294 | 1.813291 |
for topology in Topology.objects.all():
try:
topology.update()
except Exception as e:
msg = 'Failed to update {}'.format(topology.__repr__())
logger.exception(msg)
print('{0}: {1}\n'
'see networking.log for more information\n'.fo... | def update_topology() | updates all the topology
sends logs to the "nodeshot.networking" logger | 4.85762 | 4.502868 | 1.078784 |
self.host = self.host.strip()
if not self.id:
self.device = self.__create_device()
if self.store is True:
super(DeviceConnector, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | Custom save does the following:
* strip trailing whitespace from host attribute
* create device and all other related objects
* store connection config in DB if store attribute is True | 5.933266 | 3.499097 | 1.695656 |
self._validate_backend()
self._validate_config()
self._validate_netengine()
self._validate_duplicates() | def clean(self, *args, **kwargs) | validation | 12.664082 | 10.421623 | 1.215174 |
if not self.backend:
return None
if not self.__backend_class:
self.__backend_class = self._get_netengine_backend()
return self.__backend_class | def backend_class(self) | returns python netengine backend class, importing it if needed | 4.888803 | 3.026503 | 1.615331 |
# return None if no backend chosen yet
if not self.backend:
return None
# init instance of the netengine backend if not already done
if not self.__netengine:
NetengineBackend = self.backend_class
arguments = self._build_netengine_arguments()
... | def netengine(self) | access netengine instance | 5.456006 | 4.98174 | 1.095201 |
try:
self.backend_class
# if we get an import error the specified path is wrong
except (ImportError, AttributeError) as e:
raise ValidationError(_('No valid backend found, got the following python exception: "%s"') % e) | def _validate_backend(self) | ensure backend string representation is correct | 9.568199 | 8.562064 | 1.117511 |
# exit if no backend specified
if not self.backend:
return
# exit if no required config keys
if len(self.REQUIRED_CONFIG_KEYS) < 1:
return
self.config = self.config or {} # default to empty dict of no config
required_keys_set = set(self.... | def _validate_config(self) | ensure REQUIRED_CONFIG_KEYS are filled | 2.595381 | 2.472737 | 1.049599 |
if self.backend:
try:
self.netengine.validate()
except NetEngineError as e:
raise ValidationError(e) | def _validate_netengine(self) | call netengine validate() method
verifies connection parameters are correct | 5.702559 | 5.068475 | 1.125103 |
# if connector is being created right now
if not self.id:
duplicates = []
self.netengine_dict = self.netengine.to_dict()
# loop over interfaces and check mac address
for interface in self.netengine_dict['interfaces']:
# avoid check... | def _validate_duplicates(self) | Ensure we're not creating a device that already exists
Runs only when the DeviceConnector object is created, not when is updated | 4.66827 | 4.40035 | 1.060886 |
# inspect netengine class
backend_class = self._get_netengine_backend()
argspec = inspect.getargspec(backend_class.__init__)
# store args
args = argspec.args
# remove known arguments
for argument_name in ['self', 'host', 'port']:
args.remove(a... | def _get_netengine_arguments(self, required=False) | returns list of available config params
returns list of required config params if required is True
for internal use only | 4.68836 | 4.760082 | 0.984933 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.