问:
What is wrong with my solution of SPOJ ACTIV?
Here is the link for the problem:SPOJ - ACTIV

I came up with the recurrence for the problem as:

```<code>F(i) = 1+F(i+1)+F(next(activities[i].endtime))
</code>```

where next() finds out the index of the activity with start time>= end time of the current activity, while the activities have been sorted in increasing order of their Start time.

This is my java solution, although it passes many test cases of SPOJ toolkit, however it does give WA for some. What is the problem in my concept/solution?

```<code>import java.util.*;
import java.io.*;
class Pair<T>{
    final T x;
    final T y;
    Pair(T a, T b){
        this.x = a;
        this.y = b;
    }
}

public class Activities{
    private static int search(Pair<Integer> []p,int key, int l, int h)
    {
        int ll=l;
        while(l<h)
        {
            int mid = (l+h)/2;
            if(p[mid].x < key)l=mid+1;
            else if(p[mid].x == key){
                while(mid>=ll && p[mid].x == key)mid--;
                return mid+1;
            }
            else h=mid;
        }
        if(l==h && l>=0 && p[l].x>=key)return l;
        return -1;
    }
    public static void main(String[] args)throws IOException {
        final long mod = 100000000;
        BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
    while(true)
    {
        int n = Integer.parseInt(buff.readLine());
        if(n==-1)return;
        Pair <Integer> p [] = new Pair[n];
        for(int i=0;i<n;i++){
            String [] in = buff.readLine().split(" ");
            int x = Integer.parseInt(in[0]), y = Integer.parseInt(in[1]);
            p[i] = new <Integer>Pair(x,y);
        }
        Arrays.sort(p, new Comparator<Pair<Integer>>(){
            public int compare(Pair<Integer> p1, Pair<Integer> p2){
                if(p1.x == p2.x)return p1.y - p2.y;
                else return p1.x - p2.x;
            }
        });

        long dp[] = new long[n];
        dp[n-1] = 1;
        for(int i=n-2;i>=0;i--)
        {
            int idx = search(p,p[i].y,i,n-1);
            dp[i] = 1+dp[i+1];
            if(idx != -1)dp[i]=dp[i]+dp[idx];
        }
        String res = (dp[0]%mod)+"";
        while(res.length()<8)res = '0'+res;
        System.out.println(res);
    }

}
}
</code>```

答:
Your code is able to exceed a long type scope. You should perform your calculation with more frequent casting to the [0, mod) range. This should be enough to fix your issue and solve this Spoj's problem:

```<code>for(int i=n-2;i>=0;i--)
{
    int idx = search(p,p[i].y,i,n-1);
    dp[i] = 1+dp[i+1]%mod;
    if(idx != -1)dp[i]=(dp[i]%mod+dp[idx]%mod)%mod;
}
</code>```

Body:
Here is the link for the problem:SPOJ - ACTIV

I came up with the recurrence for the problem as:

F(i) = 1+F(i+1)+F(next(activities[i].endtime))

where next() finds out the index of the activity with start time>= end time of the current activity, while the activities have been sorted in increasing order of their Start time.

This is my java solution, although it passes many test cases of SPOJ toolkit, however it does give WA for some. What is the problem in my concept/solution?

import java.util.*;
import java.io.*;
class Pair<T>{
    final T x;
    final T y;
    Pair(T a, T b){
        this.x = a;
        this.y = b;
    }
}

public class Activities{
    private static int search(Pair<Integer> []p,int key, int l, int h)
    {
        int ll=l;
        while(l<h)
        {
            int mid = (l+h)/2;
            if(p[mid].x < key)l=mid+1;
            else if(p[mid].x == key){
                while(mid>=ll && p[mid].x == key)mid--;
                return mid+1;
            }
            else h=mid;
        }
        if(l==h && l>=0 && p[l].x>=key)return l;
        return -1;
    }
    public static void main(String[] args)throws IOException {
        final long mod = 100000000;
        BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
    while(true)
    {
        int n = Integer.parseInt(buff.readLine());
        if(n==-1)return;
        Pair <Integer> p [] = new Pair[n];
        for(int i=0;i<n;i++){
            String [] in = buff.readLine().split(" ");
            int x = Integer.parseInt(in[0]), y = Integer.parseInt(in[1]);
            p[i] = new <Integer>Pair(x,y);
        }
        Arrays.sort(p, new Comparator<Pair<Integer>>(){
            public int compare(Pair<Integer> p1, Pair<Integer> p2){
                if(p1.x == p2.x)return p1.y - p2.y;
                else return p1.x - p2.x;
            }
        });

        long dp[] = new long[n];
        dp[n-1] = 1;
        for(int i=n-2;i>=0;i--)
        {
            int idx = search(p,p[i].y,i,n-1);
            dp[i] = 1+dp[i+1];
            if(idx != -1)dp[i]=dp[i]+dp[idx];
        }
        String res = (dp[0]%mod)+"";
        while(res.length()<8)res = '0'+res;
        System.out.println(res);
    }

}
}

Body:
Your code is able to exceed a long type scope. You should perform your calculation with more frequent casting to the [0, mod) range. This should be enough to fix your issue and solve this Spoj's problem:

for(int i=n-2;i>=0;i--)
{
    int idx = search(p,p[i].y,i,n-1);
    dp[i] = 1+dp[i+1]%mod;
    if(idx != -1)dp[i]=(dp[i]%mod+dp[idx]%mod)%mod;
}


来源: stackexchange

问:
show ProgressBar above WebView so that it does not hide when scrolling down WebView
I have a ProgressBar as a child of WebView, which works fine.

Problem is When I scroll the WebView up, the progress bar hides.
Here is my activity_main.xml

```<code> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ionicframework.VendeeTouch.MainActivity">

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <ProgressBar
            android:id="@+id/progressbar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_x="5dp"
            android:layout_y="26dp"
            android:padding="2dip"></ProgressBar>

        <TextView
            android:id="@+id/tV1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="119dp"
            android:layout_y="286dp"
            android:text="Loading, please wait . . ."
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#000000"></TextView>
    </WebView>

</RelativeLayout>
</code>```

How do I keep it fixed at the top so that when I scroll down it does not hide?

答:
Set windowSoftInputMode to adjustResize for your activity in which you are using this web view. It will adjust the screen.

```<code>   <activity android:name=".Your Activity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize">
    </activity>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a ProgressBar as a child of WebView, which works fine.

Problem is When I scroll the WebView up, the progress bar hides.
Here is my activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ionicframework.VendeeTouch.MainActivity">

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <ProgressBar
            android:id="@+id/progressbar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_x="5dp"
            android:layout_y="26dp"
            android:padding="2dip"></ProgressBar>

        <TextView
            android:id="@+id/tV1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="119dp"
            android:layout_y="286dp"
            android:text="Loading, please wait . . ."
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#000000"></TextView>
    </WebView>

</RelativeLayout>

How do I keep it fixed at the top so that when I scroll down it does not hide?

Body:
Set windowSoftInputMode to adjustResize for your activity in which you are using this web view. It will adjust the screen.

   <activity android:name=".Your Activity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize">
    </activity>


问:
SMTP connect() failed. While Sending Authentication Email
I'm Trying to send email via php by using php mailer, but it's showing SMTP connect() failed. here is my code. can't find out what is problem in that. if somebody help to track error it will be very helpful for me.

```<code>$mail = new PHPMailer;

$mail->isSMTP();                                   // Set mailer to use SMTP
$mail->Host = 'dds.uemtv.com';                    // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                            // Enable SMTP authentication
$mail->Username = 'no-reply@domain.com';          // SMTP username
$mail->Password = 'pssword'; // SMTP password
$mail->SMTPSecure = 'tls';                         // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                 // TCP port to connect to

$mail->setFrom('no-reply@domain.com', 'title');
$mail->addReplyTo($email, '$name');
$mail->addAddress($email);   // Add a recipient
//$mail->addCC('cc@example.com');
//$mail->addBCC('bcc@example.com');

$mail->isHTML(true);  // Set email format to HTML

