问:
Adding data to related model (custom user model)
I have a custom User Model. I can successfully add user to it and want to add the relationship to a related model. It gives me no errors but does not link the user to the related field compusers in the company model. Basically I need it to after creating a user, also add the user to the related compusers field.

This is the code I am trying in the view:

```<code>self.object.compusers.add(self.object.id)
</code>```

The Model

```<code>class Company(models.Model):
    user = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='compusers')
    name = models.CharField(max_length=265, blank=True)
    tel = models.IntegerField(blank=True, null=True)
    email = models.EmailField(max_length=265,blank=True)
    address = models.TextField(blank=True)
    postal = models.TextField(blank=True)
    regno = models.CharField(max_length=265,blank=True)
    vatno = models.CharField(max_length=265,blank=True)

  def __str__(self):
        return self.name

  def get_absolute_url(self):
        return reverse('nodisoapp:home')
</code>```

The View

```<code>class AddStaffView(CreateView):
    form_class = forms.AddStaffMember
    success_url = reverse_lazy('nodisoapp:home')
    template_name = "scrty/addstaff.html"
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.password = get_random_string(length=8)
        self.object.save()
        self.object.compusers.add(self.object.id)
        return super(AddStaffView, self).form_valid(form)
</code>```

The form

```<code>Class AddStaffMember(forms.ModelForm):
    usrtype = forms.ChoiceField(choices=[('Admin','Admin'),('Manager','Manager'),('Employee','Employee')],label="User Type: See below for descriptions" )
    class Meta:
        model = get_user_model()
        fields = ("firstname","lastname","email","usrtype")
        labels = {
            "firstname": _("First Name"),
            "lastname": _("Last Name"),
            "email": _("E-mail"),

         }
</code>```

答:
I recently went through this same process.  It's not finalized, but it should help.  With this project, I create a user, and that user (customer) has obvious attributes that are required (e.g. first name, last name, phone, email, company, and site).  There was a lot of problems in just simply trying to extend the django User model and add relationships that work well, so I went with having my own user model.  This model retains the use of Username.  I can provide projects that uses email instead of username.  This project also uses some styling widgets on the login form.  I have other projects that style other parts of auth as well.

main/models.py

```<code>from django.contrib.auth.models import (
    AbstractBaseUser,
    PermissionsMixin,
    BaseUserManager,
)
from django.core.mail import send_mail
from django.db import models
from django.utils.translation import ugettext_lazy as _
from customers import models as customers_models

class TravelModel(models.Model):
   mileageRate = models.DecimalField(max_digits=4, decimal_places=3)

   def __str__(self):
      return '%s' % (self.mileageRate)

   class Meta:
      verbose_name = "Current Federal Milage Rate"
      #verbose_name_plural = "Milage"

class UserManager(BaseUserManager):
    def create_user(self, username, email, firstName, lastName, company, phone, password=None, **kwargs):
        if not email:
            raise ValueError('Users must have an email address')
        user = self.model(
            username = userName,
            email=self.normalize_email(email),
            firstName = firstName,
            lastName = lastName,
            company = company,
            phone = phone
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email, firstName, lastName, password=None, **kwargs):
        user = self.model(
              username = username,
              email = self.normalize_email(email),
              firstName = firstName,
              lastName = lastName,
        )
        user.set_password(password)
        user.is_superuser = True
        user.is_admin = True
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser, PermissionsMixin):
      username = models.CharField(_('Username'), max_length=150, unique=True, null=False, blank=False)
      email = models.EmailField(_('E-mail Address'), max_length=255, unique=True)
      firstName = models.CharField(_('First Name'),max_length=50, blank=False, null=False)
      lastName = models.CharField(_('Last Name'),max_length=50, blank=False, null=False)
      company = models.ForeignKey(customers_models.CompanyModel, on_delete=models.PROTECT, null=False)
      phone = models.ForeignKey(customers_models.PhoneModel, on_delete=models.PROTECT, null=False)
      is_admin = models.BooleanField(
            _('staff status'),
            default=False,
            help_text=_(
                  'Designates whether the user can log into this admin '
                  'site.'
            )
      )
      is_active = models.BooleanField(
            _('active'),
            default=True,
            help_text=_(
                  'Designates whether this user should be treated as '
                  'active. Unselect this instead of deleting accounts.'
            )
      )

      objects = UserManager()

      USERNAME_FIELD = 'username'
      REQUIRED_FIELDS = ['email','firstName', 'lastName']

      class Meta(object):
            ordering = ['firstName']
            verbose_name = _('Contact')
            verbose_name_plural = _('Contacts')

      def __str__(self):
            return '%s - %s %s - %s - %s' % (self.company, self.firstName, self.lastName, self.email, self.phone)

      def get_full_name(self):
            return self.email

      def get_short_name(self):

      def has_perm(self, perm, obj=None):
            return True

      def has_module_perms(self, app_label):
            return True

      def email_user(self, subject, message, from_email=None, **kwargs):
            send_mail(subject, message, from_email, [self.email], **kwargs)
      @property
      def is_staff(self):
            return self.is_admin
</code>```

main/views.py

```<code>from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import logout, login, authenticate, update_session_auth_hash
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.forms import PasswordChangeForm
from django.core.mail import send_mail
from .models import MyUser
from .forms import RegistrationForm, LoginForm, ResetPasswordForm

def IndexView(request):
    return render(request, 'main/index.html')

def ContactView(request):
    return render(request, 'main/contact.html')

def LoginView(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            return redirect('home')
    else:
        form = LoginForm()
        args={ 'form': form }
    return render(request, 'main/login.html', args)

def LogoutView(request):
    logout(request)

@login_required
def PasswordChangeView(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, form.user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('change_password_done')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'main/change_password_form.html', {
        'form': form
    })

@permission_required(['auth.add_customuser', 'auth.change_customuser'], raise_exception=True)
def RegisterView(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
        return redirect('main')
    else:
        form = RegistrationForm()

    args = {'form': form}
    return render(request, 'main/register.html', args)
</code>```

main/urls.py

```<code>from django.conf.urls import url, include
from django.urls import reverse_lazy
from .views import IndexView, RegisterView, ContactView, PasswordChangeView
from .forms import LoginForm
from django.contrib.auth.views import (
    LogoutView,
    login,
    PasswordChangeView,
    PasswordChangeDoneView,
    PasswordResetView,
    PasswordResetDoneView,
    PasswordResetConfirmView,
    PasswordResetCompleteView,
)

# main app URLS extend from the base url i.e. www.website.com/*

urlpatterns = [
    url(r'^$', IndexView, name='main'),
    url(r'^register/$', RegisterView, name='register'),
    url(r'^contact/$', ContactView, name='contact'),
    url(r'^logout/$', LogoutView.as_view(next_page=reverse_lazy('main')),
    name='logout'
    ),
        url(r'^service/', include('service.urls')),
        url(r'^consultation/', include('consultation.urls')),
    # successful logins are redirected to the settings.LOGIN_REDIRECT_URL
    url(r'^login/$', login, name='login', kwargs={'template_name':'main/login.html', 'authentication_form':LoginForm},
        ),
    url(r'^change_password/$',
        PasswordChangeView.as_view(
            template_name='main/change_password_form.html'
        ),
        name='password_change'),
    url(r'^change_password/done/$',
        PasswordChangeDoneView.as_view(
        template_name='main/change_password_done.html'
        ),
        name='password_change_done'),
    url(r'^password_reset/$',
        PasswordResetView.as_view(template_name='main/reset_password_form.html'),
        name='password_reset'),
    url(r'^password_reset/done/$',
        PasswordResetDoneView.as_view(template_name='main/reset_password_done.html'),
        name='password_reset_done'),
    url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        PasswordResetConfirmView.as_view(template_name='main/reset_password_confirm.html'),
        name='password_reset_confirm'),
    url(r'^reset/done/$',
        PasswordResetCompleteView.as_view(template_name='main/reset_password_complete.html'),
        name='password_reset_complete'),
]
</code>```

main/forms.py

```<code>   from django import forms
    from django.contrib.auth.forms import (
        AuthenticationForm,
        UserCreationForm,
        UserChangeForm,
        PasswordResetForm,
    )
    from .models import MyUser

    class ResetPasswordForm(PasswordResetForm):
        pass

    class LoginForm(AuthenticationForm):
        username = forms.CharField(label='Username',
                                   widget=forms.TextInput(attrs={'placeholder':'Username'}))
        password = forms.CharField(label='Password',
                                   widget=forms.PasswordInput(attrs={'placeholder':'Password'}))

    class RegistrationForm(UserCreationForm):
        email = forms.EmailField(required=True)

        class Meta:
            model = MyUser
            fields = (
                'username',
                'firstName',
                'lastName',
                'email',
                'password1',
                'password2'
            )

        def save(self, commit=True):
            user = super(RegistrationForm, self).save(commit=False)
            user.first_name = self.cleaned_data['firstName']
            user.last_name = self.cleaned_data['lastName']
            user.email = self.cleaned_data['email']

            if commit:
                user.save()

            return user
</code>```

customers/models.py

