问:
Formatting JSON data and displaying in a PHP for loop
I have some form data which I'm saving in JSON format using jQuery (this is all working fine).

But I then want to take the JSON data and display it in a PHP for loop. This is where I'm having trouble as jQuery's serializeArray and JSON.stringify just adds each form value in one bit chunk e.g.

```<code>check in, check out, room, adults, children, check in, check out, room, adults, children, check in, check out, room, adults, children
</code>```

But I want to separate each room e.g.

```<code>(Room 1) check in, check out, room, adults, children
(Room 2) check in, check out, room, adults, children
(Room 3) check in, check out, room, adults, children
</code>```

JSFiddle of how the form data is created (everything working fine): https://jsfiddle.net/kuohhm2q/

PHP I'm using to try a display JSON data in for loop (not working):

```<code><?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);

//print_r($data);

foreach($data as $key => $val) { ?>

    <?php echo $key; ?>

<?php } ?>
</code>```

答:
you should use $data as $key and echo $key['name']

```<code> <?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);
// echo "```";
// print_r($data);
$i=0;
foreach($data as $key) {
  if($i==2) break;
 echo 'Name: '.$key['name'];
 echo "
";
 echo 'Value: '.$key['value'];
 echo "
";
$i++;
 }
 ?>
```

Body:
I have some form data which I'm saving in JSON format using jQuery (this is all working fine).

But I then want to take the JSON data and display it in a PHP for loop. This is where I'm having trouble as jQuery's serializeArray and JSON.stringify just adds each form value in one bit chunk e.g.

check in, check out, room, adults, children, check in, check out, room, adults, children, check in, check out, room, adults, children

But I want to separate each room e.g.

(Room 1) check in, check out, room, adults, children
(Room 2) check in, check out, room, adults, children
(Room 3) check in, check out, room, adults, children

JSFiddle of how the form data is created (everything working fine): https://jsfiddle.net/kuohhm2q/

PHP I'm using to try a display JSON data in for loop (not working):

<?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);

//print_r($data);

foreach($data as $key => $val) { ?>

    <?php echo $key; ?>

<?php } ?>

Body:
you should use $data as $key and echo $key['name']

 <?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);
// echo "<pre>";
// print_r($data);
$i=0;
foreach($data as $key) {
  if($i==2) break;
 echo 'Name: '.$key['name'];
 echo "<br>";
 echo 'Value: '.$key['value'];
 echo "<br>";
$i++;
 }
 ?>


来源: stackexchange

问:
How to count an hourly average number of persons using Hive?
I have this data in a table my_table:

```<code>person_id         datetime
1                 2017-03-02 18:06:20
1                 2017-03-02 18:05:10
1                 2017-04-01 18:04:09
1                 2017-03-02 19:06:50
1                 2017-04-01 19:07:22
2                 2017-03-03 18:09:15
2                 2017-05-03 19:07:05
2                 2017-05-03 20:19:08
</code>```

I need to count the number of persons (non-unique) per hour. The problem is that I should get averaged counts (averaged over days).

Imagine that today there are 10 visitors between 18:00 and 19:00, while yesterday there were 5 visitors in the same timeframe. So, what is the average number of visitors over these two days? (10 + 5)/2 = 15 / 2 = 7.5

I expect this result:

```<code>person_id   HOUR   HOURLY_AVG_COUNT
1           18     1.5
1           19     1
1           20     0
2           18     1
2           19     1
2           20     1
</code>```

I wrote the following query in Hive, but it calculates total number of persons per hour over all days:

```<code>SELECT person_id, HOUR(datetime), count(*)
FROM my_table
GROUP BY person_id, HOUR(datetime)
ORDER BY person_id
</code>```

答:
If I understand correctly, you can use count(distinct) to get the average:

```<code>SELECT person_id, HOUR(datetime),
       COUNT(*) / COUNT(DISTINCT DATE(datetime))
FROM my_table
GROUP BY person_id, HOUR(datetime)
ORDER BY person_id;
</code>```

Note:  This does not count days with no values.  Your question does not explain what to do in that case.

ContentLicense: CC BY-SA 3.0

Body:
I have this data in a table my_table:

person_id         datetime
1                 2017-03-02 18:06:20
1                 2017-03-02 18:05:10
1                 2017-04-01 18:04:09
1                 2017-03-02 19:06:50
1                 2017-04-01 19:07:22
2                 2017-03-03 18:09:15
2                 2017-05-03 19:07:05
2                 2017-05-03 20:19:08

I need to count the number of persons (non-unique) per hour. The problem is that I should get averaged counts (averaged over days).

Imagine that today there are 10 visitors between 18:00 and 19:00, while yesterday there were 5 visitors in the same timeframe. So, what is the average number of visitors over these two days? (10 + 5)/2 = 15 / 2 = 7.5

I expect this result:

person_id   HOUR   HOURLY_AVG_COUNT
1           18     1.5
1           19     1
1           20     0
2           18     1
2           19     1
2           20     1

I wrote the following query in Hive, but it calculates total number of persons per hour over all days:

SELECT person_id, HOUR(datetime), count(*)
FROM my_table
GROUP BY person_id, HOUR(datetime)
ORDER BY person_id

Body:
If I understand correctly, you can use count(distinct) to get the average:

SELECT person_id, HOUR(datetime),
       COUNT(*) / COUNT(DISTINCT DATE(datetime))
FROM my_table
GROUP BY person_id, HOUR(datetime)
ORDER BY person_id;

Note:  This does not count days with no values.  Your question does not explain what to do in that case.


问:
what is the difference between dataform webpart and normal list webpart in sharepoint server?
We can directly create a list in sharepoint UI (not sharepoint designer) or we can convert this list webpart into a datafrom webpart using sharepoint designer.What difference does it makes?</p>

答:
When you convert it into dataform webpart, the rendering mode is converted to XSLT. This XSLT can be edited in sharepoint designer or webpart properties itself to change the rendering of items.

Moreover, the type of webpart is changed from ListViewWebPart to DataFormWebPart.

The benefit of having rendering control , comes with some disadvantages. For ex, functionalities of ListViewWebPart like sorting, filtering, export to excel are unavailable/limited in functionality because of XSL limitations.

ContentLicense: CC BY-SA 2.5


问:
count the number of points at the end of a string
I need to count the number of points at the END of string.
The number of points in the middle of the string are not relevant and should not be countet.

How can this be done?

```<code>string sample = "This.is.a.sample.string.....";
</code>```

for the example above the correct answer would be 5 because there are 5 points at the end of the string.

because of performace reasons I would prefer a fast solution. Don't know if Regular Expressions

```<code>\.*$
</code>```

should be used in such a case.

答:
A simple solution using an extension method.</p>

```<code>var test = "this.is.a.test........";
Console.WriteLine(test.CountTrailingDots());