$bodyContent = '<h1>Your Registration Completed. </h1>'
$mail->Subject = 'Verify Account- Rozgar';
$mail->Body    = $bodyContent;
if(!$mail->send()) {

    echo $data->msg = $mail->ErrorInfo;
} else {
    // echo 'Message has been sent';
    echo $data->msg="Please Verify Your Email Address";
}
</code>```

Showing this error.

2017-06-07 05:36:44 SERVER -> CLIENT: 220-dds.uemtv.com ESMTP Exim 4.89 #1 Wed, 07 Jun 2017 10:36:40 +0500 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.

  2017-06-07 05:36:44  CLIENT -> SERVER: EHLO localhost

  2017-06-07 05:36:44  SERVER -> CLIENT: 250-dds.uemtv.com Hello localhost  [182.186.132.245] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-STARTTLS 250 HELP

  2017-06-07 05:36:44  CLIENT -> SERVER: STARTTLS

  2017-06-07 05:36:45  SERVER -> CLIENT: 220 TLS go ahead

  2017-06-07 05:36:46  CLIENT -> SERVER: EHLO localhost

  2017-06-07 05:36:47  SERVER -> CLIENT: 250-dds.uemtv.com Hello localhost [182.186.132.245] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-AUTH PLAIN LOGIN 250 HELP

  2017-06-07 05:36:47  CLIENT -> SERVER: AUTH LOGIN

  2017-06-07 05:36:47  SERVER -> CLIENT: 334 VXNlcm5hbWU6

  2017-06-07 05:36:47  CLIENT -> SERVER: xxx=

  2017-06-07 05:36:47  SERVER -> CLIENT: 334 UGFzc3dvcmQ6

  2017-06-07 05:36:47  CLIENT -> SERVER: xxx

  2017-06-07 05:36:49  SERVER -> CLIENT: 535 Incorrect authentication data

  2017-06-07 05:36:49  SMTP ERROR: Password command failed: 535 Incorrect authentication data

  2017-06-07 05:36:49  SMTP Error: Could not authenticate.

  2017-06-07 05:36:49  CLIENT -> SERVER: QUIT

  2017-06-07 05:36:50  SERVER -> CLIENT: 221 dds.uemtv.com closing connection

  2017-06-07 05:36:50  SMTP connect() failed.  https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

答: There's probably nothing wrong with your code. The server you are using doesn't allow relaying without authentication. There's authentication errors in your log, so perhaps you're using incorrect credentials. </p>

Body:
I'm Trying to send email via php by using php mailer, but it's showing SMTP connect() failed. here is my code. can't find out what is problem in that. if somebody help to track error it will be very helpful for me.

$mail = new PHPMailer;

$mail->isSMTP();                                   // Set mailer to use SMTP
$mail->Host = 'dds.uemtv.com';                    // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                            // Enable SMTP authentication
$mail->Username = 'no-reply@domain.com';          // SMTP username
$mail->Password = 'pssword'; // SMTP password
$mail->SMTPSecure = 'tls';                         // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                 // TCP port to connect to

$mail->setFrom('no-reply@domain.com', 'title');
$mail->addReplyTo($email, '$name');
$mail->addAddress($email);   // Add a recipient
//$mail->addCC('cc@example.com');
//$mail->addBCC('bcc@example.com');

$mail->isHTML(true);  // Set email format to HTML

$bodyContent = '
Your Registration Completed.
'
$mail->Subject = 'Verify Account- Rozgar';
$mail->Body    = $bodyContent;
if(!$mail->send()) {

    echo $data->msg = $mail->ErrorInfo;
} else {
    // echo 'Message has been sent';
    echo $data->msg="Please Verify Your Email Address";
}

Showing this error.

2017-06-07 05:36:44 SERVER -> CLIENT: 220-dds.uemtv.com ESMTP Exim 4.89 #1 Wed, 07 Jun 2017 10:36:40 +0500 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.

  2017-06-07 05:36:44  CLIENT -> SERVER: EHLO localhost

  2017-06-07 05:36:44  SERVER -> CLIENT: 250-dds.uemtv.com Hello localhost  [182.186.132.245] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-STARTTLS 250 HELP

  2017-06-07 05:36:44  CLIENT -> SERVER: STARTTLS

  2017-06-07 05:36:45  SERVER -> CLIENT: 220 TLS go ahead

  2017-06-07 05:36:46  CLIENT -> SERVER: EHLO localhost

  2017-06-07 05:36:47  SERVER -> CLIENT: 250-dds.uemtv.com Hello localhost [182.186.132.245] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-AUTH PLAIN LOGIN 250 HELP

  2017-06-07 05:36:47  CLIENT -> SERVER: AUTH LOGIN

  2017-06-07 05:36:47  SERVER -> CLIENT: 334 VXNlcm5hbWU6

  2017-06-07 05:36:47  CLIENT -> SERVER: xxx=

  2017-06-07 05:36:47  SERVER -> CLIENT: 334 UGFzc3dvcmQ6

  2017-06-07 05:36:47  CLIENT -> SERVER: xxx

  2017-06-07 05:36:49  SERVER -> CLIENT: 535 Incorrect authentication data

  2017-06-07 05:36:49  SMTP ERROR: Password command failed: 535 Incorrect authentication data

  2017-06-07 05:36:49  SMTP Error: Could not authenticate.

  2017-06-07 05:36:49  CLIENT -> SERVER: QUIT

  2017-06-07 05:36:50  SERVER -> CLIENT: 221 dds.uemtv.com closing connection

  2017-06-07 05:36:50  SMTP connect() failed.  https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting


问:
call mono_method(pointer) from c
i have mono code

public static unsafe int* mono_method (int* p)

{

//....

return p;

}

and want to call it from native c

MonoObject *result = mono_runtime_invoke(mono_method, NULL, args, NULL);

I tried out some different pointers, variables in the args flag (should be void**)

but always get SIGSEGV error when i execute the runtime invoke.

My question is:
Is it possible to pass pointers from c to mono via runtime_invoke and how?

best regards.

答: This question was just asked here, but take a look this for the answer.</p>

ContentLicense: CC BY-SA 2.5

Title: call mono_method(pointer) from c


问:
Old value in multiple select option in laravel blade
Here is my select option

```<code><select name="recomemded_food[]" value="" style="width:560px;" multiple class="chosen-select" >
<option value="American Black Bear">American Black Bear</option>
<option value="Asiatic Black Bear">Asiatic Black Bear</option>
<option value="Brown Bear">Brown Bear</option>
<option value="Giant Panda">Giant Panda</option>
</select>
</code>```

And below is my code trying to use the foreach loop to get the array value. but I am receiving the following error:

```<code>@foreach (explode(',',old('recomemded_food')) as $recomemded_food)
{{$recomemded_food}}
@endforeach
</code>```

Error Message : explode() expects parameter 2 to be string

答:
The question was asked for multiple chosen.

Assuming you have a field called designation and you need to choose multiple designation for adding 1 record and the field name is forWhom

During Add

You need to add this {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}  peace of code to your option tag

which will look like

```<code><select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
    <option value="">--- Select ---</option>
    @foreach ($desgInfo as $key => $value)
        <option value="{{ $key }}"
           {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}  />
           {{ $value }}
        </option>
    @endforeach