```<code>from django.db import models
from django.core.validators import RegexValidator
from main import models as main_models
from django.utils.translation import ugettext_lazy as _

class PhoneModel(models.Model):
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
                                 message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
                                )
    phone_number = models.CharField(_('Phone Number'),validators=[phone_regex],
                                    max_length=15, blank=True
                                   ) # validators should be a list

    def __str__(self):
        return '%s' % (self.phone_number)

    class Meta:
        verbose_name = "Phone Number"
        #verbose_name_plural = "Phone Numbers"

class CompanyModel(models.Model):
    name = models.CharField(_('Company Name'),max_length=255)
    since = models.DateField(auto_now_add=True)

    def __str__(self):
        return '%s - Customer since %s' % (self.name, self.since)

    class Meta:
        ordering = ['name']
        verbose_name = "Company Name"
        #verbose_name_plural = "Companies"

class DetailsModel(models.Model):
    company = models.OneToOneField(CompanyModel, on_delete=models.CASCADE, primary_key=True)
    distance = models.SmallIntegerField(blank=True)
    rate = models.DecimalField(max_digits=5, decimal_places=2)

    def __str__(self):
        return '%s - Distance: %s - Rate: %s' % (self.company, self.distance, self.rate)

    class Meta:
        ordering = ['company']
        verbose_name = "Customer Agreement Information"
        #verbose_name_plural = "Details"

class SiteModel(models.Model):
    company = models.ForeignKey(CompanyModel, on_delete=models.CASCADE)
    #contact = models.ForeignKey(main_models.User.email, on_delete=models.CASCADE)
    details = models.ForeignKey(DetailsModel, on_delete=models.CASCADE)
    street1 = models.CharField(max_length=255)
    street2 = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=2)
    zipcode = models.IntegerField()
    country = models.CharField(max_length=50)

    def __str__(self):
        return '%s - %s, %s' % (self.company, self.city, self.state)

    class Meta:
        ordering = ['company']
        verbose_name = "Customer Site Information"
        #verbose_name_plural = "Sites"

class ContactModel(models.Model):
    company = models.ForeignKey(CompanyModel, on_delete=models.PROTECT, null=True)
    first_name = models.CharField(_('First Name'),max_length=255)
    last_name = models.CharField(_('First Name'),max_length=255)
    email = models.EmailField(_('E-mail Address'), max_length=255, unique=True)
    phone = models.ForeignKey(PhoneModel, on_delete=models.PROTECT, null=True)

    def __str__(self):
        return '%s %s of %s' % (self.first_name, self.last_name, self.company)
</code>```

Body:
I have a custom User Model. I can successfully add user to it and want to add the relationship to a related model. It gives me no errors but does not link the user to the related field compusers in the company model. Basically I need it to after creating a user, also add the user to the related compusers field.

This is the code I am trying in the view:

self.object.compusers.add(self.object.id)

The Model

class Company(models.Model):
    user = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='compusers')
    name = models.CharField(max_length=265, blank=True)
    tel = models.IntegerField(blank=True, null=True)
    email = models.EmailField(max_length=265,blank=True)
    address = models.TextField(blank=True)
    postal = models.TextField(blank=True)
    regno = models.CharField(max_length=265,blank=True)
    vatno = models.CharField(max_length=265,blank=True)

  def __str__(self):
        return self.name

  def get_absolute_url(self):
        return reverse('nodisoapp:home')

The View

class AddStaffView(CreateView):
    form_class = forms.AddStaffMember
    success_url = reverse_lazy('nodisoapp:home')
    template_name = "scrty/addstaff.html"
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.password = get_random_string(length=8)
        self.object.save()
        self.object.compusers.add(self.object.id)
        return super(AddStaffView, self).form_valid(form)

The form

Class AddStaffMember(forms.ModelForm):
    usrtype = forms.ChoiceField(choices=[('Admin','Admin'),('Manager','Manager'),('Employee','Employee')],label="User Type: See below for descriptions" )
    class Meta:
        model = get_user_model()
        fields = ("firstname","lastname","email","usrtype")
        labels = {
            "firstname": _("First Name"),
            "lastname": _("Last Name"),
            "email": _("E-mail"),

         }

Body:
I recently went through this same process.  It's not finalized, but it should help.  With this project, I create a user, and that user (customer) has obvious attributes that are required (e.g. first name, last name, phone, email, company, and site).  There was a lot of problems in just simply trying to extend the django User model and add relationships that work well, so I went with having my own user model.  This model retains the use of Username.  I can provide projects that uses email instead of username.  This project also uses some styling widgets on the login form.  I have other projects that style other parts of auth as well.

main/models.py

from django.contrib.auth.models import (
    AbstractBaseUser,
    PermissionsMixin,
    BaseUserManager,
)
from django.core.mail import send_mail
from django.db import models
from django.utils.translation import ugettext_lazy as _
from customers import models as customers_models

class TravelModel(models.Model):
   mileageRate = models.DecimalField(max_digits=4, decimal_places=3)

   def __str__(self):
      return '%s' % (self.mileageRate)

   class Meta:
      verbose_name = "Current Federal Milage Rate"
      #verbose_name_plural = "Milage"

class UserManager(BaseUserManager):
    def create_user(self, username, email, firstName, lastName, company, phone, password=None, **kwargs):
        if not email:
            raise ValueError('Users must have an email address')
        user = self.model(
            username = userName,
            email=self.normalize_email(email),
            firstName = firstName,
            lastName = lastName,
            company = company,
            phone = phone
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email, firstName, lastName, password=None, **kwargs):
        user = self.model(
              username = username,
              email = self.normalize_email(email),
              firstName = firstName,
              lastName = lastName,
        )
        user.set_password(password)
        user.is_superuser = True
        user.is_admin = True
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser, PermissionsMixin):
      username = models.CharField(_('Username'), max_length=150, unique=True, null=False, blank=False)
      email = models.EmailField(_('E-mail Address'), max_length=255, unique=True)
      firstName = models.CharField(_('First Name'),max_length=50, blank=False, null=False)
      lastName = models.CharField(_('Last Name'),max_length=50, blank=False, null=False)
      company = models.ForeignKey(customers_models.CompanyModel, on_delete=models.PROTECT, null=False)
      phone = models.ForeignKey(customers_models.PhoneModel, on_delete=models.PROTECT, null=False)
      is_admin = models.BooleanField(
            _('staff status'),
            default=False,
            help_text=_(
                  'Designates whether the user can log into this admin '
                  'site.'
            )
      )
      is_active = models.BooleanField(
            _('active'),
            default=True,
            help_text=_(
                  'Designates whether this user should be treated as '
                  'active. Unselect this instead of deleting accounts.'
            )
      )

      objects = UserManager()

      USERNAME_FIELD = 'username'
      REQUIRED_FIELDS = ['email','firstName', 'lastName']

      class Meta(object):
            ordering = ['firstName']
            verbose_name = _('Contact')
            verbose_name_plural = _('Contacts')

      def __str__(self):
            return '%s - %s %s - %s - %s' % (self.company, self.firstName, self.lastName, self.email, self.phone)

      def get_full_name(self):
            return self.email

      def get_short_name(self):

      def has_perm(self, perm, obj=None):
            return True

      def has_module_perms(self, app_label):
            return True

      def email_user(self, subject, message, from_email=None, **kwargs):
            send_mail(subject, message, from_email, [self.email], **kwargs)
      @property
      def is_staff(self):
            return self.is_admin

main/views.py

from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import logout, login, authenticate, update_session_auth_hash
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.forms import PasswordChangeForm
from django.core.mail import send_mail
from .models import MyUser
from .forms import RegistrationForm, LoginForm, ResetPasswordForm

def IndexView(request):
    return render(request, 'main/index.html')

def ContactView(request):
    return render(request, 'main/contact.html')

def LoginView(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            return redirect('home')
    else:
        form = LoginForm()
        args={ 'form': form }
    return render(request, 'main/login.html', args)

def LogoutView(request):
    logout(request)

@login_required
def PasswordChangeView(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, form.user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('change_password_done')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'main/change_password_form.html', {
        'form': form
    })

@permission_required(['auth.add_customuser', 'auth.change_customuser'], raise_exception=True)
def RegisterView(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
        return redirect('main')
    else:
        form = RegistrationForm()

    args = {'form': form}
    return render(request, 'main/register.html', args)

main/urls.py

from django.conf.urls import url, include
from django.urls import reverse_lazy
from .views import IndexView, RegisterView, ContactView, PasswordChangeView
from .forms import LoginForm
from django.contrib.auth.views import (
    LogoutView,
    login,
    PasswordChangeView,
    PasswordChangeDoneView,
    PasswordResetView,
    PasswordResetDoneView,
    PasswordResetConfirmView,
    PasswordResetCompleteView,
)

# main app URLS extend from the base url i.e. www.website.com/*

urlpatterns = [
    url(r'^$', IndexView, name='main'),
    url(r'^register/$', RegisterView, name='register'),
    url(r'^contact/$', ContactView, name='contact'),
    url(r'^logout/$', LogoutView.as_view(next_page=reverse_lazy('main')),
    name='logout'
    ),
        url(r'^service/', include('service.urls')),
        url(r'^consultation/', include('consultation.urls')),
    # successful logins are redirected to the settings.LOGIN_REDIRECT_URL
    url(r'^login/$', login, name='login', kwargs={'template_name':'main/login.html', 'authentication_form':LoginForm},
        ),
    url(r'^change_password/$',
        PasswordChangeView.as_view(
            template_name='main/change_password_form.html'
        ),
        name='password_change'),
    url(r'^change_password/done/$',
        PasswordChangeDoneView.as_view(
        template_name='main/change_password_done.html'
        ),
        name='password_change_done'),
    url(r'^password_reset/$',
        PasswordResetView.as_view(template_name='main/reset_password_form.html'),
        name='password_reset'),
    url(r'^password_reset/done/$',
        PasswordResetDoneView.as_view(template_name='main/reset_password_done.html'),
        name='password_reset_done'),
    url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        PasswordResetConfirmView.as_view(template_name='main/reset_password_confirm.html'),
        name='password_reset_confirm'),
    url(r'^reset/done/$',
        PasswordResetCompleteView.as_view(template_name='main/reset_password_complete.html'),
        name='password_reset_complete'),
]

main/forms.py

   from django import forms
    from django.contrib.auth.forms import (
        AuthenticationForm,
        UserCreationForm,
        UserChangeForm,
        PasswordResetForm,
    )
    from .models import MyUser

    class ResetPasswordForm(PasswordResetForm):
        pass

    class LoginForm(AuthenticationForm):
        username = forms.CharField(label='Username',
                                   widget=forms.TextInput(attrs={'placeholder':'Username'}))
        password = forms.CharField(label='Password',
                                   widget=forms.PasswordInput(attrs={'placeholder':'Password'}))

    class RegistrationForm(UserCreationForm):
        email = forms.EmailField(required=True)

        class Meta:
            model = MyUser
            fields = (
                'username',
                'firstName',
                'lastName',
                'email',
                'password1',
                'password2'
            )

        def save(self, commit=True):
            user = super(RegistrationForm, self).save(commit=False)
            user.first_name = self.cleaned_data['firstName']
            user.last_name = self.cleaned_data['lastName']
            user.email = self.cleaned_data['email']

            if commit:
                user.save()

            return user

customers/models.py

from django.db import models
from django.core.validators import RegexValidator
from main import models as main_models
from django.utils.translation import ugettext_lazy as _

class PhoneModel(models.Model):
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
                                 message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
                                )
    phone_number = models.CharField(_('Phone Number'),validators=[phone_regex],
                                    max_length=15, blank=True
                                   ) # validators should be a list

    def __str__(self):
        return '%s' % (self.phone_number)

    class Meta:
        verbose_name = "Phone Number"
        #verbose_name_plural = "Phone Numbers"

