问:
WTForms validation error not working
I am trying to create a login form wherein if the username is blank, it throws an error.

```<code>from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Email, length, ValidationError

app = Flask(__name__)
app.config['SECRET_KEY'] = 'This is a secret'
class LoginForm(FlaskForm):
  username = StringField('username', validators=[InputRequired()])
  password = PasswordField('password')

@app.route('/form', methods=['GET','POST'])
def form():
  form=LoginForm()
  return render_template('form.html', form=form)

if __name__== '__main__':
  app.run(debug=True)
</code>```

The html code is as below:

```<code><html>
<title> MY FORM </title>
<body>
<form method="POST" action="{{ url_for('form') }}">
  {{form.csrf_token}}
  {{ form.username.label }}
  {{ form.username }}
  <ul>
  {% for error in form.username.errors %}
    <li style="color: red;">{{ error }} </li>

  {% endfor %}
  </ul>
  {{ form.password }}
  {{ form.password.label }}
  <input type="submit" value="Submit">

</form>
</body>
</html>
</code>```

Apparently, the for loop is skipped and nothing happens on clicking the submit button while the user field is null

答:
You are not validating the form at all in the form function. Edit the function and add a validation line. It is after validation that the errors are found. Otherwise, the form variable in your template will not have errors attributes. The following should do:

```<code>@app.route('/form', methods=['GET','POST'])
def form():
    this_form = LoginForm()
    this_form.validate()
    return render_template('form.html', form=this_form)
</code>```

Also, avoid naming your form form since you already named the function form. You should change either the function name or the variable name for the form.

I hope this helps.

Title: WTForms validation error not working

Body:
I am trying to create a login form wherein if the username is blank, it throws an error.

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Email, length, ValidationError

app = Flask(__name__)
app.config['SECRET_KEY'] = 'This is a secret'
class LoginForm(FlaskForm):
  username = StringField('username', validators=[InputRequired()])
  password = PasswordField('password')

@app.route('/form', methods=['GET','POST'])
def form():
  form=LoginForm()
  return render_template('form.html', form=form)

if __name__== '__main__':
  app.run(debug=True)

The html code is as below:

<title> MY FORM </title>

<form method="POST" action="{{ url_for('form') }}">
  {{form.csrf_token}}
  {{ form.username.label }}
  {{ form.username }}

  {% for error in form.username.errors %}

{{ error }}

  {% endfor %}

  {{ form.password }}
  {{ form.password.label }}
  <input type="submit" value="Submit">

</form>

Apparently, the for loop is skipped and nothing happens on clicking the submit button while the user field is null

Body:
You are not validating the form at all in the form function. Edit the function and add a validation line. It is after validation that the errors are found. Otherwise, the form variable in your template will not have errors attributes. The following should do:

@app.route('/form', methods=['GET','POST'])
def form():
    this_form = LoginForm()
    this_form.validate()
    return render_template('form.html', form=this_form)

Also, avoid naming your form form since you already named the function form. You should change either the function name or the variable name for the form.

I hope this helps.


来源: stackexchange

问:
Is there a performance hit by added nonenforced foreign keys to a SQL Server 2008 database?
I'm working with a database and I want to start using LINQ To SQL with it. The database doesn't have any FKs inside of it right now for performance reasons. We are inserting millions of rows at a time to the DB which is why there aren't any FKs.

So I'm thinking I'm going to add nonenforced FKs to the database to describe the relationships between the tables for my LINQ To SQL but I don't want there to be a performance hit by adding nonenforced foreign keys.

Does anyone know what the effect of this might be?

Update: I'm using LINQ-To-SQL for the nonperformance intesive stuff. 80% of the data access is through stored procs on production. But for writing unit tests and other non performance critical tasks, LINQ-To-SQL makes data access really easy.

Update: Here is how you add a nonenforced FK

ALTER TABLE [dbo].[ACI]  WITH NOCHECK ADD  CONSTRAINT [FK_ACI_CustomerInformation] FOREIGN KEY([ACIOI])
REFERENCES [dbo].[CustomerInformation] ([ACI_OI])
NOT FOR REPLICATION
GO

ALTER TABLE [dbo].[ACI] NOCHECK CONSTRAINT [FK_ACI_CustomerInformation]
GO

答: The answer can be different for different environments (data/logs on same drive, tempdb on same drive, lots of cache vs little, etc) so the best way to find this out is to benchmark.  Create two identical databases, one with fk's and one without.  Do your normal million-row-load into each database, and measure your transactions per second.  That way you'll know for sure in your own environment.</p>

OwnerDisplayName: Paul Mendoza

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Paul Mendoza

OwnerDisplayName: Brent Ozar


问:
How to detect if a link was clicked through an email in gmail
I am working on an email that will be sent out as a marketing effort.
Within the email there will be a button that will allow people to "save the date" of the event and I want to be able to detect if the email was opened in gmail after the button is clicked, and if it was opened in gmail it would serve a Google Add to Calendar link - else it would serve an ICS file.

There is another email that does exactly this, it does not detect user agent since, regardless of the browser and os and device, if the email was opened in gmail it would redirect to google's add to calendar!

I've been trying to figure this out for a while now and have tried many trick, though none successful, I would love to see what other ideas people have.

Edit: I noticed that gmail will add data-saferedirecturl to all links

I'm wondering if there is a way to detect this?

答:
If you to know the source of the click on your link, you can do so by using a trick with images:

