问:
Align a set of inline-blocks by a middle element
Consider we have a bunch of inline-blocks in a row:

```<code><div class="elements-row">
  <div class="element">January</div>
  <div class="element">February</div>
  <div class="element">March</div>
  <div class="element featured">April</div>
  <div class="element">May</div>
  <div class="element">June</div>
  <div class="element">July</div>
<div>
</code>```

```<code>.elements-row {
    height: 140px;
    display: inline-block;
    text-align: center;
    overflow: hidden;
}

.elements-row .element {
    display: inline-block;
    font-size: 40px;
    color: #abb8c2;
    margin: 0 15px;
}

.elements-row .element.featured {
    margin: 0 40px;
    color: #4a667f;
}
</code>```

Is there a way to horizontally align the row the way that .featured block always remains in the middle of the .elements-row block no matter what other elements width is (its' content is dynamic). Elements are allowed to go out of row's boundaries, but a space between all elements except of .featured should be constant.

A demo on CodePen

答:
You could do it this way:

.elements-row {
    height: 140px;
    display: block;
    text-align: center;
    overflow: hidden;
}

.elements-row .element {
    display: inline-block;
    font-size: 10px;
    color: #abb8c2;
    margin: 0 15px;
}

.elements-row .element.featured {
    margin: 0 40px;
    color: #4a667f;
}

.elements-center {
    display: inline-block;
    position: relative;
}

.elements-left {
    top: 0;
    position: absolute;
    right: 100%;
    white-space: nowrap;
}

.elements-right {
    top: 0;
    position: absolute;
    left: 100%;
    white-space: nowrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="elements-row">
    <div class="elements-center">
        <div class="elements-left">
            <div class="element">January</div>
            <div class="element">February</div>
            <div class="element">March</div>
        </div>
        <div class="element featured">April</div>
        <div class="elements-right">
            <div class="element">May</div>
            <div class="element">June</div>
            <div class="element">July</div>
        </div>
    </div>
</div></code>```

Also on JSFiddle... at least something to start with.

Body:
Consider we have a bunch of inline-blocks in a row:

January

February

March

April

May

June

July

.elements-row {
    height: 140px;
    display: inline-block;
    text-align: center;
    overflow: hidden;
}

.elements-row .element {
    display: inline-block;
    font-size: 40px;
    color: #abb8c2;
    margin: 0 15px;
}

.elements-row .element.featured {
    margin: 0 40px;
    color: #4a667f;
}

Is there a way to horizontally align the row the way that .featured block always remains in the middle of the .elements-row block no matter what other elements width is (its' content is dynamic). Elements are allowed to go out of row's boundaries, but a space between all elements except of .featured should be constant.

A demo on CodePen

Body:
You could do it this way:

.elements-row {
    height: 140px;
    display: block;
    text-align: center;
    overflow: hidden;
}

.elements-row .element {
    display: inline-block;
    font-size: 10px;
    color: #abb8c2;
    margin: 0 15px;
}

.elements-row .element.featured {
    margin: 0 40px;
    color: #4a667f;
}

.elements-center {
    display: inline-block;
    position: relative;
}

.elements-left {
    top: 0;
    position: absolute;
    right: 100%;
    white-space: nowrap;
}

.elements-right {
    top: 0;
    position: absolute;
    left: 100%;
    white-space: nowrap;
}

<div class="elements-row">
    <div class="elements-center">
        <div class="elements-left">
            <div class="element">January</div>
            <div class="element">February</div>
            <div class="element">March</div>
        </div>
        <div class="element featured">April</div>
        <div class="elements-right">
            <div class="element">May</div>
            <div class="element">June</div>
            <div class="element">July</div>
        </div>
    </div>
</div>

Also on JSFiddle... at least something to start with.


来源: stackexchange

问:
How I See my Result in Select from Where MYSQL using PHP?
I have this code, i try to call my data from table database mysql , but didn't see any result. always go to else , not go to the process. what would i do?

<?php
require('connectDB.php');
                 $nama = $_GET['nama'];
                 echo $nama;
                    $query = "SELECT * FROM pesan
                    WHERE nama = '%" . mysqli_real_escape_string($connection, $nama) . "%'

                    ";
              $results = mysqli_query($connection, $query);
              $baris = mysqli_num_rows($results);

              if (!$results) {
               die('Invalid query: ' . mysql_error());
              }

              if ( $baris > 0) {
               while($row = mysqli_fetch_assoc($results)) {
               ?>

Nama Mobil : <?php echo $row['mobil'] ?>

ID Pembelian : <?php echo $row['id']; ?>

Nama anda : <?php echo $row['nama']; ?>

Alamat : <?php echo $row['alamat']; ?>

Tanggal Masuk : <?php echo $row['tgl_masuk']; ?>

              <?php
               }
              }else{
               echo "error";
              }
              ?>```
</div>
</div>
</p>

<p>What wrong with my code?
Thanks!</p>

<p>im sorry , this is my ConnectDB.php , i include in my html. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
$connection = mysqli_connect('localhost', 'root', '', 'dealermobil');
if (!$connection){
    die("Database Connection Failed" . mysqli_error());
}

// $db = new PDO ('mysql:host=localhost;dbname=db_login;charset=utf8mb4','root','');
?></code>```

答:
use this you are using = it should be LIKE when you are trying to search a field in database.

```<code> $query = "SELECT * FROM `pesan` WHERE `nama` LIKE '%". mysqli_real_escape_string($connection, $nama) ."%'";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this code, i try to call my data from table database mysql , but didn't see any result. always go to else , not go to the process. what would i do?

<?php
require('connectDB.php');
                 $nama = $_GET['nama'];
                 echo $nama;
                    $query = "SELECT * FROM pesan
                    WHERE nama = '%" . mysqli_real_escape_string($connection, $nama) . "%'

                    ";
              $results = mysqli_query($connection, $query);
              $baris = mysqli_num_rows($results);

              if (!$results) {
               die('Invalid query: ' . mysql_error());
              }

              if ( $baris > 0) {
               while($row = mysqli_fetch_assoc($results)) {
               ?>

Nama Mobil : <?php echo $row['mobil'] ?>

ID Pembelian : <?php echo $row['id']; ?>

Nama anda : <?php echo $row['nama']; ?>

Alamat : <?php echo $row['alamat']; ?>

Tanggal Masuk : <?php echo $row['tgl_masuk']; ?>

              <?php
               }
              }else{
               echo "error";
              }
              ?>

What wrong with my code?
Thanks!

im sorry , this is my ConnectDB.php , i include in my html.

<?php
$connection = mysqli_connect('localhost', 'root', '', 'dealermobil');
if (!$connection){
    die("Database Connection Failed" . mysqli_error());
}

// $db = new PDO ('mysql:host=localhost;dbname=db_login;charset=utf8mb4','root','');
?>

Body:
use this you are using = it should be LIKE when you are trying to search a field in database.

 $query = "SELECT * FROM `pesan` WHERE `nama` LIKE '%". mysqli_real_escape_string($connection, $nama) ."%'";


问:
How to show all decimal digits in an Excel cell programatically using VBA
I have an Excel macro which stores some business values.

For one of the cell the value should display 999.999999 but it shows 1000 and in formula bar i see the value shown as 999.999999. Since these are converted values from one type to another, the customer wants me to show the value as it is without the decimal places getting rounded.

One workaround i thought was to convert the cell into text format before populating the value but this doesn't work as i need to support this in various regional settings.

Any suggestions on how to get the Excel VBA to know the number of digits after decimal to be displayed will be a great help.

Current code to populate cell value :

Range.Offset(0,0).Value = Response

Here, Response is the converted value i.e 999.999999 in string format.

答:
Since Excel's precision is limited to a maximum of 15 decimal digits, you can merely custom format the cells as

```<code>#.###############
</code>```

(15 #'s after the decimal)

You can do this without VBA, but the VBA code might look like:

```<code>Option Explicit

Sub ShowAllDecimals()
    Dim WS As Worksheet
    Dim R As Range, C As Range

Set WS = Worksheets("sheet1")
With WS
    Set R = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With

For Each C In R
    If IsNumeric(C) Then _
        C.NumberFormat = "#.################"
Next C

End Sub
</code>```

Body:
Since Excel's precision is limited to a maximum of 15 decimal digits, you can merely custom format the cells as

#.###############

(15 #'s after the decimal)

You can do this without VBA, but the VBA code might look like:

Option Explicit

Sub ShowAllDecimals()
    Dim WS As Worksheet
    Dim R As Range, C As Range

Set WS = Worksheets("sheet1")
With WS
    Set R = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With

For Each C In R
    If IsNumeric(C) Then _
        C.NumberFormat = "#.################"
Next C

End Sub


问:
Apple CareKit not able to navigate to OCKCareCardViewController
I am trying to implement basic functionality in Apple CareKit Framework. But i am not able to navigate to OCKCareCardViewController.

Please find my code here on Github
https://github.com/sandesh271991/CareKitDemo

Please guide me where I am doing wrong

答:
You are doing    self.navigationController?.pushViewController(careCardViewController, animated: true), but your ViewController does not have a navigationController.
Add a navigation controller in your storyboard, make it initial view controller, and make your ViewController as its rootViewController, and your code should work fine (See the image attached).Navigation Controller to ViewController


问:
User Agent Switcher for Chrome
I'm looking for a User Agent Switcher for Chrome.

Searching the Chrome Web Store does not come up with a simple switcher. I understand I can run the browser via command line and arguments: Google Chrome: Change User Agent to Access Website.

Is there a user agent switcher built in to the UI of Google Chrome? If so, how do I access it?

答:
You can use webRequest API to create a chrome extension to modify the headers. When OP asked this question, this API may not exist or may be in experimental phase but now this api is quite stable.

```<code>chrome.webRequest.onBeforeSendHeaders.addListener(
  function(details) {
    for (var i = 0; i < details.requestHeaders.length; ++i) {
      if (details.requestHeaders[i].name === 'User-Agent') {
        details.requestHeaders[i].value = "Android_Browser" // Set your value here
        break;
      }
    }
    return { requestHeaders: details.requestHeaders };
  },
  {urls: ['<all_urls>']},
  [ 'blocking', 'requestHeaders']
);
</code>```

If you are looking for an already built extension, you can try Requestly where allows you to easily setup rules on website URLs or domains so that whenever that website is opened in browser, the User Agent is automatically overridden. The best part here is that you can simultaneously run multiple rules for multiple websites.

Most of the other options either allow to override User Agent for one browser tab or all of the tabs.

Here is a screenshot for your reference:

For more info, please visit blog:
https://medium.com/@requestly_ext/switching-user-agent-in-browser-f57fcf42a4b5

To install, visit chrome store page:
https://chrome.google.com/webstore/detail/requestly-redirect-url-mo/mdnleldcmiljblolnjhpnblkcekpdkpa

The extension is also available for Firefox. Visit http://www.requestly.in for details.

Title: User Agent Switcher for Chrome

Body:
You can use webRequest API to create a chrome extension to modify the headers. When OP asked this question, this API may not exist or may be in experimental phase but now this api is quite stable.

chrome.webRequest.onBeforeSendHeaders.addListener(
  function(details) {
    for (var i = 0; i < details.requestHeaders.length; ++i) {
      if (details.requestHeaders[i].name === 'User-Agent') {
        details.requestHeaders[i].value = "Android_Browser" // Set your value here
        break;
      }
    }
    return { requestHeaders: details.requestHeaders };
  },
  {urls: ['<all_urls>']},
  [ 'blocking', 'requestHeaders']
);

If you are looking for an already built extension, you can try Requestly where allows you to easily setup rules on website URLs or domains so that whenever that website is opened in browser, the User Agent is automatically overridden. The best part here is that you can simultaneously run multiple rules for multiple websites.

Most of the other options either allow to override User Agent for one browser tab or all of the tabs.

Here is a screenshot for your reference:

For more info, please visit blog:
https://medium.com/@requestly_ext/switching-user-agent-in-browser-f57fcf42a4b5

To install, visit chrome store page:
https://chrome.google.com/webstore/detail/requestly-redirect-url-mo/mdnleldcmiljblolnjhpnblkcekpdkpa

The extension is also available for Firefox. Visit http://www.requestly.in for details.


问:
Odd entry in WordPress 'Admin_Panel.php' file?
I just migrated a Wordpress install from one of my servers to another for a client (client's website which I set up and manage) and as a precautionary measure, I was perusing the 'Theme > Edit' listed files in the Wordpress Admin panel just to check for any links to the old server/domain and try to clean everything up.

When I got to the 'admin_panel.php' file, I found this entry at the very bottom of the file (it was the last entry):

function ranking() {
  $pshow = "                                               Live sex , webcam sex , Mature Female , Livejasmin , Girl";
  echo $pshow;
}

Now, I'm not sure where the theme that I modified for the client came from, as he supplied it, but this is just... odd.

To note, the admin_panel.php file is for the backend theme settings section, so it isn't seen by the public. I also couldn't find anything in there that reflects this entry, but then again I'm not sure I would.

I'm not a coder, so I figured I would just see if anyone had any input on this. Is this likely something that was included by the theme coder? Or should I grill my client about where he sourced this theme and see if he got it from some shady website?

I'm just really unfamiliar with PHP, and while this looks harmless as far as site security is concerned, I figured I'd make sure.

I did remove the entry and everything seems fine, but better safe than sorry, right?

Thanks!

答:
Whoever has made the template ( I presume "elenaa") chucked some hidden links in there to increase the google rankings of these websites. Replace the function with the following if your worried about it.

```<code>function ranking(){ return ''; }
</code>```

If you just delete it you could get missing function errors.

Although the function is in the admin section is it possible the function could be called somewhere on the front end of the website?

ContentLicense: CC BY-SA 2.5

Body:
Whoever has made the template ( I presume "elenaa") chucked some hidden links in there to increase the google rankings of these websites. Replace the function with the following if your worried about it.

function ranking(){ return ''; }

If you just delete it you could get missing function errors.

Although the function is in the admin section is it possible the function could be called somewhere on the front end of the website?


问:
warning: implicit declaration of function 'system'
I am getting an error in my compiler:

```<code>Warning: implicit declaration of function 'system'
</code>```

I added:

```<code>system("cls");
</code>```

To be able to clear the screen, and now I get the error. I am using this code to test:

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

int nothing; //random name

int main()
{
printf("this is a msg");
scanf("%d",&nothing);
system("cls");
printf("hello");
getchar();

return 0;
}
</code>```

This is just a test code, so it's very sloppy. I am new to coding so any help would be appreciated.

答: This warning is reported when a function is called before its declaration. In your case, you haven't included the library stdlib.h at the start of your code. So the compiler sees the call to function before its prototype.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am getting an error in my compiler:

Warning: implicit declaration of function 'system'

I added:

system("cls");

To be able to clear the screen, and now I get the error. I am using this code to test:

#include <stdio.h>

int nothing; //random name

int main()
{
printf("this is a msg");
scanf("%d",&nothing);
system("cls");
printf("hello");
getchar();

return 0;
}

This is just a test code, so it's very sloppy. I am new to coding so any help would be appreciated.


问:
How to Calculate sum of data in php?

In this table I have multiple value like CGST, SGST, NET AMOUNT, MRP I want to find total of all value in below given CGST, SGCST etc...

Please help me how to find total of all data.

This is the code:

```<code><table class="table table-striped">
                        <thead>
                            <tr>
                                <th><strong>Sr. No</strong></th>
                                <th><strong>Item Name</strong></th>
                                <th><strong>Serial No</strong></th>
                                <th><strong>CGST</strong></th>
                                <th><strong>SGST</strong></th>
                                <th><strong>NET AMOUNT</strong></th>
                                <th><strong>MRP</strong></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                                $counter = 0;

                                    $getData = mysql_query("SELECT CUSTOMER_ID, ITEM_ID, DATE, FLAG, GROUP_CONCAT(SERIAL_NO) AS SERIAL_NO FROM cart_mst WHERE CUSTOMER_ID = '".$_SESSION['cust']."' AND FLAG = '0' GROUP BY ITEM_ID");

                                    while($row = mysql_fetch_array($getData))
                                    {
                                        $getItem = mysql_query("SELECT * FROM item_details WHERE ITEM_ID = '".$row['ITEM_ID']."'");
                                        $rowItem = mysql_fetch_array($getItem);

                            ?>

                            <tr>
                                <td><?php echo ++$counter ?></td>
                                <td>
                                    <?php echo $rowItem['ITEM_NAME'];

                                        $schools_array = explode(",", $row['SERIAL_NO']);
                                        $qty = count($schools_array);
                                    ?>
                                </td>
                                <td>
                                    <?php
                                        $hobbies = explode(',', $row['SERIAL_NO']);
                                        foreach ($hobbies as $hobby)
                                        {
                                            // output each hobby and decorate/separate them however you'd like
                                            echo $hobby . ', ';
                                        }
                                    ?>
                                </td>

                                <td>
                                    <?php
                                        if($rowItem['TYPE'] == "BAT")
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/128;
                                            $cgst = $net_amt * 14/100;
                                            echo round($cgst, 2);
                                        }
                                        else
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/118;
                                            $cgst = $net_amt * 9/100;
                                            echo round($cgst, 2);
                                        }
                                    ?>
                                </td>
                                <td>
                                    <?php
                                        if($rowItem['TYPE'] == "BAT")
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/128;
                                            $sgst = $net_amt * 14/100;
                                            echo round($cgst, 2);
                                        }
                                        else
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/118;
                                            $cgst = $net_amt * 9/100;
                                            echo round($cgst, 2);
                                        }
                                    ?>
                                </td>
                                <td>
                                    <?php
                                        if($rowItem['TYPE'] =="BAT")
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/128;
                                            echo round($net_amt, 2);
                                        }
                                        else
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/118;
                                            echo round($net_amt, 2);
                                        }
                                    ?>
                                </td>
                                <td>
                                    <?php
                                        $a = $rowItem['MRP'];
                                        $tot = $a * $qty;
                                        echo $tot;
                                    ?>
                                </td>
                            </tr>

                            <?php
                                    }

                            ?>
                        </tbody>
                    </table>