public static int CountTrailingDots(this string value)
{
    return value.Length - value.TrimEnd('.').Length;
}
</code>```

Body:
I need to count the number of points at the END of string.
The number of points in the middle of the string are not relevant and should not be countet.

How can this be done?

string sample = "This.is.a.sample.string.....";

for the example above the correct answer would be 5 because there are 5 points at the end of the string.

because of performace reasons I would prefer a fast solution. Don't know if Regular Expressions

\.*$

should be used in such a case.

Body:
A simple solution using an extension method.

var test = "this.is.a.test........";
Console.WriteLine(test.CountTrailingDots());

public static int CountTrailingDots(this string value)
{
    return value.Length - value.TrimEnd('.').Length;
}


问:
Set $PROJECT_NAME in docker-compose file
I am using the same docker-compose.yml file for multiple projects. I am really lazy, so I don't want to start them with docker-compose -p $PROJECT_NAME up.

As of Docker version 17.06.0, is it possible to set the variable directly in the docker-compose.yml file?

答:
UPDATE: You can now use the top-level name property in your docker-compose YAML file. This is available from Docker Compose v2.3.3

This is the result of the #745 proposal. An issue which persevered for about 8 years.

Previously:
Right now, we can use the .env file to set the custom project name like this:

```<code>COMPOSE_PROJECT_NAME=SOMEPROJECTNAME
</code>```

It's not flexible, but it's better than nothing. Currently, there is an open issue regarding this as a proposal.

ContentLicense: CC BY-SA 4.0

Body:
UPDATE: You can now use the top-level name property in your docker-compose YAML file. This is available from Docker Compose v2.3.3

This is the result of the #745 proposal. An issue which persevered for about 8 years.

Previously:
Right now, we can use the .env file to set the custom project name like this:

COMPOSE_PROJECT_NAME=SOMEPROJECTNAME

It's not flexible, but it's better than nothing. Currently, there is an open issue regarding this as a proposal.


问:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
I'm using php and pdo

Here is my code:

```<code>try {
    $sql="LOCK TABLE appleid WRITE, appleid AS appleid1 READ;";
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $sql="SELECT MAX(num) FROM appleid;";//to know how many rows it has
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $result=$stmt->fetch();
    $table_top=$result[0];

    if (empty($head)) $head = 1;
    $check=$table_top - $head;
    $check++;//number of available rows that are ready to use

    if($check>=$this->apple_id_num)
    {
        $sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
        appleid AS appleid1
        WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
        DESC;";
        $stmt = $GLOBALS['$connection']->prepare($sql);
        $stmt->execute();
        $this->pre_head=$head;
        $head=1+$head+$this->apple_id_num;
        $sql="UNLOCK TABLES;";
        $this->num_rows = $stmt->rowCount();
        echo $stmt->rowCount();
    }
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}
</code>```

I get this error :

SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM appleid AS
  appleid1 WHERE num>=1 LIMIT 1 ORDER BY TimeStamp DESC;
  SQLSTATE[42000]: Syntax error

or access violation: 1064 You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near 'ORDER BY TimeStamp DESC' at line 2

I got confused and I don't know what is wrong with this query and how to fix it.

答:
Use orderby clause before limit clause.

```<code>$sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
appleid AS appleid1
WHERE num>=$head ORDER BY `TimeStamp` DESC LIMIT $this->apple_id_num;";
</code>```

Body:
I'm using php and pdo

Here is my code:

try {
    $sql="LOCK TABLE appleid WRITE, appleid AS appleid1 READ;";
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $sql="SELECT MAX(num) FROM appleid;";//to know how many rows it has
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $result=$stmt->fetch();
    $table_top=$result[0];

    if (empty($head)) $head = 1;
    $check=$table_top - $head;
    $check++;//number of available rows that are ready to use

    if($check>=$this->apple_id_num)
    {
        $sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
        appleid AS appleid1
        WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
        DESC;";
        $stmt = $GLOBALS['$connection']->prepare($sql);
        $stmt->execute();
        $this->pre_head=$head;
        $head=1+$head+$this->apple_id_num;
        $sql="UNLOCK TABLES;";
        $this->num_rows = $stmt->rowCount();
        echo $stmt->rowCount();
    }
}
catch(PDOException $e)
{
    echo $sql . "
" . $e->getMessage();
}

I get this error :

SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM appleid AS
  appleid1 WHERE num>=1 LIMIT 1 ORDER BY TimeStamp DESC;
  SQLSTATE[42000]: Syntax error

or access violation: 1064 You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near 'ORDER BY TimeStamp DESC' at line 2

I got confused and I don't know what is wrong with this query and how to fix it.

Body:
Use orderby clause before limit clause.

$sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
appleid AS appleid1
WHERE num>=$head ORDER BY `TimeStamp` DESC LIMIT $this->apple_id_num;";


问:
Caret not working in batch file, works in Command Prompt
I use this script to get the results of a url:

```<code>@Echo off
For /f "delims=" %%A in (
  'powershell -NonI -NoP -C "(Invoke-Webrequest "%~1").content"'
) Do set Line=%%A
</code>```

I can call it in a command prompt window like this:

```<code> WebResponse.cmd "http://websiteremoved.com/teststat.php?username^=%friend1%"
</code>```

I need to use the caret (^) to cancel out the Equal sign. However when I run that same line of code in my batch file it does not work. According to the test, %~1 is set to "http://websiteremoved.com/teststat.php?username^=Lukaka" but the powershell portion returns this:

```<code>Invoke-WebRequest : A positional parameter cannot be found that accepts argument 'Lukaka'. [] http://websiteremoved.com/teststat.php?username^=Lukaka
At line:1 char:2 [] http://websiteremoved.com/teststat.php?username^=Lukaka
+ (Invoke-Webrequest http://websiteremoved.com/teststat.p ... [] http://websiteremoved.com/teststat.php?username^=Lukaka
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [] http://websiteremoved.com/teststat.php?username^=Lukaka
    + CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException [] http://websiteremoved.com/teststat.php?username^=Lukaka
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand [] http://websiteremoved.com/teststat.php?username^=Lukaka
</code>```

Any ideas as to why it is doing this? Thanks a bunch!

答: The way I was doing it was inefficient. I am closing this question. I am working on a different version of a new script here: Add Multiple URLs to this Powershell Script? which is related.</p>

Body:
I use this script to get the results of a url:

@Echo off
For /f "delims=" %%A in (
  'powershell -NonI -NoP -C "(Invoke-Webrequest "%~1").content"'
) Do set Line=%%A

I can call it in a command prompt window like this:

 WebResponse.cmd "http://websiteremoved.com/teststat.php?username^=%friend1%"

I need to use the caret (^) to cancel out the Equal sign. However when I run that same line of code in my batch file it does not work. According to the test, %~1 is set to "http://websiteremoved.com/teststat.php?username^=Lukaka" but the powershell portion returns this:

Invoke-WebRequest : A positional parameter cannot be found that accepts argument 'Lukaka'. [] http://websiteremoved.com/teststat.php?username^=Lukaka
At line:1 char:2 [] http://websiteremoved.com/teststat.php?username^=Lukaka
+ (Invoke-Webrequest http://websiteremoved.com/teststat.p ... [] http://websiteremoved.com/teststat.php?username^=Lukaka
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [] http://websiteremoved.com/teststat.php?username^=Lukaka
    + CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException [] http://websiteremoved.com/teststat.php?username^=Lukaka
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand [] http://websiteremoved.com/teststat.php?username^=Lukaka

Any ideas as to why it is doing this? Thanks a bunch!


答:
Change

```<code>"SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
    appleid AS appleid1
    WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
    DESC;";
</code>```

to

```<code>"SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
    appleid AS appleid1
    WHERE num>=$head LIMIT {$this->apple_id_num} ORDER BY `TimeStamp`
    DESC;";
</code>```

since the double quotes would not know whether to parse the ->apple_id_num as string or part of a variable.

Title: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error

Body:
Change

"SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
    appleid AS appleid1
    WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
    DESC;";

to

"SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
    appleid AS appleid1
    WHERE num>=$head LIMIT {$this->apple_id_num} ORDER BY `TimeStamp`
    DESC;";

since the double quotes would not know whether to parse the ->apple_id_num as string or part of a variable.


问:
Net::SMTPAuthenticationError when sending email from Rails app (on staging environment)
I am sending email from my Rails application. It works well on development environment, but fails on staging. I get the following error:

```<code>Net::SMTPAuthenticationError (534-5.7.14 <https://accounts.google.com/ContinueSignIn?plt=AKgnsbtdF0yjrQccTO2D_6)
</code>```

Note, that my I don't have a domain name for my staging.

Here are my settings in staging.rb

```<code>config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => "my.ip.addr.here:80" }
config.action_mailer.smtp_settings = {
      :address => "smtp.gmail.com",
      :port => 587,
      :domain => 'my.ip.addr.here:80'
      :user_name => "my_email_name@gmail.com",
      :password => "my_email_password",
      :authentication => 'login'
}
</code>```

Please, help.

Edit.

After adding :tls => true option I get

```<code>OpenSSL::SSL::SSLError (Unrecognized SSL message, plaintext connection?)
</code>```

And then I changed port to  25 and now I get this (with  30 seconds delay):

```<code>Timeout::Error (execution expired)
</code>```

答:
I also faced the problem, and after some research in Gmail setting, I found the solution:

In gmail, go to settings.

Select "Forwarding and POP/IMAP" tab.

In the IMAP access section, select "Enable IMAP".

Body:
I am sending email from my Rails application. It works well on development environment, but fails on staging. I get the following error:

Net::SMTPAuthenticationError (534-5.7.14 <https://accounts.google.com/ContinueSignIn?plt=AKgnsbtdF0yjrQccTO2D_6)

Note, that my I don't have a domain name for my staging.

Here are my settings in staging.rb

config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => "my.ip.addr.here:80" }
config.action_mailer.smtp_settings = {
      :address => "smtp.gmail.com",
      :port => 587,
      :domain => 'my.ip.addr.here:80'
      :user_name => "my_email_name@gmail.com",
      :password => "my_email_password",
      :authentication => 'login'
}

Please, help.

Edit.

After adding :tls => true option I get

OpenSSL::SSL::SSLError (Unrecognized SSL message, plaintext connection?)

And then I changed port to  25 and now I get this (with  30 seconds delay):

Timeout::Error (execution expired)


问:
CSS - background-color not working in IE11
I have the following code:

```<code>.skills_column {
  padding: 50px !important;
  padding-top: 60px !important;

  &.--light {
    background-color: white;
  }
  &.--dark {
    background-color: #ced4db;
  }

  @include media-breakpoint-down(sm) {
    h1 {
      text-align: center;
    }
  }
}
</code>```

There are 3 columns, a light one, and two dark ones.
All of this works in Chrome & Firefox, however, it does not work in IE11:

While the light one is white as expected, the two other columns which are supposed to be dark, are also white when viewed in IE11.

What could the problem be?
I also tried to add filter: none !important; because I read that somewhere, but that does not seem to make a difference although I might have not applied it correctly, I am not sure.

I am also using flexbox, if that should make a difference. But my problem here is with the background colors not being applied.

答:
Can you try removing the double hyphen from your class names(--dark, --light). I have a feeling IE doesn't like BEM representations. Maybe single underscore or double underscore works.

```<code>.skills_column {
  padding: 50px !important;
  padding-top: 60px !important;

  &._light {
    background-color: white;
  }
  &._dark {
    background-color: #ced4db;
  }

  @include media-breakpoint-down(sm) {
    h1 {
      text-align: center;
    }
  }
}
</code>```

Body:
I have the following code:

.skills_column {
  padding: 50px !important;
  padding-top: 60px !important;

  &.--light {
    background-color: white;
  }
  &.--dark {
    background-color: #ced4db;
  }

  @include media-breakpoint-down(sm) {
    h1 {
      text-align: center;
    }
  }
}

There are 3 columns, a light one, and two dark ones.
All of this works in Chrome & Firefox, however, it does not work in IE11:

While the light one is white as expected, the two other columns which are supposed to be dark, are also white when viewed in IE11.

What could the problem be?
I also tried to add filter: none !important; because I read that somewhere, but that does not seem to make a difference although I might have not applied it correctly, I am not sure.

I am also using flexbox, if that should make a difference. But my problem here is with the background colors not being applied.

Body:
Can you try removing the double hyphen from your class names(--dark, --light). I have a feeling IE doesn't like BEM representations. Maybe single underscore or double underscore works.

.skills_column {
  padding: 50px !important;
  padding-top: 60px !important;

  &._light {
    background-color: white;
  }
  &._dark {
    background-color: #ced4db;
  }

  @include media-breakpoint-down(sm) {
    h1 {
      text-align: center;
    }
  }
}


问:
JavaScript does not fire on click of button
I am creating a register page in which I have created some dropdown for address and on click of submit button I check if any of these values are not selected but javascript for this does not fire. My code for MVC is

```<code>    <div class="form-group">
    <label class="col-md-2 control-label">State</label>
    <div class="col-md-10">
        @*@Html.DropDownList("State_ID", null, htmlAttributes: new { @class = "form-control" })*@
        @Html.DropDownList("State_ID", null, "-- Please select a State --", htmlAttributes: new { @class = "form-control" })
    </div>
</div>

<div class="form-group">
    <label class="col-md-2 control-label">City</label>
    <div class="col-md-10">
        @Html.DropDownList("City_ID", null, "-- Please select a City --", htmlAttributes: new { @class = "form-control" })
    </div>
</div>

<div class="form-group">
    <label class="col-md-2 control-label">Area</label>
    <div class="col-md-10">
        @Html.DropDownList("Area_ID", null, "-- Please select area --", htmlAttributes: new { @class = "form-control" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(a => a.Address, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(a => a.Address, new { @class = "form-control" })
    </div>
</div>

<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input id="submitButton" value="Register" type="submit" class="btn btn-default" />
    </div>
</div>

}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryhome")
}
</code>```

and my javascript code is

```<code>    $(document).ready(function () {
    $("#State_ID").change(function () {
        //alert("Hello");
        $("#City_ID").empty();
        $.ajax({
            type: 'POST',
            //url: '@Url.Action("GetCities")',
            url: "/MyAccount/GetCities",
            dataType: 'json',
            data: { id: $("#State_ID").val() },
            success: function (cities) {
                $("#City_ID").append('<option value =0>-- Please select a City --</option>');
                $.each(cities, function (i, city) {
                    $("#City_ID").append('<option value="' + city.Value + '">' + city.Text + '</option>');
                    //alert(city.Text);
                });
                //alert("Success");
            },
            error: function (ex) {
                alert("Failed" + ex);
            }
        });
    });
    $("#submitButton").click(function (e) {
        if ($("#State_ID").val == '' || $("#State_ID").val == 0) {
            e.preventDefault();
            alert("Please select State");
        }
        else if ($("#City_ID").val = '' || $("#City_ID").val == 0) {
            e.preventDefault();
            alert("Please select City");
        }
        else if ($("#Area_ID").val == '' || $("#Area_ID").val == 0) {
            e.preventDefault();
            alert("Please select area");
        }
    })
});
</code>```

Can anybody help?

Edit 1: - Added HTML output

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - My ASP.NET Application</title>
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>
                Lightmap

Home

                        About Us

About

Contact

                        Services

New Connection

Download Forms

Locate Nearest Offices

Locate Nearest Complaint Centers

Right To Information

                        My Account

Log in

Register

Consumer Information

View Bill

Bill Summary

Consumption History

Consumption Calculator

                        Payment Options

Locate Payment Centers

Calculate Charges

Payment History

Tariff Charges

                        Support

Help/FAQ

Feedback

About

Register a complaint

Contact

Contact

Register

<form action="/MyAccount/Register" class="form-horizontal" method="post" role="form"><input name="__RequestVerificationToken" type="hidden" value="9IRV0jQ_Xvvr5BgyjyPPjjjdYZadB7ZhvzOpOI_2a0gMgcyJlQNK9dC7WBjNy9ObokH0CDvWxAiVTT_CCjpcGGgn0zOrBBV6rxcSdQb8AC41" />

        Name

            <input class="form-control" data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />

        Aadhar Card Number

            <input class="form-control" data-val="true" data-val-length="Enter a valid Aadhar Card Number" data-val-length-max="12" data-val-length-min="12" id="Aadhar" name="Aadhar" type="text" value="" />

        Email Address

            <input class="form-control" data-val="true" data-val-email="The Email Address field is not a valid e-mail address." id="Email" name="Email" type="text" value="" />

        Phone Number

            <input class="form-control" data-val="true" data-val-required="The Phone Number field is required." id="Phone_Number" name="Phone_Number" type="text" value="" />

        Meter Number

            <input class="form-control" data-val="true" data-val-required="The Meter Number field is required." id="Meter_Number" name="Meter_Number" type="text" value="" />

        Is board employee?

            <input class="check-box" data-val="true" data-val-required="The Is board employee? field is required." id="IsBoardEmployee" name="IsBoardEmployee" type="checkbox" value="true" /><input name="IsBoardEmployee" type="hidden" value="false" />

        State

            <select class="form-control" id="State_ID" name="State_ID"><option value="">-- Please select a State --</option>
<option value="1">Haryana</option>
<option value="2">Punjab</option>
<option value="3">Himachal Pradesh</option>
<option value="5">Kerala</option>
<option value="6">Gujrat</option>
<option value="7">Rajasthan</option>
<option value="8">Orrissa</option>
<option value="9">Tamil Nadu</option>
<option value="10">Andhra Pradesh</option>
<option value="11">Telengana</option>
<option value="12">West Bengal</option>
<option value="13">Manipur</option>
<option value="14">Aasam</option>
<option value="15">Bihar</option>
<option value="16">Jharkhand</option>
</select>

        City

            <select class="form-control" id="City_ID" name="City_ID"><option value="">-- Please select a City --</option>
<option value="1">Kurukshetra</option>
<option value="2">Ambala</option>
<option value="3">Panchkula</option>
<option value="4">Mohali</option>
<option value="5">Jalandhar</option>
<option value="6">Amritsar</option>
<option value="7">Patiala</option>
<option value="8">Ludhiana</option>
<option value="9">Jind</option>
</select>

        Area

            <select class="form-control" id="Area_ID" name="Area_ID"><option value="">-- Please select area --</option>
<option value="2">Sector 18</option>
<option value="3">Sector 17</option>
<option value="4">Sector 16</option>
<option value="5">Sector 15</option>
<option value="6">Sector 14</option>
</select>

        Address

            <input class="form-control" data-val="true" data-val-required="The Address field is required." id="Address" name="Address" type="text" value="" />

            <input id="submitButton" value="Register" type="submit" class="btn btn-default" />

</form>

© 2017 - My ASP.NET Application

```

答:
You should change val to val(). Here is a link to jQuery val()

$(document).ready(function () {
    $("#State_ID").change(function () {
        $("#City_ID").empty();
        $.ajax({
            type: 'POST',
            url: "/MyAccount/GetCities",
            dataType: 'json',
            data: { id: $("#State_ID").val() },
            success: function (cities) {
                $("#City_ID").append('<option value =0>-- Please select a City --</option>');
                $.each(cities, function (i, city) {
                    $("#City_ID").append('<option value="' + city.Value + '">' + city.Text + '</option>');
                });;
            },
            error: function (ex) {
                alert("Failed" + JSON.stringify(ex));
            }
        });
    });
    $("#submitButton").click(function (e) {
        if ($("#State_ID").val() == '' || $("#State_ID").val() == 0) {
            e.preventDefault();
            alert("Please select State");
        }
        else if ($("#City_ID").val() = '' || $("#City_ID").val() == 0) {
            e.preventDefault();
            alert("Please select City");
        }
        else if ($("#Area_ID").val() == '' || $("#Area_ID").val() == 0) {
            e.preventDefault();
            alert("Please select area");
        }
    })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - My ASP.NET Application</title>
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

    <script src="/Scripts/modernizr-2.8.3.js"></script>

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                Lightmap
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>Home</li>
                    <li class="dropdown">
                        About Us
                        <ul class="dropdown-menu">
                            <li>About</li>
                            <li>Contact</li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        Services
                        <ul class="dropdown-menu">
                            <li>New Connection</li>
                            <li>Download Forms</li>
                            <li>Locate Nearest Offices</li>
                            <li>Locate Nearest Complaint Centers</li>
                            <li>Right To Information</li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        My Account
                        <ul class="dropdown-menu">
                            <li>Log in</li>
                            <li>Register</li>
                            <li>Consumer Information</li>
                            <li>View Bill</li>
                            <li>Bill Summary</li>
                            <li>Consumption History</li>
                            <li>Consumption Calculator</li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        Payment Options
                        <ul class="dropdown-menu">
                            <li>Locate Payment Centers</li>
                            <li>Calculate Charges</li>
                            <li>Payment History</li>
                            <li>Tariff Charges</li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        Support
                        <ul class="dropdown-menu">
                            <li>Help/FAQ</li>
                            <li>Feedback</li>
                            <li>About</li>
                            <li>Register a complaint</li>
                            <li>Contact</li>
                            <li>Contact</li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">

<h2>Register</h2>

<form action="/MyAccount/Register" class="form-horizontal" method="post" role="form"><input name="__RequestVerificationToken" type="hidden" value="9IRV0jQ_Xvvr5BgyjyPPjjjdYZadB7ZhvzOpOI_2a0gMgcyJlQNK9dC7WBjNy9ObokH0CDvWxAiVTT_CCjpcGGgn0zOrBBV6rxcSdQb8AC41" /><div class="validation-summary-valid text-danger" data-valmsg-summary="true"><ul><li style="display:none"></li>
</ul></div>    <div class="form-group">
        <label class="col-md-2 control-label" for="Name">Name</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="Aadhar">Aadhar Card Number</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-length="Enter a valid Aadhar Card Number" data-val-length-max="12" data-val-length-min="12" id="Aadhar" name="Aadhar" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="Email">Email Address</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-email="The Email Address field is not a valid e-mail address." id="Email" name="Email" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="Phone_Number">Phone Number</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-required="The Phone Number field is required." id="Phone_Number" name="Phone_Number" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="Meter_Number">Meter Number</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-required="The Meter Number field is required." id="Meter_Number" name="Meter_Number" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-10">
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="IsBoardEmployee">Is board employee?</label>
        <div class="col-md-10">
            <input class="check-box" data-val="true" data-val-required="The Is board employee? field is required." id="IsBoardEmployee" name="IsBoardEmployee" type="checkbox" value="true" /><input name="IsBoardEmployee" type="hidden" value="false" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">State</label>
        <div class="col-md-10">

            <select class="form-control" id="State_ID" name="State_ID"><option value="">-- Please select a State --</option>
<option value="1">Haryana</option>
<option value="2">Punjab</option>
<option value="3">Himachal Pradesh</option>
<option value="5">Kerala</option>
<option value="6">Gujrat</option>
<option value="7">Rajasthan</option>
<option value="8">Orrissa</option>
<option value="9">Tamil Nadu</option>
<option value="10">Andhra Pradesh</option>
<option value="11">Telengana</option>
<option value="12">West Bengal</option>
<option value="13">Manipur</option>
<option value="14">Aasam</option>
<option value="15">Bihar</option>
<option value="16">Jharkhand</option>
</select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">City</label>
        <div class="col-md-10">
            <select class="form-control" id="City_ID" name="City_ID"><option value="">-- Please select a City --</option>
<option value="1">Kurukshetra</option>
<option value="2">Ambala</option>
<option value="3">Panchkula</option>
<option value="4">Mohali</option>
<option value="5">Jalandhar</option>
<option value="6">Amritsar</option>
<option value="7">Patiala</option>
<option value="8">Ludhiana</option>
<option value="9">Jind</option>
</select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">Area</label>
        <div class="col-md-10">
            <select class="form-control" id="Area_ID" name="Area_ID"><option value="">-- Please select area --</option>
<option value="2">Sector 18</option>
<option value="3">Sector 17</option>
<option value="4">Sector 16</option>
<option value="5">Sector 15</option>
<option value="6">Sector 14</option>
</select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="Address">Address</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-required="The Address field is required." id="Address" name="Address" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input id="submitButton" value="Register" type="submit" class="btn btn-default" />
        </div>
    </div>
</form>

        <hr />
        <footer>
            <p>© 2017 - My ASP.NET Application</p>
        </footer>
    </div>

    <script src="/Scripts/jquery-3.1.1.js"></script>

    <script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>

    <script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/MyAccount/Register.js"></script></code>```

Body:
I am creating a register page in which I have created some dropdown for address and on click of submit button I check if any of these values are not selected but javascript for this does not fire. My code for MVC is

    State

        @*@Html.DropDownList("State_ID", null, htmlAttributes: new { @class = "form-control" })*@
        @Html.DropDownList("State_ID", null, "-- Please select a State --", htmlAttributes: new { @class = "form-control" })

    City

        @Html.DropDownList("City_ID", null, "-- Please select a City --", htmlAttributes: new { @class = "form-control" })

    Area

        @Html.DropDownList("Area_ID", null, "-- Please select area --", htmlAttributes: new { @class = "form-control" })

    @Html.LabelFor(a => a.Address, new { @class = "col-md-2 control-label" })

        @Html.TextBoxFor(a => a.Address, new { @class = "form-control" })

        <input id="submitButton" value="Register" type="submit" class="btn btn-default" />

}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryhome")
}

and my javascript code is

    $(document).ready(function () {
    $("#State_ID").change(function () {
        //alert("Hello");
        $("#City_ID").empty();
        $.ajax({
            type: 'POST',
            //url: '@Url.Action("GetCities")',
            url: "/MyAccount/GetCities",
            dataType: 'json',
            data: { id: $("#State_ID").val() },
            success: function (cities) {
                $("#City_ID").append('<option value =0>-- Please select a City --</option>');
                $.each(cities, function (i, city) {
                    $("#City_ID").append('<option value="' + city.Value + '">' + city.Text + '</option>');
                    //alert(city.Text);
                });
                //alert("Success");
            },
            error: function (ex) {
                alert("Failed" + ex);
            }
        });
    });
    $("#submitButton").click(function (e) {
        if ($("#State_ID").val == '' || $("#State_ID").val == 0) {
            e.preventDefault();
            alert("Please select State");
        }
        else if ($("#City_ID").val = '' || $("#City_ID").val == 0) {
            e.preventDefault();
            alert("Please select City");
        }
        else if ($("#Area_ID").val == '' || $("#Area_ID").val == 0) {
            e.preventDefault();
            alert("Please select area");
        }
    })
});

Can anybody help?

Edit 1: - Added HTML output

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - My ASP.NET Application</title>
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>
                Lightmap

Home

                        About Us

About

Contact

                        Services

New Connection

Download Forms

Locate Nearest Offices

Locate Nearest Complaint Centers

Right To Information

                        My Account

Log in

Register

Consumer Information

View Bill

Bill Summary

Consumption History

Consumption Calculator

                        Payment Options

Locate Payment Centers

Calculate Charges

Payment History

Tariff Charges

                        Support

Help/FAQ

Feedback

About

Register a complaint

Contact

Contact

Register

<form action="/MyAccount/Register" class="form-horizontal" method="post" role="form"><input name="__RequestVerificationToken" type="hidden" value="9IRV0jQ_Xvvr5BgyjyPPjjjdYZadB7ZhvzOpOI_2a0gMgcyJlQNK9dC7WBjNy9ObokH0CDvWxAiVTT_CCjpcGGgn0zOrBBV6rxcSdQb8AC41" />

        Name

            <input class="form-control" data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />

        Aadhar Card Number

            <input class="form-control" data-val="true" data-val-length="Enter a valid Aadhar Card Number" data-val-length-max="12" data-val-length-min="12" id="Aadhar" name="Aadhar" type="text" value="" />

        Email Address

            <input class="form-control" data-val="true" data-val-email="The Email Address field is not a valid e-mail address." id="Email" name="Email" type="text" value="" />

        Phone Number

            <input class="form-control" data-val="true" data-val-required="The Phone Number field is required." id="Phone_Number" name="Phone_Number" type="text" value="" />

        Meter Number

            <input class="form-control" data-val="true" data-val-required="The Meter Number field is required." id="Meter_Number" name="Meter_Number" type="text" value="" />

        Is board employee?

            <input class="check-box" data-val="true" data-val-required="The Is board employee? field is required." id="IsBoardEmployee" name="IsBoardEmployee" type="checkbox" value="true" /><input name="IsBoardEmployee" type="hidden" value="false" />

        State

            <select class="form-control" id="State_ID" name="State_ID"><option value="">-- Please select a State --</option>
<option value="1">Haryana</option>
<option value="2">Punjab</option>
<option value="3">Himachal Pradesh</option>
<option value="5">Kerala</option>
<option value="6">Gujrat</option>
<option value="7">Rajasthan</option>
<option value="8">Orrissa</option>
<option value="9">Tamil Nadu</option>
<option value="10">Andhra Pradesh</option>
<option value="11">Telengana</option>
<option value="12">West Bengal</option>
<option value="13">Manipur</option>
<option value="14">Aasam</option>
<option value="15">Bihar</option>
<option value="16">Jharkhand</option>
</select>

        City

            <select class="form-control" id="City_ID" name="City_ID"><option value="">-- Please select a City --</option>
<option value="1">Kurukshetra</option>
<option value="2">Ambala</option>
<option value="3">Panchkula</option>
<option value="4">Mohali</option>
<option value="5">Jalandhar</option>
<option value="6">Amritsar</option>
<option value="7">Patiala</option>
<option value="8">Ludhiana</option>
<option value="9">Jind</option>
</select>

        Area

            <select class="form-control" id="Area_ID" name="Area_ID"><option value="">-- Please select area --</option>
<option value="2">Sector 18</option>
<option value="3">Sector 17</option>
<option value="4">Sector 16</option>
<option value="5">Sector 15</option>
<option value="6">Sector 14</option>
</select>

        Address

            <input class="form-control" data-val="true" data-val-required="The Address field is required." id="Address" name="Address" type="text" value="" />

            <input id="submitButton" value="Register" type="submit" class="btn btn-default" />

</form>

© 2017 - My ASP.NET Application

Body:
You should change val to val(). Here is a link to jQuery val()

$(document).ready(function () {
    $("#State_ID").change(function () {
        $("#City_ID").empty();
        $.ajax({
            type: 'POST',
            url: "/MyAccount/GetCities",
            dataType: 'json',
            data: { id: $("#State_ID").val() },
            success: function (cities) {
                $("#City_ID").append('<option value =0>-- Please select a City --</option>');
                $.each(cities, function (i, city) {
                    $("#City_ID").append('<option value="' + city.Value + '">' + city.Text + '</option>');
                });;
            },
            error: function (ex) {
                alert("Failed" + JSON.stringify(ex));
            }
        });
    });
    $("#submitButton").click(function (e) {
        if ($("#State_ID").val() == '' || $("#State_ID").val() == 0) {
            e.preventDefault();
            alert("Please select State");
        }
        else if ($("#City_ID").val() = '' || $("#City_ID").val() == 0) {
            e.preventDefault();
            alert("Please select City");
        }
        else if ($("#Area_ID").val() == '' || $("#Area_ID").val() == 0) {
            e.preventDefault();
            alert("Please select area");
        }
    })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - My ASP.NET Application</title>
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

    <script src="/Scripts/modernizr-2.8.3.js"></script>

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/">Lightmap</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a href="/">Home</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">About Us</a>
                        <ul class="dropdown-menu">
                            <li><a href="/Home/About">About</a></li>
                            <li><a href="/Home/Contact">Contact</a></li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Services</a>
                        <ul class="dropdown-menu">
                            <li><a href="/Home/About">New Connection</a></li>
                            <li><a href="/Home/Forms">Download Forms</a></li>
                            <li><a href="/Home/Offices">Locate Nearest Offices</a></li>
                            <li><a href="/Home/Complaint">Locate Nearest Complaint Centers</a></li>
                            <li><a href="/Home/RTI">Right To Information</a></li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">My Account</a>
                        <ul class="dropdown-menu">
                            <li><a href="/MyAccount/Login" id="loginLink">Log in</a></li>
                            <li><a href="/MyAccount/Register" id="loginLink">Register</a></li>
                            <li><a href="/MyAccount/Information">Consumer Information</a></li>
                            <li><a href="/MyAccount/ViewBill">View Bill</a></li>
                            <li><a href="/MyAccount/BillSummary">Bill Summary</a></li>
                            <li><a href="/MyAccount/History">Consumption History</a></li>
                            <li><a href="/MyAccount/Calculate">Consumption Calculator</a></li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Payment Options</a>
                        <ul class="dropdown-menu">
                            <li><a href="/Payment/Centers">Locate Payment Centers</a></li>
                            <li><a href="/Payment/CalculateCharges">Calculate Charges</a></li>
                            <li><a href="/Payment/History">Payment History</a></li>
                            <li><a href="/Payment/Tariff">Tariff Charges</a></li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Support</a>
                        <ul class="dropdown-menu">
                            <li><a href="/Support/About">Help/FAQ</a></li>
                            <li><a href="/Support/Feedback">Feedback</a></li>
                            <li><a href="/Home/About">About</a></li>
                            <li><a href="/Home/Contact">Register a complaint</a></li>
                            <li><a href="/Home/Contact">Contact</a></li>
                            <li><a href="/Home/Contact">Contact</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">

<h2>Register</h2>

<form action="/MyAccount/Register" class="form-horizontal" method="post" role="form"><input name="__RequestVerificationToken" type="hidden" value="9IRV0jQ_Xvvr5BgyjyPPjjjdYZadB7ZhvzOpOI_2a0gMgcyJlQNK9dC7WBjNy9ObokH0CDvWxAiVTT_CCjpcGGgn0zOrBBV6rxcSdQb8AC41" /><div class="validation-summary-valid text-danger" data-valmsg-summary="true"><ul><li style="display:none"></li>
</ul></div>    <div class="form-group">
        <label class="col-md-2 control-label" for="Name">Name</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="Aadhar">Aadhar Card Number</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-length="Enter a valid Aadhar Card Number" data-val-length-max="12" data-val-length-min="12" id="Aadhar" name="Aadhar" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="Email">Email Address</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-email="The Email Address field is not a valid e-mail address." id="Email" name="Email" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="Phone_Number">Phone Number</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-required="The Phone Number field is required." id="Phone_Number" name="Phone_Number" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="Meter_Number">Meter Number</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-required="The Meter Number field is required." id="Meter_Number" name="Meter_Number" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-10">
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="IsBoardEmployee">Is board employee?</label>
        <div class="col-md-10">
            <input class="check-box" data-val="true" data-val-required="The Is board employee? field is required." id="IsBoardEmployee" name="IsBoardEmployee" type="checkbox" value="true" /><input name="IsBoardEmployee" type="hidden" value="false" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">State</label>
        <div class="col-md-10">

            <select class="form-control" id="State_ID" name="State_ID"><option value="">-- Please select a State --</option>
<option value="1">Haryana</option>
<option value="2">Punjab</option>
<option value="3">Himachal Pradesh</option>
<option value="5">Kerala</option>
<option value="6">Gujrat</option>
<option value="7">Rajasthan</option>
<option value="8">Orrissa</option>
<option value="9">Tamil Nadu</option>
<option value="10">Andhra Pradesh</option>
<option value="11">Telengana</option>
<option value="12">West Bengal</option>
<option value="13">Manipur</option>
<option value="14">Aasam</option>
<option value="15">Bihar</option>
<option value="16">Jharkhand</option>
</select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">City</label>
        <div class="col-md-10">
            <select class="form-control" id="City_ID" name="City_ID"><option value="">-- Please select a City --</option>
<option value="1">Kurukshetra</option>
<option value="2">Ambala</option>
<option value="3">Panchkula</option>
<option value="4">Mohali</option>
<option value="5">Jalandhar</option>
<option value="6">Amritsar</option>
<option value="7">Patiala</option>
<option value="8">Ludhiana</option>
<option value="9">Jind</option>
</select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">Area</label>
        <div class="col-md-10">
            <select class="form-control" id="Area_ID" name="Area_ID"><option value="">-- Please select area --</option>
<option value="2">Sector 18</option>
<option value="3">Sector 17</option>
<option value="4">Sector 16</option>
<option value="5">Sector 15</option>
<option value="6">Sector 14</option>
</select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label" for="Address">Address</label>
        <div class="col-md-10">
            <input class="form-control" data-val="true" data-val-required="The Address field is required." id="Address" name="Address" type="text" value="" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input id="submitButton" value="Register" type="submit" class="btn btn-default" />
        </div>
    </div>
</form>

        <hr />
        <footer>
            <p>&copy; 2017 - My ASP.NET Application</p>
        </footer>
    </div>

    <script src="/Scripts/jquery-3.1.1.js"></script>

    <script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>

    <script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/MyAccount/Register.js"></script>


问:
What does an "&" before a pseudo element in CSS mean?
In the following CSS taken from Twitter Bootstrap what does the ampersand (&) character mean?</p>

```<code>.clearfix {
  *zoom: 1;
  &:before,
  &:after {
    display: table;
    content: "";
  }
  &:after {
    clear: both;
  }
}
</code>```

答:
Here is an SCSS/LESS example:

```<code>a {
   text-decoration: underline;
   @include padding(15px);
   display: inline-block;

     & img  {
                padding-left: 7px;
               margin-top: -4px;
             }
 }
</code>```

and its equivalent in CSS:

```<code>a {
  text-decoration: underline;
  @include padding(15px);
  display: inline-block;
}

a img  {
     padding-left: 7px;
     margin-top: -4px;
   }
</code>```

Body:
In the following CSS taken from Twitter Bootstrap what does the ampersand (&) character mean?

.clearfix {
  *zoom: 1;
  &:before,
  &:after {
    display: table;
    content: "";
  }
  &:after {
    clear: both;
  }
}

Body:
Here is an SCSS/LESS example:

a {
   text-decoration: underline;
   @include padding(15px);
   display: inline-block;

     & img  {
                padding-left: 7px;
               margin-top: -4px;
             }
 }

and its equivalent in CSS:

a {
  text-decoration: underline;
  @include padding(15px);
  display: inline-block;
}

a img  {
     padding-left: 7px;
     margin-top: -4px;
   }


问:
Searching files filtering by extension returns too many results
I'm developing a C++ console application that has to manage files on Windows OS. I need to obtain a 'list' of file names which have a specific extension. I've found a lot of solutions, the most suggested one is the following one:

```<code>HANDLE hFind;
WIN32_FIND_DATA data;

hFind = FindFirstFile("C:\\PWS\\*.sda", &data);
if (hFind != INVALID_HANDLE_VALUE) {
    do {
        cout << data.cFileName << endl;

    } while (FindNextFile(hFind, &data));
    FindClose(hFind);
}
</code>```

Suppose I have these files inside the C:\\PWS folder:

f001.sdac

f002.sda

f003.sdab

f004.sda

The above code prints all of them, while I only need f002.sda and f004.sda.

Any hint?

NB: I don't want to use boost library.

答:
Something like this should filter the results for you:</p>

```<code>bool hasFileExtension(TCHAR cFileName[], TCHAR* ptcExtension)
{
    bool result = true;
    int iFileNameLength = _tcslen(cFileName);
    int iExtensionLength = _tcslen(ptcExtension);

    if (iFileNameLength >= iExtensionLength)
    {
        for (int i = 1; i < iExtensionLength + 1 && result; i++)
        {
            if (cFileName[iFileNameLength - i] != ptcExtension[iExtensionLength - i])
            {
                result = false;
            }
        }
    }
    else
    {
        result = false;
    }

    return result;
}

void listFilesWithExtension(LPCTSTR lpFileName, TCHAR* ptcExtension)
{
    HANDLE hFind;
    WIN32_FIND_DATA data;

    hFind = FindFirstFile(lpFileName, &data);
    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            if (hasFileExtension(data.cFileName, ptcExtension))
            {
                wcout << data.cFileName << endl;
            }
        } while (FindNextFile(hFind, &data));
        FindClose(hFind);
    }
}

int main()
{
    LPCTSTR lpFileName = L"C:\\PWS\\*.sda";
    TCHAR* ptcExtension = _T(".sda");
    listFilesWithExtension(lpFileName, ptcExtension);
    Sleep(5000);
    return 0;
}
</code>```

Body:
I'm developing a C++ console application that has to manage files on Windows OS. I need to obtain a 'list' of file names which have a specific extension. I've found a lot of solutions, the most suggested one is the following one:

HANDLE hFind;
WIN32_FIND_DATA data;

hFind = FindFirstFile("C:\\PWS\\*.sda", &data);
if (hFind != INVALID_HANDLE_VALUE) {
    do {
        cout << data.cFileName << endl;

    } while (FindNextFile(hFind, &data));
    FindClose(hFind);
}

Suppose I have these files inside the C:\\PWS folder:

f001.sdac

f002.sda

f003.sdab

f004.sda

The above code prints all of them, while I only need f002.sda and f004.sda.

Any hint?

NB: I don't want to use boost library.

Body:
Something like this should filter the results for you:

bool hasFileExtension(TCHAR cFileName[], TCHAR* ptcExtension)
{
    bool result = true;
    int iFileNameLength = _tcslen(cFileName);
    int iExtensionLength = _tcslen(ptcExtension);

    if (iFileNameLength >= iExtensionLength)
    {
        for (int i = 1; i < iExtensionLength + 1 && result; i++)
        {
            if (cFileName[iFileNameLength - i] != ptcExtension[iExtensionLength - i])
            {
                result = false;
            }
        }
    }
    else
    {
        result = false;
    }

    return result;
}

void listFilesWithExtension(LPCTSTR lpFileName, TCHAR* ptcExtension)
{
    HANDLE hFind;
    WIN32_FIND_DATA data;

    hFind = FindFirstFile(lpFileName, &data);
    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            if (hasFileExtension(data.cFileName, ptcExtension))
            {
                wcout << data.cFileName << endl;
            }
        } while (FindNextFile(hFind, &data));
        FindClose(hFind);
    }
}

int main()
{
    LPCTSTR lpFileName = L"C:\\PWS\\*.sda";
    TCHAR* ptcExtension = _T(".sda");
    listFilesWithExtension(lpFileName, ptcExtension);
    Sleep(5000);
    return 0;
}


答:
The issue is how you're building the JSON. Each item has it's own object due to the use of serializeArray() on the form, which means you have no idea what property is for what room.

To fix this use map() to build the array of objects per room. Like this:

```<code>function save_all_rooms() {
  $(".save_all_rooms").on('click', function(e) {
    var formData = $('.add_new_form .the_form').map(function() {
      return {
        check_in: $(this).find('[name="check_in"]').val(),
        check_out: $(this).find('[name="check_out"]').val(),
        room_type: $(this).find('[name="room_type"]').val(),
        adults: $(this).find('[name="adults"]').val(),
        children: $(this).find('[name="children"]').val()
      }
    }).get();
    console.log(formData);
  });
}
</code>```

Updated fiddle

The result of this will be in the below format, where each object contains the properties of a room. This can then be easily iterated over:

```<code>[{
  "check_in": "07/04/2017",
  "check_out": "07/10/2017",
  "room_type": "option_1",
  "adults": "1",
  "children": "1"
}, {
  "check_in": "07/28/2017",
  "check_out": "07/31/2017",
  "room_type": "option_3",
  "adults": "3",
  "children": "3"
}]
</code>```

Title: Formatting JSON data and displaying in a PHP for loop

Body:
I have some form data which I'm saving in JSON format using jQuery (this is all working fine).

But I then want to take the JSON data and display it in a PHP for loop. This is where I'm having trouble as jQuery's serializeArray and JSON.stringify just adds each form value in one bit chunk e.g.

check in, check out, room, adults, children, check in, check out, room, adults, children, check in, check out, room, adults, children

But I want to separate each room e.g.

(Room 1) check in, check out, room, adults, children
(Room 2) check in, check out, room, adults, children
(Room 3) check in, check out, room, adults, children

JSFiddle of how the form data is created (everything working fine): https://jsfiddle.net/kuohhm2q/

PHP I'm using to try a display JSON data in for loop (not working):

<?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);

//print_r($data);

foreach($data as $key => $val) { ?>

    <?php echo $key; ?>

<?php } ?>

Body:
The issue is how you're building the JSON. Each item has it's own object due to the use of serializeArray() on the form, which means you have no idea what property is for what room.

To fix this use map() to build the array of objects per room. Like this:

function save_all_rooms() {
  $(".save_all_rooms").on('click', function(e) {
    var formData = $('.add_new_form .the_form').map(function() {
      return {
        check_in: $(this).find('[name="check_in"]').val(),
        check_out: $(this).find('[name="check_out"]').val(),
        room_type: $(this).find('[name="room_type"]').val(),
        adults: $(this).find('[name="adults"]').val(),
        children: $(this).find('[name="children"]').val()
      }
    }).get();
    console.log(formData);
  });
}

Updated fiddle

The result of this will be in the below format, where each object contains the properties of a room. This can then be easily iterated over:

[{
  "check_in": "07/04/2017",
  "check_out": "07/10/2017",
  "room_type": "option_1",
  "adults": "1",
  "children": "1"
}, {
  "check_in": "07/28/2017",
  "check_out": "07/31/2017",
  "room_type": "option_3",
  "adults": "3",
  "children": "3"
}]


问:
ng-repeat is Working perfectly with static json But fires exception with dynamic json data
I have a ng-repeat put on a list to display in table.

the script html code is like this :

```<code>`<tr ng-repeat="user in users track by $index" ng-class="{'selected':$index == selectedRow}">
                    <td>
                        {{user.FirstName}}
                    </td>
                    <td>
                        {{user.LastName}}
                    </td>
                    <td>
                        {{user.EmailId}}
                    </td>
                    <td>
                        {{user.ContactNumber}}
                    </td>
                    <td>
                        <button type="button" class="btn btn-warning">
                            <span class="glyphicon glyphicon-pencil"></span>
                        </button>
                        <button type="button" class="btn btn-danger">
                            <span class="glyphicon glyphicon-remove"></span>
                        </button>
                    </td>
                </tr>`
</code>```

and in angular script the routing is defined as bellow:

```<code>var routingApp = angular.module('App', []);
routingApp.controller("MovieController", ['$scope', '$http', function ($scope, $http) {

$scope.edit = false;
$scope.error = false;
$scope.success = false;
//TO DO : Below portion to be replaced with ajax call to get list of movies from DB
var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
console.log(users); //debugger;
    $scope.users = users;

}]);
</code>```

This part is working absolutely fine.

but when i replace the static json data ie;

```<code> var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
</code>```

with

```<code>$http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {
    dt = JSON.stringify(response.data);
    $scope.users = dt;
    //console.log(dt);
    //console.log(JSON.parse(dt));
})
</code>```

it will through this exception :

```<code>`[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: string:", Duplicate value`
</code>```

But the output of the api is exactly same as static json, in fact i have copied json from api output itself.

Even i have tried removing  track by $index but No luck.
are there any solutions to this issue?

答:
try this without stringifying the response and itrate through users.</p>

```<code>$http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {

$scope.users = response.data;

})
</code>```

Body:
I have a ng-repeat put on a list to display in table.

the script html code is like this :

`

                        {{user.FirstName}}

                        {{user.LastName}}

                        {{user.EmailId}}

                        {{user.ContactNumber}}

                        <button type="button" class="btn btn-warning">

                        </button>
                        <button type="button" class="btn btn-danger">

                        </button>

`

and in angular script the routing is defined as bellow:

var routingApp = angular.module('App', []);
routingApp.controller("MovieController", ['$scope', '$http', function ($scope, $http) {

$scope.edit = false;
$scope.error = false;
$scope.success = false;
//TO DO : Below portion to be replaced with ajax call to get list of movies from DB
var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
console.log(users); //debugger;
    $scope.users = users;

}]);

This part is working absolutely fine.

but when i replace the static json data ie;

 var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];

with

$http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {
    dt = JSON.stringify(response.data);
    $scope.users = dt;
    //console.log(dt);
    //console.log(JSON.parse(dt));
})

it will through this exception :

`[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: string:", Duplicate value`

But the output of the api is exactly same as static json, in fact i have copied json from api output itself.

Even i have tried removing  track by $index but No luck.
are there any solutions to this issue?

Body:
try this without stringifying the response and itrate through users.

$http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {

$scope.users = response.data;

})


问:
Displaying MySQL Data with Images in Table
I have set up a table that displays data from my SQL database using

```<code> $sql = "SELECT company_id, stk_buy, stk_sell FROM price";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
       echo "<table><tr><th>ID</th><th>Company</th><th>Buying Price</th><th>Selling Price</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["company_id"]."</td><td>".$row["stk_buy"]."</td><td>".$row["stk_sell"]."</td></tr>";
    }
    echo "</table>";
   } else {
       echo "0 results";
   }
</code>```

I want to have images display in the Company column, different ones in each row.
Similar to:
Is there a possible way of displaying images with my current html table setup or do I have to fetch each row to display images?

答:
You need to fetch the image name from the database, after fetching the images you need to put it inside a  tag.

The source of the image considering the img as you mention in the comment.

SQL: $sql = "SELECT company_id, stk_buy, stk_sell FROM price";

```<code>echo "<tr><td>".$row["company_id"]."</td><td><img src='img/".$row[company_id].".png' style='width:175px;height:75px;'/></td><td>".$row["stk_buy"]."</td><td>".$row["stk_sell"]."</td></tr>";
</code>```

Body:
I have set up a table that displays data from my SQL database using

 $sql = "SELECT company_id, stk_buy, stk_sell FROM price";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
       echo "

ID	Company	Buying Price	Selling Price
";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "
".$row["company_id"]."	".$row["stk_buy"]."	".$row["stk_sell"]."
";
    }
    echo "