</select>
</code>```

During Edit

You need to add

```<code>{{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}

{{ (in_array($key,$info->forWhom)) ? 'selected' : ''}}
</code>```

which will look like

```<code><select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
        <option value="">--- Select ---</option>
        @foreach ($desgInfo as $key => $value)
            <option value="{{ $key }}"
               {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}
               {{ (in_array($key,$info->forWhom)) ? 'selected' : ''}}
               />
               {{ $value }}
            </option>
        @endforeach
    </select>
</code>```

Select all selected id's in a multiselect dropdown in laravel 5.4 with harvest chosen

Thanks

Body:
Here is my select option

<select name="recomemded_food[]" value="" style="width:560px;" multiple class="chosen-select" >
<option value="American Black Bear">American Black Bear</option>
<option value="Asiatic Black Bear">Asiatic Black Bear</option>
<option value="Brown Bear">Brown Bear</option>
<option value="Giant Panda">Giant Panda</option>
</select>

And below is my code trying to use the foreach loop to get the array value. but I am receiving the following error:

@foreach (explode(',',old('recomemded_food')) as $recomemded_food)
{{$recomemded_food}}
@endforeach

Error Message : explode() expects parameter 2 to be string

Body:
The question was asked for multiple chosen.

Assuming you have a field called designation and you need to choose multiple designation for adding 1 record and the field name is forWhom

During Add

You need to add this {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}  peace of code to your option tag

which will look like

<select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
    <option value="">--- Select ---</option>
    @foreach ($desgInfo as $key => $value)
        <option value="{{ $key }}"
           {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}  />
           {{ $value }}
        </option>
    @endforeach
</select>

During Edit

You need to add

{{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}

{{ (in_array($key,$info->forWhom)) ? 'selected' : ''}}

which will look like

<select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
        <option value="">--- Select ---</option>
        @foreach ($desgInfo as $key => $value)
            <option value="{{ $key }}"
               {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}
               {{ (in_array($key,$info->forWhom)) ? 'selected' : ''}}
               />
               {{ $value }}
            </option>
        @endforeach
    </select>

Select all selected id's in a multiselect dropdown in laravel 5.4 with harvest chosen

Thanks


问:
Intalling pg-trajectory on windows
I am trying to install pg-trajectory on windows through mingw command window and while entering this line

```<code>$ mingw32-make PG_CONFIG=E:\PostgreSQL\9.5\bin\pg_config.exe
</code>```

I am encountering this error:

```<code>Process_begin: CreateProcess(NULL, E:PostgresSQL9.5binpg_config.exe –pgxs, …) failed

Mingw32-make: *** No targets. Stop.
</code>```

Is there is an alternative or solution to this? Kindly inform me

答:
Download library from source: https://bitbucket.org/gsudmlab/pg-trajectory

Execute pg_trajectory--0.0.1.sql file.

To execute, you can copy it and paste to psql or use command \q pg_trajectory--0.0.1.sql

Make sure you installed pre-requisite (PostGIS).

Alternatively, install.sh script should work as well.

Title: Intalling pg-trajectory on windows

Body:
I am trying to install pg-trajectory on windows through mingw command window and while entering this line

$ mingw32-make PG_CONFIG=E:\PostgreSQL\9.5\bin\pg_config.exe

I am encountering this error:

Process_begin: CreateProcess(NULL, E:PostgresSQL9.5binpg_config.exe –pgxs, …) failed

Mingw32-make: *** No targets. Stop.

Is there is an alternative or solution to this? Kindly inform me


问:
how to make text over images in a row using bootstrap?
Now it is not responsive, the two images should be in one row. I want to make text like painting and photography over these images. how can it be possible?

.caption {
  position: absolute;
  top: 9%;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.caption1 {
  position: absolute;
  top: -51px;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.imageandtext {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-two imageandtext">
  <figure>

    <img src="http://lorempixel.com/300/300/" class="img-thumbnail">
    <div class="caption">
      <p>Painting</p>
    </div>
    <div class="imageandtext image_grid">
      <img src="http://lorempixel.com/300/300/?r" class="img-thumbnail">
      <div class="caption1">
        <p>Photography</p>
      </div>
    </div>
  </figure>
</div></code>```

答:
Modified your HTML and CSS a bit

.image_and_text {
  position: relative;
}

.image_and_text .caption {
  position: absolute;
  top: auto;
  bottom: 0px;
  left: 30px;
  color: white;
  text-shadow: 2px 0px 6px rgba(0, 0, 0, 0.5);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row">
    <div class="col-xs-6 image_and_text">
      <img src="http://lorempixel.com/300/300/" class="img-responsive img-thumbnail">
      <div class="caption">
        <p>Painting</p>
      </div>
    </div>
    <div class="col-xs-6 image_and_text">
      <img src="http://lorempixel.com/300/300/?r" class="img-responsive img-thumbnail">
      <div class="caption">
        <p>Photography</p>
      </div>
    </div>
  </div>
</div></code>```

Body:
Now it is not responsive, the two images should be in one row. I want to make text like painting and photography over these images. how can it be possible?

.caption {
  position: absolute;
  top: 9%;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.caption1 {
  position: absolute;
  top: -51px;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.imageandtext {
  position: relative;
}

Painting

Photography

Body:
Modified your HTML and CSS a bit

.image_and_text {
  position: relative;
}

.image_and_text .caption {
  position: absolute;
  top: auto;
  bottom: 0px;
  left: 30px;
  color: white;
  text-shadow: 2px 0px 6px rgba(0, 0, 0, 0.5);
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row">
    <div class="col-xs-6 image_and_text">
      <img src="http://lorempixel.com/300/300/" class="img-responsive img-thumbnail">
      <div class="caption">
        <p>Painting</p>
      </div>
    </div>
    <div class="col-xs-6 image_and_text">
      <img src="http://lorempixel.com/300/300/?r" class="img-responsive img-thumbnail">
      <div class="caption">
        <p>Photography</p>
      </div>
    </div>
  </div>
</div>


问:
Spark word2vec example explanation and how to get similarity between strings
I followed the example in the Spark documentation page to use word2vec, link. It worked but I didn't quite understand what it is trying to compute.

Are the output vectors the output strings representation?

If yes, I tried to compute the cosine similarity between them but I got negative values because the vectors are not positive.

Can Spark word2vec create positive only vectors?

How to compute similarity between a list of strings using Spark word2vec?

答:
The output vector(by using transform on dataset) is a representation of the document(possibly sentence or sentences) which is supplied to the model .So; in essence this output is a combination of all the vector representation of each of the words in the given document(most likely a simple vector sum).

You can use findSynonyms to get "num" number of words closest in similarity to the given word. findSynonyms is based on cosine similarity only.
     Currently I am using it to generate feature Vectors which I am using as input to  another model.

In order to compute similarity between two strings as some kind of a no. you would need to implement some variation of findSynonyms method.The current implementation generates a cosVec corresponding to input string and then tries to find the word Vecs which are closest to this vec .

I am not sure about the part whether it can create only positive vectors and whether it is at all required/(makes sense) to generate only positive vectors.


问:
openpyxl causing loss of existing DataValidation in excel
I am importing an existing excel sheet using openpyxl and attempting to fill in some values and resave, but I noticed that the existing Data Validation dropdown boxes in the spreadsheet get messed up when doing so.  This happens even when just loading the spreadsheet, doing no other operations, and then resaving, so it seems to be something intrinsic with openpyxl.  The Data Validation in the spreadsheet consists of dropboxes in certain cells which take their possible values from a set of other cells about 20 columns over (this is to generate QC reports for a company).  For example cell C13 has an initial Data Validation "source" of $Z$6:$AB$6, but after loading and saving the excel sheet it is erroneously changed to $Z$5:$AB$5 for that cell.  Strangely, this is not consistent across all cells; some cells remain with the correct range, and some cells are five or so rows off instead.  It looks like it is only off by rows, not columns.  All of the cells with Data Validation are merged, I'm not sure if that matters or not.  Does anyone know why this may happen, or how to fix it?  There is not much code to show, but here is a simple example of a load/save function that will cause this problem:

```<code>    wb = load_workbook(filename='myspreadsheet.xlsx')
    wb.save('myspreadsheet.xlsx')
</code>```

Thanks in advance!
Robert

答:
It might be that your excel sheet has data validations defined for overlapping cell ranges, causing confusion for openpxyl and/or excel.

When using this code:

```<code>wb = load_workbook(filename='DataValidationErrorExample.XLSX')
ws = wb.worksheets[0]
print(ws.data_validations)
</code>```

I get:

```<code><openpyxl.worksheet.datavalidation.DataValidationList object>
Parameters:
disablePrompts=None, xWindow=None, yWindow=None, count=10, dataValidation=[<openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C15:C28 D15:D28 E15:E28 F15:F28 G15:G28 H15:H28 I15 J15 K15', formula1='$Z$12:$AB$12', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='I12 J12 K12', formula1='$Z$5:$AC$5', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C13:C26 D13:D26 E13:E26 F13:F26 G13:G26 H13:H26 I13 J13 K13', formula1='$Z$6:$AB$6', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C12:C25 D12:D25 E12:E25 F12:F25 G12:G25 H12:H25', formula1='$Z$5:$AB$5', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='G8', formula1='$Z$8:$AB$8', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C16:C29 D16:D29 E16:E29 F16:F29 G16:G29 H16:H29 I16 J16 K16', formula1='$Z$9:$AA$9', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C17:C30 D17:D30 E17:E30 F17:F30 G17:G30 H17:H30 I17 J17 K17', formula1='$Z$10:$AC$10', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C14:C27 D14:D27 E14:E27 F14:F27 G14:G27 H14:H27 I14 J14 K14', formula1='$Z$11:$AA$11', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='date', errorStyle=None, imeMode=None, operator=None, sqref='C8 D8', formula1='41275', formula2='43101', <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='J8 K8', formula1='$Z$4:$AA$4', formula2=None]
</code>```

The sqref property shows to which cells a data validation applies, and as you can see there is some overlap between the different data validations.

Body:
I am importing an existing excel sheet using openpyxl and attempting to fill in some values and resave, but I noticed that the existing Data Validation dropdown boxes in the spreadsheet get messed up when doing so.  This happens even when just loading the spreadsheet, doing no other operations, and then resaving, so it seems to be something intrinsic with openpyxl.  The Data Validation in the spreadsheet consists of dropboxes in certain cells which take their possible values from a set of other cells about 20 columns over (this is to generate QC reports for a company).  For example cell C13 has an initial Data Validation "source" of $Z$6:$AB$6, but after loading and saving the excel sheet it is erroneously changed to $Z$5:$AB$5 for that cell.  Strangely, this is not consistent across all cells; some cells remain with the correct range, and some cells are five or so rows off instead.  It looks like it is only off by rows, not columns.  All of the cells with Data Validation are merged, I'm not sure if that matters or not.  Does anyone know why this may happen, or how to fix it?  There is not much code to show, but here is a simple example of a load/save function that will cause this problem:

    wb = load_workbook(filename='myspreadsheet.xlsx')
    wb.save('myspreadsheet.xlsx')

Thanks in advance!
Robert

Body:
It might be that your excel sheet has data validations defined for overlapping cell ranges, causing confusion for openpxyl and/or excel.

When using this code:

wb = load_workbook(filename='DataValidationErrorExample.XLSX')
ws = wb.worksheets[0]
print(ws.data_validations)

I get:

<openpyxl.worksheet.datavalidation.DataValidationList object>
Parameters:
disablePrompts=None, xWindow=None, yWindow=None, count=10, dataValidation=[<openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C15:C28 D15:D28 E15:E28 F15:F28 G15:G28 H15:H28 I15 J15 K15', formula1='$Z$12:$AB$12', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='I12 J12 K12', formula1='$Z$5:$AC$5', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C13:C26 D13:D26 E13:E26 F13:F26 G13:G26 H13:H26 I13 J13 K13', formula1='$Z$6:$AB$6', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C12:C25 D12:D25 E12:E25 F12:F25 G12:G25 H12:H25', formula1='$Z$5:$AB$5', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='G8', formula1='$Z$8:$AB$8', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C16:C29 D16:D29 E16:E29 F16:F29 G16:G29 H16:H29 I16 J16 K16', formula1='$Z$9:$AA$9', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C17:C30 D17:D30 E17:E30 F17:F30 G17:G30 H17:H30 I17 J17 K17', formula1='$Z$10:$AC$10', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='C14:C27 D14:D27 E14:E27 F14:F27 G14:G27 H14:H27 I14 J14 K14', formula1='$Z$11:$AA$11', formula2=None, <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='date', errorStyle=None, imeMode=None, operator=None, sqref='C8 D8', formula1='41275', formula2='43101', <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, sqref='J8 K8', formula1='$Z$4:$AA$4', formula2=None]

The sqref property shows to which cells a data validation applies, and as you can see there is some overlap between the different data validations.


问:
Switch between classes / jQuery
I have a login form with some input methods like drop downs, blank fields. My client needs a feature that select yes or no switch like this.

So I used jQuery add/remove functions when click.

HTML:

```<code><div class="form-group">
  <label for="member" class="col-md-5 col-sm-12 control-label">
    Do you have the car right now?
  </label>
  <div class="col-lg-10">
    <div class="btn-group">
      <button type="button" class="btn btn-default btn-switch switch1 active"> <span class="goods">Yes</span>
      </button>
      <div class="btn-group">
        <button type="button" class="btn btn-default btn-switch switch1"><span class="services">No</span>
        </button>
      </div>
    </div>
  </div>
</div>
</code>```

CSS:

```<code>.switch1.active{
  background: #e46a5d!important;
  color: #fff;
  font-weight: normal;
  text-shadow: none;
}
</code>```

Here is a working link for jsfiddle But my problem is..

In some pages, I need to add more yes or no fields like 5 or 6. So I need to repeat jquery script more time.

So looking for a best practice to do in this kind of situation.

答:
You should wrap the button in same parent, as I think there is no benefit wrapping No button in another .btn-group

```<code><div class="btn-group">
  <button type="button" class="btn btn-default btn-switch active"> <span class="goods">Yes</span>
  </button>
  <button type="button" class="btn btn-default btn-switch"><span class="services">No</span>
  </button>
</div>
</code>```

Use a common class to attach the event handler i.e. .btn-switch, then use DOM relationship to remove the classes with the parent DOM structure.

```<code> $(document).on("click", ".btn-switch", function() {
   var btnGroup = $(this).closest('.btn-group');
   btnGroup.find(".active").removeClass("active");

   //$(this).siblings(".active").removeClass("active");

   $(this).addClass("active");
 });
</code>```

Fiddle

References

.closest()

.find()

.siblings()

$(document).on("click", ".btn-switch", function() {
  var btnGroup = $(this).closest('.btn-group');
  btnGroup.find(".active").removeClass("active");
  $(this).addClass("active");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn-switch.active {
  background: #e46a5d!important;
  color: #fff;
  font-weight: normal;
  text-shadow: none;
}</code>```

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    Do you have the car right now?

      <button type="button" class="btn btn-default btn-switch active"> Yes
      </button>
      <button type="button" class="btn btn-default btn-switch">No
      </button>

    Do you have the car right now?

      <button type="button" class="btn btn-default btn-switch active"> Yes
      </button>
      <button type="button" class="btn btn-default btn-switch">No
      </button>

    Do you have the car right now?

      <button type="button" class="btn btn-default btn-switch active"> Yes
      </button>
      <button type="button" class="btn btn-default btn-switch">No
      </button>

```

Title: Switch between classes / jQuery

Body:
I have a login form with some input methods like drop downs, blank fields. My client needs a feature that select yes or no switch like this.

So I used jQuery add/remove functions when click.

HTML:

    Do you have the car right now?

      <button type="button" class="btn btn-default btn-switch switch1 active"> Yes
      </button>

        <button type="button" class="btn btn-default btn-switch switch1">No
        </button>

CSS:

.switch1.active{
  background: #e46a5d!important;
  color: #fff;
  font-weight: normal;
  text-shadow: none;
}

Here is a working link for jsfiddle But my problem is..

In some pages, I need to add more yes or no fields like 5 or 6. So I need to repeat jquery script more time.

So looking for a best practice to do in this kind of situation.

Body:
You should wrap the button in same parent, as I think there is no benefit wrapping No button in another .btn-group

<div class="btn-group">
  <button type="button" class="btn btn-default btn-switch active"> <span class="goods">Yes</span>
  </button>
  <button type="button" class="btn btn-default btn-switch"><span class="services">No</span>
  </button>
</div>

Use a common class to attach the event handler i.e. .btn-switch, then use DOM relationship to remove the classes with the parent DOM structure.

 $(document).on("click", ".btn-switch", function() {
   var btnGroup = $(this).closest('.btn-group');
   btnGroup.find(".active").removeClass("active");

   //$(this).siblings(".active").removeClass("active");

   $(this).addClass("active");
 });

Fiddle

References

.closest()

.find()

.siblings()

$(document).on("click", ".btn-switch", function() {
  var btnGroup = $(this).closest('.btn-group');
  btnGroup.find(".active").removeClass("active");
  $(this).addClass("active");
});

.btn-switch.active {
  background: #e46a5d!important;
  color: #fff;
  font-weight: normal;
  text-shadow: none;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="form-group">
  <label for="member" class="col-md-5 col-sm-12 control-label">
    Do you have the car right now?
  </label>
  <div class="col-lg-10">
    <div class="btn-group">
      <button type="button" class="btn btn-default btn-switch active"> <span class="goods">Yes</span>
      </button>
      <button type="button" class="btn btn-default btn-switch"><span class="services">No</span>
      </button>
    </div>
  </div>
</div>

<div class="form-group">
  <label for="member" class="col-md-5 col-sm-12 control-label">
    Do you have the car right now?
  </label>
  <div class="col-lg-10">
    <div class="btn-group">
      <button type="button" class="btn btn-default btn-switch active"> <span class="goods">Yes</span>
      </button>
      <button type="button" class="btn btn-default btn-switch"><span class="services">No</span>
      </button>
    </div>
  </div>
</div>

<div class="form-group">
  <label for="member" class="col-md-5 col-sm-12 control-label">
    Do you have the car right now?
  </label>
  <div class="col-lg-10">
    <div class="btn-group">
      <button type="button" class="btn btn-default btn-switch active"> <span class="goods">Yes</span>
      </button>
      <button type="button" class="btn btn-default btn-switch"><span class="services">No</span>
      </button>
    </div>
  </div>
</div>


问:
Why can we supply a Comparator to TreeSet but not something like Hasher to HashSet?
In Java 6, my understanding is that you can supply a Comparator to a TreeSet when creating it to override the "natural ordering" of the objects in the set.

Do you have any thoughts why Java doesn't support supplying a "Hasher" that overrides the "natural hashing" of objects in the set as well?

EDIT:
Getting input from you might help me when designing APIs in the future.

Thanks.

答:
It does! Check out the Object.hashCode method.

After reading your question again I might have jumped the gun. I now see that you said "override" the natural hshing. Usually we override the hash value at the object level and forgo the use of a overriding Hasher.

Hashes are meant to be more universal that comparators. That is, hashes should almost always create uniform distrusted values with little chance of collision. The container in which they are used should rarely need a specialized hasher.


问:
Can a MVC 5 project change browser level zoom?
I have a MVC 5 app, and I need to have a default zoom out. I don't want to use JavaScript or CSS.

Does such a way exist to change zoom level across all browsers?

答:
I wonder had not you try this by setting body zoom atribute:</p>

```<code>private void webBrowser_getDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        webBrowser1.Document.Body.Style = "zoom:300%;";
    }
</code>```

Body:
I wonder had not you try this by setting body zoom atribute:

private void webBrowser_getDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        webBrowser1.Document.Body.Style = "zoom:300%;";
    }


问:
Active Directory OAuth 2.0 - Request an Authorization Code through PHP different than browser request
I'm following this documentation: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code

Under, REQUEST AN AUTHORIZATION CODE, it gives a sample code involving an endpoint for OAuth 2.0. I've followed this structure to base my own request resembling:

```<code>https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=https://example.com
&response_mode=query
&resource=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
</code>```

During my tests, I've even tried (getting the request as bare as possible):

```<code>https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
</code>```

Here's the interesting thing: If I access these domains through the browser, they return a "successful" call, like so:

```<code>https://example.com/?code=AOA...................................
</code>```

However, I can't seem to get this same result (acquire a code) through a PHP workaround.

I've tried:

```<code>file_get_contents($my_url);
</code>```

But all that returns is an error and a login page for Microsoft.

I've also tried doing so in cURL, but no luck.

Can anyone advise on how to replicate getting such a code (automatically)?

答:
The need here was to access APIs as a user later as well.

When you redeem an authorization code, you get an access token and a refresh token. The access token you attach to API calls, and expires in 1 hour by default. But the refresh token expires in 14 days by default, and can be used to get a new access token and refresh token. So you can have perpetual access as long as you use the refresh token to get new tokens always within 14 days.

The user's access will be checked every time you refresh, so if their account is disabled or access is removed, you will get an error instead of new tokens.

Short answer: you can't. To get an authorization code, you must redirect the browser so the user can sign in, go through MFA if necessary, sign in to their org local AD... As an end result, the user will be sent back to your app with the code, which you can then redeem for access tokens to APIs you want to call that are protected by Azure AD.

Body:
I'm following this documentation: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code

Under, REQUEST AN AUTHORIZATION CODE, it gives a sample code involving an endpoint for OAuth 2.0. I've followed this structure to base my own request resembling:

https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=https://example.com
&response_mode=query
&resource=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345

During my tests, I've even tried (getting the request as bare as possible):

https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code

Here's the interesting thing: If I access these domains through the browser, they return a "successful" call, like so:

https://example.com/?code=AOA...................................

However, I can't seem to get this same result (acquire a code) through a PHP workaround.

I've tried:

file_get_contents($my_url);

But all that returns is an error and a login page for Microsoft.

I've also tried doing so in cURL, but no luck.

Can anyone advise on how to replicate getting such a code (automatically)?


问:
How to insert a stored procedure in to Exixting database?
I have a database created as ready with some stored procedures. Now i want to add another stored procedure(external) into my existing database using MySql or SqlYog. Can anybody Help me ??</p>

答:
Use MySQL work bench to script the stored procedure on the database instance you would like to add the stored procedure.

See this link: http://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx

It will guide you through the process.


问:
Reverse last push on Github.
I have pushed on the wrong branch, I want to push on new branch but I have pushed on the master branch. Is there any way to Reverse the last committed push and get the last code and pushed again to the new branch?

答:
```<code>git log
</code>```

This will give you a log of all the commits and then git reset --hard "commit id"
This will reset to the given head

Title: Reverse last push on Github.

Body:
git log

This will give you a log of all the commits and then git reset --hard "commit id"
This will reset to the given head


问:
flot chart pulling data from mysql ajax js
i'm trying to pull  data from a mysql database and plot in a flot chart. i've seen dozens of posts but it's not working for me.
I successfully get flot charts working in php
http://oven.luckybat.space/batoven1.0_s.php

firstly here's the url for the data
intellipool.overcast.net.au/PCsystem/getdataforflot.php
it seems to be in the correct format.
i want to plot temperature versus time

I get an 'error alert' when i load the page that runs this script

there is a

```<code>     <p> id="graph3" style="width:1000px;height:500px;">graph3</p>
</code>```

on the wordpress webpage

help appreciated

```<code>$.ajax({
  type: "GET",
  dataType: 'json',
  url: 'http://intellipool.overcast.net.au/PCsystem/getdataforflot.php',

    error: function() {
      alert("An error occurred.");
    },
  success: function(data) {
    alert("got the data dude");
    var options = {
      xaxis: {
        mode: "time",
        mintickSize: [1, "hours"],
        axisLabel: 'Time',
        min: ((new Date().getTime()) - 24 * 60 * 60 * 1000),
        max: (new Date()).getTime()
      },
      yaxes: [{
        tickFormatter: function(val, axis) {
          return val + "\u00B0C";
        },
        max: 50,
        axisLabel: "Temperature",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 12,
        axisLabelPadding: 5
      }, {
        position: "right",
        tickFormatter: function(val, axis) {
          return val + "%";
        },
        max: 100,
        axisLabel: "Humidity",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 12,
        axisLabelPadding: 10
      }],
    };
    $.plot("#graph3", data, options);
  }

});
</code>```

as per instructions i've added

```<code>         <header> ('Access-Control-Allow-Origin: *'); </header>
</code>```

to http://intellipool.overcast.net.au/PCsystem/getdataforflot.php

i'm still getting the error, do i need to do more on the server (by contacting hosting?)

do i need to assign JSON data coming in to a variable?

the full function() is

```<code> function ajaxplot() {
 document.write('hello!! there ajaxplot() AJAX has been called');
 $.ajaxSetup({ cache: false });

  $.ajax({
    type: "GET",
    dataType: 'json',
    url: 'http://intellipool.overcast.net.au/PCsystem/getdataforflot.php',

    error: function() {
    alert("An error occurred.");
  },
success: function(data) {
   alert("got the data dude");
   var options = {
    xaxis: {
    mode: "time",
    mintickSize: [1, "hours"],
    axisLabel: 'Time',
     min: ((new Date().getTime()) - 24 * 60 * 60 * 1000),
     max: (new Date()).getTime()
  },
  yaxes: [{
    tickFormatter: function(val, axis) {
      return val + "\u00B0C";
    },
    max: 50,
    axisLabel: "Temperature",
    axisLabelUseCanvas: true,
    axisLabelFontSizePixels: 12,
    axisLabelPadding: 5
  }, {
    position: "right",
    tickFormatter: function(val, axis) {
      return val + "%";
    },
    max: 100,
    axisLabel: "Humidity",
    axisLabelUseCanvas: true,
    axisLabelFontSizePixels: 12,
    axisLabelPadding: 10
  }],
};
$.plot("#graph3", data, options);
}

 });
}
</code>```

答:
Open your http://overcast.net.au/js-tests/ link open console write below function

```<code>function ajaxplot() {
$.ajaxSetup({ cache: false });

$.ajax({
  type: "GET",
  dataType: 'json',
  url: '/getdataforflot.php',
  error: function() {
      alert("An error occurred.");
    },
  success: function(data) {
    debugger;
    alert("got the data dude");
    //var data1 = [[1496765558000,"26"],[1496764656000,"26"],[1496763754000,"26"],[1496762851000,"26"],[1496761949000,"26"]];
    var data1 = data;
    var options = {
      xaxis: {
        mode: "time",
        mintickSize: [1, "hours"],
        axisLabel: 'Time',
         min: ((new Date().getTime()) - 24 * 60 * 60 * 1000),
         max: (new Date()).getTime()
      },
      yaxes: [{
        tickFormatter: function(val, axis) {
          return val + "\u00B0C";
        },
        max: 50,
        axisLabel: "Temperature",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 12,
        axisLabelPadding: 5
      }, {
        position: "right",
        tickFormatter: function(val, axis) {
          return val + "%";
        },
        max: 100,
        axisLabel: "Humidity",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 12,
        axisLabelPadding: 10
      }],
    };
    $.plot("#graph3", data1, options);
    },

});
}
</code>```

THEN

call ajaxplot() in console it should work.

See screenshot

In your console there are many errors resolve all and it should work..

Body:
i'm trying to pull  data from a mysql database and plot in a flot chart. i've seen dozens of posts but it's not working for me.
I successfully get flot charts working in php
http://oven.luckybat.space/batoven1.0_s.php

firstly here's the url for the data
intellipool.overcast.net.au/PCsystem/getdataforflot.php
it seems to be in the correct format.
i want to plot temperature versus time

I get an 'error alert' when i load the page that runs this script

there is a

 id="graph3" style="width:1000px;height:500px;">graph3

on the wordpress webpage

help appreciated

$.ajax({
  type: "GET",
  dataType: 'json',
  url: 'http://intellipool.overcast.net.au/PCsystem/getdataforflot.php',

    error: function() {
      alert("An error occurred.");
    },
  success: function(data) {
    alert("got the data dude");
    var options = {
      xaxis: {
        mode: "time",
        mintickSize: [1, "hours"],
        axisLabel: 'Time',
        min: ((new Date().getTime()) - 24 * 60 * 60 * 1000),
        max: (new Date()).getTime()
      },
      yaxes: [{
        tickFormatter: function(val, axis) {
          return val + "\u00B0C";
        },
        max: 50,
        axisLabel: "Temperature",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 12,
        axisLabelPadding: 5
      }, {
        position: "right",
        tickFormatter: function(val, axis) {
          return val + "%";
        },
        max: 100,
        axisLabel: "Humidity",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 12,
        axisLabelPadding: 10
      }],
    };
    $.plot("#graph3", data, options);
  }

});

as per instructions i've added

          ('Access-Control-Allow-Origin: *');

to http://intellipool.overcast.net.au/PCsystem/getdataforflot.php

i'm still getting the error, do i need to do more on the server (by contacting hosting?)

do i need to assign JSON data coming in to a variable?

the full function() is

 function ajaxplot() {
 document.write('hello!! there ajaxplot() AJAX has been called');
 $.ajaxSetup({ cache: false });

  $.ajax({
    type: "GET",
    dataType: 'json',
    url: 'http://intellipool.overcast.net.au/PCsystem/getdataforflot.php',

    error: function() {
    alert("An error occurred.");
  },
success: function(data) {
   alert("got the data dude");
   var options = {
    xaxis: {
    mode: "time",
    mintickSize: [1, "hours"],
    axisLabel: 'Time',
     min: ((new Date().getTime()) - 24 * 60 * 60 * 1000),
     max: (new Date()).getTime()
  },
  yaxes: [{
    tickFormatter: function(val, axis) {
      return val + "\u00B0C";
    },
    max: 50,
    axisLabel: "Temperature",
    axisLabelUseCanvas: true,
    axisLabelFontSizePixels: 12,
    axisLabelPadding: 5
  }, {
    position: "right",
    tickFormatter: function(val, axis) {
      return val + "%";
    },
    max: 100,
    axisLabel: "Humidity",
    axisLabelUseCanvas: true,
    axisLabelFontSizePixels: 12,
    axisLabelPadding: 10
  }],
};
$.plot("#graph3", data, options);
}

 });
}

Body:
Open your http://overcast.net.au/js-tests/ link open console write below function

function ajaxplot() {
$.ajaxSetup({ cache: false });

$.ajax({
  type: "GET",
  dataType: 'json',
  url: '/getdataforflot.php',
  error: function() {
      alert("An error occurred.");
    },
  success: function(data) {
    debugger;
    alert("got the data dude");
    //var data1 = [[1496765558000,"26"],[1496764656000,"26"],[1496763754000,"26"],[1496762851000,"26"],[1496761949000,"26"]];
    var data1 = data;
    var options = {
      xaxis: {
        mode: "time",
        mintickSize: [1, "hours"],
        axisLabel: 'Time',
         min: ((new Date().getTime()) - 24 * 60 * 60 * 1000),
         max: (new Date()).getTime()
      },
      yaxes: [{
        tickFormatter: function(val, axis) {
          return val + "\u00B0C";
        },
        max: 50,
        axisLabel: "Temperature",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 12,
        axisLabelPadding: 5
      }, {
        position: "right",
        tickFormatter: function(val, axis) {
          return val + "%";
        },
        max: 100,
        axisLabel: "Humidity",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 12,
        axisLabelPadding: 10
      }],
    };
    $.plot("#graph3", data1, options);
    },

});
}

THEN

call ajaxplot() in console it should work.

See screenshot

In your console there are many errors resolve all and it should work..


问:
SQLAlchemy: get average of greatest-n-per-group
I'm trying to create a Flask app (Postgresql database) that shows the latest score from individual players, including the average scores and goals for the team. So a player can have multiple scores, but on the leaderboard I only want to show her most recent score, and show an average number of goals for the whole team, based on the latest score per player.

My Models.py

```<code>class Player(db.Model):
    __tablename__ = 'player'
    id = db.Column(db.Integer, primary_key=True)
    firstname = db.Column(db.String, nullable=False)
    score = db.relationship('Score', backref='player', lazy='dynamic')

    def __init__(self, firstname):
        self.firstname = firstname

    def __repr__(self):
        return '<id {}>'.format(self.id)

class Score(db.Model):
    __tablename__ = 'score'
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.DateTime, nullable=False)
    score = db.Column(db.Integer, nullable=True)
    goals = db.Column(db.Integer, nullable=True)
    player_id = db.Column(db.Integer, db.ForeignKey('player.id'))

    def __init__(self, score, player_id):
        self.timestamp = datetime.now()
        self.score = score
        self.player_id = player_id

    def __repr__(self):
        return '<id {}>'.format(self.id)