</code>```

答:
You can do this: while you are iterating from loop at that time sum each variable. After loop you will find the total value</p>

```<code><table class="table table-striped">
    <thead>
        <tr>
            <th><strong>Sr. No</strong></th>
            <th><strong>Item Name</strong></th>
            <th><strong>Serial No</strong></th>
            <th><strong>CGST</strong></th>
            <th><strong>SGST</strong></th>
            <th><strong>NET AMOUNT</strong></th>
            <th><strong>MRP</strong></th>
        </tr>
    </thead>
    <tbody>
        <?php
            $counter = 0;

                $getData = mysql_query("SELECT CUSTOMER_ID, ITEM_ID, DATE, FLAG, GROUP_CONCAT(SERIAL_NO) AS SERIAL_NO FROM cart_mst WHERE CUSTOMER_ID = '".$_SESSION['cust']."' AND FLAG = '0' GROUP BY ITEM_ID");
                $cgst_sum = 0;
                $sgst_sum = 0;
                $net_sum = 0;
                $mrp_sum = 0;
                while($row = mysql_fetch_array($getData))
                {
                    $getItem = mysql_query("SELECT * FROM item_details WHERE ITEM_ID = '".$row['ITEM_ID']."'");
                    $rowItem = mysql_fetch_array($getItem);

        ?>

        <tr>
            <td><?php echo ++$counter ?></td>
            <td>
                <?php echo $rowItem['ITEM_NAME'];

                    $schools_array = explode(",", $row['SERIAL_NO']);
                    $qty = count($schools_array);
                ?>
            </td>
            <td>
                <?php
                    $hobbies = explode(',', $row['SERIAL_NO']);
                    foreach ($hobbies as $hobby)
                    {
                        // output each hobby and decorate/separate them however you'd like
                        echo $hobby . ', ';
                    }
                ?>
            </td>

            <td>
                <?php
                    if($rowItem['TYPE'] == "BAT")
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/128;
                        $cgst = $net_amt * 14/100;
                        echo round($cgst, 2);
                    }
                    else
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/118;
                        $cgst = $net_amt * 9/100;
                        echo round($cgst, 2);
                    }
                    $cgst_sum += $cgst;
                ?>
            </td>
            <td>
                <?php
                    if($rowItem['TYPE'] == "BAT")
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/128;
                        $sgst = $net_amt * 14/100;
                        echo round($cgst, 2);
                    }
                    else
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/118;
                        $sgst = $net_amt * 9/100;
                        echo round($sgst, 2);
                    }
                    $sgst_sum += $sgst;
                ?>
            </td>
            <td>
                <?php
                    if($rowItem['TYPE'] =="BAT")
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/128;
                        echo round($net_amt, 2);
                    }
                    else
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/118;
                        echo round($net_amt, 2);
                    }
                    $net_sum += $net_amt;
                ?>
            </td>
            <td>
                <?php
                    $a = $rowItem['MRP'];
                    $tot = $a * $qty;
                    echo $tot;
                    $mrp_sum += $tot;
                ?>
            </td>
        </tr>

        <?php
                }

        ?>
    </tbody>