";
   } else {
       echo "0 results";
   }

I want to have images display in the Company column, different ones in each row.
Similar to:
Is there a possible way of displaying images with my current html table setup or do I have to fetch each row to display images?

Body:
You need to fetch the image name from the database, after fetching the images you need to put it inside a <IMG src=""> tag.

The source of the image considering the img as you mention in the comment.

SQL: $sql = "SELECT company_id, stk_buy, stk_sell FROM price";

echo "<tr><td>".$row["company_id"]."</td><td><img src='img/".$row[company_id].".png' style='width:175px;height:75px;'/></td><td>".$row["stk_buy"]."</td><td>".$row["stk_sell"]."</td></tr>";


问:
replicate json encoded assoc array?
I have a json string

```<code>{
   "to": {
      "data": [
         {
            "name": "f8",
            "id": "11204705797"
         },
         {
            "name": "f9",
            "id": "11205705797"
         }
      ]
   }
}
</code>```

and I need to replicate it in php, what I have is a array of name&id's like this

```<code>Array
(
    [friends] => Array
        (
            [0] => 939394934-Steve
            [1] => 939394934-Steve
            [2] => 939394934-Steve
            [3] => 939394934-Steve
        )

)
</code>```

and I would explode by - to get id-name

How can I do this?

答:
If I understand correctly, you want something like this:</p>