</code>```

My app.py:

```<code>@app.route('/', methods=['GET', 'POST'])
@login_required
def home():

    #Latest score per player
    latest_scores_per_player = db.session.query(Player, Score).\
        join(Score).\
        distinct(Player.id).\
        filter(Player.user_id == current_user.id).\
        order_by(Player.id, Score.timestamp.desc())

    #Average goals per player
    avarage_goals = db.session.query(Player, Score).\
        join(Score).\
        distinct(Player.id).\
        filter(Player.user_id == current_user.id).\
        order_by(Player.id, Score.timestamp.desc()).\
        func.avg(Score.goals).label('average').scalar()

    return render_template(
        'home.html',
        latest_scores_per_player=latest_scores_per_player,
        avarage_goals=avarage_goals)
</code>```

'Latest score per player' is properly showing the latest entered score per player. But 'Average goals per player' returns an error:

AttributeError: 'BaseQuery' object has no attribute 'func'

How can I query for the average goals across all players for only the latest entered score per player?

Update:
I feel I'm closer with:

```<code>#Average goals per player
avarage_goals = db.session.query(Player, Score, func.avg(Score.goals)).\
  join(Score).\
  distinct(Player.id).\
  filter(Player.user_id == current_user.id).\
  order_by(Player.id, Score.timestamp.desc()).scalar()