</table>
<?php
echo "Sum of cgst =".$cgst_sum."<br>";
echo "Sum of sgst =".$sgst_sum."<br>";
echo "Sum of Net amount =".$net_sum."<br>";
echo "Sum of mrp =".$mrp_sum."<br>";
?>
</code>```

Title: How to Calculate sum of data in php?

Body:
In this table I have multiple value like CGST, SGST, NET AMOUNT, MRP I want to find total of all value in below given CGST, SGCST etc...

Please help me how to find total of all data.

This is the code:

                                Sr. No
                                Item Name
                                Serial No
                                CGST
                                SGST
                                NET AMOUNT
                                MRP

                            <?php
                                $counter = 0;

                                    $getData = mysql_query("SELECT CUSTOMER_ID, ITEM_ID, DATE, FLAG, GROUP_CONCAT(SERIAL_NO) AS SERIAL_NO FROM cart_mst WHERE CUSTOMER_ID = '".$_SESSION['cust']."' AND FLAG = '0' GROUP BY ITEM_ID");

                                    while($row = mysql_fetch_array($getData))
                                    {
                                        $getItem = mysql_query("SELECT * FROM item_details WHERE ITEM_ID = '".$row['ITEM_ID']."'");
                                        $rowItem = mysql_fetch_array($getItem);

                            ?>

                                <?php echo ++$counter ?>

                                    <?php echo $rowItem['ITEM_NAME'];

                                        $schools_array = explode(",", $row['SERIAL_NO']);
                                        $qty = count($schools_array);
                                    ?>

                                    <?php
                                        $hobbies = explode(',', $row['SERIAL_NO']);
                                        foreach ($hobbies as $hobby)
                                        {
                                            // output each hobby and decorate/separate them however you'd like
                                            echo $hobby . ', ';
                                        }
                                    ?>

                                    <?php
                                        if($rowItem['TYPE'] == "BAT")
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/128;
                                            $cgst = $net_amt * 14/100;
                                            echo round($cgst, 2);
                                        }
                                        else
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/118;
                                            $cgst = $net_amt * 9/100;
                                            echo round($cgst, 2);
                                        }
                                    ?>

                                    <?php
                                        if($rowItem['TYPE'] == "BAT")
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/128;
                                            $sgst = $net_amt * 14/100;
                                            echo round($cgst, 2);
                                        }
                                        else
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/118;
                                            $cgst = $net_amt * 9/100;
                                            echo round($cgst, 2);
                                        }
                                    ?>

                                    <?php
                                        if($rowItem['TYPE'] =="BAT")
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/128;
                                            echo round($net_amt, 2);
                                        }
                                        else
                                        {
                                            $mrp = $rowItem['MRP'];
                                            $tot = $mrp * $qty;
                                            $net_amt = $tot * 100/118;
                                            echo round($net_amt, 2);
                                        }
                                    ?>

                                    <?php
                                        $a = $rowItem['MRP'];
                                        $tot = $a * $qty;
                                        echo $tot;
                                    ?>

                            <?php
                                    }

                            ?>

Body:
You can do this: while you are iterating from loop at that time sum each variable. After loop you will find the total value

<table class="table table-striped">
    <thead>
        <tr>
            <th><strong>Sr. No</strong></th>
            <th><strong>Item Name</strong></th>
            <th><strong>Serial No</strong></th>
            <th><strong>CGST</strong></th>
            <th><strong>SGST</strong></th>
            <th><strong>NET AMOUNT</strong></th>
            <th><strong>MRP</strong></th>
        </tr>
    </thead>
    <tbody>
        <?php
            $counter = 0;

                $getData = mysql_query("SELECT CUSTOMER_ID, ITEM_ID, DATE, FLAG, GROUP_CONCAT(SERIAL_NO) AS SERIAL_NO FROM cart_mst WHERE CUSTOMER_ID = '".$_SESSION['cust']."' AND FLAG = '0' GROUP BY ITEM_ID");
                $cgst_sum = 0;
                $sgst_sum = 0;
                $net_sum = 0;
                $mrp_sum = 0;
                while($row = mysql_fetch_array($getData))
                {
                    $getItem = mysql_query("SELECT * FROM item_details WHERE ITEM_ID = '".$row['ITEM_ID']."'");
                    $rowItem = mysql_fetch_array($getItem);

        ?>

        <tr>
            <td><?php echo ++$counter ?></td>
            <td>
                <?php echo $rowItem['ITEM_NAME'];

                    $schools_array = explode(",", $row['SERIAL_NO']);
                    $qty = count($schools_array);
                ?>
            </td>
            <td>
                <?php
                    $hobbies = explode(',', $row['SERIAL_NO']);
                    foreach ($hobbies as $hobby)
                    {
                        // output each hobby and decorate/separate them however you'd like
                        echo $hobby . ', ';
                    }
                ?>
            </td>

            <td>
                <?php
                    if($rowItem['TYPE'] == "BAT")
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/128;
                        $cgst = $net_amt * 14/100;
                        echo round($cgst, 2);
                    }
                    else
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/118;
                        $cgst = $net_amt * 9/100;
                        echo round($cgst, 2);
                    }
                    $cgst_sum += $cgst;
                ?>
            </td>
            <td>
                <?php
                    if($rowItem['TYPE'] == "BAT")
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/128;
                        $sgst = $net_amt * 14/100;
                        echo round($cgst, 2);
                    }
                    else
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/118;
                        $sgst = $net_amt * 9/100;
                        echo round($sgst, 2);
                    }
                    $sgst_sum += $sgst;
                ?>
            </td>
            <td>
                <?php
                    if($rowItem['TYPE'] =="BAT")
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/128;
                        echo round($net_amt, 2);
                    }
                    else
                    {
                        $mrp = $rowItem['MRP'];
                        $tot = $mrp * $qty;
                        $net_amt = $tot * 100/118;
                        echo round($net_amt, 2);
                    }
                    $net_sum += $net_amt;
                ?>
            </td>
            <td>
                <?php
                    $a = $rowItem['MRP'];
                    $tot = $a * $qty;
                    echo $tot;
                    $mrp_sum += $tot;
                ?>
            </td>
        </tr>

        <?php
                }

        ?>
    </tbody>
</table>
<?php
echo "Sum of cgst =".$cgst_sum."<br>";
echo "Sum of sgst =".$sgst_sum."<br>";
echo "Sum of Net amount =".$net_sum."<br>";
echo "Sum of mrp =".$mrp_sum."<br>";
?>


问:
How to add a variable value with auto increment value in an insert query
I have a localhost and I want to do something I hope I can explain it.
I have a table named 'students' in a database named 'theway', there is a column named 's_class_id' its kind is auto increment , and in php I insert some values in this table. But I want to insert a variable+the auto increment in the column named 's_class_id'.
For example : The variable's value is 'a', and the auto increment value is '5'. I want the value which be inserted in the 's_class_id' like this 'a5'.
Any help?</p>

答: If it is auto-increment, the field should be an integer. Do not think that it is possible to change it to eg: 'a5'. You could run an update query searching for the s_class_id and update another string field to set it to be 'a5'.</p>


问:
How to play video using QPython
I am new to QPython and all I need to do is play a video (stored on the Android Tablet), and wait until the video finish playing.

I found the Androidhelper library commands mediaPlay and mediaIsPlaying functions, but I would not know where to start to use these functions.

Sorry, I did say I am new, so I would appreciate the basics, like how to get the source file directory, etc., a one line example would be fine.

Also if there is a better library to do this, please let me know.

Thanks

答:
I think there is not API for Qpython, but there is a a8player.py in scripts after you having installed the Qpython, which maybe show how to call a player app's API.

BTW: you could post the requiement in official's facebook page. The dev team is very nice.

Title: How to play video using QPython


问:
Swift - performance wise - comparing two arrays and get the difference in each and common in both
Hope you are having a great day.

I'm trying to understand what is the fastest approach to do the following:

Assuming I have these two Arrays:

```<code>var firstArray = ["a","b","c"]
var secondArray = ["a","d","e"]
</code>```

I'd like to get as an output:

1)Array of objects that inside firstArray but no in secondArray .

1)Array of objects that inside secondArray but no in firstArray .

3)Array of the common objects between firstArray and secondArray.

So basically the output would be:

1) ["b","c"]

2) ["d","e"]

3) ["a"]

The main issue here is to understand what is the most efficient way to do so. Thank you very much!

答:
If your arrays are sorted and the items are unique in each array, the fastest way would be to handle each of the items only once.  Start by comparing the first items in each array; if they are equal, put that into the common array and then move on to the second items.  If one item is less than another, it goes into the unique array of the lesser item and you move on to the next item in the lesser array.  Continue this process until you run out of items for one array, then put the remaining items of the second array into the unique items array for that array.

```<code>var i = 0
var j = 0