```<code>$data = array();
foreach ($array['friends'] as $friend) {
    list($id, $name) = explode('-', $friend, 2);
    $data[] = array(
        'name' => $name,
        'id' => $id,
    );
}

$to = new stdClass; // 'to' appears to be an object... because of {}
$to->data = $data;
echo json_encode(array('to'=>$to));
</code>```

Title: replicate json encoded assoc array?

Body:
I have a json string

{
   "to": {
      "data": [
         {
            "name": "f8",
            "id": "11204705797"
         },
         {
            "name": "f9",
            "id": "11205705797"
         }
      ]
   }
}

and I need to replicate it in php, what I have is a array of name&id's like this

Array
(
    [friends] => Array
        (
            [0] => 939394934-Steve
            [1] => 939394934-Steve
            [2] => 939394934-Steve
            [3] => 939394934-Steve
        )

)

and I would explode by - to get id-name

How can I do this?

Body:
If I understand correctly, you want something like this:

$data = array();
foreach ($array['friends'] as $friend) {
    list($id, $name) = explode('-', $friend, 2);
    $data[] = array(
        'name' => $name,
        'id' => $id,
    );
}

$to = new stdClass; // 'to' appears to be an object... because of {}
$to->data = $data;
echo json_encode(array('to'=>$to));