class CompanyModel(models.Model):
    name = models.CharField(_('Company Name'),max_length=255)
    since = models.DateField(auto_now_add=True)

    def __str__(self):
        return '%s - Customer since %s' % (self.name, self.since)

    class Meta:
        ordering = ['name']
        verbose_name = "Company Name"
        #verbose_name_plural = "Companies"

class DetailsModel(models.Model):
    company = models.OneToOneField(CompanyModel, on_delete=models.CASCADE, primary_key=True)
    distance = models.SmallIntegerField(blank=True)
    rate = models.DecimalField(max_digits=5, decimal_places=2)

    def __str__(self):
        return '%s - Distance: %s - Rate: %s' % (self.company, self.distance, self.rate)

    class Meta:
        ordering = ['company']
        verbose_name = "Customer Agreement Information"
        #verbose_name_plural = "Details"

class SiteModel(models.Model):
    company = models.ForeignKey(CompanyModel, on_delete=models.CASCADE)
    #contact = models.ForeignKey(main_models.User.email, on_delete=models.CASCADE)
    details = models.ForeignKey(DetailsModel, on_delete=models.CASCADE)
    street1 = models.CharField(max_length=255)
    street2 = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=2)
    zipcode = models.IntegerField()
    country = models.CharField(max_length=50)

    def __str__(self):
        return '%s - %s, %s' % (self.company, self.city, self.state)

    class Meta:
        ordering = ['company']
        verbose_name = "Customer Site Information"
        #verbose_name_plural = "Sites"

class ContactModel(models.Model):
    company = models.ForeignKey(CompanyModel, on_delete=models.PROTECT, null=True)
    first_name = models.CharField(_('First Name'),max_length=255)
    last_name = models.CharField(_('First Name'),max_length=255)
    email = models.EmailField(_('E-mail Address'), max_length=255, unique=True)
    phone = models.ForeignKey(PhoneModel, on_delete=models.PROTECT, null=True)

    def __str__(self):
        return '%s %s of %s' % (self.first_name, self.last_name, self.company)


来源: stackexchange

问:
Using XPath, how are attributes that contain a colon character processed?
Given the following XML (fragment):

```<code><node id="b071f9fa-14b0-4217-8e97-eb41da73f598" type="Group" ext:score="90">
<node id="b071f9fa-14b0-4217-8e97-eb41da73f599" type="Person" ext:score="100">
<node id="b071f9fa-14b0-4217-8e97-eb41da73f600" type="Business" ext:score="80">
</code>```

I want to retrieve the id of nodes that have an ext:score of 100.

The current code:

```<code>match = dom.xpath('//node[@ext:score="100"]/@id')[0]
</code>```

Returns an exception:

```<code>lxml.etree.XPathEvalError: Undefined namespace prefix
</code>```

I have read (both here and in XPath docs) that ext would first need to be defined as a valid namespace, as the DOM cannot be parsed as an attribute if it contains special characters.  However, I have been unable to find a good example of how to do this.  There is no definition of ext in the excerpts I am processing and I'm not sure how to create a namespace prefix.

Any thoughts?

答:
The colon character in an XML attribute (or element) name such as ext:score separates the namespace prefix, ext, from the local name, score.  Namespace prefixes themselves are significant only by virtue of their association with a namespace value.

For this XML,

```<code><metadata xmlns:ext="http://musicbrainz.org/ns/mmd-2.0#">
  <node id="b071f9fa-14b0-4217-8e97-eb41da73f598" type="Group" ext:score="90">
  <node id="b071f9fa-14b0-4217-8e97-eb41da73f599" type="Person" ext:score="100">
  <node id="b071f9fa-14b0-4217-8e97-eb41da73f600" type="Business" ext:score="80">
</metadata>
</code>```

This XPath,

```<code>//node[@ext:score="100"]/@id
</code>```