Inside your mail, insert a tiny image pointing to your domain (Preferably with a different identifier for every recipient.

When user first opens your mail, the Gmail proxy server will send your server a request to get the picture.

You can identify the request coming from the Gmail proxy server using any of the indicative elements of the request (Like IP address, User-Agent and such).

Though, note that: If the recipient opens the mail again in Gmail, you won't see a request to your server, since this picture is saved in the proxy server's cache.

ContentLicense: CC BY-SA 3.0


问:
How to get all possible combination of column from the data frame?
```<code>R> set.seed(123)
R> data <- matrix(rnorm(6),3,10)
R> colnames(data) <- c("s1","s2","s3","s4","s5","s6","s7","s8","s9","s10")
R> print(data)

sorry, I don't know how to show the print
</code>```

I would like to get all possible combination of column from the data frame by R package? Less time is better

The result look like this,

```<code>All possible two pair combination
column S1 and S2
column S2 and S3
column S3 and S4
...

all possible three pair combination
column S1, S2 and S3
column S2, S3 and S4
column S3, S4 and S5
...
</code>```

答:
I have made a function to do this which comes in handy whenever I need it:

```<code>make_combinations <- function(x) {

  l <- length(x)
  mylist <- lapply(2:l, function(y) {
    combn(x, y, simplify = FALSE)
  })
  mylist

}

results <- make_combinations(colnames(data))
results[[1]]
# [[1]]
# [1] "s1" "s2"
#
# [[2]]
# [1] "s1" "s3"
#
# [[3]]
# [1] "s1" "s4"
#
# [[4]]
# [1] "s1" "s5"
#
# [[5]]
# [1] "s1" "s6"
#
# [[6]]
# [1] "s1" "s7"
#and so on...
</code>```

The function outputs a list, where each element is another list with all the 2-way, 3-way, 4-way... combinations. In your case it has 9 elements starting from the 2-way combinations all the way to the 10-way combination.

ContentLicense: CC BY-SA 4.0

Body:
R> set.seed(123)
R> data <- matrix(rnorm(6),3,10)
R> colnames(data) <- c("s1","s2","s3","s4","s5","s6","s7","s8","s9","s10")
R> print(data)

sorry, I don't know how to show the print

I would like to get all possible combination of column from the data frame by R package? Less time is better

The result look like this,

All possible two pair combination
column S1 and S2
column S2 and S3
column S3 and S4
...

all possible three pair combination
column S1, S2 and S3
column S2, S3 and S4
column S3, S4 and S5
...

Body:
I have made a function to do this which comes in handy whenever I need it:

make_combinations <- function(x) {

  l <- length(x)
  mylist <- lapply(2:l, function(y) {
    combn(x, y, simplify = FALSE)
  })
  mylist

}

results <- make_combinations(colnames(data))
results[[1]]
# [[1]]
# [1] "s1" "s2"
#
# [[2]]
# [1] "s1" "s3"
#
# [[3]]
# [1] "s1" "s4"
#
# [[4]]
# [1] "s1" "s5"
#
# [[5]]
# [1] "s1" "s6"
#
# [[6]]
# [1] "s1" "s7"
#and so on...

The function outputs a list, where each element is another list with all the 2-way, 3-way, 4-way... combinations. In your case it has 9 elements starting from the 2-way combinations all the way to the 10-way combination.


问:
Highstock tooltip.positioner isn t working
I can t change the position of tooltip in highcharts:

```<code>    tooltip: {
    positioner: function() {
        return {
            x: 20,
            y: 20
        };
    }},
</code>```

http://jsfiddle.net/e07s2oq6/

Doc:
https://api.highcharts.com/highstock/tooltip.positioner

I want to change the tooltip like this:

答:
Here is an ugly solution that solves your problem.

I set the tool-tip positioner to the following:

```<code>tooltip: {
  split: false,
  positioner: function() {
    return {
      x: this.now.anchorX - this.label.width/2,
      y: 20
    };
  }
},
</code>```

Now it shows a tool-tip centered above the point that is being hovered.

Working example: http://jsfiddle.net/ewolden/e07s2oq6/3/

Body:
I can t change the position of tooltip in highcharts:

    tooltip: {
    positioner: function() {
        return {
            x: 20,
            y: 20
        };
    }},

http://jsfiddle.net/e07s2oq6/

Doc:
https://api.highcharts.com/highstock/tooltip.positioner

I want to change the tooltip like this:

Body:
Here is an ugly solution that solves your problem.

I set the tool-tip positioner to the following:

tooltip: {
  split: false,
  positioner: function() {
    return {
      x: this.now.anchorX - this.label.width/2,
      y: 20
    };
  }
},

Now it shows a tool-tip centered above the point that is being hovered.

Working example: http://jsfiddle.net/ewolden/e07s2oq6/3/


问:
Gitlab upgrade but gitlab.rb unchange
I am using GitLab CE. I upgrade GitLab CE from 7.14.3 to 8.9.6 through apt-get upgrade. After successfully upgrade, I found that the gitlab configuration file which locates in /etc/gitlab/gitlab.rb keeps the same.

But why? I thought that GitLab upgrade would automatically update the new features to gitlab.rb. For now, I have to copy the newest configuration file and find the difference and then merge it to my current gitlab.rb.

Is there any way to auto upgrade configuration file to the newest and merge the configuration which I had changed?

答:
You can easily check the diff with gitlab-ctl diff-config.

Then change what's new so the diff is minimal or if you have no changed done to gitlab.rb you can just copy /opt/gitlab/etc/gitlab.rb.template over it.

Title: Gitlab upgrade but gitlab.rb unchange


问:
Add Font-Awesome to Angular-Cli project when build in production
I have followed the steps explained in the Angular-Cli documentation to include Font-Awesome to my project https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/include-font-awesome.md

So I have this in my angular-cli.json:

```<code>"styles": [
            "../node_modules/boosted/dist/css/boosted.min.css",
            "../node_modules/boosted/dist/css/orangeIcons.min.css",
            "../node_modules/font-awesome/css/font-awesome.min.css",
            "styles.css"
],
</code>```

And everything worked fine when doing ng serve and seeing my project on localhost:4200.

Unfortunately, when doing ng build --prod, it generate the dist folder, including the font-awesome files:

And I also verified if the font was added to my style.[...].bundle.css and it does:

Then, when deployed on a server (Apache Tomcat 8.5), no font-awesome icons are displayed.

I don't use SASS by the way.

Here is my Angular configuration/version:

```<code>@angular/cli: 1.4.3
node: 6.11.3
os: win32 x64
@angular/animations: 4.4.4
@angular/common: 4.4.4
@angular/compiler: 4.4.4
@angular/core: 4.4.4
@angular/forms: 4.4.4
@angular/http: 4.4.4
@angular/platform-browser: 4.4.4
@angular/platform-browser-dynamic: 4.4.4
@angular/router: 4.4.4
@angular/cli: 1.4.3
@angular/compiler-cli: 4.4.4
@angular/language-service: 4.4.4
typescript: 2.3.4
</code>```

So, what can I do to make this work ?

答:
Okay, so I have see someone say something about this, but I didn't try at that moment.
My solution is to put the "../node_modules/font-awesome/css/font-awesome.min.css" above the other style file in angular-cli.json.

It seems that the other .css files overwrite the font-awesome style, but in that case, I don't understand why anything was wrong in development mode.

So, my styles in angular-cli.json looks like this now:

```<code>"styles": [
        "../node_modules/font-awesome/css/font-awesome.min.css",
        "../node_modules/boosted/dist/css/boosted.min.css",
        "../node_modules/boosted/dist/css/orangeIcons.min.css",
        "styles.css"
],
</code>```

Body:
I have followed the steps explained in the Angular-Cli documentation to include Font-Awesome to my project https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/include-font-awesome.md

So I have this in my angular-cli.json:

"styles": [
            "../node_modules/boosted/dist/css/boosted.min.css",
            "../node_modules/boosted/dist/css/orangeIcons.min.css",
            "../node_modules/font-awesome/css/font-awesome.min.css",
            "styles.css"
],

And everything worked fine when doing ng serve and seeing my project on localhost:4200.

Unfortunately, when doing ng build --prod, it generate the dist folder, including the font-awesome files:

And I also verified if the font was added to my style.[...].bundle.css and it does:

Then, when deployed on a server (Apache Tomcat 8.5), no font-awesome icons are displayed.

I don't use SASS by the way.

Here is my Angular configuration/version:

@angular/cli: 1.4.3
node: 6.11.3
os: win32 x64
@angular/animations: 4.4.4
@angular/common: 4.4.4
@angular/compiler: 4.4.4
@angular/core: 4.4.4
@angular/forms: 4.4.4
@angular/http: 4.4.4
@angular/platform-browser: 4.4.4
@angular/platform-browser-dynamic: 4.4.4
@angular/router: 4.4.4
@angular/cli: 1.4.3
@angular/compiler-cli: 4.4.4
@angular/language-service: 4.4.4
typescript: 2.3.4

So, what can I do to make this work ?

Body:
Okay, so I have see someone say something about this, but I didn't try at that moment.
My solution is to put the "../node_modules/font-awesome/css/font-awesome.min.css" above the other style file in angular-cli.json.

It seems that the other .css files overwrite the font-awesome style, but in that case, I don't understand why anything was wrong in development mode.

So, my styles in angular-cli.json looks like this now:

"styles": [
        "../node_modules/font-awesome/css/font-awesome.min.css",
        "../node_modules/boosted/dist/css/boosted.min.css",
        "../node_modules/boosted/dist/css/orangeIcons.min.css",
        "styles.css"
],


问:
Django Users not showing the date_of_birth in the admin site
I am registering users by sending token activation email using built-in register and activate functions. The register form subclass the UserCreationForm to add extra fields for email and date_of_birth validations. My code is the following:

forms.py:

```<code>class UserRegisterForm(UserCreationForm):

date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1)))
email = forms.EmailField(required=True)

def clean_username(self):
    username = self.cleaned_data.get('username')
    if User.objects.filter(username__iexact=username).exists():
        raise forms.ValidationError('Username already exists')
    return username

def clean_date_of_birth(self):
    '''
    Only accept users aged 13 and above
    '''
    userAge = 13
    dob = self.cleaned_data.get('date_of_birth')
    today = date.today()
    if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day):
        raise forms.ValidationError('Users must be aged {} years old or above.'.format(userAge))
    return dob

def clean_email(self):
    email = self.cleaned_data.get('email')
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError('A user has already registered using this email')
    return email

def clean_password2(self):
    '''
    we must ensure that both passwords are identical
    '''
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError('Passwords must match')
    return password2

class Meta:
    model = User
    fields = ['username', 'email', 'date_of_birth', 'password1', 'password2']
</code>```

views.py:

```<code>def register(request):
   if request.method == 'POST':
       form = UserRegisterForm(request.POST)
       if form.is_valid():
          email = form.cleaned_data.get('email')
          date_of_birth = form.cleaned_data.get('date_of_birth')
          new_user = form.save(commit=False)
          new_user.is_active = False
          new_user.save()
          current_site = get_current_site(request)
          message = render_to_string('email_activation_link.html', {
            'new_user':new_user,
            'domain':current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(new_user.pk)),
            'token': account_activation_token.make_token(new_user),
          })
          mail_subject = 'Activate your Frac account.'
          to_email = EmailMessage(mail_subject, message, to=[email])
          to_email.send()
        return render(request, 'register_confirm.html', {'form': form})
   else:
      form = UserRegisterForm()

   return render(request, 'register.html', {'form': form})

def activate(request, uidb64, token):
   try:
       uid = force_text(urlsafe_base64_decode(uidb64))
       new_user = User.objects.get(pk=uid)
   except(TypeError, ValueError, OverflowError, User.DoesNotExist):
       new_user = None
   if new_user is not None and account_activation_token.check_token(new_user, token):
      new_user.is_active = True
      new_user.save()
      return render(request, 'register_complete.html', {})
   else:
      return render(request, 'registration_incomplete.html', {})
</code>```

models.py:

```<code>class UserProfile(models.Model):
   '''
   Extends the Django User model
   '''
   user = models.OneToOneField(settings.AUTH_USER_MODEL,
                            related_name='profile')
   email = models.EmailField(blank=True)
   date_of_birth = models.DateField(blank=True, null=True)
   profile_photo = models.ImageField(blank=True)
   following = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                    blank=True,
                                    related_name='followed_by')

   def __str__(self):
       return 'Followers({});Following({})'.format(self.user.followed_by.all().count(),self.get_following().count())

def post_save_user_receiver(sender, instance, created, *args, **kwargs):
   '''
   Django signals to automatically create
   a user profile when a user object is created
   '''
   if created:
       new_profile, is_created = UserProfile.objects.get_or_create(user=instance)

post_save.connect(post_save_user_receiver, sender=settings.AUTH_USER_MODEL)
</code>```

admin.py:

```<code>from django.contrib import admin

from .models import UserProfile

class ProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'id', 'date_of_birth', 'profile_photo', '__str__']

admin.site.register(UserProfile, ProfileAdmin)
</code>```

The new user is registered properly. However, only the username and email fields appear in Users section of the Django admin site. I can't figure out why the date_of_birth field is not showing for the newly-registered user.

答:
You haven't extended the user model, you've added a related user profile. You don't do anything anywhere to actually create instances of this user profile or populate them with the data from the form; you get the DOB and email values in your view but then proceed to ignore them.

You need to create a Profile with those values:

```<code>   if form.is_valid():
      new_user = form.save(commit=False)
      new_user.is_active = False
      new_user.save()
      email = form.cleaned_data.get('email')
      date_of_birth = form.cleaned_data.get('date_of_birth')
      UserProfile.objects.create(user=new_user, email=email, date_of_birth=date_of_birth)
</code>```

Body:
I am registering users by sending token activation email using built-in register and activate functions. The register form subclass the UserCreationForm to add extra fields for email and date_of_birth validations. My code is the following:

forms.py:

class UserRegisterForm(UserCreationForm):

date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1)))
email = forms.EmailField(required=True)

def clean_username(self):
    username = self.cleaned_data.get('username')
    if User.objects.filter(username__iexact=username).exists():
        raise forms.ValidationError('Username already exists')
    return username

def clean_date_of_birth(self):
    '''
    Only accept users aged 13 and above
    '''
    userAge = 13
    dob = self.cleaned_data.get('date_of_birth')
    today = date.today()
    if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day):
        raise forms.ValidationError('Users must be aged {} years old or above.'.format(userAge))
    return dob

def clean_email(self):
    email = self.cleaned_data.get('email')
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError('A user has already registered using this email')
    return email

def clean_password2(self):
    '''
    we must ensure that both passwords are identical
    '''
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError('Passwords must match')
    return password2

class Meta:
    model = User
    fields = ['username', 'email', 'date_of_birth', 'password1', 'password2']

views.py:

def register(request):
   if request.method == 'POST':
       form = UserRegisterForm(request.POST)
       if form.is_valid():
          email = form.cleaned_data.get('email')
          date_of_birth = form.cleaned_data.get('date_of_birth')
          new_user = form.save(commit=False)
          new_user.is_active = False
          new_user.save()
          current_site = get_current_site(request)
          message = render_to_string('email_activation_link.html', {
            'new_user':new_user,
            'domain':current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(new_user.pk)),
            'token': account_activation_token.make_token(new_user),
          })
          mail_subject = 'Activate your Frac account.'
          to_email = EmailMessage(mail_subject, message, to=[email])
          to_email.send()
        return render(request, 'register_confirm.html', {'form': form})
   else:
      form = UserRegisterForm()

   return render(request, 'register.html', {'form': form})

def activate(request, uidb64, token):
   try:
       uid = force_text(urlsafe_base64_decode(uidb64))
       new_user = User.objects.get(pk=uid)
   except(TypeError, ValueError, OverflowError, User.DoesNotExist):
       new_user = None
   if new_user is not None and account_activation_token.check_token(new_user, token):
      new_user.is_active = True
      new_user.save()
      return render(request, 'register_complete.html', {})
   else:
      return render(request, 'registration_incomplete.html', {})

models.py:

class UserProfile(models.Model):
   '''
   Extends the Django User model
   '''
   user = models.OneToOneField(settings.AUTH_USER_MODEL,
                            related_name='profile')
   email = models.EmailField(blank=True)
   date_of_birth = models.DateField(blank=True, null=True)
   profile_photo = models.ImageField(blank=True)
   following = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                    blank=True,
                                    related_name='followed_by')

   def __str__(self):
       return 'Followers({});Following({})'.format(self.user.followed_by.all().count(),self.get_following().count())

def post_save_user_receiver(sender, instance, created, *args, **kwargs):
   '''
   Django signals to automatically create
   a user profile when a user object is created
   '''
   if created:
       new_profile, is_created = UserProfile.objects.get_or_create(user=instance)

post_save.connect(post_save_user_receiver, sender=settings.AUTH_USER_MODEL)

admin.py:

from django.contrib import admin

from .models import UserProfile

class ProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'id', 'date_of_birth', 'profile_photo', '__str__']

admin.site.register(UserProfile, ProfileAdmin)

The new user is registered properly. However, only the username and email fields appear in Users section of the Django admin site. I can't figure out why the date_of_birth field is not showing for the newly-registered user.

Body:
You haven't extended the user model, you've added a related user profile. You don't do anything anywhere to actually create instances of this user profile or populate them with the data from the form; you get the DOB and email values in your view but then proceed to ignore them.