let a = ["a", "b", "c"]
let b = ["a", "d", "e"]

var aUnique = [String]()
var bUnique = [String]()
var common = [String]()

while i < a.count && j < b.count {
    if a[i] == b[j] {
        common.append(a[i])
        i += 1
        j += 1
    } else if a[i] < b[j] {
        aUnique.append(a[i])
        i += 1
    } else {
        bUnique.append(b[j])
        j += 1
    }
}

if i < a.count {
    // put remaining items into aUnique
    aUnique += a[i ..< a.count]
} else if j < b.count {
    // put remaining items into bUnique
    bUnique += b[j ..< b.count]
}

print(common)  // ["a"]
print(aUnique) // ["b", "c"]
print(bUnique) // ["d", "e"]
</code>```

Analysis

This algorithm appends one item to one of the arrays each time through the loop.  It will loop at most a.count + b.count - 1 times if both arrays are unique relative to each other, or only their last item is common.

If both arrays are identical, it will loop only a.count times.

If all elements of array b are greater than the elements of array a, it will loop only a.count times.  If all elements of array a are greater than the elements of array b, it will loop only b.count times.

Body:
Hope you are having a great day.

I'm trying to understand what is the fastest approach to do the following:

Assuming I have these two Arrays:

var firstArray = ["a","b","c"]
var secondArray = ["a","d","e"]

I'd like to get as an output:

1)Array of objects that inside firstArray but no in secondArray .

1)Array of objects that inside secondArray but no in firstArray .

3)Array of the common objects between firstArray and secondArray.

So basically the output would be:

1) ["b","c"]

2) ["d","e"]

3) ["a"]

The main issue here is to understand what is the most efficient way to do so. Thank you very much!

Body:
If your arrays are sorted and the items are unique in each array, the fastest way would be to handle each of the items only once.  Start by comparing the first items in each array; if they are equal, put that into the common array and then move on to the second items.  If one item is less than another, it goes into the unique array of the lesser item and you move on to the next item in the lesser array.  Continue this process until you run out of items for one array, then put the remaining items of the second array into the unique items array for that array.

var i = 0
var j = 0

let a = ["a", "b", "c"]
let b = ["a", "d", "e"]

var aUnique = [String]()
var bUnique = [String]()
var common = [String]()

while i < a.count && j < b.count {
    if a[i] == b[j] {
        common.append(a[i])
        i += 1
        j += 1
    } else if a[i] < b[j] {
        aUnique.append(a[i])
        i += 1
    } else {
        bUnique.append(b[j])
        j += 1
    }
}

if i < a.count {
    // put remaining items into aUnique
    aUnique += a[i ..< a.count]
} else if j < b.count {
    // put remaining items into bUnique
    bUnique += b[j ..< b.count]
}

print(common)  // ["a"]
print(aUnique) // ["b", "c"]
print(bUnique) // ["d", "e"]

Analysis

This algorithm appends one item to one of the arrays each time through the loop.  It will loop at most a.count + b.count - 1 times if both arrays are unique relative to each other, or only their last item is common.

If both arrays are identical, it will loop only a.count times.

If all elements of array b are greater than the elements of array a, it will loop only a.count times.  If all elements of array a are greater than the elements of array b, it will loop only b.count times.


问:
Symfony : render collection with custom protoype
Situation : I have an entity CompetenceGroupe (with attributes "titre" and "competence_items") and an entity "CompetenceItem" (with attributes "libelle" and "niveau"). A CompetenceGroupe can have multiple CompetenceItem, so it's a collection.

For that, I have created my own prototype to customize the render of the collections. It's working fine, but I have a problem when I want to edit an existing CompetenceGroupe, because the childrens CompetenceItem are not rendered in the form.

I show you my code.

CompetenceGroupeType

```<code>class CompetenceGroupeType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('titre')
            ->add('competence_items', CollectionType::class, array(
                'entry_type'   => CompetenceItemType::class,
                'allow_add'    => true,
                'allow_delete' => true,
                'label' => false,
                'prototype' => true,

            ))
            //->add('save',      SubmitType::class)
            ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\CompetenceGroupe',
        ));
    }
}
</code>```

CompetenceItemType

```<code>class CompetenceItemType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('libelle')
            ->add('niveau', EntityType::class, array(
                'class' => 'AppBundle:CompetenceNiveau',
                'choice_label' => 'libelle_competence_niveau_fr',
                'required' => false,
            ))
            ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\CompetenceItem',
        ));
    }
}
</code>```

The form for CompetenceGroupe

```<code>{{ form_start(formAddCompetence, { 'attr': {'class': 'formCompetenceAdd'} }) }}

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">{{ libelleCategorie }}</h4>
    </div>

    <div class="modal-body">

        {{ dump(formAddCompetence) }}

        <h4><span class="label label-default">Les champs marqués d'un astérisque sont obligatoires.</span></h4>

        {# render the task's only field: description #}
        {{ form_row(formAddCompetence.titre) }}

        <div id="competence_groupe_competence_items"
             data-prototype="
             {% filter escape %}
                 {{ include('espaceUtilisateur/forms/prototypes/competence_item_prototype.html.twig', { 'item': formAddCompetence.competence_items.vars.prototype }) }}
             {% endfilter %}">

        </div>

        {{ form_widget(formAddCompetence._token) }}

        <br>
        <a href="#" id="add_category" class="btn btn-default">Ajouter une catégorie</a>

    </div>

    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>

        {% if objectCompetence.idCompetenceGroupe is not empty %}
            {{ form_widget(formAddCompetence.edit) }}
            <input type="hidden" name="idCompetenceGroupe" id="idCompetenceGroupe" value="{{ objectCompetence.idCompetenceGroupe }}">
        {% else %}
            {{ form_widget(formAddCompetence.save) }}
        {% endif %}
    </div>

<script type="text/javascript">
    $(document).ready(function() {
        // On récupère la balise <div> en question qui contient l'attribut « data-prototype » qui nous intéresse.
        var $container = $('div#competence_groupe_competence_items');

        // On définit un compteur unique pour nommer les champs qu'on va ajouter dynamiquement
        var index = $container.find(':input').length;

        // On ajoute un nouveau champ à chaque clic sur le lien d'ajout.
        $('#add_category').click(function(e) {
            addCategory($container);

            e.preventDefault(); // évite qu'un # apparaisse dans l'URL
            return false;
        });

        // On ajoute un premier champ automatiquement s'il n'en existe pas déjà un (cas d'une nouvelle annonce par exemple).
        if (index == 0) {
            //console.log('index');
            addCategory($container);
        } else {
            // S'il existe déjà des catégories, on ajoute un lien de suppression pour chacune d'entre elles
            $container.children('div').each(function() {
                addDeleteLink($(this));
            });
        }

        // La fonction qui ajoute un formulaire CategoryType
        function addCategory($container) {
            // Dans le contenu de l'attribut « data-prototype », on remplace :
            // - le texte "__name__label__" qu'il contient par le label du champ
            // - le texte "__name__" qu'il contient par le numéro du champ
            var template = $container.attr('data-prototype')
                            .replace(/__name__label__/g, 'Catégorie n°' + (index+1))
                            .replace(/__name__/g,        index)
                    ;

            // On crée un objet jquery qui contient ce template
            var $prototype = $(template);

            // On ajoute au prototype un lien pour pouvoir supprimer la catégorie
            addDeleteLink($prototype);

            // On ajoute le prototype modifié à la fin de la balise <div>
            $container.append($prototype);

            // Enfin, on incrémente le compteur pour que le prochain ajout se fasse avec un autre numéro
            index++;
        }

        // La fonction qui ajoute un lien de suppression d'une catégorie
        function addDeleteLink($prototype) {

            // Création du lien
            var $deleteLink = $('<div><a href="#" class="btn btn-danger">Supprimero</a></div>');

            // Ajout du lien
            $prototype.last().append($deleteLink);

            // Ajout du listener sur le clic du lien pour effectivement supprimer la catégorie
            $deleteLink.click(function(e) {
                $prototype.remove();

                e.preventDefault(); // évite qu'un # apparaisse dans l'URL
                return false;
            });
        }
    });
</script>
</code>```

And my custom prototype

```<code><div class="form-group">
    {{ form_label(item.libelle, "libelle a", {'label_attr': {'class': 'col-md-3 control-label'}}) }}
    {{ form_errors(item.libelle) }}
    <div>
        {{ form_widget(item.libelle) }}
    </div>
</div>

<div class="form-group">
    {{ form_label(item.niveau, "niveau a", {'label_attr': {'class': 'col-md-3 control-label'}}) }}
    {{ form_errors(item.niveau) }}
    <div>
        {{ form_widget(item.niveau) }}
    </div>
</div>
</code>```

Maybe my problem is that the rendering of the existing CompetenceItem for a CompetenceGroupe is missing. Maybe I have to loop on it for render them... As you can see, I'm lost ...

Thanks in advance for your advices !

答:
The way you do it look really wrong so I don't think anybody will spend hours to find a tricky way to fix your issue. You should use a form theme instead of creating the prototype by yourself.

1) In CompetenceGroupeType.php, add the following method:

```<code>public function getBlockPrefix()
{
    return 'competence_group';
}
</code>```

2) wrap code in competence_item_prototype.html.twig by:

```<code>{% block competence_group_widget %}

    <div class="form-group">
        (...)
    </div>

{% endblock %}
</code>```

Also replace item by form.

3) in your view, before calling {{ form_start(formAddCompetence, {...} }) }} function, add the following:

```<code>{% form_theme formAddCompetence 'espaceUtilisateur/forms/prototypes/competence_item_prototype.html.twig' %}
</code>```

And a bit of spam for a plugin I created, but for the right purpose :) you can have a look to https://symfony-collection.fuz.org that provides many examples on how to create form collections.

Body:
Situation : I have an entity CompetenceGroupe (with attributes "titre" and "competence_items") and an entity "CompetenceItem" (with attributes "libelle" and "niveau"). A CompetenceGroupe can have multiple CompetenceItem, so it's a collection.

For that, I have created my own prototype to customize the render of the collections. It's working fine, but I have a problem when I want to edit an existing CompetenceGroupe, because the childrens CompetenceItem are not rendered in the form.

I show you my code.

CompetenceGroupeType

class CompetenceGroupeType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('titre')
            ->add('competence_items', CollectionType::class, array(
                'entry_type'   => CompetenceItemType::class,
                'allow_add'    => true,
                'allow_delete' => true,
                'label' => false,
                'prototype' => true,

            ))
            //->add('save',      SubmitType::class)
            ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\CompetenceGroupe',
        ));
    }
}

CompetenceItemType

class CompetenceItemType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('libelle')
            ->add('niveau', EntityType::class, array(
                'class' => 'AppBundle:CompetenceNiveau',
                'choice_label' => 'libelle_competence_niveau_fr',
                'required' => false,
            ))
            ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\CompetenceItem',
        ));
    }
}

The form for CompetenceGroupe

{{ form_start(formAddCompetence, { 'attr': {'class': 'formCompetenceAdd'} }) }}

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

{{ libelleCategorie }}

        {{ dump(formAddCompetence) }}

Les champs marqués d'un astérisque sont obligatoires.

        {# render the task's only field: description #}
        {{ form_row(formAddCompetence.titre) }}

        {{ form_widget(formAddCompetence._token) }}

        Ajouter une catégorie

        <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>

        {% if objectCompetence.idCompetenceGroupe is not empty %}
            {{ form_widget(formAddCompetence.edit) }}
            <input type="hidden" name="idCompetenceGroupe" id="idCompetenceGroupe" value="{{ objectCompetence.idCompetenceGroupe }}">
        {% else %}
            {{ form_widget(formAddCompetence.save) }}
        {% endif %}

And my custom prototype

    {{ form_label(item.libelle, "libelle a", {'label_attr': {'class': 'col-md-3 control-label'}}) }}
    {{ form_errors(item.libelle) }}

        {{ form_widget(item.libelle) }}

    {{ form_label(item.niveau, "niveau a", {'label_attr': {'class': 'col-md-3 control-label'}}) }}
    {{ form_errors(item.niveau) }}

        {{ form_widget(item.niveau) }}

Maybe my problem is that the rendering of the existing CompetenceItem for a CompetenceGroupe is missing. Maybe I have to loop on it for render them... As you can see, I'm lost ...

Thanks in advance for your advices !

Body:
The way you do it look really wrong so I don't think anybody will spend hours to find a tricky way to fix your issue. You should use a form theme instead of creating the prototype by yourself.

1) In CompetenceGroupeType.php, add the following method:

public function getBlockPrefix()
{
    return 'competence_group';
}

2) wrap code in competence_item_prototype.html.twig by:

{% block competence_group_widget %}

    <div class="form-group">
        (...)
    </div>

{% endblock %}

Also replace item by form.

3) in your view, before calling {{ form_start(formAddCompetence, {...} }) }} function, add the following:

{% form_theme formAddCompetence 'espaceUtilisateur/forms/prototypes/competence_item_prototype.html.twig' %}

And a bit of spam for a plugin I created, but for the right purpose :) you can have a look to https://symfony-collection.fuz.org that provides many examples on how to create form collections.


问:
why is maximum single-line length limited to 132 characters in Fortran Standard?
Is it about performance, clean source code, compilers, ...? I know that many compilers allow longer single-line codes. But, if this extension is possible without any compromise, then why does Fortran standard strictly adhere to this rule?

I know that this is very general question (stackoverflow warns me that this question might be downvoted given its title), but I cannot find any resources that explain the logic behind a max length of 132 characters in modern Fortran standard.

Update Oct 22, 2019: See https://j3-fortran.org/doc/year/19/19-138r1.txt for a proposal accepted as a work item for the next 202X revision of the Fortran standard, which eliminates the maximum line length and continuation limits.

答: The old IBM line printers has 132 character width, so when IBM designed Fortran, that was the max line length</p>


问:
Recursive thinking
I would like to ask if it is really necessary to track every recursive call when writing it, because I am having troubles if recursive call is inside a loop or inside multiple for loops. I just get lost when I am trying to understand what is happening.
Do you have some advice how to approach recursive problems and how to imagine it. I have already read a lot about it but I havent found a perfect answer yet. I understand for example how factorial works or fibonacci recursion. I get lost for example when I am trying to print all combinations from 1 to 5 length of 3 or all the solutions for n-queen problem</p>

答:
Everyone may have a different mental approach towards towards modeling a recursive problem. If you can solve the n queens problem in a non-recursive way, then you are just fine. It is certainly helpful to grasp the concept of recursion to break down a problem, though. If you are up for the mental exercise, then I suggest a text book on PROLOG. It is fun and very much teaches recursion from the very beginning.

Attempting a bit of a brain dump on n-queens. It goes like "how would I do it manually" by try and error. For n-queens, I propose to in your mind call it 8-queens as a start, just to make it look more familiar and intuitive. "n" is not an iterator here but specifies the problem size.

you reckon that n-queens has a self-similarity which is that you place single queens on a board - that is your candidate recursive routine

for a given board you have a routine to test if the latest queen added is in conflict with the prior placed ones

for a given board you have a routine to find a position for the queen that you have not tested yet if that test is not successful for the current  position

you print out all queen positions if the queen you just placed was the nth (last) queen

otherwise (if the current queen was validly placed) you position an additional queen

The above is your program. Your routine will pass a list of positions of earlier queens. The first invocation is with an empty list.

Title: Recursive thinking


问:
Xamarin Forms get the hours of the phone
I am a novice in Xamarin.

I am looking for a way to get the local date time of my phone in hours in order to compare it with 19h00 or 7:00pm depending on the country

Here is my code but it is not okey:

```<code>// Handle when your app starts
DateTime dt = DateTime.Now.ToLocalTime();
DateTime hour_only = dt.Hour;
if (hour_only = "19:00")
{
    Debug.WriteLine("it time ");
}
</code>```

If there is a  better example I will take ,

thanks

答:
The property Hour of a DateTime is an int type that represents the actual hour in 24 hours format.

As you can see in the Microsoft documentation

```<code>public int Hour { get; }
</code>```

Property Value

Type: System.Int32

The hour component, expressed as a value between 0 and 23.

So if you want to compare the actual hour with 7PM, you have to use the following code:

```<code>DateTime dt = DateTime.Now.ToLocalTime();

int hour_only = dt.Hour;

if (hour_only == 19) {

    Debug.WriteLine("it time ");

}
</code>```

Be careful that use two == symbols to make a comparation, you were using only one:

if (hour_only = "19:00") {

Body:
I am a novice in Xamarin.

I am looking for a way to get the local date time of my phone in hours in order to compare it with 19h00 or 7:00pm depending on the country

Here is my code but it is not okey:

// Handle when your app starts
DateTime dt = DateTime.Now.ToLocalTime();
DateTime hour_only = dt.Hour;
if (hour_only = "19:00")
{
    Debug.WriteLine("it time ");
}

If there is a  better example I will take ,

thanks

Body:
The property Hour of a DateTime is an int type that represents the actual hour in 24 hours format.

As you can see in the Microsoft documentation

public int Hour { get; }

Property Value

Type: System.Int32

The hour component, expressed as a value between 0 and 23.

So if you want to compare the actual hour with 7PM, you have to use the following code:

DateTime dt = DateTime.Now.ToLocalTime();

int hour_only = dt.Hour;

if (hour_only == 19) {

    Debug.WriteLine("it time ");

}

Be careful that use two == symbols to make a comparation, you were using only one:

if (hour_only = "19:00") {


问:
QPython cannot install requests module
Trying to install the requests module on QPython 3 using pip install requests gives me this error

pip.log

What is the cause of this error and how can it be resolved?

答: Have you tried the 1.4.x ? I thought it had solved the issue.</p>

Title: QPython cannot install requests module


问:
How to overload a built-in CUDA function?
CUDA has some built-in math functions, such as norm(). I want to create my own version of the norm() function, and use my version throughout the code. However when I define my own norm() function like so:

```<code>__device__ float norm(float a, float b) {
    return sqrt(a*a+b*b);
}
</code>```

I get the following compilation error:

```<code>kernel.cu(9): error: more than one instance of overloaded function "norm" has "C" linkage
</code>```

Is there a way I can overload the norm() function, or do I have to just give my own function a unique name?

I'm using PyCuda to compile my CUDA code.

答:
The problem here is the use of C linkage in your code.

You may or may not be explicitly specifying extern "C"anywhere. Irrespective of whether you are, if you are using the PyCUDA SourceModule facility to compile your code, it is (un)helpfully, automagically bracketing the code you submit with extern "C".

If you look at the documentation for SourceModule, you will see the option no_extern_c. Set that to True and this problem will go away. But note that everything you compile will now be compiled with C++ linkage and symbol mangling. You will have to adapt your Python code accordingly (see here for some of the gory details).

And after that, read the other answer, which contains some very sage advice about the perils of overloading standard libraries and a best practice alternative.

Body:
CUDA has some built-in math functions, such as norm(). I want to create my own version of the norm() function, and use my version throughout the code. However when I define my own norm() function like so:

__device__ float norm(float a, float b) {
    return sqrt(a*a+b*b);
}

I get the following compilation error:

kernel.cu(9): error: more than one instance of overloaded function "norm" has "C" linkage

Is there a way I can overload the norm() function, or do I have to just give my own function a unique name?

I'm using PyCuda to compile my CUDA code.


问:
Spring JPA java.util.Date to Mysql timestamp with wrong date value
I have a JPA entity with a date field is persisted into Mysql DateTime.

Field:

```<code>  @Column(name = "CREATION_DATE")
  private Date creationDate;
</code>```

Column:

  CREATION_DATE datetime DEFAULT NULL,

Setter:

```<code>request.setCreationDate(new Date());//Value set to current date
</code>```

I am getting an strange error that persisted date is 8 hours lesser than the current time. Tried few approaches as below:

Using @Temporal(TemporalType.TIMESTAMP) for the field

Setting default TimeZone

TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));

Printing the date before setting, which displays the correct value.

Setting the timezone at mysql layer as well:

SET GLOBAL time_zone = '+8:00';
SET SESSION time_zone = '+8:00';

Changing the field type to java.sql.Timestamp

none of the above approaches helped. Anyone had a similar issue? Any clue?

答:
Found the issue, the problem was in jdbc connection URL.

spring.datasource.url=jdbc:mysql://:3307/dbname?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

due to the server time zone setting in the URL, GMT+8 time was converted to UTC which was leading to the 8 hours time difference. After removing the serverTimezone parameter in the URL, date is working fine. Thank you Neil and Shazin for your time and support.

Body:
I have a JPA entity with a date field is persisted into Mysql DateTime.

Field:

  @Column(name = "CREATION_DATE")
  private Date creationDate;

Column:

  CREATION_DATE datetime DEFAULT NULL,

Setter:

request.setCreationDate(new Date());//Value set to current date

I am getting an strange error that persisted date is 8 hours lesser than the current time. Tried few approaches as below:

Using @Temporal(TemporalType.TIMESTAMP) for the field

Setting default TimeZone

TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));

Printing the date before setting, which displays the correct value.

Setting the timezone at mysql layer as well:

SET GLOBAL time_zone = '+8:00';
SET SESSION time_zone = '+8:00';

Changing the field type to java.sql.Timestamp

none of the above approaches helped. Anyone had a similar issue? Any clue?


问:
'Cannot add two pointers' adding LPCWSTR with WCHAR
I declared two variable like:

```<code>WCHAR w_ErrorMessage[256];
LPCWSTR lp_ErrMsg;
</code>```

The first variable is for returned SQLite error message, And the second variable is for MessageBox text. I tried and wrote this code:

```<code>lp_ErrMsg = L"Database sql error: " + WCHAR(w_ErrorMessage);
MessageBox(0, lp_ErrMsg, L"Error", MB_ICONERROR | MB_OK);
</code>```

but something like this shows for message:
ScreenShot

If I remove the WCHAR behind the w_ErrorMessage variable I get the "Error: Cannot add two pointers".

I want MessageBox show error: SQLite Error: %TheActualErrorMessage%.
How can I do that?

答: The + operator is not used to concatenate strings in C/C++. Use wcscat function instead.</p>

Body:
I declared two variable like:

WCHAR w_ErrorMessage[256];
LPCWSTR lp_ErrMsg;

The first variable is for returned SQLite error message, And the second variable is for MessageBox text. I tried and wrote this code:

lp_ErrMsg = L"Database sql error: " + WCHAR(w_ErrorMessage);
MessageBox(0, lp_ErrMsg, L"Error", MB_ICONERROR | MB_OK);

but something like this shows for message:
ScreenShot

If I remove the WCHAR behind the w_ErrorMessage variable I get the "Error: Cannot add two pointers".

I want MessageBox show error: SQLite Error: %TheActualErrorMessage%.
How can I do that?


问:
Magick++ in VS2010 - unresolved external symbol
I'm trying to use ImageMagick Magick++ for a C++ Project in VS2010.
I installed the Library from here: klick

Then in my Project, I added c:/program files/ImageMagick-6.6.6-Q16/include to the include folders. Then I tried to use Magick++ with this code:

```<code>#include <Magick++.h>
void main(int argc, char ** argv){
    InitializeMagick(*argv);
}
</code>```

But this does not work!
VS2010 returns the following errors:

```<code>error LNK2001: unresolved external symbol "__declspec(dllimport) void __cdecl    Magick::InitializeMagick(char const *)" (__imp_?InitializeMagick@Magick@@YAXPBD@Z)
error LNK1120: 1 unresolved externals
</code>```

What am I doing wrong?

Thanks very much for your help!

UPDATE:

Set Linker -> Input -> Additionnal Dependencies to:

```<code>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;CORE_RL_Magick++_.lib
</code>```

And Linker -> General -> Additionnal Library Directories to:

```<code>C:\Program Files\ImageMagick-6.6.6-Q16\lib
</code>```

It still results in the same error...

UPDATE 2

Opening the .lib files in C:\Program Files\ImageMagick-6.6.6-Q16\lib results in this error:

UPDATE 3

CORE_RL_Magick++_.lib does contain ?InitializeMagick@Magick@@YAXPEBD@Z, but not ?InitializeMagick@Magick@@YAXPBD@Z. Does this mean the .lib file is corrupted?

UPDATE 4

I solved my problem by manually compliling the .lib files.
Thanks to all!

答: The documentation says: "Windows users may get started by manually editing a project file for one of the Magick++ demo programs." Did you try that?</p>

Body:
I'm trying to use ImageMagick Magick++ for a C++ Project in VS2010.
I installed the Library from here: klick

Then in my Project, I added c:/program files/ImageMagick-6.6.6-Q16/include to the include folders. Then I tried to use Magick++ with this code:

#include <Magick++.h>
void main(int argc, char ** argv){
    InitializeMagick(*argv);
}

But this does not work!
VS2010 returns the following errors:

error LNK2001: unresolved external symbol "__declspec(dllimport) void __cdecl    Magick::InitializeMagick(char const *)" (__imp_?InitializeMagick@Magick@@YAXPBD@Z)
error LNK1120: 1 unresolved externals

What am I doing wrong?

Thanks very much for your help!

UPDATE:

Set Linker -> Input -> Additionnal Dependencies to:

kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;CORE_RL_Magick++_.lib

And Linker -> General -> Additionnal Library Directories to:

C:\Program Files\ImageMagick-6.6.6-Q16\lib

It still results in the same error...

UPDATE 2

Opening the .lib files in C:\Program Files\ImageMagick-6.6.6-Q16\lib results in this error:

UPDATE 3

CORE_RL_Magick++_.lib does contain ?InitializeMagick@Magick@@YAXPEBD@Z, but not ?InitializeMagick@Magick@@YAXPBD@Z. Does this mean the .lib file is corrupted?

UPDATE 4

I solved my problem by manually compliling the .lib files.
Thanks to all!


问:
react-native how to import project root directory?
```<code>App
 |-- application
      |-- config
      |    |-- themes.js
      |    |-- redux.js
      +-- views
      |    |-- login
      |    |    |-- login.js
      |-- index.js
</code>```

index.js

```<code>....
import themes from './config/themes';
import themes from './config/redux';
...
</code>```

login.js

```<code>....
import themes from '../../config/themes';
import themes from '../../config/redux';
...
</code>```

I hope it like this:

```<code>....
import themes from '@root/application/config/themes';
import themes from '@root/application/config/redux';
import ... from '@root/...';
...
</code>```

if methods of php

```<code>$root = 'User/React-Native-Project/';
include $root.'/application/config/themes.php';
</code>```

This can improve the development efficiency and avoid the wrong path and other issues.my english is not good.

答:
You can create a package.json file containing {"name": "root"} in your root folder. Note that this may be a different file than the original 'package.json' that every project has.

And in case you want to use another folder named X populate the package.json with {"name": "X"}. so now you can simply use import foo from 'X/foo' in your project.

For more information check these:

https://github.com/facebook/react-native/issues/3099#issuecomment-221815006
https://medium.com/@davidjwoody/how-to-use-absolute-paths-in-react-native-6b06ae3f65d1

Body:
App
 |-- application
      |-- config
      |    |-- themes.js
      |    |-- redux.js
      +-- views
      |    |-- login
      |    |    |-- login.js
      |-- index.js

index.js

....
import themes from './config/themes';
import themes from './config/redux';
...

login.js

....
import themes from '../../config/themes';
import themes from '../../config/redux';
...

I hope it like this:

....
import themes from '@root/application/config/themes';
import themes from '@root/application/config/redux';
import ... from '@root/...';
...

if methods of php

$root = 'User/React-Native-Project/';
include $root.'/application/config/themes.php';

This can improve the development efficiency and avoid the wrong path and other issues.my english is not good.


问:
How does using a factory class to query database improve efficiency
I learned PHP with Robin Nixon's book and his examples used functions like this to query MySQL database

```<code><?php
require 'config.php';
function queryMysql($query) {
    global $connection; // accessible from config.php
    $result = $connection->query($query);
    if (!$result) die($connection->error);
    return $result;
}
?>
</code>```

config.php

```<code><?php
$dbhost  = 'localhost';
$dbname  = 'database_name';
$dbuser  = 'database_username';
$dbpass  = 'database_password';

$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);