will select the id attributes of all node elements with an ext:score attribute value of 100, provided you have a way to bind a namespace prefix (ext) to a namespace value (http://musicbrainz.org/ns/mmd-2.0# in the language or tool from which XPath is being called.

To bind a namespace prefix to a namespace value in Python (see How does XPath deal with XML namespaces? for Python and other language examples):

```<code>from lxml import etree
f = StringIO('your XML here')
doc = etree.parse(f)
r = doc.xpath('//node[@ext:score="100"]/@id',
              namespaces={'ext':'http://musicbrainz.org/ns/ext#-2.0'})
</code>```

Note that if your XML uses ext without declaring it, it is not namespace-well-formed.

ContentLicense: CC BY-SA 3.0

Body:
Given the following XML (fragment):

<node id="b071f9fa-14b0-4217-8e97-eb41da73f598" type="Group" ext:score="90">
<node id="b071f9fa-14b0-4217-8e97-eb41da73f599" type="Person" ext:score="100">
<node id="b071f9fa-14b0-4217-8e97-eb41da73f600" type="Business" ext:score="80">

I want to retrieve the id of nodes that have an ext:score of 100.

The current code:

match = dom.xpath('//node[@ext:score="100"]/@id')[0]

Returns an exception:

lxml.etree.XPathEvalError: Undefined namespace prefix

I have read (both here and in XPath docs) that ext would first need to be defined as a valid namespace, as the DOM cannot be parsed as an attribute if it contains special characters.  However, I have been unable to find a good example of how to do this.  There is no definition of ext in the excerpts I am processing and I'm not sure how to create a namespace prefix.

Any thoughts?

Body:
The colon character in an XML attribute (or element) name such as ext:score separates the namespace prefix, ext, from the local name, score.  Namespace prefixes themselves are significant only by virtue of their association with a namespace value.

For this XML,

<metadata xmlns:ext="http://musicbrainz.org/ns/mmd-2.0#">
  <node id="b071f9fa-14b0-4217-8e97-eb41da73f598" type="Group" ext:score="90">
  <node id="b071f9fa-14b0-4217-8e97-eb41da73f599" type="Person" ext:score="100">
  <node id="b071f9fa-14b0-4217-8e97-eb41da73f600" type="Business" ext:score="80">
</metadata>

This XPath,

//node[@ext:score="100"]/@id

will select the id attributes of all node elements with an ext:score attribute value of 100, provided you have a way to bind a namespace prefix (ext) to a namespace value (http://musicbrainz.org/ns/mmd-2.0# in the language or tool from which XPath is being called.

To bind a namespace prefix to a namespace value in Python (see How does XPath deal with XML namespaces? for Python and other language examples):

from lxml import etree
f = StringIO('your XML here')
doc = etree.parse(f)
r = doc.xpath('//node[@ext:score="100"]/@id',
              namespaces={'ext':'http://musicbrainz.org/ns/ext#-2.0'})

Note that if your XML uses ext without declaring it, it is not namespace-well-formed.


问:
Adding RVM to path Ubuntu
I'm having difficulty installing rvm and setting the path for it.

```<code>rvm install ruby
</code>```

This yield "rvm: command not found"

When I echo $PATH

This yields "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"

So obviously, rvm is not in my path. I see that I have rvm in my "/usr/local/rvm"

However, when I try export PATH=$PATH:/usr/local/rvm

And then .. rvm install ruby

Still.. there is no command found.

Here is my .bashrc

```<code># ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
    # We have color support; assume it's compliant with Ecma-48
    # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
    # a case would tend to support setf rather than setaf.)
    color_prompt=yes
    else
    color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    #alias dir='dir --color=auto'
    #alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Add an "alert" alias for long running commands.  Use like so:
#   sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

export PATH=$PATH:/usr/local/rvm
</code>```

答:
I just added source /usr/local/rvm/scripts/rvm on Ubuntu 14.04LTS
in /etc/environment.

```<code># cat /etc/environment
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
source /usr/local/rvm/scripts/rvm
</code>```

Title: Adding RVM to path Ubuntu

Body:
I'm having difficulty installing rvm and setting the path for it.

rvm install ruby

This yield "rvm: command not found"

When I echo $PATH

This yields "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"

So obviously, rvm is not in my path. I see that I have rvm in my "/usr/local/rvm"

However, when I try export PATH=$PATH:/usr/local/rvm

And then .. rvm install ruby

Still.. there is no command found.

Here is my .bashrc

# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
    # We have color support; assume it's compliant with Ecma-48
    # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
    # a case would tend to support setf rather than setaf.)
    color_prompt=yes
    else
    color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    #alias dir='dir --color=auto'
    #alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Add an "alert" alias for long running commands.  Use like so:
#   sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

export PATH=$PATH:/usr/local/rvm

Body:
I just added source /usr/local/rvm/scripts/rvm on Ubuntu 14.04LTS
in /etc/environment.

# cat /etc/environment
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
source /usr/local/rvm/scripts/rvm


问:
AWS auto-scaling group AMI
I have four EC2(API server) instances running on AWS with ELB and I would like to apply auto-scaling group. From my understanding, I first should create an AMI of one of four EC2 instances that I am running and it auto scales from the AMI that I have created based on configuration. At this point, should I re-create the AMI whenever pushing new codes so that it scales up from a latest version of it?</p>

答:
There is more than one option to manage your AMIs for launching; from full-baked AMI to base OS AMIs that are configured on launch. Each has its pros and cons.

After many years of managing fully baked AMIs, we are moving towards an AMI build pipeline approach - with instances that self-configure on first launch - that will manage AMI provisioning in a more "continuous integration" way.

So to answer your question, yes you can use pre-baked AMI to use in your auto-scaling groups. But this approach limits flexibility, and can produce maintenance headaches, especially if running multiple accounts and/or environments.

From AWS AMI Design:

AMI design options fall along a spectrum of deployment simplicity in
  relation to deployment flexibility. The simplest AMIs are fully baked
  and purpose-built to deploy a complete running instance, including the
  installation and configuration of all required software. However, this
  approach limits flexibility, as a fully baked AMI can only be used to
  deploy a single instance or a farm of identical instances. The most
  flexible AMIs include only minimal configurations and software before
  then dynamically installing the required packages on first boot. This
  approach trades simplicity for flexibility as each instance must be
  properly bootstrapped before it can function as intended.

The right approach will consider your skill set, AWS experience, and DevOps infrastructure.

Title: AWS auto-scaling group AMI


问:
Filter For Dates Outputted From Remote Logs Using Powershell
Please see my current code bellow, the code will continue to keep running until stopped by user. The end goal is having the script to run and find a certain day and successfully stop or find results between 2 dates.

I have tried using -before -after flags with combinations of (get-date). IE .date .datetime .addday(+/-1) but when using them it finds the correct date and stops but takes 2/3 minutes before starting the script again or moving to the next machine in the list. I have also tried { $_.TimeGenerated -lt "00/00/000" }

Any idea's how this can be done? I've tried a few other things but having no joy.

```<code>$ComputerName = 'CSV File'
$UserProperty = @{n="User";e={(New-Object System.Security.Principal.SecurityIdentifier $_.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}}
$TypeProperty = @{n="Action";e={if($_.EventID -eq 7001) {"Logon"} else {"Logoff"}}}
$TimeProperty = @{n="Time";e={$_.TimeGenerated}}
$MachineNameProperty = @{n="MachineName";e={$_.MachineName}}

foreach ($computer in $ComputerName) {
Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer | select $UserProperty,$TypeProperty,$TimeProperty ,$MachineNameProperty
}
</code>```

答:
I'm not positive exactly what issue you are having but this worked fine for me:

```<code>Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer -before '2017-11-09' -after '2017-10-27' -InstanceId @(7001, 7002) | select $UserProperty,$TypeProperty,$TimeProperty ,$MachineNameProperty
</code>```

As I stated in the comment, getting remote event logs is generally a pretty slow process.

Here is a little timing info:

First I ran the request againsta server with no time filter at all:

```<code>measure-Command -Expression {$noTimeFilter = Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer -InstanceId @(7001, 7002)}
</code>```

This took 292.85 seconds and returned 79 events. Next I ran it against the same server filtering for just the last 24 hours:

```<code>measure-Command -Expression {$withTimeFilter = Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer -after (Get-Date).AddDays(-1) -InstanceId @(7001, 7002)}
</code>```

This took 243 seconds and returned 2 events.

So for this admittedly limited test filtering was actually faster. In my granted anecdotal experience filtering doesn't really make much difference one way or the other. I'm pretty sure the query gets all the events then filters them. If you are actually consistently seeing a faster return without a filter you could certainly just get everything every time then pipe that to a Where-Object block to get just the events that you wanted. This would be contrary to my experience though and as FoxDeploy pointed out potentially detrimental to the performance of your remote machines.

Body:
Please see my current code bellow, the code will continue to keep running until stopped by user. The end goal is having the script to run and find a certain day and successfully stop or find results between 2 dates.

I have tried using -before -after flags with combinations of (get-date). IE .date .datetime .addday(+/-1) but when using them it finds the correct date and stops but takes 2/3 minutes before starting the script again or moving to the next machine in the list. I have also tried { $_.TimeGenerated -lt "00/00/000" }

Any idea's how this can be done? I've tried a few other things but having no joy.

$ComputerName = 'CSV File'
$UserProperty = @{n="User";e={(New-Object System.Security.Principal.SecurityIdentifier $_.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}}
$TypeProperty = @{n="Action";e={if($_.EventID -eq 7001) {"Logon"} else {"Logoff"}}}
$TimeProperty = @{n="Time";e={$_.TimeGenerated}}
$MachineNameProperty = @{n="MachineName";e={$_.MachineName}}

foreach ($computer in $ComputerName) {
Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer | select $UserProperty,$TypeProperty,$TimeProperty ,$MachineNameProperty
}

Body:
I'm not positive exactly what issue you are having but this worked fine for me:

Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer -before '2017-11-09' -after '2017-10-27' -InstanceId @(7001, 7002) | select $UserProperty,$TypeProperty,$TimeProperty ,$MachineNameProperty

As I stated in the comment, getting remote event logs is generally a pretty slow process.

Here is a little timing info:

First I ran the request againsta server with no time filter at all:

measure-Command -Expression {$noTimeFilter = Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer -InstanceId @(7001, 7002)}

This took 292.85 seconds and returned 79 events. Next I ran it against the same server filtering for just the last 24 hours:

measure-Command -Expression {$withTimeFilter = Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer -after (Get-Date).AddDays(-1) -InstanceId @(7001, 7002)}

This took 243 seconds and returned 2 events.

So for this admittedly limited test filtering was actually faster. In my granted anecdotal experience filtering doesn't really make much difference one way or the other. I'm pretty sure the query gets all the events then filters them. If you are actually consistently seeing a faster return without a filter you could certainly just get everything every time then pipe that to a Where-Object block to get just the events that you wanted. This would be contrary to my experience though and as FoxDeploy pointed out potentially detrimental to the performance of your remote machines.


问:
How innodb tables are locked when ON INSERT trigger is processed?
I have two innodb tables:

articles

```<code>id     | title    | sum_votes
------------------------------
1      | art 1    | 5
2      | art 2    | 8
3      | art 3    | 35
</code>```

votes

```<code>id     | article_id    | vote
------------------------------
1      | 1             | 1
2      | 1             | 2
3      | 1             | 2
4      | 2             | 10
5      | 2             | -2
6      | 3             | 10
7      | 3             | 15
8      | 3             | 12
9      | 3             | -2
</code>```

When a new record is inserted into the votes table, I want to update the sum_votes field in articles table by calculating the sum of all votes.

The question

Which way is more efficient, if the SUM() calculation itself is a very heavy one (votes table has 700K records).

1. Creating a trigger

```<code>CREATE TRIGGER `views_on_insert`
AFTER INSERT
ON `votes`
FOR EACH ROW
BEGIN
   UPDATE `articles` SET
       sum_votes = (
           SELECT SUM(`vote`)
           FROM `votes`
           WHERE `id` = NEW.article_id
       )
    WHERE `id` = NEW.article_id;
END;
</code>```

2. Using two queries in my application

```<code>SELECT SUM(`vote`) FROM `votes` WHERE `article_id` = 1;
UPDATE `articles`
   SET sum_votes = <1st_query_result>
 WHERE `id` = 1;
</code>```

1st way seems cleaner, but will the table be locked the whole time the SELECT query runs?

答:
About the concurrency problems, you have an 'easy' way to prevent any concurrency problems in the 2nd method, inside your transaction perform a select on the articles line (the For update is now implicit). Any concurrent insert on the same article will not be able to obtain this same lock and will wait for you.

With the new default isolation levels, without even using serialization level in the transaction you wouldn't see any concurrent insert on the vote table until the end of your transaction. So your SUM should stay coherent or looks like coherent. But if a concurrent transaction insert a vote on same article and commit before you (and this 2nd one does not see your insert), the last transaction to commit will overwrite the counter and you'll loose  1 vote. So perform a row lock on article by using a select before (and do your work in a transaction, of course). It's easy to test, open 2 interactive sessions on MySQL and start transactions with BEGIN.

If you use the trigger you are in a transaction by default. But I think you should perform as well the select on the article table to make an implicit row lock for concurrent triggers running (harder to test).

Do not forget delete triggers.

Do not forget update triggers.

If you do not use triggers and stay
in code, be careful every
insert/delete/update query on vote
should perform a row lock on the
corresponding article before in the
transaction. It's not very hard to
forget one.

Last point: make harder transactions, before starting the transaction use:

```<code>SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
</code>```

This way you do not need row locks on articles, MySQL will detect that a potential write on the same row occurs and will block the others transaction until you finish. But do not use something you have computed from a previous request. The update query will be waiting for a lock release on articles, when the lock is released by the 1st transaction COMMIT the computing of SUM should be done again to count. So the update query should contain the SUM or make an addition.

```<code>update articles set nb_votes=(SELECT count(*) from vote) where id=2;
</code>```

And here you'll see that MySQL is smart, a deadlock is detected if 2 transactions are trying to do this while insert has been done in a concurrent time. In serialization levels I haven't found a way to obtain a wrong value with :

```<code>   SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
   BEGIN;
       insert into vote (...
       update articles set nb_votes=(
         SELECT count(*) from vote where article_id=xx
       ) where id=XX;
    COMMIT;
</code>```

But be ready to handle breaking transaction that you must redo.

Body:
I have two innodb tables:

articles

id     | title    | sum_votes
------------------------------
1      | art 1    | 5
2      | art 2    | 8
3      | art 3    | 35

votes

id     | article_id    | vote
------------------------------
1      | 1             | 1
2      | 1             | 2
3      | 1             | 2
4      | 2             | 10
5      | 2             | -2
6      | 3             | 10
7      | 3             | 15
8      | 3             | 12
9      | 3             | -2

When a new record is inserted into the votes table, I want to update the sum_votes field in articles table by calculating the sum of all votes.

The question

Which way is more efficient, if the SUM() calculation itself is a very heavy one (votes table has 700K records).

1. Creating a trigger

CREATE TRIGGER `views_on_insert`
AFTER INSERT
ON `votes`
FOR EACH ROW
BEGIN
   UPDATE `articles` SET
       sum_votes = (
           SELECT SUM(`vote`)
           FROM `votes`
           WHERE `id` = NEW.article_id
       )
    WHERE `id` = NEW.article_id;
END;

2. Using two queries in my application

SELECT SUM(`vote`) FROM `votes` WHERE `article_id` = 1;
UPDATE `articles`
   SET sum_votes = <1st_query_result>
 WHERE `id` = 1;

1st way seems cleaner, but will the table be locked the whole time the SELECT query runs?

Body:
About the concurrency problems, you have an 'easy' way to prevent any concurrency problems in the 2nd method, inside your transaction perform a select on the articles line (the For update is now implicit). Any concurrent insert on the same article will not be able to obtain this same lock and will wait for you.

With the new default isolation levels, without even using serialization level in the transaction you wouldn't see any concurrent insert on the vote table until the end of your transaction. So your SUM should stay coherent or looks like coherent. But if a concurrent transaction insert a vote on same article and commit before you (and this 2nd one does not see your insert), the last transaction to commit will overwrite the counter and you'll loose  1 vote. So perform a row lock on article by using a select before (and do your work in a transaction, of course). It's easy to test, open 2 interactive sessions on MySQL and start transactions with BEGIN.

If you use the trigger you are in a transaction by default. But I think you should perform as well the select on the article table to make an implicit row lock for concurrent triggers running (harder to test).

Do not forget delete triggers.

Do not forget update triggers.

If you do not use triggers and stay
in code, be careful every
insert/delete/update query on vote
should perform a row lock on the
corresponding article before in the
transaction. It's not very hard to
forget one.

Last point: make harder transactions, before starting the transaction use:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

This way you do not need row locks on articles, MySQL will detect that a potential write on the same row occurs and will block the others transaction until you finish. But do not use something you have computed from a previous request. The update query will be waiting for a lock release on articles, when the lock is released by the 1st transaction COMMIT the computing of SUM should be done again to count. So the update query should contain the SUM or make an addition.

update articles set nb_votes=(SELECT count(*) from vote) where id=2;

And here you'll see that MySQL is smart, a deadlock is detected if 2 transactions are trying to do this while insert has been done in a concurrent time. In serialization levels I haven't found a way to obtain a wrong value with :

   SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
   BEGIN;
       insert into vote (...
       update articles set nb_votes=(
         SELECT count(*) from vote where article_id=xx
       ) where id=XX;
    COMMIT;

But be ready to handle breaking transaction that you must redo.


问:
"Object 'freq' not found" error applying colour in UpSetR
If I run this reprex, I get the required output:

```<code>``` r
library(UpSetR)
listInput <- list(one = c(1, 2, 3, 5, 7, 8, 11, 12, 13),
                  two = c(1, 2, 4, 5, 10),
                  three = c(1, 5, 6, 7, 8, 9, 10, 12, 13))

upset(fromList(listInput), order.by = "freq")
```
</code>```

If I apply a colour, I get the following error.

```<code>``` r
library(UpSetR)
listInput <- list(one = c(1, 2, 3, 5, 7, 8, 11, 12, 13),
                  two = c(1, 2, 4, 5, 10),
                  three = c(1, 5, 6, 7, 8, 9, 10, 12, 13))

upset(fromList(listInput), order.by = "freq",
      queries = list(list(query = intersects, params = list("one"), color = "orange", active = T)))
#> Error in eval(expr, envir, enclos): object 'freq' not found
```
</code>```

I've looked at the colouring "example 5" in the vignettes, but can't spot my misstep.

答:
Add a column of integers to the dataframe inputted into upset.

```<code>library(UpSetR)
listInput <- list(one = c(1, 2, 3, 5, 7, 8, 11, 12, 13),
                  two = c(1, 2, 4, 5, 10),
                  three = c(1, 5, 6, 7, 8, 9, 10, 12, 13))
df <- fromList(listInput)
df$n <- sample(1:nrow(df))

upset(df, order.by = "freq",
      queries = list(list(query = intersects,
                          params = list("one"),
                          color = "orange")))
</code>```

Body:
If I run this reprex, I get the required output:

``` r
library(UpSetR)
listInput <- list(one = c(1, 2, 3, 5, 7, 8, 11, 12, 13),
                  two = c(1, 2, 4, 5, 10),
                  three = c(1, 5, 6, 7, 8, 9, 10, 12, 13))

upset(fromList(listInput), order.by = "freq")
```

If I apply a colour, I get the following error.

``` r
library(UpSetR)
listInput <- list(one = c(1, 2, 3, 5, 7, 8, 11, 12, 13),
                  two = c(1, 2, 4, 5, 10),
                  three = c(1, 5, 6, 7, 8, 9, 10, 12, 13))

upset(fromList(listInput), order.by = "freq",
      queries = list(list(query = intersects, params = list("one"), color = "orange", active = T)))
#> Error in eval(expr, envir, enclos): object 'freq' not found
```

I've looked at the colouring "example 5" in the vignettes, but can't spot my misstep.

Body:
Add a column of integers to the dataframe inputted into upset.

library(UpSetR)
listInput <- list(one = c(1, 2, 3, 5, 7, 8, 11, 12, 13),
                  two = c(1, 2, 4, 5, 10),
                  three = c(1, 5, 6, 7, 8, 9, 10, 12, 13))
df <- fromList(listInput)
df$n <- sample(1:nrow(df))

upset(df, order.by = "freq",
      queries = list(list(query = intersects,
                          params = list("one"),
                          color = "orange")))


问:
Get Logstash to parse a whole log line by line
Currently at the end of my Jenkins build I grab the console log and add it to a json blob along with the build details, and I send that to logstash via curl

```<code>def payload = JsonOutput.toJson([
            CONSOLE: getConsoleText(),
            BUILD_RESULT: currentBuild.result,
            ] << manager.getEnvVars()
        )
sh "curl -i -X PUT -H \'content-type: application/json\' --insecure -d @data.json http://mylogstash/jenkins"
</code>```

Logstash then put this straight into elasticsearch against a Jenkins index for the day.  This works great and the whole log gets stored in elasticsearch, but it doesnt make it very searchable.

What I would like to do is send the log to logstash as a whole (as it is quite large), and for logstash to parse it line by line and apply filters. Then any lines I dont filter out to be posted to ES as a document by itself.
Is this possible, or would I have to send it line by line from Jenkins? As the log files are thousands of lines long would result in loads of requests to logstash.

答:
If you have the flexibilty to it, i would suggest you to write the console logs to a log file. In this way you can use filebeat to automatically read the log line by line and send it over to the logstash. By using filebeat, you get the advantage of guaranteed single delivery of the data and automatic retires if and when the logstash goes down.

Once the data reaches logstash, you can use the pipeline to parse/filter the data as per your requirement. The Grok debugger available in this link is handy --> http://grokdebug.herokuapp.com/.

After transforming the data, the document can be sent to ES for persistance.

Body:
Currently at the end of my Jenkins build I grab the console log and add it to a json blob along with the build details, and I send that to logstash via curl

def payload = JsonOutput.toJson([
            CONSOLE: getConsoleText(),
            BUILD_RESULT: currentBuild.result,
            ] << manager.getEnvVars()
        )
sh "curl -i -X PUT -H \'content-type: application/json\' --insecure -d @data.json http://mylogstash/jenkins"

Logstash then put this straight into elasticsearch against a Jenkins index for the day.  This works great and the whole log gets stored in elasticsearch, but it doesnt make it very searchable.

What I would like to do is send the log to logstash as a whole (as it is quite large), and for logstash to parse it line by line and apply filters. Then any lines I dont filter out to be posted to ES as a document by itself.
Is this possible, or would I have to send it line by line from Jenkins? As the log files are thousands of lines long would result in loads of requests to logstash.


问:
Repeating msgbox
I've created 3 combobox as below which are to generate results from a listbox. I would like to generate an error box if any of the 3 comboboxes are left empty. However, the code I wrote generates multiple error msg boxes. How do I fix this so msgbox only appears once?</p>

```<code>Private Sub Generateresults_Click()
Dim x As Integer
Dim i As Integer
Dim j As Integer
Dim p As Integer
p = Sheets("Training1A").UsedRange.Rows.Count
Sheets("Results").Range("A2:P" & p).ClearContents
x = 2
For i = 0 To Me.Listtest.ListCount - 1
    If Me.Searchoption = "AND" Then
        If Me.Listtest.Column(1, i) = Search1 And Me.Listtest.Column(2, i) = Search2 Then
            For j = 0 To 9
                Sheets("results").Cells(x, j + 1) = Me.Listtest.Column(j, i)
            Next j
            x = x + 1
        Else
            x = x
        End If

        ElseIf Me.Searchoption = "OR" Then
            If Me.Listtest.Column(1, i) = Search1 Or Me.Listtest.Column(2, i) = Search2 Then
                For j = 0 To 9
                    Sheets("results").Cells(x, j + 1) = Me.Listtest.Column(j, i)
                Next j
                x = x + 1
            Else
                x = x
            End If

        ElseIf Me.Searchoption = "ALL" Then
            For j = 0 To 9
                Sheets("results").Cells(x, j + 1) = Me.Listtest.Column(j, i)
            Next j
            x = x + 1
        Else
            x = x
            **If Searchoption = "" Or Search1 = "" Or Search2 = "" Then
                MsgBox "Select an option"
            End If**
        End If
Next i
End Sub
</code>```

答:
If you want to bail out after dispaying the first MsgBox, put Exit Sub under it.

```<code>If Searchoption = "" Or Search1 = "" Or Search2 = "" Then
    MsgBox "Select an option"
    Exit Sub
End If
</code>```

Otherwise, the MsgBox call being inside the For...Next loop body, it will be repeated for every iteration that satisfies the conditions.

If you need to run more code between Next and End Sub regardless of whether the MsgBox was shown or not, then you can also Exit For, to exit the loop but remain inside the procedure:

```<code>If Searchoption = "" Or Search1 = "" Or Search2 = "" Then
    MsgBox "Select an option"
    Exit For
End If
</code>```

ContentLicense: CC BY-SA 4.0

Title: Repeating msgbox

Body:
I've created 3 combobox as below which are to generate results from a listbox. I would like to generate an error box if any of the 3 comboboxes are left empty. However, the code I wrote generates multiple error msg boxes. How do I fix this so msgbox only appears once?

Private Sub Generateresults_Click()
Dim x As Integer
Dim i As Integer
Dim j As Integer
Dim p As Integer
p = Sheets("Training1A").UsedRange.Rows.Count
Sheets("Results").Range("A2:P" & p).ClearContents
x = 2
For i = 0 To Me.Listtest.ListCount - 1
    If Me.Searchoption = "AND" Then
        If Me.Listtest.Column(1, i) = Search1 And Me.Listtest.Column(2, i) = Search2 Then
            For j = 0 To 9
                Sheets("results").Cells(x, j + 1) = Me.Listtest.Column(j, i)
            Next j
            x = x + 1
        Else
            x = x
        End If

        ElseIf Me.Searchoption = "OR" Then
            If Me.Listtest.Column(1, i) = Search1 Or Me.Listtest.Column(2, i) = Search2 Then
                For j = 0 To 9
                    Sheets("results").Cells(x, j + 1) = Me.Listtest.Column(j, i)
                Next j
                x = x + 1
            Else
                x = x
            End If

        ElseIf Me.Searchoption = "ALL" Then
            For j = 0 To 9
                Sheets("results").Cells(x, j + 1) = Me.Listtest.Column(j, i)
            Next j
            x = x + 1
        Else
            x = x
            **If Searchoption = "" Or Search1 = "" Or Search2 = "" Then
                MsgBox "Select an option"
            End If**
        End If
Next i
End Sub

Body:
If you want to bail out after dispaying the first MsgBox, put Exit Sub under it.

If Searchoption = "" Or Search1 = "" Or Search2 = "" Then
    MsgBox "Select an option"
    Exit Sub
End If

Otherwise, the MsgBox call being inside the For...Next loop body, it will be repeated for every iteration that satisfies the conditions.

If you need to run more code between Next and End Sub regardless of whether the MsgBox was shown or not, then you can also Exit For, to exit the loop but remain inside the procedure:

If Searchoption = "" Or Search1 = "" Or Search2 = "" Then
    MsgBox "Select an option"
    Exit For
End If


问:
Seed nodejs express heroku app

mongoose.connect('mongodb://localhost:27017/smartphones');
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));

var smartphones = [
    new Smartphone({
        title: "V3",
        usp: "20MP Softlight Camera",
        image_path: "/image/phone_v3max.png",
        qty: 1,
        price: 200
    }),
    new Smartphone({
        title: "V5",
        usp: "Feel the Real Speed",
        image_path: "/image/phone_v5.png",
        qty: 1,
        price: 450
    })
];

var done = 0;
for(var i = 0; i < smartphones.length; i++) {
    smartphones[i].save(function(err, result) {
        done++;
        if(done === smartphones.length) {
            exit();
        }
    });
}

function exit() {
    mongoose.disconnect();
}```

When I work locally on Nodejs App I could run and seed the data file (smartphoneIndex-seeder.js) that is included the project by running the command line. But how should that be done when the app has been pushed to Heroku, how can I seed the data from there? The app is running but pages that runs by the seed data would not show up on my page unfortunately. Anyone an idea how I could connect the seed date so my entire app would be run properly.

答:
It sounds to me like you want some sort of pre-boot process. You probably want to write some code that executes before you tell your application to start listening on a port. This code will look at the database, look to see if any data exists, and if it doesn't then it will call some code (such as your smartphoneIndex-seeder function which will push data into the application.

Once that decision is made, you can then call your normal app.listen() express code.

Title: Seed nodejs express heroku app

Body:
mongoose.connect('mongodb://localhost:27017/smartphones');
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));

var smartphones = [
    new Smartphone({
        title: "V3",
        usp: "20MP Softlight Camera",
        image_path: "/image/phone_v3max.png",
        qty: 1,
        price: 200
    }),
    new Smartphone({
        title: "V5",
        usp: "Feel the Real Speed",
        image_path: "/image/phone_v5.png",
        qty: 1,
        price: 450
    })
];

var done = 0;
for(var i = 0; i < smartphones.length; i++) {
    smartphones[i].save(function(err, result) {
        done++;
        if(done === smartphones.length) {
            exit();
        }
    });
}

function exit() {
    mongoose.disconnect();
}

When I work locally on Nodejs App I could run and seed the data file (smartphoneIndex-seeder.js) that is included the project by running the command line. But how should that be done when the app has been pushed to Heroku, how can I seed the data from there? The app is running but pages that runs by the seed data would not show up on my page unfortunately. Anyone an idea how I could connect the seed date so my entire app would be run properly.


问:
Problem in WPF's DataGrid validation - MVVM
Scenario: I have a DataGrid(only 1 Column) in my View. I have applied RowValidationRule on DataGrid in XAML. Whenever user leave a DataGridCell blank, my validation rule fires an error and user can see the red boundary around the row and a tooltip explaining the error. The DataGrid's default  behavior doesn't allow user to change any other cell until user fix this current invalid cell.  But if user click on Invalid Cell and presses Escape Key the red error message goes away and user can change any other record. What escape key does is it places the last valid value in to the cell.

I am creating column using this XAML

```<code> <DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
              <TextBlock Text="{Binding Path=Type, UpdateSourceTrigger=PropertyChanged}"/>
          </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>

    <DataGridTemplateColumn.CellEditingTemplate>
         <DataTemplate>
              <TextBox Text="{Binding Type, UpdateSourceTrigger=PropertyChanged}"/>
         </DataTemplate>
     </DataGridTemplateColumn.CellEditingTemplate>
 </DataGridTemplateColumn>
</code>```

Problem: When user presses Escape key on the invalid cell, the cell become valid(using previous value) but the previous value never appears until the user click the previously invalid cell i.e. until the cell style changes to Textbox. In other words the TextBlock never shows the previous value if user presses Escape key and restore the previous value until user again click the cell and tries to edit the value.

So is there any way I can force Textblock to show the value after escape key is pressed without first going in to the Textbox mode?

if above thing is not possible, is there any way that I can stop the Escape key behavior? so that user can't edit any other row until the invalid row is fixed..

答:
I changed the UpdateSourceTrigger to explicit and it solved the issue</p>

```<code>     <DataTemplate>
          <TextBox Text="{Binding Type, UpdateSourceTrigger=Explicit}"/>
     </DataTemplate>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Scenario: I have a DataGrid(only 1 Column) in my View. I have applied RowValidationRule on DataGrid in XAML. Whenever user leave a DataGridCell blank, my validation rule fires an error and user can see the red boundary around the row and a tooltip explaining the error. The DataGrid's default  behavior doesn't allow user to change any other cell until user fix this current invalid cell.  But if user click on Invalid Cell and presses Escape Key the red error message goes away and user can change any other record. What escape key does is it places the last valid value in to the cell.

I am creating column using this XAML

 <DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
              <TextBlock Text="{Binding Path=Type, UpdateSourceTrigger=PropertyChanged}"/>
          </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>

    <DataGridTemplateColumn.CellEditingTemplate>
         <DataTemplate>
              <TextBox Text="{Binding Type, UpdateSourceTrigger=PropertyChanged}"/>
         </DataTemplate>
     </DataGridTemplateColumn.CellEditingTemplate>
 </DataGridTemplateColumn>

Problem: When user presses Escape key on the invalid cell, the cell become valid(using previous value) but the previous value never appears until the user click the previously invalid cell i.e. until the cell style changes to Textbox. In other words the TextBlock never shows the previous value if user presses Escape key and restore the previous value until user again click the cell and tries to edit the value.

So is there any way I can force Textblock to show the value after escape key is pressed without first going in to the Textbox mode?

if above thing is not possible, is there any way that I can stop the Escape key behavior? so that user can't edit any other row until the invalid row is fixed..

Body:
I changed the UpdateSourceTrigger to explicit and it solved the issue

     <DataTemplate>
          <TextBox Text="{Binding Type, UpdateSourceTrigger=Explicit}"/>
     </DataTemplate>


问:
adding tabs in java (swing)
i was given a project to make a java program named doctors care which has login panel( username and password) and a panel which has 3 tabs. the problem is i could add only one tab and when i tried to add another tab by duplicating the objects( like label2, panel2 etc) it does not appear in the executed JAR file. i have posted the code below.

public void actionPerformed(ActionEvent ae)

```<code>   {String value1 = text1.getText();
    String value2 = text2.getText();
    if(value1.equals("admin") && value2.equals("admin123456")) {
        NextPage page=new NextPage();
        page.setVisible(true);

        JTabbedPane tabbedPane1 = new JTabbedPane();
        ImageIcon icon1 = createImageIcon("images/middle.gif");
        JComponent panel1 = makeTextPanel("panel#1");
        tabbedPane1.addTab("Booking", icon1, panel1, "For booking appointments");
        JLabel label = new JLabel("Welcome "+value1);
        page.getContentPane().add(label);
        page.getContentPane().add(tabbedPane1);
        //page.add(icon);
        page.getContentPane().add(panel1);

  JTabbedPane tabbedPane2 = new JTabbedPane();
    ImageIcon icon2 = createImageIcon("images/middle.gif");
    JComponent panel2 = makeTextPanel("panel#2");
    tabbedPane2.addTab("Doctors", icon2, panel2, "For choosing appointments");
    JLabel label2 = new JLabel("Welcome "+value2);
    page.getContentPane().add(label2);
    page.getContentPane().add(tabbedPane2);
    //page.add(icon2);
    page.getContentPane().add(panel2);}
</code>```

答:
I, generally, always consider GUI builders as best tools for this task.

It is not true that code is not portable

```<code>  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">
  private void initComponents() {

    jTabbedPane = new javax.swing.JTabbedPane();
    jPanelFirst = new javax.swing.JPanel();
    jPanelSecond = new javax.swing.JPanel();
    jPanelThird = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanelFirst.setLayout(null);
    jTabbedPane.addTab("tab1", jPanelFirst);

    jPanelSecond.setLayout(null);
    jTabbedPane.addTab("tab2", jPanelSecond);

    jPanelThird.setLayout(null);
    jTabbedPane.addTab("tab3", jPanelThird);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jTabbedPane)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jTabbedPane)
    );

    pack();
  }// </editor-fold>
</code>```

Of course, if you load it inside Eclipse, and do some "manual mess", you will probably complain that NetBeans fails to load it. That's true.

Personally, I always ask myself. Do I want to devote my time to writing all the  code manually or would I rather focus on business logic and do all the GUI building inside some tools that help to do it quickly?

There are always trade-offs.

Title: adding tabs in java (swing)

Body:
i was given a project to make a java program named doctors care which has login panel( username and password) and a panel which has 3 tabs. the problem is i could add only one tab and when i tried to add another tab by duplicating the objects( like label2, panel2 etc) it does not appear in the executed JAR file. i have posted the code below.

public void actionPerformed(ActionEvent ae)

   {String value1 = text1.getText();
    String value2 = text2.getText();
    if(value1.equals("admin") && value2.equals("admin123456")) {
        NextPage page=new NextPage();
        page.setVisible(true);

        JTabbedPane tabbedPane1 = new JTabbedPane();
        ImageIcon icon1 = createImageIcon("images/middle.gif");
        JComponent panel1 = makeTextPanel("panel#1");
        tabbedPane1.addTab("Booking", icon1, panel1, "For booking appointments");
        JLabel label = new JLabel("Welcome "+value1);
        page.getContentPane().add(label);
        page.getContentPane().add(tabbedPane1);
        //page.add(icon);
        page.getContentPane().add(panel1);

  JTabbedPane tabbedPane2 = new JTabbedPane();
    ImageIcon icon2 = createImageIcon("images/middle.gif");
    JComponent panel2 = makeTextPanel("panel#2");
    tabbedPane2.addTab("Doctors", icon2, panel2, "For choosing appointments");
    JLabel label2 = new JLabel("Welcome "+value2);
    page.getContentPane().add(label2);
    page.getContentPane().add(tabbedPane2);
    //page.add(icon2);
    page.getContentPane().add(panel2);}

Body:
I, generally, always consider GUI builders as best tools for this task.

It is not true that code is not portable

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">
  private void initComponents() {

    jTabbedPane = new javax.swing.JTabbedPane();
    jPanelFirst = new javax.swing.JPanel();
    jPanelSecond = new javax.swing.JPanel();
    jPanelThird = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanelFirst.setLayout(null);
    jTabbedPane.addTab("tab1", jPanelFirst);

    jPanelSecond.setLayout(null);
    jTabbedPane.addTab("tab2", jPanelSecond);

    jPanelThird.setLayout(null);
    jTabbedPane.addTab("tab3", jPanelThird);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jTabbedPane)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jTabbedPane)
    );

    pack();
  }// </editor-fold>