You need to create a Profile with those values:

   if form.is_valid():
      new_user = form.save(commit=False)
      new_user.is_active = False
      new_user.save()
      email = form.cleaned_data.get('email')
      date_of_birth = form.cleaned_data.get('date_of_birth')
      UserProfile.objects.create(user=new_user, email=email, date_of_birth=date_of_birth)


问:
jquery: mouseout event firing even after I used a click event to hide the div
```<code>jQuery("#na").mouseover(function()
{
    jQuery("#na").animate({width:"325px", height:"203px", left:"-40px", top:"-25px"}, 200)
});

jQuery("#na").mouseout(function()
{
    jQuery("#na").stop()
    jQuery("#na").animate({width:"244px",height:"152px", left:0, top:0}, 200)
});

jQuery("#na").click(function()
{
    jQuery("#na").hide()
    jQuery("#back").show()
});
</code>```

so thats my code, the problem is when the click event is triggered all is fine, na dissapears but the moment you move your mouse it reappers again. I figured the problem is that the mouseout event is being triggered, but for the life of me cant figure out how to fix it. any ideas?

答:
Inside the mouseout method, check if the "na" is visible or hidden. If it is hidden, dont do anything, else you can do the animate.

EDIT:

Try your mouseout method like this:

```<code>jQuery("#na").mouseout(function(){
    if(jQuery("#na").is(":visible")){
       jQuery("#na").stop()
       jQuery("#na").animate({width:"244px",height:"152px", left:0, top:0}, 200)
    }
});
</code>```

Body:
jQuery("#na").mouseover(function()
{
    jQuery("#na").animate({width:"325px", height:"203px", left:"-40px", top:"-25px"}, 200)
});

jQuery("#na").mouseout(function()
{
    jQuery("#na").stop()
    jQuery("#na").animate({width:"244px",height:"152px", left:0, top:0}, 200)
});

jQuery("#na").click(function()
{
    jQuery("#na").hide()
    jQuery("#back").show()
});

so thats my code, the problem is when the click event is triggered all is fine, na dissapears but the moment you move your mouse it reappers again. I figured the problem is that the mouseout event is being triggered, but for the life of me cant figure out how to fix it. any ideas?

Body:
Inside the mouseout method, check if the "na" is visible or hidden. If it is hidden, dont do anything, else you can do the animate.

EDIT:

Try your mouseout method like this:

jQuery("#na").mouseout(function(){
    if(jQuery("#na").is(":visible")){
       jQuery("#na").stop()
       jQuery("#na").animate({width:"244px",height:"152px", left:0, top:0}, 200)
    }
});


问:
How to know RDS free storage
I've created a RDS postgres instance with size of 65GB initially.
Is it possible to get free space available using any postgres query.

If not, how can I achieve the same?

Thank you in advance.

答:
A couple ways to do it

Using the AWS Console

Go to the RDS console and select the region your database is in. Click on the Show Monitoring button and pick your database instance. There will be a graph (like below image) that shows Free Storage Space.

This is documented over at AWS RDS documentation.

Using the API via AWS CLI

Alternatively, you can use the AWS API to get the information from cloudwatch.

I will show how to do this with the AWS CLI.

This assumes you have set up the AWS CLI credentials. I export AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in my environment variables, but there are multiple ways to configure the CLI (or SDKS).

```<code>REGION="eu-west-1"
START="$(date -u -d '5 minutes ago' '+%Y-%m-%dT%T')"
END="$(date -u '+%Y-%m-%dT%T')"
INSTANCE_NAME="tstirldbopgs001"

AWS_DEFAULT_REGION="$REGION" aws cloudwatch get-metric-statistics \
  --namespace AWS/RDS --metric-name FreeStorageSpace \
  --start-time $START --end-time $END --period 300 \
  --statistics Average \
  --dimensions "Name=DBInstanceIdentifier, Value=${INSTANCE_NAME}"

{
    "Label": "FreeStorageSpace",
    "Datapoints": [
        {
            "Timestamp": "2017-11-16T14:01:00Z",
            "Average": 95406264320.0,
            "Unit": "Bytes"
        }
    ]
}
</code>```

Using the API via Java SDK

Here's a rudimentary example of how to get the same data via the Java AWS SDK, using the Cloudwatch API.

build.gradle contents

```<code>apply plugin: 'java'
apply plugin: 'application'

sourceCompatibility = 1.8

repositories {
    jcenter()
}

dependencies {
    compile 'com.amazonaws:aws-java-sdk-cloudwatch:1.11.232'
}

mainClassName = 'GetRDSInfo'
</code>```

Java class

Again, I rely on the credential chain to get AWS API credentials (I set them in my environment). You can change the call to the builder to change this behavior (see Working with AWS Credentials documentation).

```<code>import java.util.Calendar;
import java.util.Date;

import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult;
import com.amazonaws.services.cloudwatch.model.StandardUnit;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.Datapoint;

public class GetRDSInfo {
    public static void main(String[] args) {
        final long GIGABYTE = 1024L * 1024L * 1024L;

        // calculate our endTime as now and startTime as 5 minutes ago.
        Calendar cal = Calendar.getInstance();
        Date endTime = cal.getTime();
        cal.add(Calendar.MINUTE, -5);
        Date startTime = cal.getTime();

        String dbIdentifier = "tstirldbopgs001";
        Regions region = Regions.EU_WEST_1;

        Dimension dim = new Dimension()
            .withName("DBInstanceIdentifier")
            .withValue(dbIdentifier);

        final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.standard()
                                        .withRegion(region)
                                        .build();

        GetMetricStatisticsRequest req = new GetMetricStatisticsRequest()
            .withNamespace("AWS/RDS")
            .withMetricName("FreeStorageSpace")
            .withStatistics("Average")
            .withStartTime(startTime)
            .withEndTime(endTime)
            .withDimensions(dim)
            .withPeriod(300);

        GetMetricStatisticsResult res = cw.getMetricStatistics(req);

        for (Datapoint dp : res.getDatapoints()) {
            // We requested only the average free space over the last 5 minutes
            // so we only have one datapoint
            double freespaceGigs = dp.getAverage() / GIGABYTE;
            System.out.println(String.format("Free Space: %.2f GB", freespaceGigs));
        }
    }
}
</code>```

Example Java Code Execution

```<code>> gradle run

> Task :run
Free Space: 88.85 GB

BUILD SUCCESSFUL in 7s
</code>```

Title: How to know RDS free storage

Body:
A couple ways to do it

Using the AWS Console

Go to the RDS console and select the region your database is in. Click on the Show Monitoring button and pick your database instance. There will be a graph (like below image) that shows Free Storage Space.

This is documented over at AWS RDS documentation.

Using the API via AWS CLI

Alternatively, you can use the AWS API to get the information from cloudwatch.

I will show how to do this with the AWS CLI.

This assumes you have set up the AWS CLI credentials. I export AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in my environment variables, but there are multiple ways to configure the CLI (or SDKS).

REGION="eu-west-1"
START="$(date -u -d '5 minutes ago' '+%Y-%m-%dT%T')"
END="$(date -u '+%Y-%m-%dT%T')"
INSTANCE_NAME="tstirldbopgs001"

AWS_DEFAULT_REGION="$REGION" aws cloudwatch get-metric-statistics \
  --namespace AWS/RDS --metric-name FreeStorageSpace \
  --start-time $START --end-time $END --period 300 \
  --statistics Average \
  --dimensions "Name=DBInstanceIdentifier, Value=${INSTANCE_NAME}"

{
    "Label": "FreeStorageSpace",
    "Datapoints": [
        {
            "Timestamp": "2017-11-16T14:01:00Z",
            "Average": 95406264320.0,
            "Unit": "Bytes"
        }
    ]
}

Using the API via Java SDK

Here's a rudimentary example of how to get the same data via the Java AWS SDK, using the Cloudwatch API.

build.gradle contents

apply plugin: 'java'
apply plugin: 'application'

sourceCompatibility = 1.8

repositories {
    jcenter()
}

dependencies {
    compile 'com.amazonaws:aws-java-sdk-cloudwatch:1.11.232'
}

mainClassName = 'GetRDSInfo'

Java class

Again, I rely on the credential chain to get AWS API credentials (I set them in my environment). You can change the call to the builder to change this behavior (see Working with AWS Credentials documentation).

import java.util.Calendar;
import java.util.Date;

import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult;
import com.amazonaws.services.cloudwatch.model.StandardUnit;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.Datapoint;

public class GetRDSInfo {
    public static void main(String[] args) {
        final long GIGABYTE = 1024L * 1024L * 1024L;

        // calculate our endTime as now and startTime as 5 minutes ago.
        Calendar cal = Calendar.getInstance();
        Date endTime = cal.getTime();
        cal.add(Calendar.MINUTE, -5);
        Date startTime = cal.getTime();

        String dbIdentifier = "tstirldbopgs001";
        Regions region = Regions.EU_WEST_1;

        Dimension dim = new Dimension()
            .withName("DBInstanceIdentifier")
            .withValue(dbIdentifier);

        final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.standard()
                                        .withRegion(region)
                                        .build();

        GetMetricStatisticsRequest req = new GetMetricStatisticsRequest()
            .withNamespace("AWS/RDS")
            .withMetricName("FreeStorageSpace")
            .withStatistics("Average")
            .withStartTime(startTime)
            .withEndTime(endTime)
            .withDimensions(dim)
            .withPeriod(300);

        GetMetricStatisticsResult res = cw.getMetricStatistics(req);

        for (Datapoint dp : res.getDatapoints()) {
            // We requested only the average free space over the last 5 minutes
            // so we only have one datapoint
            double freespaceGigs = dp.getAverage() / GIGABYTE;
            System.out.println(String.format("Free Space: %.2f GB", freespaceGigs));
        }
    }
}

Example Java Code Execution

> gradle run

> Task :run
Free Space: 88.85 GB

BUILD SUCCESSFUL in 7s


问:
Add additional properties to the output json
There is a collection of User

```{
    "_id" : ObjectId("5a0d45ca8af3a91847b7cf95"),
    "updatedAt" : ISODate("2017-11-16T09:34:14.651Z"),
    "createdAt" : ISODate("2017-11-16T08:01:14.119Z"),
    "name" : "John",
    "email" : "test1@gmail.com",
    "groupsFavorite" : [
        ObjectId("5a0d45db8af3a91847b7cf96")
    ],
    "groups" : [
        ObjectId("5a0d45db8af3a91847b7cf96"),
        ObjectId("5a0d45e18af3a91847b7cf97")
    ],
    "__v" : 3
}```

There is a collection of Groups

```/* 1 */
{
    "_id" : ObjectId("5a0d45db8af3a91847b7cf96"),
    "updatedAt" : ISODate("2017-11-16T08:01:31.815Z"),
    "createdAt" : ISODate("2017-11-16T08:01:31.815Z"),
    "userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
    "title" : "New title",
    "slug" : "new-title-1",
    "description" : "Lorem",
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("5a0d45e18af3a91847b7cf97"),
    "updatedAt" : ISODate("2017-11-16T08:01:37.005Z"),
    "createdAt" : ISODate("2017-11-16T08:01:37.005Z"),
    "userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
    "title" : "New title",
    "slug" : "new-title-2",
    "description" : "Lorem",
    "__v" : 0
}

/* 3 */
{
    "_id" : ObjectId("5a0d5cb0cd59342da943d55a"),
    "updatedAt" : ISODate("2017-11-16T09:38:56.912Z"),
    "createdAt" : ISODate("2017-11-16T09:38:56.912Z"),
    "userId" : ObjectId("5a0d5c48cd59342da943d559"),
    "title" : "New title",
    "slug" : "new-title-3",
    "description" : "Lorem",
    "__v" : 0
}```

