<commit_before># coding: utf-8
import datetime

from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, View, FormView, TemplateView
from django.views.generic.detail import SingleObjectTemplateResponseMixin, BaseDetailView, SingleObjectMixin
from django.template import RequestContext
from django.core.urlresolvers import reverse_lazy, reverse
from django.contrib.auth.models import Group
from django.shortcuts import render_to_response
from reversion.models import Version
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponseBadRequest
from django.contrib import messages
from django.utils.timezone import utc
from django.utils import timezone
import reversion
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.db.transaction import atomic
from django.conf import settings

from devices.models import Device, Template, Room, Building, Manufacturer, Lending, Note, Bookmark
from devicetypes.models import TypeAttribute, TypeAttributeValue
from network.models import IpAddress
from mail.models import MailTemplate, MailHistory
from devices.forms import IpAddressForm, SearchForm, LendForm, DeviceViewForm, IpAddressPurposeForm
from devices.forms import ViewForm, DeviceForm, DeviceMailForm, VIEWSORTING, VIEWSORTING_DEVICES, FilterForm, \
    DeviceStorageForm, ReturnForm
from devicetags.forms import DeviceTagForm
from users.models import Lageruser, Department
from Lagerregal.utils import PaginationMixin
from devicetags.models import Devicetag
from permission.decorators import permission_required
from django.db.models import Q

@permission_required('devices.read_device', raise_exception=True)
class DeviceList(PaginationMixin, ListView):
    context_object_name = 'device_list'
    template_name = 'devices/device_list.html'
    viewfilter = None
    viewsorting = None

    def get_queryset(self):
        self.viewfilter = self.kwargs.get("filter", "active")
        devices = None
        lendings = None
        if self.viewfilter == "all":
            devices = Device.objects.all()
        elif self.viewfilter == "available":
            devices = Device.active().filter(currentlending=None)
        elif self.viewfilter == "lent":
            lendings = Lending.objects.filter(returndate=None)
        elif self.viewfilter == "archived":
            devices = Device.objects.exclude(archived=None)
        elif self.viewfilter == "trashed":
            devices = Device.objects.exclude(trashed=None)
        elif self.viewfilter == "overdue":
            lendings = Lending.objects.filter(returndate=None, duedate__lt=datetime.date.today())
        elif self.viewfilter == "returnsoon":
            soon = datetime.date.today() + datetime.timedelta(days=10)
            lendings = Lending.objects.filter(returndate=None, duedate__lte=soon,
                                              duedate__gt=datetime.date.today())
        elif self.viewfilter == "temporary":
            devices = Device.active().filter(templending=True)
        elif self.viewfilter == "bookmark":
            if self.request.user.is_authenticated:
                devices = self.request.user.bookmarks.all()
        else:
            devices = Device.active()

        if self.request.user.main_department != None:
            self.departmentfilter = self.kwargs.get("department", self.request.user.main_department.id)
        else:
            self.departmentfilter = self.kwargs.get("department", "all")

        if self.departmentfilter != "all":
            try:
                departmentid = int(self.departmentfilter)
                self.departmentfilter = Department.objects.get(id=departmentid)
            except:
                self.departmentfilter = Department.objects.get(name=self.departmentfilter)

        if self.viewfilter == "lent" or self.viewfilter == "overdue" or self.viewfilter == "returnsoon":
            if self.departmentfilter != "all":
                lendings = lendings.filter(owner__departments=self.departmentfilter)
            lendings = lendings.exclude(~Q(device__department__in=self.request.user.departments.all()) &
                                        ~Q(device=None), device__is_private=True)
            return lendings.values("device__id", "device__name", "device__inventorynumber",
                                       "device__devicetype__name", "device__room__name", "device__group",
                                       "device__room__building__name", "owner__username", "owner__id",
                                       "duedate", "smalldevice")
        else:
            if self.departmentfilter != "all":
                devices = devices.filter(department=self.departmentfilter)
            devices = devices.exclude(~Q(department__in=self.request.user.departments.all()), is_private=True)
            self.viewsorting = self.kwargs.get("sorting", "name")
            if self.viewsorting in [s[0] for s in VIEWSORTING_DEVICES]:
                devices = devices.order_by(self.viewsorting)

            return devices.values("id", "name", "inventorynumber", "devicetype__name", "room__name", "room__building__name",
                              "group__name", "currentlending__owner__username", "currentlending__duedate")

    def get_context_data(self, **kwargs):
        context = super(DeviceList, self).get_context_data(**kwargs)
        context["viewform"] = DeviceViewForm(initial={
            'viewfilter': self.viewfilter,
            "viewsorting": self.viewsorting,
            "departmentfilter": self.departmentfilter
        })
        context["today"] = datetime.datetime.today()
        context["template_list"] = Template.objects.all()
        context["viewfilter"] = self.viewfilter
        context["breadcrumbs"] = [[reverse("device-list"), _("Devices")]]
        if context["is_paginated"] and context["page_obj"].number > 1:
            context["breadcrumbs"].append(["", context["page_obj"].number])
        return context