答:
```<code>SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
        appleid AS appleid1
        WHERE num>=$head ORDER BY `TimeStamp`
        DESC LIMIT $this->apple_id_num ;
</code>```

put your limit after orderby

Body:
I'm using php and pdo

Here is my code:

try {
    $sql="LOCK TABLE appleid WRITE, appleid AS appleid1 READ;";
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $sql="SELECT MAX(num) FROM appleid;";//to know how many rows it has
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $result=$stmt->fetch();
    $table_top=$result[0];

    if (empty($head)) $head = 1;
    $check=$table_top - $head;
    $check++;//number of available rows that are ready to use

    if($check>=$this->apple_id_num)
    {
        $sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
        appleid AS appleid1
        WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
        DESC;";
        $stmt = $GLOBALS['$connection']->prepare($sql);
        $stmt->execute();
        $this->pre_head=$head;
        $head=1+$head+$this->apple_id_num;
        $sql="UNLOCK TABLES;";
        $this->num_rows = $stmt->rowCount();
        echo $stmt->rowCount();
    }
}
catch(PDOException $e)
{
    echo $sql . "
" . $e->getMessage();
}

I get this error :

SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM appleid AS
  appleid1 WHERE num>=1 LIMIT 1 ORDER BY TimeStamp DESC;
  SQLSTATE[42000]: Syntax error