There is a method that returns groups of a particular user.
It is necessary to add these data to the new property of favorite: true or false for building a table.

For example:

```{
    "_id" :"5a0d45db8af3a91847b7cf96",
    "updatedAt" : "2017-11-16T08:01:31.815Z",
    "createdAt" : "2017-11-16T08:01:31.815Z",
    "userId" : "5a0d45ca8af3a91847b7cf95",
    "title" : "New title",
    "slug" : "new-title-1",
    "description" : "Lorem",
    "favorite": "true"
},
{
    "_id" : "5a0d45e18af3a91847b7cf97",
    "updatedAt" : "2017-11-16T08:01:37.005Z",
    "createdAt" : "2017-11-16T08:01:37.005Z",
    "userId" : "5a0d45ca8af3a91847b7cf95",
    "title" : "New title",
    "slug" : "new-title-2",
    "description" : "Lorem",
    "favorite": "false"
},
{
    "_id" : "5a0d5cb0cd59342da943d55a",
    "updatedAt" : "2017-11-16T09:38:56.912Z",
    "createdAt" : "2017-11-16T09:38:56.912Z",
    "userId" : "5a0d5c48cd59342da943d559",
    "title" : "New title",
    "slug" : "new-title-3",
    "description" : "Lorem",
    "favorite": "false"
}```

答:
You can use $lookup operator for checking the _id and userId fields in "User" collection. And also for determining it is in or not, you can use $eq operator.

```<code>db.getCollection('Groups').aggregate([
   {
      $lookup:
      {
        from: "User",
        localField: "_id",
        foreignField: "groupsFavorite",
        as: "FavoriteByGrp"
      }
   }
  ,{
      $lookup:
      {
        from: "User",
        localField: "userId",
        foreignField: "_id",
        as: "FavoriteByUsr"
      }
   }
  ,{
       "$project":
       {
           _id:1,
           updatedAt:1,
           createdAt:1,
           userId:1,
           title:1,
           slug:1,
           description:1,
           favorite:
           {
               "$cond":
               {
                   if: { "$eq": [ "$FavoriteByGrp._id", "$FavoriteByUsr._id" ] },
                   then: "true",
                   else: "false"
               }
           }
       }

   }
 ])
</code>```

Result:

```<code>/* 1 */
{
    "_id" : ObjectId("5a0d45db8af3a91847b7cf96"),
    "updatedAt" : ISODate("2017-11-16T08:01:31.815Z"),
    "createdAt" : ISODate("2017-11-16T08:01:31.815Z"),
    "userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
    "title" : "New title",
    "slug" : "new-title-1",
    "description" : "Lorem",
    "favorite" : "true"
}

/* 2 */
{
    "_id" : ObjectId("5a0d45e18af3a91847b7cf97"),
    "updatedAt" : ISODate("2017-11-16T08:01:37.005Z"),
    "createdAt" : ISODate("2017-11-16T08:01:37.005Z"),
    "userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
    "title" : "New title",
    "slug" : "new-title-2",
    "description" : "Lorem",
    "favorite" : "false"
}

/* 3 */
{
    "_id" : ObjectId("5a0d5cb0cd59342da943d55a"),
    "updatedAt" : ISODate("2017-11-16T09:38:56.912Z"),
    "createdAt" : ISODate("2017-11-16T09:38:56.912Z"),
    "userId" : ObjectId("5a0d5c48cd59342da943d559"),
    "title" : "New title",
    "slug" : "new-title-3",
    "description" : "Lorem",
    "favorite" : "false"
}
</code>```

Body:
There is a collection of User

{
    "_id" : ObjectId("5a0d45ca8af3a91847b7cf95"),
    "updatedAt" : ISODate("2017-11-16T09:34:14.651Z"),
    "createdAt" : ISODate("2017-11-16T08:01:14.119Z"),
    "name" : "John",
    "email" : "test1@gmail.com",
    "groupsFavorite" : [
        ObjectId("5a0d45db8af3a91847b7cf96")
    ],
    "groups" : [
        ObjectId("5a0d45db8af3a91847b7cf96"),
        ObjectId("5a0d45e18af3a91847b7cf97")
    ],
    "__v" : 3
}

There is a collection of Groups

/* 1 */
{
    "_id" : ObjectId("5a0d45db8af3a91847b7cf96"),
    "updatedAt" : ISODate("2017-11-16T08:01:31.815Z"),
    "createdAt" : ISODate("2017-11-16T08:01:31.815Z"),
    "userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
    "title" : "New title",
    "slug" : "new-title-1",
    "description" : "Lorem",
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("5a0d45e18af3a91847b7cf97"),
    "updatedAt" : ISODate("2017-11-16T08:01:37.005Z"),
    "createdAt" : ISODate("2017-11-16T08:01:37.005Z"),
    "userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
    "title" : "New title",
    "slug" : "new-title-2",
    "description" : "Lorem",
    "__v" : 0
}

/* 3 */
{
    "_id" : ObjectId("5a0d5cb0cd59342da943d55a"),
    "updatedAt" : ISODate("2017-11-16T09:38:56.912Z"),
    "createdAt" : ISODate("2017-11-16T09:38:56.912Z"),
    "userId" : ObjectId("5a0d5c48cd59342da943d559"),
    "title" : "New title",
    "slug" : "new-title-3",
    "description" : "Lorem",
    "__v" : 0
}

There is a method that returns groups of a particular user.
It is necessary to add these data to the new property of favorite: true or false for building a table.

For example:

{
    "_id" :"5a0d45db8af3a91847b7cf96",
    "updatedAt" : "2017-11-16T08:01:31.815Z",
    "createdAt" : "2017-11-16T08:01:31.815Z",
    "userId" : "5a0d45ca8af3a91847b7cf95",
    "title" : "New title",
    "slug" : "new-title-1",
    "description" : "Lorem",
    "favorite": "true"
},
{
    "_id" : "5a0d45e18af3a91847b7cf97",
    "updatedAt" : "2017-11-16T08:01:37.005Z",
    "createdAt" : "2017-11-16T08:01:37.005Z",
    "userId" : "5a0d45ca8af3a91847b7cf95",
    "title" : "New title",
    "slug" : "new-title-2",
    "description" : "Lorem",
    "favorite": "false"
},
{
    "_id" : "5a0d5cb0cd59342da943d55a",
    "updatedAt" : "2017-11-16T09:38:56.912Z",
    "createdAt" : "2017-11-16T09:38:56.912Z",
    "userId" : "5a0d5c48cd59342da943d559",
    "title" : "New title",
    "slug" : "new-title-3",
    "description" : "Lorem",
    "favorite": "false"
}

Body:
You can use $lookup operator for checking the _id and userId fields in "User" collection. And also for determining it is in or not, you can use $eq operator.

db.getCollection('Groups').aggregate([
   {
      $lookup:
      {
        from: "User",
        localField: "_id",
        foreignField: "groupsFavorite",
        as: "FavoriteByGrp"
      }
   }
  ,{
      $lookup:
      {
        from: "User",
        localField: "userId",
        foreignField: "_id",
        as: "FavoriteByUsr"
      }
   }
  ,{
       "$project":
       {
           _id:1,
           updatedAt:1,
           createdAt:1,
           userId:1,
           title:1,
           slug:1,
           description:1,
           favorite:
           {
               "$cond":
               {
                   if: { "$eq": [ "$FavoriteByGrp._id", "$FavoriteByUsr._id" ] },
                   then: "true",
                   else: "false"
               }
           }
       }

   }
 ])

Result:

/* 1 */
{
    "_id" : ObjectId("5a0d45db8af3a91847b7cf96"),
    "updatedAt" : ISODate("2017-11-16T08:01:31.815Z"),
    "createdAt" : ISODate("2017-11-16T08:01:31.815Z"),
    "userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
    "title" : "New title",
    "slug" : "new-title-1",
    "description" : "Lorem",
    "favorite" : "true"
}

/* 2 */
{
    "_id" : ObjectId("5a0d45e18af3a91847b7cf97"),
    "updatedAt" : ISODate("2017-11-16T08:01:37.005Z"),
    "createdAt" : ISODate("2017-11-16T08:01:37.005Z"),
    "userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
    "title" : "New title",
    "slug" : "new-title-2",
    "description" : "Lorem",
    "favorite" : "false"
}

/* 3 */
{
    "_id" : ObjectId("5a0d5cb0cd59342da943d55a"),
    "updatedAt" : ISODate("2017-11-16T09:38:56.912Z"),
    "createdAt" : ISODate("2017-11-16T09:38:56.912Z"),
    "userId" : ObjectId("5a0d5c48cd59342da943d559"),
    "title" : "New title",
    "slug" : "new-title-3",
    "description" : "Lorem",
    "favorite" : "false"
}


问:
Does scala compiler converts the type of an object dynamically (at run time)
In following code, a is declared as AnyRef but its type check for type String is also true. Does Scala compiler convert the type of an object at runtime?

```<code>scala> val a:AnyRef = "hello"
a: AnyRef = hello

scala> a.isInstanceOf[String]
res6: Boolean = true

scala> a.isInstanceOf[Any]
res8: Boolean = true

scala> a.isInstanceOf[AnyRef]
res9: Boolean = true

scala> a.isInstanceOf[Object]
res12: Boolean = true
</code>```

答:
There are two different concepts involved: static (compile-time) type and runtime type. By declaring val a: AnyRef you only affect its static type, but at runtime its value is "hello" and so the runtime type is String. isInstanceOf tests the runtime type.

The compiler is not "assessing the value and treating a as a String"; the JVM is.

Body:
In following code, a is declared as AnyRef but its type check for type String is also true. Does Scala compiler convert the type of an object at runtime?

scala> val a:AnyRef = "hello"
a: AnyRef = hello

scala> a.isInstanceOf[String]
res6: Boolean = true

scala> a.isInstanceOf[Any]
res8: Boolean = true

scala> a.isInstanceOf[AnyRef]
res9: Boolean = true

scala> a.isInstanceOf[Object]
res12: Boolean = true


答:
You cant pass javascript to mailreader.
But you can add Email Tracking Pixel.</p>

Title: How to detect if a link was clicked through an email in gmail

Body:
I am working on an email that will be sent out as a marketing effort.
Within the email there will be a button that will allow people to "save the date" of the event and I want to be able to detect if the email was opened in gmail after the button is clicked, and if it was opened in gmail it would serve a Google Add to Calendar link - else it would serve an ICS file.

There is another email that does exactly this, it does not detect user agent since, regardless of the browser and os and device, if the email was opened in gmail it would redirect to google's add to calendar!

I've been trying to figure this out for a while now and have tried many trick, though none successful, I would love to see what other ideas people have.

Edit: I noticed that gmail will add data-saferedirecturl to all links

I'm wondering if there is a way to detect this?


问:
DocumentDB querying child elements in a document
In the DocumentDB document below, what's the correct way to query on the DevicePin? ie WHERE DevicePin = '1234'
I'm using Node.js and have the basic query working, I can query on things like Email and Name, just can't get the syntax for the DevicePin correct</p>