</code>```

But not really there yet. Struggling to get the func.avg to work together with the distinct and order_by.

答:
If I understood you correctly, then you simply need to use latest scores per player as a subquery and average the results. Since you store the Query object in latest scores per player, you can use that:

```<code>@app.route('/', methods=['GET', 'POST'])
@login_required
def home():

    # Latest score per player
    latest_scores_per_player = db.session.query(Player, Score).\
        join(Score).\
        distinct(Player.id).\
        filter(Player.user_id == current_user.id).\
        order_by(Player.id, Score.timestamp.desc())

    # Create a subquery that queries only the goals from the groups
    subq = latest_scores_per_player.\
        with_entities(Score.goals).\
        subquery()

    #Average goals *across all players*
    average_goals = db.session.query(func.avg(subq.c.goals)).scalar()

    return render_template(
        'home.html',
        latest_scores_per_player=latest_scores_per_player,
        avarage_goals=average_goals)
</code>```

This will do 2 trips to the DB. You could also just query the results of latest scores per player and calculate the average in Python. With a recent enough version of Python you can use the statistics module:

```<code>import statistics

@app.route('/', methods=['GET', 'POST'])
@login_required
def home():

    # Latest score per player
    # Materialize the results to a list here for calculating average
    latest_scores_per_player = db.session.query(Player, Score).\
        join(Score).\
        distinct(Player.id).\
        filter(Player.user_id == current_user.id).\
        order_by(Player.id, Score.timestamp.desc()).\
        all()

    average_goals = None
    if latest_scores_per_player:
        average_goals = statistics.mean(
            score.goals for player, score in latest_scores_per_player)

    return render_template(
        'home.html',
        latest_scores_per_player=latest_scores_per_player,
        avarage_goals=average_goals)