// some other codes
?>
</code>```

then this will normally follow anywhere in your code where you want to query the database $result=queryMysql($query); This is what I've been using all this while and I recently learnt that using a factory class is better and should save you stress as your website grows and also if you happen to later to use multiple types of databases.

I came across an article that suggested database should be queried this way (modified a bit to suit what am doing)

MYSQL class

```<code><?php
class MYSQL
{
    private $host, $database_name, $username, $password;

    public function setHost($host) {
        $this->host = $host; // localhost
    }

    public function setDatabase($database_name) {
        $this->database_name = $database_name; // database name
    }

    public function setUsermame($username) {
        $this->username = $username; // db username
    }

    public function setPassword($password) {
        $this->password = $password; // db password
    }

    public function connect () {
        return $connection = new mysqli($this->host, $this->username, $this->password, $this->database_name);
        if ($connection->connect_error)
            // die($connection->connect_error);
            false;
        return $connection;
    }
}
?>
</code>```

FACTORY class

```<code><?php
class ConnectionFactory
{
    private $driver = null;

    public function setDriver($driver) {
        $this->driver = $driver;
    }

    public function connect($host, $username, $password, $database_name) {
        switch($this->driver) {
            case 'mysql':
                $DB = new MYSQL();
            break;
            default:
                $DB = new MYSQL();
        }

        $DB->setHost($host);
        $DB->setDatabase($database_name);
        $DB->setUsermame($username);
        $DB->setPassword($password);
        return $DB->connect();
    }
}
?>
</code>```

Now to make query

```<code><?php
$db_factory = new ConnectionFactory();
$db_factory->setDriver('mysql');
$connection = $db_factory->connect('localhost', 'database_username', 'database_password', 'database_name');
if ($connection->connect_error)
    die($connection->connect_error);