```<code>{
    "id": "2ca572d0-858d-4376-8537-c228a8379638",
    "Email": "dave@test.com",
    "Name": "dave",
    "OrgRoles": null,
    "DeviceIDs": [
        {
            "DeviceID": "12121212",
            "DevicePin": "1234"
        }
    ],
    "UpdatedDate": "2017-11-10T13:18:32.0110724Z",
    "CreatedDate": "2017-11-10T13:18:27.220764Z",
    "IsDeleted": true,
    "_rid": "kIddAMqgTQBFAAAAAAAAAA==",
    "_self": "dbs/kIddAA==/colls/kIddAMqgTQA=/docs/kIddAMqgTQBFAAAAAAAAAA==/",
    "_etag": "\"02007530-0000-0000-0000-5a0d685b0000\"",
    "_attachments": "attachments/",
    "_ts": 1510828123
}
</code>```

答:
If you don't know the array element number then you can use </p>

```<code> SELECT * FROM c WHERE
    array_contains(c.DeviceIDs, {"DevicePin": "1234"})
</code>```

Body:
In the DocumentDB document below, what's the correct way to query on the DevicePin? ie WHERE DevicePin = '1234'
I'm using Node.js and have the basic query working, I can query on things like Email and Name, just can't get the syntax for the DevicePin correct

{
    "id": "2ca572d0-858d-4376-8537-c228a8379638",
    "Email": "dave@test.com",
    "Name": "dave",
    "OrgRoles": null,
    "DeviceIDs": [
        {
            "DeviceID": "12121212",
            "DevicePin": "1234"
        }
    ],
    "UpdatedDate": "2017-11-10T13:18:32.0110724Z",
    "CreatedDate": "2017-11-10T13:18:27.220764Z",
    "IsDeleted": true,
    "_rid": "kIddAMqgTQBFAAAAAAAAAA==",
    "_self": "dbs/kIddAA==/colls/kIddAMqgTQA=/docs/kIddAMqgTQBFAAAAAAAAAA==/",
    "_etag": "\"02007530-0000-0000-0000-5a0d685b0000\"",
    "_attachments": "attachments/",
    "_ts": 1510828123
}

Body:
If you don't know the array element number then you can use

 SELECT * FROM c WHERE
    array_contains(c.DeviceIDs, {"DevicePin": "1234"})


问:
Laravel dusk 'No tests executed!'
I am trying to run the test that I made with laravel dusk but when I run the command php artisan dusk I get the message that he can't find any tests which I made with php artisan dusk:make. Here is the code of one of my tests:

```<code><?php

namespace Tests\Browser\Pages\Auth;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use \App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class testSignin extends DuskTestCase
{
    use DatabaseMigrations;
    public function setUp()
    {
        parent::setUp();

        $this->seed();
    }
    /**
     * @tests signin
     * @group auth
     * @return void
     */
    public function test_Signin()
    {
        $user = factory(User::class)->create();
        $this->browse(function (Browser $browser) use ($user) {
            $browser->visit('/relation')
                ->assertPathIs('/signin')
                ->type('login', $user->username)
                ->type('password', $user->password)
                ->press('Inloggen')
                ->assertPathIs('/relation');
        });
    }
}
</code>```

What is exactly wrong with my code that he can't find my test?

答:
I assume Dusk is working same way as PHPUnit.

So .... rename your file and class to SigningTest (file SigningTest.php) and mark action as test @test

Title: Laravel dusk 'No tests executed!'

Body:
I am trying to run the test that I made with laravel dusk but when I run the command php artisan dusk I get the message that he can't find any tests which I made with php artisan dusk:make. Here is the code of one of my tests:

<?php

namespace Tests\Browser\Pages\Auth;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use \App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class testSignin extends DuskTestCase
{
    use DatabaseMigrations;
    public function setUp()
    {
        parent::setUp();

        $this->seed();
    }
    /**
     * @tests signin
     * @group auth
     * @return void
     */
    public function test_Signin()
    {
        $user = factory(User::class)->create();
        $this->browse(function (Browser $browser) use ($user) {
            $browser->visit('/relation')
                ->assertPathIs('/signin')
                ->type('login', $user->username)
                ->type('password', $user->password)
                ->press('Inloggen')
                ->assertPathIs('/relation');
        });
    }
}

What is exactly wrong with my code that he can't find my test?


问:
Using expandable headerview in Swift3
I have tried several times but no luck. I made it expandable with Swift3 and I can get the JSON data but when parsing data to expandable tableview that appear only one. Here's my coding I use:

Here JSON:

```<code>"project": [
        {
            "bu_name": "IT and Digital Ecosystem Solution Delivery",
            "project_list": [
                {
                    "project_id": 8791520,
                    "project_name": "MobApps Radio"
                }
            ]
        },
        {
            "bu_name": "Business Solution, Delivery & MO",
            "project_list": [
                {
                    "project_id": 8791392,
                    "project_name": "Research and Development Hololens (Augmented Virtual Reality)"
                },
                {
                    "project_id": 8790857,
                    "project_name": "Application Development for Probis Digital Service”
                },
                {
                    "project_id": 8436483,
                    "project_name": "Non Project - Application DMO"
                },
                {
                    "project_id": 8179950,
                    "project_name": "Release Quality Improvement"
                },
                {
                    "project_id": 7548089,
                    "project_name": "Application Development"                }
            ]
        }
    ]
</code>```

Here coding get JSON data:

```<code>var perfArrProjectId = [String]()
var perfArrProjectName = [String]()
var namabu = ""

    if let itemProject = jsonData?["project"] as? NSArray {
        for i in 0..<itemProject.count {
            if let obj = itemProject[i] as? NSDictionary {
               let stringBU = obj.makeIterator().next()
                namabu = stringBU?.value as! String
                print("BU Name: \(namabu)")

                let buName2 = obj["bu_name"] as! String
                 perfArrBuName.append(buName2)

                 guard let projectList = obj["project_list"] as? [[String: Any]] else {return}

                 for list in projectList {
                     let projectId = list["project_id"] as! Int
                     let projectName = list["project_name"] as! String

                     perfArrProjectId.append(String(projectId))
                      perfArrProjectName.append(projectName)

                    print("_Project ID: \(projectId) \n_Project Name: \(projectName) \n”)

                        listPerformances = [
ModelPerformances(bussines: namaBU, projectid: perfArrProjectId, projectName: perfArrProjectName expand: false)
]

                      }
                  }
             }
        }
</code>```

Here output:

```<code>BU Name: IT and Digital Solution Delivery
__Project ID: 8791520
__Project Name: MobApps Radio

BU Name: Business Solution, Delivery & MO
__Project ID: 8791392
__Project Name: Research and Development (Augmented Virtual Reality)

__Project ID: 8790857
__Project Name: Application Development for Digital

__Project ID: 8436483
__Project Name: Non Project - Application DMO

__Project ID: 8179950
__Project Name: Release Quality Improvement Program

__Project ID: 7548089
__Project Name: Application Development
</code>```

答:
I think your problem, you dont know how many submenu item you have.

change them

```<code> perfArrProjectId.append(String(projectId))
 perfArrProjectName.append(projectName)
</code>```

with

```<code> perfArrProjectId[[String]]
 perfArrProjectName[[String]]

 inside the first for

 perfArrProjectId.append([String]())
 perfArrProjectName.append([String]())

 second for

 perfArrProjectId[i].append(String(projectId))
 perfArrProjectName[i].append(projectName)
</code>```

Title: Using expandable headerview in Swift3

Body:
I have tried several times but no luck. I made it expandable with Swift3 and I can get the JSON data but when parsing data to expandable tableview that appear only one. Here's my coding I use:

Here JSON:

"project": [
        {
            "bu_name": "IT and Digital Ecosystem Solution Delivery",
            "project_list": [
                {
                    "project_id": 8791520,
                    "project_name": "MobApps Radio"
                }
            ]
        },
        {
            "bu_name": "Business Solution, Delivery & MO",
            "project_list": [
                {
                    "project_id": 8791392,
                    "project_name": "Research and Development Hololens (Augmented Virtual Reality)"
                },
                {
                    "project_id": 8790857,
                    "project_name": "Application Development for Probis Digital Service”
                },
                {
                    "project_id": 8436483,
                    "project_name": "Non Project - Application DMO"
                },
                {
                    "project_id": 8179950,
                    "project_name": "Release Quality Improvement"
                },
                {
                    "project_id": 7548089,
                    "project_name": "Application Development"                }
            ]
        }
    ]

Here coding get JSON data:

var perfArrProjectId = [String]()
var perfArrProjectName = [String]()
var namabu = ""

    if let itemProject = jsonData?["project"] as? NSArray {
        for i in 0..<itemProject.count {
            if let obj = itemProject[i] as? NSDictionary {
               let stringBU = obj.makeIterator().next()
                namabu = stringBU?.value as! String
                print("BU Name: \(namabu)")

                let buName2 = obj["bu_name"] as! String
                 perfArrBuName.append(buName2)

                 guard let projectList = obj["project_list"] as? [[String: Any]] else {return}

                 for list in projectList {
                     let projectId = list["project_id"] as! Int
                     let projectName = list["project_name"] as! String

                     perfArrProjectId.append(String(projectId))
                      perfArrProjectName.append(projectName)

                    print("_Project ID: \(projectId) \n_Project Name: \(projectName) \n”)

                        listPerformances = [
ModelPerformances(bussines: namaBU, projectid: perfArrProjectId, projectName: perfArrProjectName expand: false)
]

                      }
                  }
             }
        }

Here output:

BU Name: IT and Digital Solution Delivery
__Project ID: 8791520
__Project Name: MobApps Radio

BU Name: Business Solution, Delivery & MO
__Project ID: 8791392
__Project Name: Research and Development (Augmented Virtual Reality)

__Project ID: 8790857
__Project Name: Application Development for Digital

__Project ID: 8436483
__Project Name: Non Project - Application DMO

__Project ID: 8179950
__Project Name: Release Quality Improvement Program

__Project ID: 7548089
__Project Name: Application Development

Body:
I think your problem, you dont know how many submenu item you have.

change them

 perfArrProjectId.append(String(projectId))
 perfArrProjectName.append(projectName)

with

 perfArrProjectId[[String]]
 perfArrProjectName[[String]]

 inside the first for

 perfArrProjectId.append([String]())
 perfArrProjectName.append([String]())

 second for

 perfArrProjectId[i].append(String(projectId))
 perfArrProjectName[i].append(projectName)


问:
Checking a column with two attributes
I have list of names that have either one checking account and/or one saving account linked to their direct deposit. 22 means checking and 32 means savings.

If they have just a checking account (22) or just a savings account (32) in the column then I want to have a '100%' in the column next to it. However, if a person has a checking and a savings account, I want to leave it blank. (We have to manually look in another software for the information)

Example

Employee #   Account      Allocated %
 100          22

 100          32

 101          22              100
 102          32              100

How would I go about this?

答:
You can group by Employee #, and have a flag that checks for a 22 and a flag that checks for 32 using a case statement.

Test Scenario

```<code>select *
into ##tempAccounts
from (
select EmployeeNum = 100, Account = 22
union all select EmployeeNum = 100, Account = 32
union all select EmployeeNum = 101, Account = 22
union all select EmployeeNum = 102, Account = 32
) x

select *  from ##tempAccounts

select
    Accounts.EmployeeNum,
    Accounts.Account,
    case when AccountStatHelper.Has22 = 1 and AccountStatHelper.Has32 = 1 then Null else '100%' end
from ##tempAccounts as Accounts
left join
(
    select
        EmployeeNum,
        Has22 = max(case when Account = 22 then 1 else 0 end),
        Has32 = max(case when Account = 32 then 1 else 0 end)
    from ##tempAccounts
    group by EmployeeNum
) AccountStatHelper on Accounts.EmployeeNum = AccountStatHelper.EmployeeNum

drop table ##tempAccounts
</code>```

Result

```<code>EmployeeNum Account
----------- ----------- ----
100         22          NULL
100         32          NULL
101         22          100%
102         32          100%
</code>```

Title: Checking a column with two attributes

Body:
You can group by Employee #, and have a flag that checks for a 22 and a flag that checks for 32 using a case statement.

Test Scenario

select *
into ##tempAccounts
from (
select EmployeeNum = 100, Account = 22
union all select EmployeeNum = 100, Account = 32
union all select EmployeeNum = 101, Account = 22
union all select EmployeeNum = 102, Account = 32
) x

select *  from ##tempAccounts

select
    Accounts.EmployeeNum,
    Accounts.Account,
    case when AccountStatHelper.Has22 = 1 and AccountStatHelper.Has32 = 1 then Null else '100%' end
from ##tempAccounts as Accounts
left join
(
    select
        EmployeeNum,
        Has22 = max(case when Account = 22 then 1 else 0 end),
        Has32 = max(case when Account = 32 then 1 else 0 end)
    from ##tempAccounts
    group by EmployeeNum
) AccountStatHelper on Accounts.EmployeeNum = AccountStatHelper.EmployeeNum

drop table ##tempAccounts

Result

EmployeeNum Account
----------- ----------- ----
100         22          NULL
100         32          NULL
101         22          100%
102         32          100%


问:
How can I use datepicker for filter in p:dateTable?
i am new in jsf with primeFaces.I am trying to filter DateTable with datepicker.I made DateTable filter when i select the date from datepicket filter works, but When I delete text from the field, the filter is still active.How can i fix that this is my code from xhtml.

```<code><p:column headerText="Date" filterBy="#{example.date}" sortBy="#{example.date}" filterMatchMode="contains">

                   <f:facet name="filter">
                        <p:calendar  pattern="dd/MM/yyyy">
                          <p:ajax event="dateSelect"  oncomplete="PF('table').filter()"/>
                         </p:calendar>
                    </f:facet>

                    <h:outputText value="#{example.date}">
                    </h:outputText>
</code>```

How can i handle event on filter text input change?

答:
I slove problem adding event "onblur". This is my code now </p>

```<code> <f:facet name="filter">
<p:calendar pattern="dd/MM/yyyy" onblur="PF('table').filter()">
<p:ajax event="dateSelect" oncomplete="PF('table').filter()" />
</p:calendar>
</f:facet>
</code>```

Body:
i am new in jsf with primeFaces.I am trying to filter DateTable with datepicker.I made DateTable filter when i select the date from datepicket filter works, but When I delete text from the field, the filter is still active.How can i fix that this is my code from xhtml.

                   <f:facet name="filter">

                    </f:facet>

                    <h:outputText value="#{example.date}">
                    </h:outputText>

How can i handle event on filter text input change?

Body:
I slove problem adding event "onblur". This is my code now

 <f:facet name="filter">
<p:calendar pattern="dd/MM/yyyy" onblur="PF('table').filter()">
<p:ajax event="dateSelect" oncomplete="PF('table').filter()" />
</p:calendar>
</f:facet>


问:
Contents of Checked List Box not showing in .copyfromscreen method
I have a print function that invokes the graphics.copyfromscreen method to take a screen shot then uses the print page event to print said screenshot. Everything is working fine for all of the controls except the contents of the Checked list box are not displaying on print Any help with getting them to show on print would be appreciated.

Here is the code for the .copyfromscreen method.

```<code>Private Sub CaptureScreen()
    Dim myGraphics As Graphics = Me.CreateGraphics()
    Dim s As Size = Me.Size
    MemoryImage = New Bitmap(s.Width, s.Height, myGraphics)
    Dim memoryGraphics As Graphics = Graphics.FromImage(MemoryImage)
    For Each ctl As Control In Me.Controls
        If TypeOf (ctl) Is Button Then
            ctl.Visible = False
        End If
    Next ctl
    Me.FormBorderStyle = FormBorderStyle.None
    memoryGraphics.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, s)
    Me.FormBorderStyle = FormBorderStyle.Sizable
    For Each ctl As Control In Me.Controls
        If TypeOf (ctl) Is Button Then
            ctl.Visible = True
        End If
    Next ctl
End Sub
</code>```

答:
Instead of taking a literal screenshot of the form, use the Control.DrawToBitmap() method to make it draw itself onto a bitmap. It should show the contents of the CheckedListBox as well as it forces it to be drawn onto the bitmap like if it were a regular form.

```<code>'Hide all buttons.
For Each btn As Button In Me.Controls.OfType(Of Button)
    btn.Visible = False
Next

'Dispose of the old bitmap to release memory.
If MemoryImage IsNot Nothing Then MemoryImage.Dispose()

MemoryImage = New Bitmap(Me.Width, Me.Height)
Me.DrawToBitmap(MemoryImage, New Rectangle(Point.Empty, Me.Size))

'Show all buttons.
For Each btn As Button In Me.Controls.OfType(Of Button)
    btn.Visible = True
Next
</code>```

Body:
I have a print function that invokes the graphics.copyfromscreen method to take a screen shot then uses the print page event to print said screenshot. Everything is working fine for all of the controls except the contents of the Checked list box are not displaying on print Any help with getting them to show on print would be appreciated.

Here is the code for the .copyfromscreen method.

Private Sub CaptureScreen()
    Dim myGraphics As Graphics = Me.CreateGraphics()
    Dim s As Size = Me.Size
    MemoryImage = New Bitmap(s.Width, s.Height, myGraphics)
    Dim memoryGraphics As Graphics = Graphics.FromImage(MemoryImage)
    For Each ctl As Control In Me.Controls
        If TypeOf (ctl) Is Button Then
            ctl.Visible = False
        End If
    Next ctl
    Me.FormBorderStyle = FormBorderStyle.None
    memoryGraphics.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, s)
    Me.FormBorderStyle = FormBorderStyle.Sizable
    For Each ctl As Control In Me.Controls
        If TypeOf (ctl) Is Button Then
            ctl.Visible = True
        End If
    Next ctl
End Sub

Body:
Instead of taking a literal screenshot of the form, use the Control.DrawToBitmap() method to make it draw itself onto a bitmap. It should show the contents of the CheckedListBox as well as it forces it to be drawn onto the bitmap like if it were a regular form.

'Hide all buttons.
For Each btn As Button In Me.Controls.OfType(Of Button)
    btn.Visible = False
Next

'Dispose of the old bitmap to release memory.
If MemoryImage IsNot Nothing Then MemoryImage.Dispose()

MemoryImage = New Bitmap(Me.Width, Me.Height)
Me.DrawToBitmap(MemoryImage, New Rectangle(Point.Empty, Me.Size))

'Show all buttons.
For Each btn As Button In Me.Controls.OfType(Of Button)
    btn.Visible = True
Next


问:
All possible 0 and 1 matrices of a normal graph
To better explain what I need, here is my first code:

```<code>function allpos = f1(x)
allpos=reshape(permute((dec2base(0:power(2,x*x)-1,2)-'0'),[3 2 1]),x,x,[]);
</code>```

This code does exactly what I need it to. If the users inputs f1(2), it returns every matrix from [0 0; 0 0] to [1 1; 1 1]. However, it also gives me a lot of useless matrices. I only want matrices that are mirrored across the diagonal, with only zeros on the diagonal.

To put more simply, for f1(3), I only want
[0 0 0; 0 0 0; 0 0 0] to [0 1 1; 1 0 1; 1 1 0]. That means that if I run the new f1(3); it will return 8 matrices, not 512.

How do I rewrite the function to do this? I know that it will require some sort of addition of a triangular matrix and its transposed self, but I cant piece it together. Thanks!

答:
A similar solution to @jodag's one, but more concise...</p>

```<code>function allops=f1(x)
allops=zeros(x,x,2^(sum(1:x-1)));
allops(find(triu(ones(x),1))+x^2*(0:2^(sum(1:x-1))-1))=[dec2base(0:2^(sum(1:x-1))-1,2)-'0'].';
allops=allops+permute(allops,[2 1 3])
end
</code>```

Body:
To better explain what I need, here is my first code:

function allpos = f1(x)
allpos=reshape(permute((dec2base(0:power(2,x*x)-1,2)-'0'),[3 2 1]),x,x,[]);

This code does exactly what I need it to. If the users inputs f1(2), it returns every matrix from [0 0; 0 0] to [1 1; 1 1]. However, it also gives me a lot of useless matrices. I only want matrices that are mirrored across the diagonal, with only zeros on the diagonal.

To put more simply, for f1(3), I only want
[0 0 0; 0 0 0; 0 0 0] to [0 1 1; 1 0 1; 1 1 0]. That means that if I run the new f1(3); it will return 8 matrices, not 512.

How do I rewrite the function to do this? I know that it will require some sort of addition of a triangular matrix and its transposed self, but I cant piece it together. Thanks!

Body:
A similar solution to @jodag's one, but more concise...

function allops=f1(x)
allops=zeros(x,x,2^(sum(1:x-1)));
allops(find(triu(ones(x),1))+x^2*(0:2^(sum(1:x-1))-1))=[dec2base(0:2^(sum(1:x-1))-1,2)-'0'].';
allops=allops+permute(allops,[2 1 3])
end


问:
Xcode Instruments: Analyze Network Traffic
i have a problem with testing my iPhone app: i want a summary of how much network traffic the app needs for a special operation.

I have tried using instruments, but the network activity monitor has no sum of the traffic (and i really neeeeeeed a sum!!!).

So how can i get the sum out of the network activity monitor?

Best regards and thank you,
Christian

答: Let your iPhone connect to wifi.  Stick a PC on the same LAN.  Now use the PC to run Wireshark and spy the traffic to and from your iPhone.  You have exact number of packets and their sizes.</p>


问:
AJAX serialized data empty
I'm trying to post form data via AJAX.

When I remove the AJAX function and do a standard form POST method the data is being inserted into DB fine. When I console.log the serialized data of the form on submit it shows fine.

It's when the AJAX function is fired that the data seemingly disappears. The function fires as a success but no data is inserted and the formdata variable is seemingly empty. Can anyone shine any light on this?

Here's the code so far -

jQuery/AJAX -

```<code>$('#calendar-form').submit(function() {
  var formdata = $(this).serialize();
  console.log(formdata);
  $.ajax({
    url: "insert.php",
    type: "POST",
    data: formdata,
    success: function() {
      alert('success')
    },
    error: function() {
      alert('ERROR');
    }
  });

  return false;
});
</code>```

HTML

```<code><form id="calendar-form" action="" method="" accept-charset="utf-8">
    <input type="text" name="name" id="name">
    <input type="text" name="email" id="email">
    <input type="hidden" name="site" id="site" value="<? echo $_SERVER['HTTP_HOST'] ?>">
    <input class="submit" type="submit" name="submit" value="Submit">
</form>
</code>```

PHP