</code>```

Or do it yourself (add necessary conversions to float, if using Python 2):

```<code>    average_goals = None
    if latest_scores_per_player:
        average_goals = sum(
            score.goals for player, score in latest_scores_per_player)
        average_goals /= len(latest_scores_per_player)
</code>```

Body:
I'm trying to create a Flask app (Postgresql database) that shows the latest score from individual players, including the average scores and goals for the team. So a player can have multiple scores, but on the leaderboard I only want to show her most recent score, and show an average number of goals for the whole team, based on the latest score per player.

My Models.py

class Player(db.Model):
    __tablename__ = 'player'
    id = db.Column(db.Integer, primary_key=True)
    firstname = db.Column(db.String, nullable=False)
    score = db.relationship('Score', backref='player', lazy='dynamic')

    def __init__(self, firstname):
        self.firstname = firstname

    def __repr__(self):
        return '<id {}>'.format(self.id)

class Score(db.Model):
    __tablename__ = 'score'
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.DateTime, nullable=False)
    score = db.Column(db.Integer, nullable=True)
    goals = db.Column(db.Integer, nullable=True)
    player_id = db.Column(db.Integer, db.ForeignKey('player.id'))

    def __init__(self, score, player_id):
        self.timestamp = datetime.now()
        self.score = score
        self.player_id = player_id

    def __repr__(self):
        return '<id {}>'.format(self.id)

My app.py:

@app.route('/', methods=['GET', 'POST'])
@login_required
def home():

    #Latest score per player
    latest_scores_per_player = db.session.query(Player, Score).\
        join(Score).\
        distinct(Player.id).\
        filter(Player.user_id == current_user.id).\
        order_by(Player.id, Score.timestamp.desc())

    #Average goals per player
    avarage_goals = db.session.query(Player, Score).\
        join(Score).\
        distinct(Player.id).\
        filter(Player.user_id == current_user.id).\
        order_by(Player.id, Score.timestamp.desc()).\
        func.avg(Score.goals).label('average').scalar()

    return render_template(
        'home.html',
        latest_scores_per_player=latest_scores_per_player,
        avarage_goals=avarage_goals)

'Latest score per player' is properly showing the latest entered score per player. But 'Average goals per player' returns an error:

AttributeError: 'BaseQuery' object has no attribute 'func'

How can I query for the average goals across all players for only the latest entered score per player?

Update:
I feel I'm closer with:

#Average goals per player
avarage_goals = db.session.query(Player, Score, func.avg(Score.goals)).\
  join(Score).\
  distinct(Player.id).\
  filter(Player.user_id == current_user.id).\
  order_by(Player.id, Score.timestamp.desc()).scalar()

But not really there yet. Struggling to get the func.avg to work together with the distinct and order_by.

Body:
If I understood you correctly, then you simply need to use latest scores per player as a subquery and average the results. Since you store the Query object in latest scores per player, you can use that:

@app.route('/', methods=['GET', 'POST'])
@login_required
def home():

    # Latest score per player
    latest_scores_per_player = db.session.query(Player, Score).\
        join(Score).\
        distinct(Player.id).\
        filter(Player.user_id == current_user.id).\
        order_by(Player.id, Score.timestamp.desc())

    # Create a subquery that queries only the goals from the groups
    subq = latest_scores_per_player.\
        with_entities(Score.goals).\
        subquery()

    #Average goals *across all players*
    average_goals = db.session.query(func.avg(subq.c.goals)).scalar()

    return render_template(
        'home.html',
        latest_scores_per_player=latest_scores_per_player,
        avarage_goals=average_goals)

This will do 2 trips to the DB. You could also just query the results of latest scores per player and calculate the average in Python. With a recent enough version of Python you can use the statistics module:

import statistics

@app.route('/', methods=['GET', 'POST'])
@login_required
def home():

    # Latest score per player
    # Materialize the results to a list here for calculating average
    latest_scores_per_player = db.session.query(Player, Score).\
        join(Score).\
        distinct(Player.id).\
        filter(Player.user_id == current_user.id).\
        order_by(Player.id, Score.timestamp.desc()).\
        all()

    average_goals = None
    if latest_scores_per_player:
        average_goals = statistics.mean(
            score.goals for player, score in latest_scores_per_player)

    return render_template(
        'home.html',
        latest_scores_per_player=latest_scores_per_player,
        avarage_goals=average_goals)

Or do it yourself (add necessary conversions to float, if using Python 2):

    average_goals = None
    if latest_scores_per_player:
        average_goals = sum(
            score.goals for player, score in latest_scores_per_player)
        average_goals /= len(latest_scores_per_player)


问:
Importing asset bundle from web server in Android mobile
In Unity, I am creating an asset bundle and am loading that assets from server and am running that app in Android.  Now the problem was asset bundle can't be loaded in Android device, but it was loaded in Editor. Can anyone give me a suggestion to load assets bundle in Android?</p>

答:
You have to build assetbundles according to the platform you're using.
Check this link for Assetbundles buildtarget

Change the BuildTarget.TargetPlatformCheck the build targets here


问:
What does [undefined × 2] mean and why is it different to [undefined,undefined]?
While answering this question ( Difference between [Object, Object] and Array(2) ) I happened across something in JavaScript arrays that I wasn't previously aware of (ironic, considering I worked on Arrays in the Chakra engine while at Microsoft).

If I enter this into Chrome's JavaScript console...

```<code>var x = Array(2);
var y = [undefined, undefined];
var z = [,];
</code>```

...then when query the x, y and z variables I get this output respectively:

```<code>> x
< [undefined × 2]
<    length: 2