$query = "SELECT * FROM users";
$result = $connection->query($query);
if (!$result)
    die($connection->error);
// echo '```' , print_r($result), '```';
?>
</code>```

I want to know really, how does the factory class above improve call to the database. I read that it helps if you may want to connect to different databases in the future. If that's it, wouldn't it be same if I created different functions with names to specify what database they called like this

```<code>function queryMysql() {
    // code here
}
function queryPostgreSQL() {
    // code here
}
</code>```

And with the factory class above, I feel (I know am wrong) it's more stressful accessing the database because it requires you to keep entering host, username, password and database name each time you try to access the database. What are the real advantages? Thanks

答:
The goal of the Factory class isn't necessarily to improve efficiency -- rather it is to improve code legibility, organization and eliminate potential redundancy.

Specifically, you are creating a ConnectionFactory which allows you to create separate database factories. If you look in the class, you can handle multiple cases i.e. MySQL. For your scenario, the benefits might not be immediately apparent but imagine if you had to hook into different databases that required different drivers -- sure you could still do it but in a huge application it would be ridiculously confusing and impractical to maintain.

If you read the article, you can see they mention this where they mention how you could have an application that has to hook into MySQL, PostgresSQL, and/or SQLite. Specifically, they mention

Generally [specifying each config for each database] works but it creates problems in rather big applications. Above code has these problems:

Should you add more database types, code would keep on growing making it complex

The code is hard coded with database type names

Whole process becomes tedious

Body:
I learned PHP with Robin Nixon's book and his examples used functions like this to query MySQL database

<?php
require 'config.php';
function queryMysql($query) {
    global $connection; // accessible from config.php
    $result = $connection->query($query);
    if (!$result) die($connection->error);
    return $result;
}
?>

config.php

<?php
$dbhost  = 'localhost';
$dbname  = 'database_name';
$dbuser  = 'database_username';
$dbpass  = 'database_password';

$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);

// some other codes
?>

then this will normally follow anywhere in your code where you want to query the database $result=queryMysql($query); This is what I've been using all this while and I recently learnt that using a factory class is better and should save you stress as your website grows and also if you happen to later to use multiple types of databases.

I came across an article that suggested database should be queried this way (modified a bit to suit what am doing)

MYSQL class

<?php
class MYSQL
{
    private $host, $database_name, $username, $password;

    public function setHost($host) {
        $this->host = $host; // localhost
    }

    public function setDatabase($database_name) {
        $this->database_name = $database_name; // database name
    }

    public function setUsermame($username) {
        $this->username = $username; // db username
    }

    public function setPassword($password) {
        $this->password = $password; // db password
    }

    public function connect () {
        return $connection = new mysqli($this->host, $this->username, $this->password, $this->database_name);
        if ($connection->connect_error)
            // die($connection->connect_error);
            false;
        return $connection;
    }
}
?>

FACTORY class

<?php
class ConnectionFactory
{
    private $driver = null;

    public function setDriver($driver) {
        $this->driver = $driver;
    }

    public function connect($host, $username, $password, $database_name) {
        switch($this->driver) {
            case 'mysql':
                $DB = new MYSQL();
            break;
            default:
                $DB = new MYSQL();
        }

        $DB->setHost($host);
        $DB->setDatabase($database_name);
        $DB->setUsermame($username);
        $DB->setPassword($password);
        return $DB->connect();
    }
}
?>

Now to make query

<?php
$db_factory = new ConnectionFactory();
$db_factory->setDriver('mysql');
$connection = $db_factory->connect('localhost', 'database_username', 'database_password', 'database_name');
if ($connection->connect_error)
    die($connection->connect_error);

$query = "SELECT * FROM users";
$result = $connection->query($query);
if (!$result)
    die($connection->error);
// echo '
' , print_r($result), '
';
?>

I want to know really, how does the factory class above improve call to the database. I read that it helps if you may want to connect to different databases in the future. If that's it, wouldn't it be same if I created different functions with names to specify what database they called like this

function queryMysql() {
    // code here
}
function queryPostgreSQL() {
    // code here
}

And with the factory class above, I feel (I know am wrong) it's more stressful accessing the database because it requires you to keep entering host, username, password and database name each time you try to access the database. What are the real advantages? Thanks


问:
How to set OneDrive file picker (web apps) file types?
I'm trying to integrate OneDrive file picker to a web application. I have managed to initialize the file picker and show the file dialog; however, I could not find anything in the available documentations and on the internet to show how to limit the dialog to show certain file types.

I wonder if anybody knows how to set the mime type or file type to be only documents and pdf files.

Thanks.

答: This is now available! You can specify a list of file extensions that your app wants to allow the user to pick from, or use categories (like photos, folders) to specify a system-defined set of items that can be selected. More information is available here: https://dev.onedrive.com/sdk/js-v7/js-picker-open.htm#advanced-open-scenarios</p>


问:
Change OracleDependency timeout to unlimited
I am using OracleDependency to receive notification when a DB changes.
How do I change the notification timeout to an unlimited number of seconds?</p>

答:
According to Oracle, the way you specify the timeout depends upon the constructor you use when creating the OracleDependency object.

If you use OracleDependency (OracleCommand cmd), then the constructor sets the cmd.Notification property to a new OracleNotificationRequest that it creates. After the constructor returns, you have set cmd.Notification.Timeout to 0.

If you use OracleDependency (OracleCommand cmd, bool isNotifiedOnce, long timeout, bool isPersistent), then you specify a 0 for the timeout parameter.

If you use OracleDependency (), then no OracleCommand is associated with the new object and so whatever you do, you would do after you call the new object's AddCommandDependency(OracleCommand cmd) method. This means you would set cmd.Notification.Timeout to 0.

The default value for the Timeout is 50,000 seconds so you have plenty of time to modify the Timeout before the registration expires.


答:
As I mentioned in my remark, by default, SQL does not consider the order of rows in a database relevant, so it can not match the first row of one table to the first row of another and so forth.

For decades, people have accepted that, but recently sql is extended with new statements that resolve this issue. Unfortunatly, this has not been standardised, so it lead to further divergion of SQL dialects. For T-SQL, see this documentation on row_number() and rank()

The sollution is to add row numbers first, before joining:

```<code>SELECT pr.start_date,pr.end_date, p.contribution_id
FROM (select *, ROW_NUMBER()
                OVER(PARTITION BY membership_id
                ORDER BY start_date ASC) as row_nr
      from civicrm_membershipperiod ) pr