```<code>try {
    $bd = new PDO("mysql:host=localhost;dbname=;charset=utf8", "", "");
        //  $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo 'Theres been an error while attempting to connect to the database';
    }

    if(isset($_POST['submit'])){
        $name = $_POST['name'];
        $email = $_POST['email'];
        $site = $_POST['site'];

        $sql = "INSERT INTO `users`(`name`, `email`, `site`) VALUES ('$name', '$email', '$site')";

        try {
            $query = $bd->prepare($sql);
            $query->bindValue(':name', $name, PDO::PARAM_STR);
            $query->bindValue(':email', $email, PDO::PARAM_STR);
            $query->bindValue(':site', $site, PDO::PARAM_STR);

            if($query->execute()){
                echo "Success";
            }else{
                echo "Failure";
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
</code>```

Note: I've removed DB details for this post but they're there in code.

Console

name=Benji&email=email%40email.com&site=localhost%3A8888 - scripts.min.js:9:117

Network

答:
This is because jQuery's .serialize() does not include the submit button:

No submit button value is serialized since the form was not submitted using a button.

Check the console for the output of your console.log(formdata) - you'll see submit is missing.  And since it is missing, the test you do on that value on the back end will fail:

```<code>if(isset($_POST['submit'])){
</code>```

Exactly how to do solve this depends on what you're trying to do.  If you just want to make sure the request was a POST (not a GET) you could use:

```<code>if ($_SERVER['REQUEST_METHOD'] === 'POST') {
</code>```

If you want to do basic validation, you could explicitly check each of the expected values are present:

```<code>if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['site'])) {
</code>```

Title: AJAX serialized data empty

Body:
I'm trying to post form data via AJAX.

When I remove the AJAX function and do a standard form POST method the data is being inserted into DB fine. When I console.log the serialized data of the form on submit it shows fine.

It's when the AJAX function is fired that the data seemingly disappears. The function fires as a success but no data is inserted and the formdata variable is seemingly empty. Can anyone shine any light on this?

Here's the code so far -

jQuery/AJAX -

$('#calendar-form').submit(function() {
  var formdata = $(this).serialize();
  console.log(formdata);
  $.ajax({
    url: "insert.php",
    type: "POST",
    data: formdata,
    success: function() {
      alert('success')
    },
    error: function() {
      alert('ERROR');
    }
  });

  return false;
});

HTML

<form id="calendar-form" action="" method="" accept-charset="utf-8">
    <input type="text" name="name" id="name">
    <input type="text" name="email" id="email">
    <input type="hidden" name="site" id="site" value="<? echo $_SERVER['HTTP_HOST'] ?>">
    <input class="submit" type="submit" name="submit" value="Submit">
</form>

PHP