> y
< [undefined, undefined] (
<    0: undefined
<    1: undefined
<    length: 2

> z
< [undefined × 1]
<    length: 1
</code>```

MDN's relevant documentation for Array(arrayLength) and the [] literal syntax states:

If the only argument passed to the Array constructor is an integer this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values). If the argument is any other number, a RangeError exception is thrown.

I note that the documentation does not further explicate on the concept of a "slot" - I assume they're using it as a synonym for "array element" (I'm aware that JavaScript arrays can be sparse-arrays that have a different internal representation, but that shouldn't affect how consumers see them - given that JavaScript arrays and objects are abstractions over a variety of data structures anyway).

The documentation on MSDN for the same does not provide any mention of edge-case arguments for the Array function or Array-literal [] syntax.

So my questions are:

What does undefined × 2 mean?

Why does Array(2) evaluate to [undefined × 2] instead of [undefined, undefined]?

Why does [,] have a length: 1?

To attempt to answer my own questions I consulted the ECMA-262 7.0 specification on Array Literals. There's an interesting note on elided array literal elements (emphasis mine):

Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.

So the part in bold answers my third question, at least: if the last element is "missing" then it does not exist, and if a non-terminal element doesn't have a value then it's undefined. So these expressions are equivalent:

```<code>[a,]   --> [a]
[a,b,] --> [a,b]
[a,,b] --> [a,undefined,b]
</code>```

Therefore

```<code>[,]    --> [undefined]
[,,]   --> [undefined,undefined]
</code>```

So I tried this in Chrome:

```<code>> var a = [,,];
> a
> [undefined × 2]
>    length: 2
</code>```

This is unexpected! I thought [,,] to be equivalent to [undefined,undefined] as per the explicit rules of element elision, yet Chrome considers [,,] to be equivalent to Array(2) instead (note there are no indexers defined, giving it the same result as case y).

So my forth question:

Why is [,,] equivalent to Array(2) but not [undefined,undefined]?

答:
What does undefined × 2 mean?

Consoles display what some developer has decided is a useful message based on some input. It should not be regarded as normative in any sense, and in some cases is misleading. The statement:

```<code>var x = Array(2);
</code>```

Creates a variable x and assigns a new array with length 2. There are no "empty slots" in any meaningful sense. It is equivalent to:

```<code>var x = [,,];
</code>```

(noting that old IE had a bug where the above created an array with length 3 not 2). You can think of it as an object like:

```<code>var x = {length: 2};
</code>```

The number of properties that can be added is in no way limited by setting the length. However setting the length of an existing array will delete any members with indexes equal to or higher than the new length.

Having said that, implementations are free to allocate space for "length" worth of indexes, which seems to be a performance boost in some cases, but it's not specified as being required by ECMA-262.

Why does Array(2) evaluate to [undefined × 2] instead of [undefined, undefined]?

See above, the console is just trying to be helpful. There are no undefined members at all, there is just an array with length 2. For the record, IE 10 shows:

```<code>[undefined, undefined]
</code>```

which is also misleading for the above reasons. It should show [,,].

Why does [,] have a length: 1?

That is called an elision, which is part of an array initializer or array literal. It creates a "missing" member in the same way that:

```<code>var x = [];
x[0] = 0;
x[2] = 2;
</code>```

does not have a member at index 1 and is equivalent to:

```<code>var x = [0,,2];
</code>```

Noting again that old IE interpreted [,] as having length of 2. The member at index 1 is said to be "elided".

Body:
While answering this question ( Difference between [Object, Object] and Array(2) ) I happened across something in JavaScript arrays that I wasn't previously aware of (ironic, considering I worked on Arrays in the Chakra engine while at Microsoft).

If I enter this into Chrome's JavaScript console...

var x = Array(2);
var y = [undefined, undefined];
var z = [,];

...then when query the x, y and z variables I get this output respectively:

> x
< [undefined × 2]
<    length: 2

> y
< [undefined, undefined] (
<    0: undefined
<    1: undefined
<    length: 2

> z
< [undefined × 1]
<    length: 1

MDN's relevant documentation for Array(arrayLength) and the [] literal syntax states:

If the only argument passed to the Array constructor is an integer this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values). If the argument is any other number, a RangeError exception is thrown.

I note that the documentation does not further explicate on the concept of a "slot" - I assume they're using it as a synonym for "array element" (I'm aware that JavaScript arrays can be sparse-arrays that have a different internal representation, but that shouldn't affect how consumers see them - given that JavaScript arrays and objects are abstractions over a variety of data structures anyway).

The documentation on MSDN for the same does not provide any mention of edge-case arguments for the Array function or Array-literal [] syntax.

So my questions are:

What does undefined × 2 mean?

Why does Array(2) evaluate to [undefined × 2] instead of [undefined, undefined]?

Why does [,] have a length: 1?

To attempt to answer my own questions I consulted the ECMA-262 7.0 specification on Array Literals. There's an interesting note on elided array literal elements (emphasis mine):

Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.

So the part in bold answers my third question, at least: if the last element is "missing" then it does not exist, and if a non-terminal element doesn't have a value then it's undefined. So these expressions are equivalent:

[a,]   --> [a]
[a,b,] --> [a,b]
[a,,b] --> [a,undefined,b]

Therefore

[,]    --> [undefined]
[,,]   --> [undefined,undefined]

So I tried this in Chrome:

> var a = [,,];
> a
> [undefined × 2]
>    length: 2

This is unexpected! I thought [,,] to be equivalent to [undefined,undefined] as per the explicit rules of element elision, yet Chrome considers [,,] to be equivalent to Array(2) instead (note there are no indexers defined, giving it the same result as case y).

So my forth question:

Why is [,,] equivalent to Array(2) but not [undefined,undefined]?

Body:
What does undefined × 2 mean?

Consoles display what some developer has decided is a useful message based on some input. It should not be regarded as normative in any sense, and in some cases is misleading. The statement:

var x = Array(2);

Creates a variable x and assigns a new array with length 2. There are no "empty slots" in any meaningful sense. It is equivalent to:

var x = [,,];

(noting that old IE had a bug where the above created an array with length 3 not 2). You can think of it as an object like:

var x = {length: 2};

The number of properties that can be added is in no way limited by setting the length. However setting the length of an existing array will delete any members with indexes equal to or higher than the new length.

Having said that, implementations are free to allocate space for "length" worth of indexes, which seems to be a performance boost in some cases, but it's not specified as being required by ECMA-262.

Why does Array(2) evaluate to [undefined × 2] instead of [undefined, undefined]?

See above, the console is just trying to be helpful. There are no undefined members at all, there is just an array with length 2. For the record, IE 10 shows:

[undefined, undefined]

which is also misleading for the above reasons. It should show [,,].

Why does [,] have a length: 1?

That is called an elision, which is part of an array initializer or array literal. It creates a "missing" member in the same way that:

var x = [];
x[0] = 0;
x[2] = 2;

does not have a member at index 1 and is equivalent to:

var x = [0,,2];

Noting again that old IE interpreted [,] as having length of 2. The member at index 1 is said to be "elided".


问:
HttpClient POST with both JSON Body and URL Params
I am using NiFi's InvokeHTTP processor to POST to a SalesForce endpoint, particularly to the Login endpoint:

https://test.salesforce.com/services/oauth2/token

I append the client_id, client_secret, username and password field to the URL:

https://test.salesforce.com/services/oauth2/token?grant_type=password&client_id=<client_id>&client_secret=<client_secret>&username=<username>&password=<password + key>

And in addition there's a JSON message / payload that passes through InvokeHTTP processor so I configure

Content-Type: application/json

And this works fine when I run it.

[Note: Those who don't know Apache NiFi but knows HttpClient in Java and/or SFDC can answer the question, my point is the REST API endpoint works for me when on NiFi, but not when I try to reach the REST API using custom Java code]

Now because I want to convert this mechanism to a custom code in ExecuteScript processor, I tried coding in Java using HttpClient library. But it seems there are multiple ways of doing this, based on this post in Baeldung. I tried item #4 first:

```<code>CloseableHttpClient client = HttpClients.createDefault();

String urlStr = "https://test.salesforce.com/services/oauth2/token?grant_type=password&client_id=<client_id>&client_secret=<client_secret>&username=<username>&password=<password + key>";
HttpPost httpPost = new HttpPost(urlStr);

String jsonPayload = "{\"qty\":100,\"name\":\"iPad 4\"}";
StringEntity entity = new StringEntity(jsonPayload);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

CloseableHttpResponse response = client.execute(httpPost);

System.out.println(response.getStatusLine().getStatusCode());

InputStream is = response.getEntity().getContent();
String responseStr = IOUtils.toString(is, "UTF-8");

System.out.println(responseStr);

client.close();
</code>```

In which I get:

```<code>400
{"error":"invalid_grant","error_description":"authentication failure"}
</code>```

I also tried item #2 pattern in the page, without the JSON payload, as the parameters would be my entity now:

```<code>CloseableHttpClient client = HttpClients.createDefault();

String urlStr = "https://test.salesforce.com/services/oauth2/token";

HttpPost httpPost = new HttpPost(urlStr);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("grant_type", "password"));
params.add(new BasicNameValuePair("client_id", CLIENT_ID));
params.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
params.add(new BasicNameValuePair("username", USERNAME));
params.add(new BasicNameValuePair("password", PASSWORD));

httpPost.setEntity(new UrlEncodedFormEntity(params));

CloseableHttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());

InputStream is = response.getEntity().getContent();
String responseStr = IOUtils.toString(is, "UTF-8");

System.out.println(responseStr);

client.close();
</code>```

In which case, I also get the same response. Am I missing something in my Java code? How do I combine both patterns, with params and jsonPayload as entity?

答:
Here is my experience with HTTPClient,  for Bing search API

```<code>      URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/v5.0/search");

        builder.setParameter("q", line);
        builder.setParameter("count", "10");
        builder.setParameter("offset", "0");
        builder.setParameter("mkt", "en-us");
        builder.setParameter("safesearch", "Moderate");

        URI uri = builder.build();
        HttpGet request = new HttpGet(uri);

        request.setHeader(api key);
        HttpClient httpclient = HttpClients.createDefault();
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();
</code>```

Later on, you need to read entity and manipulate it as you wish.

Body:
I am using NiFi's InvokeHTTP processor to POST to a SalesForce endpoint, particularly to the Login endpoint:

https://test.salesforce.com/services/oauth2/token

I append the client_id, client_secret, username and password field to the URL:

https://test.salesforce.com/services/oauth2/token?grant_type=password&client_id=<client_id>&client_secret=<client_secret>&username=<username>&password=<password + key>

And in addition there's a JSON message / payload that passes through InvokeHTTP processor so I configure

Content-Type: application/json

And this works fine when I run it.

[Note: Those who don't know Apache NiFi but knows HttpClient in Java and/or SFDC can answer the question, my point is the REST API endpoint works for me when on NiFi, but not when I try to reach the REST API using custom Java code]

Now because I want to convert this mechanism to a custom code in ExecuteScript processor, I tried coding in Java using HttpClient library. But it seems there are multiple ways of doing this, based on this post in Baeldung. I tried item #4 first:

CloseableHttpClient client = HttpClients.createDefault();

String urlStr = "https://test.salesforce.com/services/oauth2/token?grant_type=password&client_id=<client_id>&client_secret=<client_secret>&username=<username>&password=<password + key>";
HttpPost httpPost = new HttpPost(urlStr);

String jsonPayload = "{\"qty\":100,\"name\":\"iPad 4\"}";
StringEntity entity = new StringEntity(jsonPayload);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

CloseableHttpResponse response = client.execute(httpPost);

System.out.println(response.getStatusLine().getStatusCode());

InputStream is = response.getEntity().getContent();
String responseStr = IOUtils.toString(is, "UTF-8");

System.out.println(responseStr);

client.close();

In which I get:

400
{"error":"invalid_grant","error_description":"authentication failure"}

I also tried item #2 pattern in the page, without the JSON payload, as the parameters would be my entity now:

CloseableHttpClient client = HttpClients.createDefault();

String urlStr = "https://test.salesforce.com/services/oauth2/token";

HttpPost httpPost = new HttpPost(urlStr);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("grant_type", "password"));
params.add(new BasicNameValuePair("client_id", CLIENT_ID));
params.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
params.add(new BasicNameValuePair("username", USERNAME));
params.add(new BasicNameValuePair("password", PASSWORD));

httpPost.setEntity(new UrlEncodedFormEntity(params));

CloseableHttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());

InputStream is = response.getEntity().getContent();
String responseStr = IOUtils.toString(is, "UTF-8");

System.out.println(responseStr);

client.close();

In which case, I also get the same response. Am I missing something in my Java code? How do I combine both patterns, with params and jsonPayload as entity?

Body:
Here is my experience with HTTPClient,  for Bing search API

      URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/v5.0/search");

        builder.setParameter("q", line);
        builder.setParameter("count", "10");
        builder.setParameter("offset", "0");
        builder.setParameter("mkt", "en-us");
        builder.setParameter("safesearch", "Moderate");

        URI uri = builder.build();
        HttpGet request = new HttpGet(uri);

        request.setHeader(api key);
        HttpClient httpclient = HttpClients.createDefault();
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

Later on, you need to read entity and manipulate it as you wish.


问:
Windows store application to authenticate against azure function
I'm trying to replicate the following example https://github.com/Azure-Samples/active-directory-dotnet-windows-store (a Windows store application authenticating against azure AD), but I'm replacing the Web App by an Azure Function.

In the Function, the code checking whether the user is logged in is the following:

```<code>ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Contains("user_impersonation"))
</code>```

but this does not contain the required values, and  other calls don't return any value either (e.g. ClaimsPrincipal.Current.FindFirst(ClaimTypes.GivenName));

Do you have any idea what is going on?

答:
It doesn't relative to whether the code run in web App or Azure Function. The root reason is that the difference parameter/way you acquire the token.

When you protect the Azure function with Azure AD and associate the token with the request, it also parse the token and read the claims in the token and construct the ClaimsPrincipal object.

You can parse the token in this site to check whether the claims you expected in the token.

Body:
I'm trying to replicate the following example https://github.com/Azure-Samples/active-directory-dotnet-windows-store (a Windows store application authenticating against azure AD), but I'm replacing the Web App by an Azure Function.

In the Function, the code checking whether the user is logged in is the following:

ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Contains("user_impersonation"))

but this does not contain the required values, and  other calls don't return any value either (e.g. ClaimsPrincipal.Current.FindFirst(ClaimTypes.GivenName));

Do you have any idea what is going on?


问:
Copying string content to char array
I want to copy the content in the string to char array.

Can I use this code StrLCopy(C, pChar(@S[1]), high(C));

I am currently using Delphi 2006. Will there be any problems if I upgrade my Delphi version because of Unicode support provided in newer versions?

If not, what can be the code for this conversion?

答:
This works, in a quick test:</p>

```<code>var
  ch: array[0..10] of Char;
  c: Char;
  x: Integer;
  st: string;