INNER JOIN (select *, ROW_NUMBER()
                OVER(PARTITION BY membership_id
                ORDER BY contribution_id ASC) as row_nr
      from civicrm_membership_payment ) p
ON pr.membership_id=p.membership_id and pr.row_nr = p.row_nr
where p.membership_id=11
</code>```

Title: Join doesn't give correct result

Body:
I am running the below query using join. But this join doesn't give the correct result

SELECT pr.start_date,pr.end_date, p.contribution_id
FROM civicrm_membershipperiod pr
INNER JOIN civicrm_membership_payment p ON pr.membership_id=p.membership_id
where p.membership_id=11

Both tables contains three records

mysql> select *  FROM `civicrm_membershipperiod` ;
+----+---------------+------------+------------+
| id | membership_id | start_date | end_date   |
+----+---------------+------------+------------+
|  1 |            11 | 2015-01-01 | 2015-12-31 |
|  2 |            11 | 2017-07-09 | 2018-07-08 |
|  3 |            11 | 2018-07-09 | 2019-07-08 |
+----+---------------+------------+------------+
3 rows in set (0.00 sec)
--------------------------------------------------------------------------
mysql> select *  FROM `civicrm_membership_payment` ;
+----+---------------+-----------------+
| id | membership_id | contribution_id |
+----+---------------+-----------------+
| 27 |            11 |              39 |
| 28 |            11 |              40 |
| 29 |            11 |              41 |
+----+---------------+-----------------+
3 rows in set (0.00 sec)

But result is nine records instead of three records.

mysql> SELECT pr.start_date,pr.end_date, p.contribution_id FROM civicrm_membershipperiod pr INNER JOIN civicrm_membership_payment p ON pr.membership_id=p.membership_id where p.membership_id=11;
+------------+------------+-----------------+
| start_date | end_date   | contribution_id |
+------------+------------+-----------------+
| 2015-01-01 | 2015-12-31 |              39 |
| 2015-01-01 | 2015-12-31 |              40 |
| 2015-01-01 | 2015-12-31 |              41 |
| 2017-07-09 | 2018-07-08 |              39 |
| 2017-07-09 | 2018-07-08 |              40 |
| 2017-07-09 | 2018-07-08 |              41 |
| 2018-07-09 | 2019-07-08 |              39 |
| 2018-07-09 | 2019-07-08 |              40 |
| 2018-07-09 | 2019-07-08 |              41 |
+------------+------------+-----------------+
9 rows in set (0.00 sec)

I am not sure where the error is.

This is I want:

2015-01-01  2015-12-31  39
2017-07-09  2018-07-08  40
2018-07-09  2019-07-08  41

Body:
As I mentioned in my remark, by default, SQL does not consider the order of rows in a database relevant, so it can not match the first row of one table to the first row of another and so forth.

For decades, people have accepted that, but recently sql is extended with new statements that resolve this issue. Unfortunatly, this has not been standardised, so it lead to further divergion of SQL dialects. For T-SQL, see this documentation on row_number() and rank()

The sollution is to add row numbers first, before joining:

SELECT pr.start_date,pr.end_date, p.contribution_id
FROM (select *, ROW_NUMBER()
                OVER(PARTITION BY membership_id
                ORDER BY start_date ASC) as row_nr
      from civicrm_membershipperiod ) pr
INNER JOIN (select *, ROW_NUMBER()
                OVER(PARTITION BY membership_id
                ORDER BY contribution_id ASC) as row_nr
      from civicrm_membership_payment ) p
ON pr.membership_id=p.membership_id and pr.row_nr = p.row_nr
where p.membership_id=11


问:
PHP - selecting input type using REGEX
I apologyze for the title , i didn't know how to express it properly

But here is the issue :

```<code>preg_match_all("/  (<input[^>]+>)  |  <select[^>]+>(.+?)<\/select  |  <textarea[^>]+>([^<]+)  /xims", $form, $matches);
</code>```

in the form i'm looking at, there is a File upload input

```<code><input type="file" name="upload">
</code>```

but when i do the

```<code>print_r($matches);
</code>```

I get the "text" fields but there's no "file" field fetched ..

I want to include the "file" input type in $matches[] as well.

i'm very weak in regex, and i googled alot but found nothing precise..

I'll appreciate your answer, Thanks.

答:
Try this regex:

```<code>/(?:<(select|textarea)[^>]*>[^<]+<\/\1>)|(<input[^>]*type=\"([a-z]+)\"[^>]*\/?>)/ximsg
</code>```

Regex Demo

Sample Source: (Run here)

```<code>$re = '/(?:<(select|textarea)[^>]*>[^<]+<\/\1>)|(<input[^>]*type=\"([a-z]+)\"[^>]*\/?>)/xims';
$str = '<input type="file" name="upload">
<input type="text" name="upload1">
<select > bla bla bla </select>
<textarea>abc</textarea>
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
</code>```

Title: PHP - selecting input type using REGEX

Body:
I apologyze for the title , i didn't know how to express it properly

But here is the issue :

preg_match_all("/  (<input[^>]+>)  |  <select[^>]+>(.+?)<\/select  |  <textarea[^>]+>([^<]+)  /xims", $form, $matches);

in the form i'm looking at, there is a File upload input

<input type="file" name="upload">

but when i do the

print_r($matches);

I get the "text" fields but there's no "file" field fetched ..

I want to include the "file" input type in $matches[] as well.

i'm very weak in regex, and i googled alot but found nothing precise..

I'll appreciate your answer, Thanks.

Body:
Try this regex:

/(?:<(select|textarea)[^>]*>[^<]+<\/\1>)|(<input[^>]*type=\"([a-z]+)\"[^>]*\/?>)/ximsg

Regex Demo

Sample Source: (Run here)

$re = '/(?:<(select|textarea)[^>]*>[^<]+<\/\1>)|(<input[^>]*type=\"([a-z]+)\"[^>]*\/?>)/xims';
$str = '<input type="file" name="upload">
<input type="text" name="upload1">
<select > bla bla bla </select>
<textarea>abc</textarea>
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);


问:
Please make it more easy to use phongap to install an simple plugin
Please make it more easy to use phongap to install an simple plugin.

Can it not be done with easy installing a plugin for phongegap not used with cli and will not be.

Can it not be implemented in phongap only select the plugin you want and then install it and it do the rest for you.

Why is it so complicated. This will not atract bigginers to use it.. You can use it as standard plugins but if you whant to install other third part plugins it get complicated .

Please make any changes.  Phonegap desktop installation is very easy but have not any function as install plugins to your projects. It need an expert to make that.

答:
You can download a GUI if you dont like to use the command line. Here is an unofficial GUI: https://github.com/adnanafzal565/Cordova-GUI

It has all the basic functions (creating projects, adding platforms, adding plugins, adding icons and splash screen, building the app) and works just fine.


问:
How to add a variable value with auto increment value in an insert query
I have a localhost and I want to do something I hope I can explain it.
I have a table named 'students' in a database named 'theway', there is a column named 's_class_id' its kind is auto increment , and in php I insert some values in this table. But I want to insert a variable+the auto increment in the column named 's_class_id'.
For example : The variable's value is 'a', and the auto increment value is '5'. I want the value which be inserted in the 's_class_id' like this 'a5'.
Any help?</p>

答:
You can do that task by folowing method,

First you need to insert record into theway table. After record insertion mysqli_insert_id($con) will return last inserted id. Then you need to update that row by using last inserted id.

```<code>// Insert Record
mysqli_query($con,"INSERT INTO theway  (s_class_id) VALUES ('a')");
// Getting last inserted id
$lastInsertID =  mysqli_insert_id($con);
$updatedValue = 'a'.$lastInsertID;
// Update same row with last inserted ida
$SameRowUpdate = "UPDATE theway SET s_class_id='".$updatedValue."' WHERE id=".$lastInsertID;
if (mysqli_query($conn, $SameRowUpdate )) {
    echo "Record addedd successfully";
}
</code>```

Body:
You can do that task by folowing method,

First you need to insert record into theway table. After record insertion mysqli_insert_id($con) will return last inserted id. Then you need to update that row by using last inserted id.

// Insert Record
mysqli_query($con,"INSERT INTO theway  (s_class_id) VALUES ('a')");
// Getting last inserted id
$lastInsertID =  mysqli_insert_id($con);
$updatedValue = 'a'.$lastInsertID;
// Update same row with last inserted ida
$SameRowUpdate = "UPDATE theway SET s_class_id='".$updatedValue."' WHERE id=".$lastInsertID;
if (mysqli_query($conn, $SameRowUpdate )) {
    echo "Record addedd successfully";
}


问:
Getting Weighted Average within a category with multiple sub categories
Joe owns a worldwide DVD rental store. He has stores throughout the globe in different regions. Each month he likes to see if his equipment in his stores is up-to-date by finding the percentage of his inventory with a certain status of "Current," "Needs Update," and "Must Go" for each region. This helps ensure his customers have the best experience in his stores.

Bill, his assistant, wants to build a SQL query that will show Joe the percentage of equipment in each region and their status. The guy before him used an excel to do this but Bill thinks SQL and then an SSRS report that would allow Joe to select which region he wants to view would impress him. He wants to have it dynamically transition from months to quarters as the year progresses in the report. This is what Bill has been able to come up with so far:

Comparing it to the excel from before, everything is correct and his SSRS is working perfectly all except for North America, which has percentages that are slightly off. He is thinking that a weighted average for the subregions in North America would fix this to get the percentage correct because some subregions are bigger than others.

How would Bill go about calculating the weighted averages each of the regions in North America?

答:
This query looks a little like dogs breakfast.
The main problems:

SELECT DISTINCT is not needed in GROUP BY queries as values are already distinct.
I can understand the usage of DISTINCT in COUNTS and TOT queries provided that data in TABLEIMPORT is not normalised.

Total luck of comments explaining the intention of the query.

Variable/alias naming is very poor.

I suspect the problem with the first query is here:

```<code>QTRMNTH as (
select distinct
q.Quarter  [Month]
,q.Percents [Percents]
,d.[Equipment Status]
,d.Quarter
,d.Year
,o.SelectRegion
from data d
     inner join OWN o on o.[Region] = d.[Region]
     inner join QUARTERS q on q.Quarter = d.Quarter and q.year = d.Year and q.[Equipment Status] = d.[Equipment Status]
where d.[Month] < DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 1, -1) and   d.[Month] > dateadd(MONTH,-12,GETDATE())
</code>```

I assume the above code is supposed to return quarterly results per "greater region" [SelectRegion] based on monthly data (data). If this is the case then you need to remove the DISTINCT and add the GROUP BY.

I think it would also be helpful to remove DISTINCT from all other queries to be able to spot other hidden issues.

Body:
This query looks a little like dogs breakfast.
The main problems:

SELECT DISTINCT is not needed in GROUP BY queries as values are already distinct.
I can understand the usage of DISTINCT in COUNTS and TOT queries provided that data in TABLEIMPORT is not normalised.

Total luck of comments explaining the intention of the query.

Variable/alias naming is very poor.

I suspect the problem with the first query is here:

QTRMNTH as (
select distinct
q.Quarter  [Month]
,q.Percents [Percents]
,d.[Equipment Status]
,d.Quarter
,d.Year
,o.SelectRegion
from data d
     inner join OWN o on o.[Region] = d.[Region]
     inner join QUARTERS q on q.Quarter = d.Quarter and q.year = d.Year and q.[Equipment Status] = d.[Equipment Status]
where d.[Month] < DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 1, -1) and   d.[Month] > dateadd(MONTH,-12,GETDATE())

I assume the above code is supposed to return quarterly results per "greater region" [SelectRegion] based on monthly data (data). If this is the case then you need to remove the DISTINCT and add the GROUP BY.

I think it would also be helpful to remove DISTINCT from all other queries to be able to spot other hidden issues.