or access violation: 1064 You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near 'ORDER BY TimeStamp DESC' at line 2

I got confused and I don't know what is wrong with this query and how to fix it.

Body:
SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
        appleid AS appleid1
        WHERE num>=$head ORDER BY `TimeStamp`
        DESC LIMIT $this->apple_id_num ;

put your limit after orderby


问:
What happens in the background of array initialization in c?
Given that this is legal

```<code>uint8_t bytes[4] = { 1, 2, 3, 4 };
</code>```

And this is not:

```<code>uint8_t bytes2[4];
bytes2 = { 1, 2, 3, 4 };
</code>```

what does { 1, 2, 3, 4 } represent?

Am assuming it's neither an rvalue or an lvalue. A preprocessor code candy that expands to something?

答:
A syntax like {1,2,3,4}; is called brace-enclosed initializer list, it's an initializer. It can be only used for initialization (for array type).

Quoting C11, chapter §6.7.9

P11

The initializer for a scalar shall be a single expression,

[an array is not a scalar type, so not applicable for us]

P14

An array of character type may be initialized by a character string literal or UTF−8 string
  literal, optionally enclosed in braces.

[We are not using a string literal here, so also not applicable for us]

P16

Otherwise, the initializer for an object that has aggregate or union type shall be a brace-enclosed
  list of initializers for the elements or named members.