try {
    $bd = new PDO("mysql:host=localhost;dbname=;charset=utf8", "", "");
        //  $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo 'Theres been an error while attempting to connect to the database';
    }

    if(isset($_POST['submit'])){
        $name = $_POST['name'];
        $email = $_POST['email'];
        $site = $_POST['site'];

        $sql = "INSERT INTO `users`(`name`, `email`, `site`) VALUES ('$name', '$email', '$site')";

        try {
            $query = $bd->prepare($sql);
            $query->bindValue(':name', $name, PDO::PARAM_STR);
            $query->bindValue(':email', $email, PDO::PARAM_STR);
            $query->bindValue(':site', $site, PDO::PARAM_STR);

            if($query->execute()){
                echo "Success";
            }else{
                echo "Failure";
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

Note: I've removed DB details for this post but they're there in code.

Console

name=Benji&email=email%40email.com&site=localhost%3A8888 - scripts.min.js:9:117

Network

Body:
This is because jQuery's .serialize() does not include the submit button:

No submit button value is serialized since the form was not submitted using a button.

Check the console for the output of your console.log(formdata) - you'll see submit is missing.  And since it is missing, the test you do on that value on the back end will fail:

if(isset($_POST['submit'])){

Exactly how to do solve this depends on what you're trying to do.  If you just want to make sure the request was a POST (not a GET) you could use:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

If you want to do basic validation, you could explicitly check each of the expected values are present:

if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['site'])) {


问:
Vim syntax: Spell checking some strings, but not others
This is a followup to Vim syntax: Spell checking between certain regions  I'm trying to create a syntax file for this language called Sugar Cube 2.  You can find more about it here: http://www.motoslave.net/sugarcube/2/docs/macros.html

The link has this syntax: <<link "linkText" "passageName">>  e.g.:

```<code><<link "Onward, Reginald!" "ThePassageName">>
</code>```

I would like to spell check that "Onward, Reginald!" but not "ThePassageName".  How do I do that?  I tried messing around with lines like this, but I think I'm going in the wrong direction:

```<code>syn region noSpellString  start=+"+ end=+"+ skip=+\\"+ contains=@NoSpell
syn region spellString  start=+"+ end=+"+ skip=+\\"+ nextgroup=noSpellString
syn match linkMacro "<<link\s+" nextgroup=spellString skipwhite skipempty
</code>```

答:
Your approach looks good to me. :syn region is the right choice if the strings can span multiple lines. For single-line strings, :syn match (with a suitable pattern that skips contained escaped quotes) would be better.

Your example almost works:

The linkMacro pattern needs to use \s\+ to match.

the spellString is missing the skipwhite

```<code>syn region noSpellString  start=+"+ end=+"+ skip=+\\"+ contains=@NoSpell
syn region spellString  start=+"+ end=+"+ skip=+\\"+ nextgroup=noSpellString skipwhite
syn match linkMacro "<<link\s\+" nextgroup=spellString skipwhite skipempty
</code>```

For syntax scripts, all syntax groups should start with a prefix that is equal to the syntax name. So, syntax/sugarcube2.vim should have syntax names like sugarcube2LinkMacro, sugarcube2SpellString, etc.

Body:
This is a followup to Vim syntax: Spell checking between certain regions  I'm trying to create a syntax file for this language called Sugar Cube 2.  You can find more about it here: http://www.motoslave.net/sugarcube/2/docs/macros.html

The link has this syntax: <<link "linkText" "passageName">>  e.g.:

<<link "Onward, Reginald!" "ThePassageName">>

I would like to spell check that "Onward, Reginald!" but not "ThePassageName".  How do I do that?  I tried messing around with lines like this, but I think I'm going in the wrong direction:

syn region noSpellString  start=+"+ end=+"+ skip=+\\"+ contains=@NoSpell
syn region spellString  start=+"+ end=+"+ skip=+\\"+ nextgroup=noSpellString
syn match linkMacro "<<link\s+" nextgroup=spellString skipwhite skipempty

Body:
Your approach looks good to me. :syn region is the right choice if the strings can span multiple lines. For single-line strings, :syn match (with a suitable pattern that skips contained escaped quotes) would be better.

Your example almost works:

The linkMacro pattern needs to use \s\+ to match.

the spellString is missing the skipwhite

syn region noSpellString  start=+"+ end=+"+ skip=+\\"+ contains=@NoSpell
syn region spellString  start=+"+ end=+"+ skip=+\\"+ nextgroup=noSpellString skipwhite
syn match linkMacro "<<link\s\+" nextgroup=spellString skipwhite skipempty

For syntax scripts, all syntax groups should start with a prefix that is equal to the syntax name. So, syntax/sugarcube2.vim should have syntax names like sugarcube2LinkMacro, sugarcube2SpellString, etc.


问:
What is the use of double underscore in repeat() or other steps in Tinkerpop Gremlin?
I have noticed double underscore being used in some step functions in Tinkerpop Gremlin 3.3. Could someone please tell why we use this double underscore with an example ? I could not find enough information about this in the documentation.</p>

答:
__. allows you to define an anonymous Traversal, ie. a Traversal which is not bound to a specific TraversalSource.

In the Gremlin console, all Gremlin steps are statically imported so you never need to prefix anonymous traversals with __. unless that anonymous traversal starts with a reserved keyword in the target language. In Groovy, which is the default Gremlin flavor, this is the case with in() and as() steps: because these are reserved keywords, these two steps must be prefixed with __.

In Java, you can avoid __. prefix by statically importing all steps in your program:

```<code>import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__
</code>```

See the small Note section in the documentation: http://tinkerpop.apache.org/docs/3.3.0/reference/#graph-traversal-steps

Body:
__. allows you to define an anonymous Traversal, ie. a Traversal which is not bound to a specific TraversalSource.

In the Gremlin console, all Gremlin steps are statically imported so you never need to prefix anonymous traversals with __. unless that anonymous traversal starts with a reserved keyword in the target language. In Groovy, which is the default Gremlin flavor, this is the case with in() and as() steps: because these are reserved keywords, these two steps must be prefixed with __.

In Java, you can avoid __. prefix by statically importing all steps in your program:

import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__

See the small Note section in the documentation: http://tinkerpop.apache.org/docs/3.3.0/reference/#graph-traversal-steps


问:
Validating list of variables in ng-repeat
In this plunk I have an ng-repeat of input fields. Each field has to pass two validations: (1) the value cannot be empty, and (2) if num = 1 then the value needs to be a number. I'm using ng-form in each row to validate the values independently (I cannot have the ng-repeat inside a <form>.

The problem is that messages are not displayed correctly. To replicate, in the plunk add a 1 to the third field. It becomes b1 that is not a valid number, still the Value should be a number error message is not displayed. It is displayed after you change the value again, for example to b11. Where is the problem and how to fix it?

HTML

```<code><div ng-repeat="v in vals">
  <ng-form name="formval">
      <input type="text" name="val" ng-model="v.val" style="float:left"
            ng-change="seeError(formval,v.num,v.val)" required/>
      <div ng-show="!formval.val.$valid" ng-messages="formval.val.$error" class="errorMsg">
           <div ng-message="shouldBeNumber">Value should be a number</div>
           <div ng-message="required">Value cannot be empty</div>
      </div>
      {{ 'error row #' + $index}} {{formval.val.$error}}
      <br/><br/><br/>
    </ng-form>
 </div>
</code>```

Javascript

```<code>var app = angular.module('app', []);

app.controller('ctl', function ($scope) {

    $scope.vals = [
      {val: 'a', num: 0},
      {val: 2, num: 1 },
      {val: 'b', num: 1}
    ];

    $scope.seeError = function(form,num,value){
          delete form.val.$error.shouldBeNumber;
          if (value && value.trim()==="") // omit as form will show an error
              return;
          if (num===1) // should be a number
              if (isNaN(parseFloat(value)))
                  form.val.$error.shouldBeNumber = true;
    };

});
</code>```

答:
when the list is initially displayed ng-change is not fired because

The ngChange expression is only evaluated when a change in the input
  value causes a new value to be committed to the model.

It will not be evaluated:

if the value returned from the $parsers transformation pipeline has not changed

if the input has continued to be invalid since the model will stay null

if the model is changed programmatically and not by a change to the input value

you can use a custom filter to achieve the same behaviour

html

```<code><div ng-repeat="v in vals | filter:checkError">
</div>
</code>```

js

```<code>$scope.checkError = function (item) {

    if(item.val is not number)
        displayError = true;

    return true;
};
</code>```

Body:
In this plunk I have an ng-repeat of input fields. Each field has to pass two validations: (1) the value cannot be empty, and (2) if num = 1 then the value needs to be a number. I'm using ng-form in each row to validate the values independently (I cannot have the ng-repeat inside a <form>.

The problem is that messages are not displayed correctly. To replicate, in the plunk add a 1 to the third field. It becomes b1 that is not a valid number, still the Value should be a number error message is not displayed. It is displayed after you change the value again, for example to b11. Where is the problem and how to fix it?

HTML

  <ng-form name="formval">
      <input type="text" name="val" ng-model="v.val" style="float:left"
            ng-change="seeError(formval,v.num,v.val)" required/>

Value should be a number

Value cannot be empty

      {{ 'error row #' + $index}} {{formval.val.$error}}

    </ng-form>

Javascript

var app = angular.module('app', []);

app.controller('ctl', function ($scope) {

    $scope.vals = [
      {val: 'a', num: 0},
      {val: 2, num: 1 },
      {val: 'b', num: 1}
    ];

    $scope.seeError = function(form,num,value){
          delete form.val.$error.shouldBeNumber;
          if (value && value.trim()==="") // omit as form will show an error
              return;
          if (num===1) // should be a number
              if (isNaN(parseFloat(value)))
                  form.val.$error.shouldBeNumber = true;
    };

});

Body:
when the list is initially displayed ng-change is not fired because

The ngChange expression is only evaluated when a change in the input
  value causes a new value to be committed to the model.

It will not be evaluated:

if the value returned from the $parsers transformation pipeline has not changed

if the input has continued to be invalid since the model will stay null

if the model is changed programmatically and not by a change to the input value

you can use a custom filter to achieve the same behaviour

html

<div ng-repeat="v in vals | filter:checkError">
</div>

js

$scope.checkError = function (item) {

    if(item.val is not number)
        displayError = true;

    return true;
};


问:
Get rid of custom menu items from UIMenuController
I am using UITableViewController. If I long press on a tableview cell I am creating custom menus in the UIMenuController and which is working fine (Forward, Reply). In the same view I have the textview in the bottom. If I tap on it should display the normal actions but it doesn't. It comes with default items as well as what are the items I have added for the tableview cell (Forward, Reply). How to remove the custom items from the UIMenuController or how to perform the action for a particular cell.

Inside the cell I have an UIImageView. I have added gestures to perform the action.

答:
Swift3:
in viewDidLoad of ViewController:</p>

```<code> NotificationCenter.default.addObserver(self, selector: #selector(menuControllerWillHide), name: NSNotification.Name.UIMenuControllerWillHideMenu, object: nil)

func menuControllerWillHide(notification:NSNotification){
    UIMenuController.shared.menuItems = []
}
</code>```

Body:
Swift3:
in viewDidLoad of ViewController:

 NotificationCenter.default.addObserver(self, selector: #selector(menuControllerWillHide), name: NSNotification.Name.UIMenuControllerWillHideMenu, object: nil)

func menuControllerWillHide(notification:NSNotification){
    UIMenuController.shared.menuItems = []
}


问:
Documentation examples for non-trivial ES6 code
I am struggling to find decent documentation samples/references to document ES6 code, like some sort of cheatsheet for ES6 documentation.

I'd like to align on JSDoc documentation, however amongst the most common answers to this question, I can only manage to find trivial code documentation, and not documentation that fits new ES6+/React syntaxes or more complex params like Arrays, maps, param deserializations, etc..

For instance does-javascript-have-a-standard-for-commenting-functions gives only documentation examples regarding regular JS function with standard params.

I'd like to find rules / nice way to document something like this, how to indicate params that are required or not, etc.

An exemple of method I'd like to document

```<code>const signInWithCredentials = ({ emails, password, authentication_code }, options) => {

}
</code>```

I can think of something like this

```<code>**
 * Attempts sign in with any possible credentials pair
 * (Provide either email + password, or an authentication_code and a provider name in the options
 * @param {
 *   emails: { Array<String> },
 *   password: { String },
 *   authentication_code: { String }
 * } - credentials
 * @param { Object } - options
 * @param { String } - options.provider
</code>```

But I'm not really sure how to handle deserialized params that don't really have a name function({ param1, param2 }), are nested function({ param1: { nestedParam1, nestedParam2 }) or are renamed function({ param1: name1 }) and how to handle composed types like an array of xxx

I am already using PropTypes for several method declarations but they only work when using React components, but are less useful when writing utility functions, etc. outside of react.

答:
Nevermind, I just realized the JSDoc had an official page with documentation samples and that this included a section regarding destructuration

http://usejsdoc.org/tags-param.html

```<code>Documenting a destructuring parameter
/**
 * Assign the project to an employee.
 * @param {Object} employee - The employee who is responsible for the project.
 * @param {string} employee.name - The name of the employee.
 * @param {string} employee.department - The employee's department.
 */
Project.prototype.assign = function({ name, department }) {
    // ...
};
</code>```

Body:
I am struggling to find decent documentation samples/references to document ES6 code, like some sort of cheatsheet for ES6 documentation.

I'd like to align on JSDoc documentation, however amongst the most common answers to this question, I can only manage to find trivial code documentation, and not documentation that fits new ES6+/React syntaxes or more complex params like Arrays, maps, param deserializations, etc..

For instance does-javascript-have-a-standard-for-commenting-functions gives only documentation examples regarding regular JS function with standard params.

I'd like to find rules / nice way to document something like this, how to indicate params that are required or not, etc.

An exemple of method I'd like to document

const signInWithCredentials = ({ emails, password, authentication_code }, options) => {

}

I can think of something like this

**
 * Attempts sign in with any possible credentials pair
 * (Provide either email + password, or an authentication_code and a provider name in the options
 * @param {
 *   emails: { Array<String> },
 *   password: { String },
 *   authentication_code: { String }
 * } - credentials
 * @param { Object } - options
 * @param { String } - options.provider

But I'm not really sure how to handle deserialized params that don't really have a name function({ param1, param2 }), are nested function({ param1: { nestedParam1, nestedParam2 }) or are renamed function({ param1: name1 }) and how to handle composed types like an array of xxx

I am already using PropTypes for several method declarations but they only work when using React components, but are less useful when writing utility functions, etc. outside of react.

Body:
Nevermind, I just realized the JSDoc had an official page with documentation samples and that this included a section regarding destructuration

http://usejsdoc.org/tags-param.html

Documenting a destructuring parameter
/**
 * Assign the project to an employee.
 * @param {Object} employee - The employee who is responsible for the project.
 * @param {string} employee.name - The name of the employee.
 * @param {string} employee.department - The employee's department.
 */
Project.prototype.assign = function({ name, department }) {
    // ...
};


问:
Drag item outside the scrollable container
So the "item" is draggable, but it disappears when I try to move it outside the scrollable container. I have tried with z-index but it does not seem to work. Any idea what could be wrong?

A working pen: https://codepen.io/anon/pen/ZaXVaE

```<code>body {
  background-color: lightyellow;
}

.container {
  height: 500px;
  width: 300px;
  margin: 0 auto;
  overflow-y: scroll;
  background: #ccc;
}

.item {
  border: 1px solid blue;
  width: 100px;
  margin: 0 auto;
  z-index: 9999;
}

<div class="container">
  <div class="item">
    Move me
  </div>
</div>

$(".item").draggable({revert: true});
</code>```

答:
Only one way to do this is to duplicate item in body and move this copied item.
Original item can be hidden till the end of moving.

```<code>$( ".item" ).clone().appendTo( "body" ).draggable({revert: true});
</code>```

Or even better, use native functionality of draggable element

$( ".selector" ).draggable({
  helper: "clone"
});

Body:
So the "item" is draggable, but it disappears when I try to move it outside the scrollable container. I have tried with z-index but it does not seem to work. Any idea what could be wrong?

A working pen: https://codepen.io/anon/pen/ZaXVaE

body {
  background-color: lightyellow;
}

.container {
  height: 500px;
  width: 300px;
  margin: 0 auto;
  overflow-y: scroll;
  background: #ccc;
}

.item {
  border: 1px solid blue;
  width: 100px;
  margin: 0 auto;
  z-index: 9999;
}

    Move me

$(".item").draggable({revert: true});

Body:
Only one way to do this is to duplicate item in body and move this copied item.
Original item can be hidden till the end of moving.

$( ".item" ).clone().appendTo( "body" ).draggable({revert: true});

Or even better, use native functionality of draggable element

$( ".selector" ).draggable({
  helper: "clone"
});


问:
Ant flagrantly ignoring JAVA_HOME environment variable
I just picked up the latest version of the Android SDK and started trying to use it. Unlike almost everyone else coming up with this problem, I'm running Linux, namely Linux Mint 13. I'm currently trying to compile a Hello World program using ant, installed via

```<code>sudo apt-get install ant
</code>```

and ran in the project folder:

```<code>ant debug
</code>```

However, it fails utterly to compile, eventually spitting out an error to do with setting JAVA_HOME. I amended my ~/.bashrc file  accordingly and restarted, but I still get the error:

```<code>Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "/usr/lib/jvm/java-7-openjdk-amd64/jre"

Total time: 1 second
jamie@jamie-ThinkPad-E525 ~/Downloads/adt-bundle-linux/sdk/tools/projects/new $ echo $JAVA_HOME
/usr/java/jdk1.7.0_05/
</code>```

As you can see, it's lying through its teeth.

I've found lots of references to this problem, but most people have either set their JAVA_HOME incorrectly, or set it to the JRE. Clearly, I have done neither.

I also amended my project folder's ant.properties file, adding the line

java.home=/usr/java/jdk1.7.0_05/

to no avail.

Has anyone else experienced/solved this problem, or got any ideas? Thanks.

答:
I have a server with ant 1.9.1. It needs an environment variable ANT_RESPECT_JAVA_HOME set, or it will flagrantly ignore the JAVA_HOME environment variable.  that does not seem to be the case on another server with ant 1.9.6.

So, depending on you version of ant you might need to add

```<code>export ANT_RESPECT_JAVA_HOME=true
</code>```

in addition to

```<code>export JAVA_HOME=/usr/java/jdk1.7.0_05/
</code>```

Hope that this helps someone as it took me way too long to discover...

Body:
I just picked up the latest version of the Android SDK and started trying to use it. Unlike almost everyone else coming up with this problem, I'm running Linux, namely Linux Mint 13. I'm currently trying to compile a Hello World program using ant, installed via

sudo apt-get install ant

and ran in the project folder:

ant debug

However, it fails utterly to compile, eventually spitting out an error to do with setting JAVA_HOME. I amended my ~/.bashrc file  accordingly and restarted, but I still get the error:

Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "/usr/lib/jvm/java-7-openjdk-amd64/jre"

Total time: 1 second
jamie@jamie-ThinkPad-E525 ~/Downloads/adt-bundle-linux/sdk/tools/projects/new $ echo $JAVA_HOME
/usr/java/jdk1.7.0_05/

As you can see, it's lying through its teeth.

I've found lots of references to this problem, but most people have either set their JAVA_HOME incorrectly, or set it to the JRE. Clearly, I have done neither.

I also amended my project folder's ant.properties file, adding the line

java.home=/usr/java/jdk1.7.0_05/

to no avail.

Has anyone else experienced/solved this problem, or got any ideas? Thanks.

Body:
I have a server with ant 1.9.1. It needs an environment variable ANT_RESPECT_JAVA_HOME set, or it will flagrantly ignore the JAVA_HOME environment variable.  that does not seem to be the case on another server with ant 1.9.6.

So, depending on you version of ant you might need to add

export ANT_RESPECT_JAVA_HOME=true

in addition to

export JAVA_HOME=/usr/java/jdk1.7.0_05/

Hope that this helps someone as it took me way too long to discover...