Of course, if you load it inside Eclipse, and do some "manual mess", you will probably complain that NetBeans fails to load it. That's true.

Personally, I always ask myself. Do I want to devote my time to writing all the  code manually or would I rather focus on business logic and do all the GUI building inside some tools that help to do it quickly?

There are always trade-offs.


问:
Update NSFetchedResultsController object when relationship object was deleted
Let's say I have objects in my FetchedResultsController. The objects have a relationship to another entity called Category. This can be nil, if no category was set by user, or the selected category. The user can delete and create categories whenever he wants.

However, when a category was deleted, the objects who had the specific category, instead of having nil as category property, it have the specific category, which doesn't exist anymore, giving me an error.

How can I update my frc objects so that when a category was deleted, every other object who had the category property set as the deleted category, sets the current category as nil.

This is how I save data in frc:

```<code>   func save(sumText: String, dataDescription: String, dataColor: UIColor, category: Categories?, type: String, completion: (_ finished: Bool) -> ()) {
        let budget = NSEntityDescription.insertNewObject(forEntityName: "Budget", into: managedObjectContext!) as! Budget

        budget.dataSum = sumText
        budget.dataDescription = dataDescription
        budget.dataColor = dataColor
        budget.dateSubmitted = Date()
        budget.dateSection = formatDate(date: Date())
        budget.type = type

        if let cat = category {
            budget.category = cat
        }

        do{
            try managedObjectContext?.save()
            print("Succesfully saved data")
            completion(true)
        } catch {
            debugPrint("Could not save \(error.localizedDescription)")
            completion(false)
        }
    }
</code>```