[This is the case of our interest]

and, P17,

Each brace-enclosed initializer list has an associated current object. When no
  designations are present, subobjects of the current object are initialized in order according
  to the type of the current object: array elements in increasing subscript order, structure
  members in declaration order, and the first named member of a union.[....]

So, here, the values from the brace enclosed list are not directly "assigned" to the array, they are used to initialize individual members of the array.

OTOH, an array type, is not a modifiable lvalue, so it cannot be assigned. In other words, an array variable cannot be used as the LHS of the assignment operator.

To elaborate, from C11, chapter §6.5.16

assignment operator shall have a modifiable lvalue as its left operand.

Body:
Given that this is legal

uint8_t bytes[4] = { 1, 2, 3, 4 };

And this is not:

uint8_t bytes2[4];
bytes2 = { 1, 2, 3, 4 };

what does { 1, 2, 3, 4 } represent?

Am assuming it's neither an rvalue or an lvalue. A preprocessor code candy that expands to something?


问:
iOS: How to get the constraints for button inside horizontal stack-view right?
I am new to iOS development and am following the udacity course for iOS development. I am stuck at the lesson whose link I have given below.

https://classroom.udacity.com/courses/ud585/lessons/6991272849/concepts/72642287220923#

I am unable to reduce the size of stop button in the last stack view. I tried reducing the size of the button by setting the width constraint of the button to 64 and height of stack-view containing that button to 64. But XCode gives error of conflicting constraints.