begin
  s := 'Testing';
  StrLCopy(PChar(@ch[0]), PChar(s), High(ch));
  x := 100;
  for c in ch do
  begin
    Canvas.TextOut(x, 100, c);
    Inc(c, Canvas.TextWidth(c) + 3);
  end;
end;
</code>```

Title: Copying string content to char array

Body:
This works, in a quick test:

var
  ch: array[0..10] of Char;
  c: Char;
  x: Integer;
  st: string;
begin
  s := 'Testing';
  StrLCopy(PChar(@ch[0]), PChar(s), High(ch));
  x := 100;
  for c in ch do
  begin
    Canvas.TextOut(x, 100, c);
    Inc(c, Canvas.TextWidth(c) + 3);
  end;
end;


问:
Need to hide tablix when there is no data coming from different datasets. How to use or condition for visibility
Report has multiple tablix and each tablix is getting data  from different dataset.I was trying to hide the tablix when there is no data.if only 1 tablix has data it should show only 1 tablix. And if data is there then only page break will come as there are multiple individuals reports. Need help</p>

答:
You can hide the tablix by selecting the tablix, in designer, and/or properties Window , by selecting the tablix and pressing ctrl+F4,

Then you can go to Visibility section of report tablix and in its value put the expression like

```<code>=IIF(IsNothing(First(Fields!FieldName.Value)), TRUE, FALSE)
</code>```

Make sure you select the tablix properly, and put, therein, in its Visibility, the expression,

Edit

The better way to go for it would be to try something like:-

```<code> =IIF(CountRows("YourDataSetName") < 1, TRUE, FALSE)
</code>```

Body:
You can hide the tablix by selecting the tablix, in designer, and/or properties Window , by selecting the tablix and pressing ctrl+F4,

Then you can go to Visibility section of report tablix and in its value put the expression like

=IIF(IsNothing(First(Fields!FieldName.Value)), TRUE, FALSE)

Make sure you select the tablix properly, and put, therein, in its Visibility, the expression,

Edit

The better way to go for it would be to try something like:-

 =IIF(CountRows("YourDataSetName") < 1, TRUE, FALSE)


问:
Floating point exception: 8
Why am I getting the error: Floating point exception: 8

```<code>#include<stdio.h>
//grid problem
int fact(int n)
{

    int i,f=1;
    if(n==0)
        return 1;
    for(i=1;i<=n;i++)
        f*=i;
    return f;
}

int uniquePaths(int A, int B) {
    float m;
    m=fact(A+B-2)/(fact(A-1)*fact(B-1));
    return m;
}

int main(int argc, char const *argv[])
{
    int a,b;
    //aXb grid
    scanf("%d%d",&a,&b);
    printf("%d\n",uniquePaths(a,b) );
    return 0;
}
</code>```

答:
If you add pre- and postconditions using the function assert you can make sure that parameters and function results have reasonable values:

```<code>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

//grid problem
int fact(int n)
{
    assert(n >= 0);
    int i, f = 1;
    if (n == 0) {
        return 1;
    }
    for (i = 1; i <= n; i++) {
        f *= i;
    }
    assert(f >= 1);
    return f;
}

int uniquePaths(int A, int B)
{
    assert(A >= 1);
    assert(B >= 1);
    int q = fact(A - 1) * fact(B - 1);
    assert(q > 0);
    int m = fact(A + B - 2) / q;
    assert(m >= 1);
    return m;
}

int main(int argc, char const *argv[])
{
    int a, b;
    //aXb grid
    int n = scanf("%d%d", &a, &b);
    if (n == 2) {
        printf("%d\n", uniquePaths(a, b));
    } else {
        fprintf(stderr, "invalid input\n");
        exit(1);
    }
    return 0;
}
</code>```

On my machine, running the program above with intput 10 10, for instance, will result in

```<code>t: t.c:16: int fact(int): Assertion `f >= 1' failed.
Aborted
</code>```

(I don't know why you get a floating point exception however.)

Title: Floating point exception: 8

Body:
Why am I getting the error: Floating point exception: 8

#include<stdio.h>
//grid problem
int fact(int n)
{

    int i,f=1;
    if(n==0)
        return 1;
    for(i=1;i<=n;i++)
        f*=i;
    return f;
}

int uniquePaths(int A, int B) {
    float m;
    m=fact(A+B-2)/(fact(A-1)*fact(B-1));
    return m;
}

int main(int argc, char const *argv[])
{
    int a,b;
    //aXb grid
    scanf("%d%d",&a,&b);
    printf("%d\n",uniquePaths(a,b) );
    return 0;
}

Body:
If you add pre- and postconditions using the function assert you can make sure that parameters and function results have reasonable values:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

//grid problem
int fact(int n)
{
    assert(n >= 0);
    int i, f = 1;
    if (n == 0) {
        return 1;
    }
    for (i = 1; i <= n; i++) {
        f *= i;
    }
    assert(f >= 1);
    return f;
}

int uniquePaths(int A, int B)
{
    assert(A >= 1);
    assert(B >= 1);
    int q = fact(A - 1) * fact(B - 1);
    assert(q > 0);
    int m = fact(A + B - 2) / q;
    assert(m >= 1);
    return m;
}

int main(int argc, char const *argv[])
{
    int a, b;
    //aXb grid
    int n = scanf("%d%d", &a, &b);
    if (n == 2) {
        printf("%d\n", uniquePaths(a, b));
    } else {
        fprintf(stderr, "invalid input\n");
        exit(1);
    }
    return 0;
}

On my machine, running the program above with intput 10 10, for instance, will result in

t: t.c:16: int fact(int): Assertion `f >= 1' failed.
Aborted

(I don't know why you get a floating point exception however.)


问:
DELETE request on Stash tags
This question is similar to Git delete branch without cloning? and overall very simple, but for some reason I can't find the right answer.

I am using Stash REST API to update tags in Stash repository. To send POST request and add new tag is easy (for example with python requests, but could be same with curl):

```<code>#!/usr/bin/python3.5

import requests

url = '.../rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/tags'

data = {'force': 'false',
        'message': 'Updated tag',
        'name': 'LATEST_SUCCESSFUL',
        'startPoint': 'ffffff',
        'type': 'LIGHTWEIGHT'}

headers = {'Content-Type': 'application/json',
           'X-Atlassian-Token': 'no-check'}

r = requests.post(url, data=data, header=headers)
</code>```

This works ok, but I want to keep option of remotely deleting this tag. According to documentation https://developer.atlassian.com/static/rest/stash/3.11.6/stash-scm-git-rest.html?_ga=1.6600434.1354597480.1483944905 this should work:

```<code>url = '.../rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/tags/LATEST_SUCCESSFUL
r = requests.delete(url)
</code>```

But I get 404 error here. So the question is, what is the correct way to access (and delete) single tag?

答:
The answer turned out to be simple, for tag delete requests should hit

```<code>rest/git/1.0/...
</code>```

instead of

```<code>rest/api/1.0/...
</code>```

but the latter one works fine for get requests.

Title: DELETE request on Stash tags

Body:
This question is similar to Git delete branch without cloning? and overall very simple, but for some reason I can't find the right answer.

I am using Stash REST API to update tags in Stash repository. To send POST request and add new tag is easy (for example with python requests, but could be same with curl):

#!/usr/bin/python3.5

import requests

url = '.../rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/tags'

data = {'force': 'false',
        'message': 'Updated tag',
        'name': 'LATEST_SUCCESSFUL',
        'startPoint': 'ffffff',
        'type': 'LIGHTWEIGHT'}

headers = {'Content-Type': 'application/json',
           'X-Atlassian-Token': 'no-check'}

r = requests.post(url, data=data, header=headers)

This works ok, but I want to keep option of remotely deleting this tag. According to documentation https://developer.atlassian.com/static/rest/stash/3.11.6/stash-scm-git-rest.html?_ga=1.6600434.1354597480.1483944905 this should work:

url = '.../rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/tags/LATEST_SUCCESSFUL
r = requests.delete(url)

But I get 404 error here. So the question is, what is the correct way to access (and delete) single tag?

Body:
The answer turned out to be simple, for tag delete requests should hit

rest/git/1.0/...

instead of

rest/api/1.0/...

but the latter one works fine for get requests.


问:
Loadrunner 400 error: truncate to 1000 characters
error message as below snapshot shows, it seems the request parameter's value was truncated, which caused bad request, anyone can help me to analyze what's the root cause, thanks!

Error info as below:

答: The "truncate to 1000 characters" refers to the value displayed in the snapshot view in VuGen. This was done to improve the loading time of the snapshot viewer and has no effect on actual value received from the server.</p>