This is how I delete a category:

```<code>    let deleteAction = SwipeAction(style: .destructive, title: "Sterge") { (action, indexPath) in

        guard let managedContext = appDelegate?.persistentContainer.viewContext else { return }

        managedContext.delete(userCategories[indexPath.row])

        do {
            try managedContext.save()
        } catch {}

        self.fetchCoreDataObject()
        tableView.reloadData()

    }
</code>```

So when I delete the categories I have to update all the objects with that category to be set as nil, but I don't know how.

答:
All you need to do is to specify the delete rule as Nullify.

When you use a Nullify delete rule, on deleting the object all other object having its reference as a part of their relationship gets initialized to nil as you expected. You don't need to write code for that.

Issue in your code now:

Looking at the model you posted, I can see that Budget Entity has a Relationship (one to one) with Categories Entity by name category. So now if you simply select the category relationship and set the delete rule to Nullify on deleting the Budget Category will have its reference as nil But thats not what you want.

First of all when you name a relationship between the entity thumb rule is that
Entity Name1 -> RelationShip name -> Entity Name2 should make a statement and explain the relationship explicitly.

Example: Budget isOfType Category

Inverse can be : Category is usedBy Budget.

But usedBy cant be one to one relationship as you have shown. Category can be used in multiple Budgets. You dont wanna create a separate category for each Budget entity do you ?