I am attaching screenshots below for reference.

What I actually want is:

https://d17h27t6h515a5.cloudfront.net/topher/2016/November/582a8006_interface/interface.png

答:
Another option if you want to keep the existing constraints you have in the screenshot from the course is to change the properties of the stack in Interface builder.

For topmost stack

set alignment to fill, and distribution to fill proportionally.

For your stack at bottom with button in it -

set alignment to centre and distribution equal centering.


问:
Interacting with <dialog> with Geb/Selenium (only with Chrome)
All my Geb/Spock tests were running perfectly on Firefox and then I tried with Chrome (v59) and it keep hanging when an alert or confirm pop up is raised.

With Firefox I was using withAlert{} or withConfirm{} to handle those but it doesn't work with Chrome.

So I did some digging into views and I found out that dialog were managed by this widget. So I created accessors to <dialog> in my page object but Chrome is still unable to interact with it (no way to detect that the pop up is displayed nor closing it).
I tried several things such as using displayed or waiting for the text to be shown but nothing worked.

I am not used to jQuery so maybe I am missing something here?

Here is a sample of the code I must interact with:

```<code><dialog class="qq-alert-dialog-selector">
    <div class="qq-dialog-message-selector"></div>

    <div class="qq-dialog-buttons">
        <button type="button" class="qq-cancel-button-selector">Close</button>
    </div>
</dialog>
</code>```

And this is how I try to access to it (in my page object):

```<code>alertPopUp {$("dialog", class:"qq-alert-dialog-selector")}
alertCloseButton {alertPopUp.children("div.qq-dialog-buttons").children("button")}
</code>```

And finally how I would like to test the pop up:

```<code>when: "Trying to upload ..."
uploadFileButton = incorrect.absolutePath

then: "An alerting pop up occurs"
waitFor{alertPopUp.displayed}

when: "Closing the pop up"
alertCloseButton.click(SubmitAClaim)

then: "Number of uploaded files should not change"
uploadedElements.size() == initialUploadedFiles
</code>```

Can anyone help? I guess it may have something to do with chrome's focus (I mean if it is currently on the pop up or on the page behind.

EDIT:

After all, it seems that the problem is not linked with jQuery (good thing I guess). We can verify the dialog box is open thanks to open attribute in <dialog>. I have done something like this:

```<code>when: "Trying to upload ..."
uploadFileButton = incorrect.absolutePath

then: "A alerting pop up occurs"
waitFor {alertPopUp.getAttribute("open") == "true"}
</code>```

But I still cannot interact with the dialog box: when I try to click on alertCloseButton it raise an ElementNotVisibleException. So it has something to do with browser focus, I guess.
I tried:

withWindow{} or driver.switchTo().window() but the only window available is the main one.

withFrame() but I get a NoSuchFrameException

driver.switchTo().alert() but it raise a NoAlertRaisedException

So I wonder if someone know how Chrome considers <dialog> tag (alert, confirm, ...) ?

Note: According to caniuse.com, Chrome is the only browser compatible with <dialog> for now.

答:
Finally I managed to find a way to handle this issue. I took a look into google demo for <dialog> use and I used the js object provided by Geb to execute the js example from Google. This finally gives this:

```<code>when: "Trying to upload ..."
uploadFileButton = incorrect.absolutePath

then: "A alerting pop up occurs"
waitFor {alertPopUp.getAttribute("open") == "true"}

when: "Closing the pop up"
report "After upload"
js.exec """var dialog = document.querySelector(".qq-alert-dialog-selector");
    dialog.close();
    return true;
"""

then: "Number of uploaded files should not change"
uploadedElements.size() == initialUploadedFiles
</code>```

This is really brute force and I don't like it as it relies a lot on back end, how dialogs are set up etc... But it works. I really hope Geb/Selenium will provide something easier to use (as <dialog>is W3C it will become usual on all browsers).

Body:
All my Geb/Spock tests were running perfectly on Firefox and then I tried with Chrome (v59) and it keep hanging when an alert or confirm pop up is raised.

With Firefox I was using withAlert{} or withConfirm{} to handle those but it doesn't work with Chrome.

So I did some digging into views and I found out that dialog were managed by this widget. So I created accessors to <dialog> in my page object but Chrome is still unable to interact with it (no way to detect that the pop up is displayed nor closing it).
I tried several things such as using displayed or waiting for the text to be shown but nothing worked.

I am not used to jQuery so maybe I am missing something here?

Here is a sample of the code I must interact with:

<dialog class="qq-alert-dialog-selector">

        <button type="button" class="qq-cancel-button-selector">Close</button>

</dialog>

And this is how I try to access to it (in my page object):

alertPopUp {$("dialog", class:"qq-alert-dialog-selector")}
alertCloseButton {alertPopUp.children("div.qq-dialog-buttons").children("button")}

And finally how I would like to test the pop up:

when: "Trying to upload ..."
uploadFileButton = incorrect.absolutePath

then: "An alerting pop up occurs"
waitFor{alertPopUp.displayed}

when: "Closing the pop up"
alertCloseButton.click(SubmitAClaim)

then: "Number of uploaded files should not change"
uploadedElements.size() == initialUploadedFiles

Can anyone help? I guess it may have something to do with chrome's focus (I mean if it is currently on the pop up or on the page behind.

EDIT:

After all, it seems that the problem is not linked with jQuery (good thing I guess). We can verify the dialog box is open thanks to open attribute in <dialog>. I have done something like this:

when: "Trying to upload ..."
uploadFileButton = incorrect.absolutePath

then: "A alerting pop up occurs"
waitFor {alertPopUp.getAttribute("open") == "true"}

But I still cannot interact with the dialog box: when I try to click on alertCloseButton it raise an ElementNotVisibleException. So it has something to do with browser focus, I guess.
I tried:

withWindow{} or driver.switchTo().window() but the only window available is the main one.

withFrame() but I get a NoSuchFrameException

driver.switchTo().alert() but it raise a NoAlertRaisedException

So I wonder if someone know how Chrome considers <dialog> tag (alert, confirm, ...) ?

Note: According to caniuse.com, Chrome is the only browser compatible with <dialog> for now.

Body:
Finally I managed to find a way to handle this issue. I took a look into google demo for <dialog> use and I used the js object provided by Geb to execute the js example from Google. This finally gives this:

when: "Trying to upload ..."
uploadFileButton = incorrect.absolutePath

then: "A alerting pop up occurs"
waitFor {alertPopUp.getAttribute("open") == "true"}

when: "Closing the pop up"
report "After upload"
js.exec """var dialog = document.querySelector(".qq-alert-dialog-selector");
    dialog.close();
    return true;
"""

then: "Number of uploaded files should not change"
uploadedElements.size() == initialUploadedFiles

This is really brute force and I don't like it as it relies a lot on back end, how dialogs are set up etc... But it works. I really hope Geb/Selenium will provide something easier to use (as <dialog>is W3C it will become usual on all browsers).