@permission_required('devices.read_device', raise_exception=True)
class DeviceDetail(DetailView):
    queryset = Device.objects.select_related("manufacturer", "devicetype", "currentlending")
    context_object_name = 'device'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(DeviceDetail, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['ipaddressform'] = IpAddressForm()
        context["ipaddressform"].fields["ipaddresses"].queryset = IpAddress.objects.filter(department=self.object.department, device=None, user=None)
        context['tagform'] = DeviceTagForm()
        context['tagform'].fields["tags"].queryset = Devicetag.objects.exclude(devices=context["device"])
        context["lending_list"] = Lending.objects.filter(device=context["device"]).order_by("-pk")[:10]
        context["version_list"] = Version.objects.filter(object_id=context["device"].id,
                                                         content_type_id=ContentType.objects.get(
                                                             model='device').id).order_by("-pk")[:10]
        context["mail_list"] = MailHistory.objects.filter(device=context["device"]).order_by("-pk")[:10]
        context["today"] = datetime.datetime.utcnow().replace(tzinfo=utc)
        context["weekago"] = context["today"] - datetime.timedelta(days=7)
        context["attributevalue_list"] = TypeAttributeValue.objects.filter(device=context["device"])
        context["lendform"] = LendForm()
        mailinitial = {}
        if context["device"].currentlending is not None:
            currentowner = context["device"].currentlending.owner
            mailinitial["owner"] = currentowner
            mailinitial["emailrecipients"] = ("u" + str(currentowner.id), currentowner.username)
        try:
            mailinitial["mailtemplate"] = MailTemplate.objects.get(usage="reminder")
            mailinitial["emailsubject"] = mailinitial["mailtemplate"].subject
            mailinitial["emailbody"] = mailinitial["mailtemplate"].body
        except:
            pass
        context["mailform"] = DeviceMailForm(initial=mailinitial)
        context["mailform"].fields["mailtemplate"].queryset = MailTemplate.objects.filter(department__in=self.request.user.departments.all())
        versions = reversion.get_for_object(context["device"])
        if len(versions) != 0:
            context["lastedit"] = versions[0]

        if self.object.department:
            dep = self.object.department.name
        else:
            dep = "all"

        if dep in settings.LABEL_TEMPLATES:
            if "device" in settings.LABEL_TEMPLATES[dep]:
                context["display_printbutton"] = True
                context["label_js"] = ""
                for attribute in settings.LABEL_TEMPLATES[dep]["device"][1]:
                    if attribute == "id":
                        context["label_js"] += u"\nlabel.setObjectText('{0}', '{1:07d}');".format(attribute,
                                                                                                  getattr(context["device"],
                                                                                                          attribute))
                    else:
                        context["label_js"] += u"\nlabel.setObjectText('{0}', '{1}');".format(attribute,
                                                                                              getattr(context["device"],
                                                                                                      attribute))

        context["breadcrumbs"] = [
            (reverse("device-list"), _("Devices")),
            (reverse("device-detail", kwargs={"pk": context["device"].pk}), context["device"].name)]
        return context


@permission_required('devices.change_device', raise_exception=True)
class DeviceIpAddressRemove(DeleteView):
    template_name = 'devices/unassign_ipaddress.html'
    model = IpAddress

    def get(self, request, *args, **kwargs):
        context = {"device": get_object_or_404(Device, pk=kwargs["pk"]),
                   "ipaddress": get_object_or_404(IpAddress, pk=kwargs["ipaddress"])}
        context["breadcrumbs"] = [
            (reverse("device-list"), _("Devices")),
            (reverse("device-detail", kwargs={"pk": context["device"].pk}), context["device"].name),
            ("", _("Unassign IP-Addresses"))]
        return render_to_response(self.template_name, context, RequestContext(request))

    def post(self, request, *args, **kwargs):
        device = get_object_or_404(Device, pk=kwargs["pk"])
        ipaddress = get_object_or_404(IpAddress, pk=kwargs["ipaddress"])
        ipaddress.device = None
        ipaddress.purpose = None
        reversion.set_comment(_("Removed from Device {0}".format(device.name)))
        ipaddress.save()

        return HttpResponseRedirect(reverse("device-detail", kwargs={"pk": device.pk}))


@permission_required('devices.change_device', raise_exception=True)
class DeviceIpAddress(FormView):<commit_msg>fix ipaddress error<commit_after># coding: utf-8
import datetime

from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, View, FormView, TemplateView
from django.views.generic.detail import SingleObjectTemplateResponseMixin, BaseDetailView, SingleObjectMixin
from django.template import RequestContext
from django.core.urlresolvers import reverse_lazy, reverse
from django.contrib.auth.models import Group
from django.shortcuts import render_to_response
from reversion.models import Version
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponseBadRequest
from django.contrib import messages
from django.utils.timezone import utc
from django.utils import timezone
import reversion
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.db.transaction import atomic
from django.conf import settings

from devices.models import Device, Template, Room, Building, Manufacturer, Lending, Note, Bookmark
from devicetypes.models import TypeAttribute, TypeAttributeValue
from network.models import IpAddress
from mail.models import MailTemplate, MailHistory
from devices.forms import IpAddressForm, SearchForm, LendForm, DeviceViewForm, IpAddressPurposeForm
from devices.forms import ViewForm, DeviceForm, DeviceMailForm, VIEWSORTING, VIEWSORTING_DEVICES, FilterForm, \
    DeviceStorageForm, ReturnForm
from devicetags.forms import DeviceTagForm
from users.models import Lageruser, Department
from Lagerregal.utils import PaginationMixin
from devicetags.models import Devicetag
from permission.decorators import permission_required
from django.db.models import Q

@permission_required('devices.read_device', raise_exception=True)
class DeviceList(PaginationMixin, ListView):
    context_object_name = 'device_list'
    template_name = 'devices/device_list.html'
    viewfilter = None
    viewsorting = None

    def get_queryset(self):
        self.viewfilter = self.kwargs.get("filter", "active")
        devices = None
        lendings = None
        if self.viewfilter == "all":
            devices = Device.objects.all()
        elif self.viewfilter == "available":
            devices = Device.active().filter(currentlending=None)
        elif self.viewfilter == "lent":
            lendings = Lending.objects.filter(returndate=None)
        elif self.viewfilter == "archived":
            devices = Device.objects.exclude(archived=None)
        elif self.viewfilter == "trashed":
            devices = Device.objects.exclude(trashed=None)
        elif self.viewfilter == "overdue":
            lendings = Lending.objects.filter(returndate=None, duedate__lt=datetime.date.today())
        elif self.viewfilter == "returnsoon":
            soon = datetime.date.today() + datetime.timedelta(days=10)
            lendings = Lending.objects.filter(returndate=None, duedate__lte=soon,
                                              duedate__gt=datetime.date.today())
        elif self.viewfilter == "temporary":
            devices = Device.active().filter(templending=True)
        elif self.viewfilter == "bookmark":
            if self.request.user.is_authenticated:
                devices = self.request.user.bookmarks.all()
        else:
            devices = Device.active()

        if self.request.user.main_department != None:
            self.departmentfilter = self.kwargs.get("department", self.request.user.main_department.id)
        else:
            self.departmentfilter = self.kwargs.get("department", "all")

        if self.departmentfilter != "all":
            try:
                departmentid = int(self.departmentfilter)
                self.departmentfilter = Department.objects.get(id=departmentid)
            except:
                self.departmentfilter = Department.objects.get(name=self.departmentfilter)

        if self.viewfilter == "lent" or self.viewfilter == "overdue" or self.viewfilter == "returnsoon":
            if self.departmentfilter != "all":
                lendings = lendings.filter(owner__departments=self.departmentfilter)
            lendings = lendings.exclude(~Q(device__department__in=self.request.user.departments.all()) &
                                        ~Q(device=None), device__is_private=True)
            return lendings.values("device__id", "device__name", "device__inventorynumber",
                                       "device__devicetype__name", "device__room__name", "device__group",
                                       "device__room__building__name", "owner__username", "owner__id",
                                       "duedate", "smalldevice")
        else:
            if self.departmentfilter != "all":
                devices = devices.filter(department=self.departmentfilter)
            devices = devices.exclude(~Q(department__in=self.request.user.departments.all()), is_private=True)
            self.viewsorting = self.kwargs.get("sorting", "name")
            if self.viewsorting in [s[0] for s in VIEWSORTING_DEVICES]:
                devices = devices.order_by(self.viewsorting)

            return devices.values("id", "name", "inventorynumber", "devicetype__name", "room__name", "room__building__name",
                              "group__name", "currentlending__owner__username", "currentlending__duedate")

    def get_context_data(self, **kwargs):
        context = super(DeviceList, self).get_context_data(**kwargs)
        context["viewform"] = DeviceViewForm(initial={
            'viewfilter': self.viewfilter,
            "viewsorting": self.viewsorting,
            "departmentfilter": self.departmentfilter
        })
        context["today"] = datetime.datetime.today()
        context["template_list"] = Template.objects.all()
        context["viewfilter"] = self.viewfilter
        context["breadcrumbs"] = [[reverse("device-list"), _("Devices")]]
        if context["is_paginated"] and context["page_obj"].number > 1:
            context["breadcrumbs"].append(["", context["page_obj"].number])
        return context

@permission_required('devices.read_device', raise_exception=True)
class DeviceDetail(DetailView):
    queryset = Device.objects.select_related("manufacturer", "devicetype", "currentlending")
    context_object_name = 'device'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(DeviceDetail, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['ipaddressform'] = IpAddressForm()
        context["ipaddressform"].fields["ipaddresses"].queryset = IpAddress.objects.filter(department=self.object.department, device=None, user=None)
        context['tagform'] = DeviceTagForm()
        context['tagform'].fields["tags"].queryset = Devicetag.objects.exclude(devices=context["device"])
        context["lending_list"] = Lending.objects.filter(device=context["device"]).order_by("-pk")[:10]
        context["version_list"] = Version.objects.filter(object_id=context["device"].id,
                                                         content_type_id=ContentType.objects.get(
                                                             model='device').id).order_by("-pk")[:10]
        context["mail_list"] = MailHistory.objects.filter(device=context["device"]).order_by("-pk")[:10]
        context["today"] = datetime.datetime.utcnow().replace(tzinfo=utc)
        context["weekago"] = context["today"] - datetime.timedelta(days=7)
        context["attributevalue_list"] = TypeAttributeValue.objects.filter(device=context["device"])
        context["lendform"] = LendForm()
        mailinitial = {}
        if context["device"].currentlending is not None:
            currentowner = context["device"].currentlending.owner
            mailinitial["owner"] = currentowner
            mailinitial["emailrecipients"] = ("u" + str(currentowner.id), currentowner.username)
        try:
            mailinitial["mailtemplate"] = MailTemplate.objects.get(usage="reminder")
            mailinitial["emailsubject"] = mailinitial["mailtemplate"].subject
            mailinitial["emailbody"] = mailinitial["mailtemplate"].body
        except:
            pass
        context["mailform"] = DeviceMailForm(initial=mailinitial)
        context["mailform"].fields["mailtemplate"].queryset = MailTemplate.objects.filter(department__in=self.request.user.departments.all())
        versions = reversion.get_for_object(context["device"])
        if len(versions) != 0:
            context["lastedit"] = versions[0]

        if self.object.department:
            dep = self.object.department.name
        else:
            dep = "all"

        if dep in settings.LABEL_TEMPLATES:
            if "device" in settings.LABEL_TEMPLATES[dep]:
                context["display_printbutton"] = True
                context["label_js"] = ""
                for attribute in settings.LABEL_TEMPLATES[dep]["device"][1]:
                    if attribute == "id":
                        context["label_js"] += u"\nlabel.setObjectText('{0}', '{1:07d}');".format(attribute,
                                                                                                  getattr(context["device"],
                                                                                                          attribute))
                    else:
                        context["label_js"] += u"\nlabel.setObjectText('{0}', '{1}');".format(attribute,
                                                                                              getattr(context["device"],
                                                                                                      attribute))

        context["breadcrumbs"] = [
            (reverse("device-list"), _("Devices")),
            (reverse("device-detail", kwargs={"pk": context["device"].pk}), context["device"].name)]
        return context


@permission_required('devices.change_device', raise_exception=True)
class DeviceIpAddressRemove(View):
    template_name = 'devices/unassign_ipaddress.html'

    def get(self, request, *args, **kwargs):
        context = {"device": get_object_or_404(Device, pk=kwargs["pk"]),
                   "ipaddress": get_object_or_404(IpAddress, pk=kwargs["ipaddress"])}
        context["breadcrumbs"] = [
            (reverse("device-list"), _("Devices")),
            (reverse("device-detail", kwargs={"pk": context["device"].pk}), context["device"].name),
            ("", _("Unassign IP-Addresses"))]
        return render_to_response(self.template_name, context, RequestContext(request))

    def post(self, request, *args, **kwargs):
        device = get_object_or_404(Device, pk=kwargs["pk"])
        ipaddress = get_object_or_404(IpAddress, pk=kwargs["ipaddress"])
        ipaddress.device = None
        ipaddress.purpose = None
        reversion.set_comment(_("Removed from Device {0}".format(device.name)))
        ipaddress.save()

        return HttpResponseRedirect(reverse("device-detail", kwargs={"pk": device.pk}))


@permission_required('devices.change_device', raise_exception=True)
class DeviceIpAddress(FormView):
{'fraction_non_alphanumeric': 0.11506519021253796, 'fraction_numerical': 0.0033041614574031075, 'mean_word_length': 2.7154943596549437, 'pattern_counts': {'":': 42, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 54, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2527270', 'n_tokens_mistral': 5980, 'n_tokens_neox': 5761, 'n_words': 1089}