Lets finally specify delete rule. When you delete a Category all the isOfType reference in Budget should be set to nil correct. So select the Category Entity, highlight usedBy relationship and set delete rule to Nullify

Finally if user delete the Budget, Categories should be left unaltered so Select Budget, Highlight isOfType and set delete rule to

Hope this helps :)

Body:
Let's say I have objects in my FetchedResultsController. The objects have a relationship to another entity called Category. This can be nil, if no category was set by user, or the selected category. The user can delete and create categories whenever he wants.

However, when a category was deleted, the objects who had the specific category, instead of having nil as category property, it have the specific category, which doesn't exist anymore, giving me an error.

How can I update my frc objects so that when a category was deleted, every other object who had the category property set as the deleted category, sets the current category as nil.

This is how I save data in frc:

   func save(sumText: String, dataDescription: String, dataColor: UIColor, category: Categories?, type: String, completion: (_ finished: Bool) -> ()) {
        let budget = NSEntityDescription.insertNewObject(forEntityName: "Budget", into: managedObjectContext!) as! Budget

        budget.dataSum = sumText
        budget.dataDescription = dataDescription
        budget.dataColor = dataColor
        budget.dateSubmitted = Date()
        budget.dateSection = formatDate(date: Date())
        budget.type = type

        if let cat = category {
            budget.category = cat
        }

        do{
            try managedObjectContext?.save()
            print("Succesfully saved data")
            completion(true)
        } catch {
            debugPrint("Could not save \(error.localizedDescription)")
            completion(false)
        }
    }

This is how I delete a category:

    let deleteAction = SwipeAction(style: .destructive, title: "Sterge") { (action, indexPath) in

        guard let managedContext = appDelegate?.persistentContainer.viewContext else { return }

        managedContext.delete(userCategories[indexPath.row])

        do {
            try managedContext.save()
        } catch {}

        self.fetchCoreDataObject()
        tableView.reloadData()

    }

So when I delete the categories I have to update all the objects with that category to be set as nil, but I don't know how.


问:
Android/Crosswalk app installs using debug key, but "isn't compatible" once signed
I'm currently building an app using Cordova & Crosswalk, and building it using Phonegap Build.

When creating a debug app with no key and manually installing the apk, the app installs correctly and works as expected.

However, as soon as I sign the app for production, whenever I try to install the app I get the message:

App not installed.

This app isn't compatible with your phone.

I've looked into sdk versions, features, architectures etc and as far as I can see the phone I'm using is fully compatible. I don't understand what could be changing between the unsigned and signed apps to trigger this error.

What could be changing when I sign the app which suddenly makes the app incompatible, and causes the install to fail?

答:
While I don't understand the specifics about the signed/unsigned issue, the root cause of this was a change made in Cordova Android 6.4.0 which broke compatibility with Crosswalk:

Google also has changed the Gradle DSL used and currently support for the Crosswalk WebView is broken in this version of Cordova as a result. Unfortunately, since Crosswalk is no longer supported by the Crosswalk Project, we do not know whether this issue will be fixed.

If you require support for Crosswalk, we recommend that you continue using cordova-android 6.3.0 at this time and avoid using or upgrading your project with Android Studio.

As mentioned in the article, forcing the build process to use 6.3.0 fixed the issue for me.


问:
Error While update column name with Liquibase xml
I am trying to update database column name with help of Liquibase xml on linux machine MYSQL.

My xml code for update column is

```<code> <renameColumn tableName="AAA" oldColumnName="bbb_id" newColumnName="ccc_id" columnDataType="bigint" />
</code>```

but this line is throw error like ERROR [2017-11-16 15:42:28,247] liquibase: migrations.xml: migrations.xml::3.15.1::maulik.kakadiya: Change Set migrations.xml::3.15.1::maulik.kakadiya failed.  Error: Error on rename of './MY_DB/#sql-4bf_322' to './MY_DB/AAA' (errno: 150) [Failed SQL: ALTER TABLE MY_DB.AAA CHANGE bbb_id ccc_id BIGINT]

After getting this error I have tried with bellow simple sql query

```<code><sql>ALTER TABLE `AAA` CHANGE COLUMN `bbb_id` `ccc_id` BIGINT(20);
    <comment>find onther why, beacuse rename query throw error</comment>
</sql>
</code>```

Also "bbb_id" is a foreign-key reference.

But this statement is throwing same  error.

But if I have run Simple SQL query of this statement as per bellow query

```<code>ALTER TABLE `AAA` CHANGE COLUMN `bbb_id` `ccc_id` BIGINT(20);
</code>```

Then this SQL query run successfully, but if I tried with Liquibase xml for same opration then this code is throwing error.

Any idea for this kind of problem?.

答: I don't know why it is happening, but I can suggest a troubleshooting step - instead of using the liquibase update command, try using the updateSQL command, which will generate the SQL that liquibase runs. Compare that to what you are doing manually and see if you can tell what the difference is.

Body:
I am trying to update database column name with help of Liquibase xml on linux machine MYSQL.

My xml code for update column is

 <renameColumn tableName="AAA" oldColumnName="bbb_id" newColumnName="ccc_id" columnDataType="bigint" />

but this line is throw error like ERROR [2017-11-16 15:42:28,247] liquibase: migrations.xml: migrations.xml::3.15.1::maulik.kakadiya: Change Set migrations.xml::3.15.1::maulik.kakadiya failed.  Error: Error on rename of './MY_DB/#sql-4bf_322' to './MY_DB/AAA' (errno: 150) [Failed SQL: ALTER TABLE MY_DB.AAA CHANGE bbb_id ccc_id BIGINT]

After getting this error I have tried with bellow simple sql query

<sql>ALTER TABLE `AAA` CHANGE COLUMN `bbb_id` `ccc_id` BIGINT(20);
    <comment>find onther why, beacuse rename query throw error</comment>
</sql>

Also "bbb_id" is a foreign-key reference.

But this statement is throwing same  error.

But if I have run Simple SQL query of this statement as per bellow query

ALTER TABLE `AAA` CHANGE COLUMN `bbb_id` `ccc_id` BIGINT(20);

Then this SQL query run successfully, but if I tried with Liquibase xml for same opration then this code is throwing error.

Any idea for this kind of problem?.


问:
YouTrack JavaScript Workflow - send email to global group
I am creating a state machine for YouTrack using JavaScript, and am trying to send an email to everyone in a group. In the old Workflows, this was done like this:

```<code>{group:PHP Developers}.notifyAllUsers("Subject","message");
</code>```

I can't find anything in the new JavaScript API to do this, where can I find the global (not issue or project) groups?

答:
In JS API it will look as follows:

entities.UserGroup.findByName('PHP Developers')
    .notifyAllUsers('Subject','message');

However, another (and way more reliable) way to get a particular user group is to add it to requirements and the reference inside the code:

ctx.phpdevs.notifyAllUsers('Subject','message');
...
requirements: {
  ...
  phpDevs: {
    type: entities.UserGroup,
    name: 'PHP Developers'
  }
}

You may find more details in official documentation: UserGroup and Finding Specific Entities.

Body:
I am creating a state machine for YouTrack using JavaScript, and am trying to send an email to everyone in a group. In the old Workflows, this was done like this:

{group:PHP Developers}.notifyAllUsers("Subject","message");

I can't find anything in the new JavaScript API to do this, where can I find the global (not issue or project) groups?


问:
How to disable pagination in feathers service?
Hi I try populate my datatable using feathers service in this way:

```<code>app.service('pupils').find({}, (error, result) => {

    $('#pupils > table').DataTable({
        "pageLength": view.short,
        "lengthChange": false,
        "info" : false,
        "responsive": true,
        "data": result.data,
        "deferRender": true,
        "columns": [ ... ]
    });

});
</code>```

I have more than 100 testing records but in callback I receive only 10 records.
I receive more records after added below code in feathers service:

```<code>paginate: {
   default: 100,
   max: 200
 }
</code>```

but I would like to disable pagination for received all records from mongo.
How can I do that?

答:
To disable pagination, remove the paginate option. Not recommended for production however since it might bring down both, the client and the server if you try to send many thousands of records.

Note: the response object changes depending on whether you are using pagination:

Response with pagination: object with data array property

```<code>{
   total: 572,
   limit: 50,
   skip: 4,
   data: [/* the data is here */]
}
</code>```

Response without pagination: the data array

```<code>[/* the data is here */]
</code>```

Body:
Hi I try populate my datatable using feathers service in this way:

app.service('pupils').find({}, (error, result) => {

    $('#pupils > table').DataTable({
        "pageLength": view.short,
        "lengthChange": false,
        "info" : false,
        "responsive": true,
        "data": result.data,
        "deferRender": true,
        "columns": [ ... ]
    });

});

I have more than 100 testing records but in callback I receive only 10 records.
I receive more records after added below code in feathers service:

paginate: {
   default: 100,
   max: 200
 }

but I would like to disable pagination for received all records from mongo.
How can I do that?

Body:
To disable pagination, remove the paginate option. Not recommended for production however since it might bring down both, the client and the server if you try to send many thousands of records.

Note: the response object changes depending on whether you are using pagination:

Response with pagination: object with data array property

{
   total: 572,
   limit: 50,
   skip: 4,
   data: [/* the data is here */]
}

Response without pagination: the data array

[/* the data is here */]


问:
get input from keyboard while displaying an avi with matlab
Hi all

I wrote a short program that displays an avi file. I need the program to get input from the keyboard while the movie is running (and not after it ends):
this is my code:

figure('MenuBar','none')

    set(gcf,'Color', 'white')

    set(gca,'Color','white');

    set(gca,'XColor','white');

    set(gca,'YColor','white');

    m=aviread('c:/t1.avi')

    a=30:1:100;

    b=100:-1:30;

    c=[a b a b a b a b a b] %to run the movie back and forth

    movie(m,c) %runs the movie

Thank you for any help

Ariel

答:
Maybe you can insert your video in an UIPanel (or another suitable GUI item) and use the KeyPressFcn callback.
Have a look on this : Callback Sequencing and Interruption (I don't know if it can works but it's probably worth trying).</p>