问:
Java send gmail
I'm dealing with problem sending gmail's from my app, i have following code:

```<code>public class Notificator {

public static void main(String[] args) {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("r","");
                }
            });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from@no-spam.com"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("to@no-spam.com"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler," +
                "\n\n No spam to my email, please!");

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
</code>```

}

And im getting following error :     Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect

Threfore I enabled access for less secured devices and also enabled intellij in firewall.

edit: Yes i have correct credintials, just erased them before putting here.

答:
Check the correct properties:</p>

```<code>Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true";
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
</code>```

Title: Java send gmail

Body:
I'm dealing with problem sending gmail's from my app, i have following code:

public class Notificator {

public static void main(String[] args) {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("r","");
                }
            });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from@no-spam.com"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("to@no-spam.com"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler," +
                "\n\n No spam to my email, please!");

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

}

And im getting following error :     Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect

Threfore I enabled access for less secured devices and also enabled intellij in firewall.

edit: Yes i have correct credintials, just erased them before putting here.

Body:
Check the correct properties:

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true";
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
props.put("mail.smtp.port", "587");


来源: stackexchange

问:
Converting a input (Password) into MD5
Hi I'm a bit new to this and can't exactly figure out how to get it working.

Here is my current code:

```<code>import hashlib

def PasswordCreate():
    password = input(str("Please enter a password next to this text"))
    password = hashlib.md5()
    password.update(password.encode('utf-8'))
    return password.hexdigest()

PasswordCreate()
</code>```

The error is:

```<code>AttributeError: '_hashlib.HASH' object has no attribute 'encode'
</code>```

答:
```<code>import hashlib

def PasswordCreate():
    user_in = input(str("Please enter a password next to this text"))
    password = hashlib.md5()
    password.update(user_in.encode("utf-8"))
    return password.hexdigest()

PasswordCreate()
</code>```

Just an issue in your variables. See user_in in my code

ContentLicense: CC BY-SA 3.0

Title: Converting a input (Password) into MD5

Body:
Hi I'm a bit new to this and can't exactly figure out how to get it working.

Here is my current code:

import hashlib

def PasswordCreate():
    password = input(str("Please enter a password next to this text"))
    password = hashlib.md5()
    password.update(password.encode('utf-8'))
    return password.hexdigest()

PasswordCreate()

The error is:

AttributeError: '_hashlib.HASH' object has no attribute 'encode'

Body:
import hashlib

def PasswordCreate():
    user_in = input(str("Please enter a password next to this text"))
    password = hashlib.md5()
    password.update(user_in.encode("utf-8"))
    return password.hexdigest()

PasswordCreate()

Just an issue in your variables. See user_in in my code


问:
Filling a zeros array at limited number of random places except diagonal ones
I have a 2D numpy array which has only 0s in (N,N) size. I randomly want to insert twelve 1s to this array while keeping the diagonal locations' value equal to 0. What I have tried until now is :

```<code>import numpy as np
def func(N=20):
    x= np.zeros((N,N))
    for m in range(N):
        for n in range(N):
                if m == n:
                    x[m][n] == 0
                else:
                    if np.count_nonzero(x) <= 12:
                            x.fill(1)
                            return (np.count_nonzero)
    print (x)
</code>```

The output I am getting is an N,N array full of 1s. I cannot stop inserting the 1s after their quantity reaches to 12.
How can I fix it?

答:
Since you are using NumPy and if you are okay with an alternate vectorized solution, here's one with masking and choosing those places with np.random.choice -

```<code>def random_off_diag_fill(N, num_rand = 12, fillval=1):
    # Initialize array
    x= np.zeros((N,N),dtype=type(fillval))

    # Generate flat nondiagonal indices using masking
    idx = np.flatnonzero(~np.eye(N,dtype=bool))

    # Select num_rand random indices from those and set those
    # in a flattened view of the array to be as fillval
    x.ravel()[np.random.choice(idx, num_rand, replace=0)] = fillval
    return x
</code>```

Sample runs -

```<code>In [57]: random_off_diag_fill(N=8, num_rand=12, fillval=1)
Out[57]:
array([[0, 0, 0, 0, 0, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 1, 0, 0, 0, 0, 0]])

In [63]: random_off_diag_fill(N=5, num_rand=12, fillval=2.45)
Out[63]:
array([[ 0.  ,  0.  ,  0.  ,  0.  ,  2.45],
       [ 2.45,  0.  ,  2.45,  0.  ,  2.45],
       [ 0.  ,  2.45,  0.  ,  2.45,  2.45],
       [ 2.45,  2.45,  0.  ,  0.  ,  0.  ],
       [ 2.45,  2.45,  0.  ,  2.45,  0.  ]])
</code>```

Body:
I have a 2D numpy array which has only 0s in (N,N) size. I randomly want to insert twelve 1s to this array while keeping the diagonal locations' value equal to 0. What I have tried until now is :

import numpy as np
def func(N=20):
    x= np.zeros((N,N))
    for m in range(N):
        for n in range(N):
                if m == n:
                    x[m][n] == 0
                else:
                    if np.count_nonzero(x) <= 12:
                            x.fill(1)
                            return (np.count_nonzero)
    print (x)

The output I am getting is an N,N array full of 1s. I cannot stop inserting the 1s after their quantity reaches to 12.
How can I fix it?

Body:
Since you are using NumPy and if you are okay with an alternate vectorized solution, here's one with masking and choosing those places with np.random.choice -

def random_off_diag_fill(N, num_rand = 12, fillval=1):
    # Initialize array
    x= np.zeros((N,N),dtype=type(fillval))

    # Generate flat nondiagonal indices using masking
    idx = np.flatnonzero(~np.eye(N,dtype=bool))

    # Select num_rand random indices from those and set those
    # in a flattened view of the array to be as fillval
    x.ravel()[np.random.choice(idx, num_rand, replace=0)] = fillval
    return x

Sample runs -

In [57]: random_off_diag_fill(N=8, num_rand=12, fillval=1)
Out[57]:
array([[0, 0, 0, 0, 0, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 1, 0, 0, 0, 0, 0]])

In [63]: random_off_diag_fill(N=5, num_rand=12, fillval=2.45)
Out[63]:
array([[ 0.  ,  0.  ,  0.  ,  0.  ,  2.45],
       [ 2.45,  0.  ,  2.45,  0.  ,  2.45],
       [ 0.  ,  2.45,  0.  ,  2.45,  2.45],
       [ 2.45,  2.45,  0.  ,  0.  ,  0.  ],
       [ 2.45,  2.45,  0.  ,  2.45,  0.  ]])


问:
Fibonacci sequence in Ruby (recursion)
I'm trying to implement the following function, but it keeps giving me the stack level too deep (SystemStackError) error.

Any ideas what the problem might be ?

```<code>def fibonacci( n )
    [ n ] if ( 0..1 ).include? n
    ( fibonacci( n - 1 ) + fibonacci( n - 2 ) ) if n > 1
end

puts fibonacci( 5 )
</code>```

Title: Fibonacci sequence in Ruby (recursion)

Body:
I'm trying to implement the following function, but it keeps giving me the stack level too deep (SystemStackError) error.

Any ideas what the problem might be ?

def fibonacci( n )
    [ n ] if ( 0..1 ).include? n
    ( fibonacci( n - 1 ) + fibonacci( n - 2 ) ) if n > 1
end

puts fibonacci( 5 )

Body:
This is the snippet that I used to solve a programming challenge at URI Online Judge, hope it helps.

def fib(n)
  if n == 1
    puts 0
  else
    fib = [0,1]
    (n-2).times do
      fib << fib[-1] + fib[-2]
    end
    puts fib.join(' ')
  end
end

fib(45)

An it outputs

# => 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733


问:
Dropzone.js post request in laravel 5.4
I am not receiving any request at controller's uploadGallery method. Although, the post request is received correctly.

gallery.blade.php

```<code><div class="row">
    <form action="{{ url('file-upload') }}" method="post" class="dropzone" id="my-awesome-dropzone">
                            {{ csrf_field() }}
                            <div class="dz-message">
                                <h3>Drop images here or click to upload.</h3>
                            </div>
                        </form>
                    </div>
    <script type="text/javascript">

        $(function (){

            Dropzone.options.myAwesomeDropzone = {
                paramName: "files",
                uploadMultiple:true,
                maxFilesize:6,
                autoProcessQueue: true,
                uploadMultiple: true,
                addRemoveLinks: true,
                acceptedFiles: ".png, .jpg, .jpeg",
                dictFallbackMessage:"Your browser does not support drag'n'drop file uploads.",
                dictRemoveFile: "Remove",
                dictFileTooBig:"Image is bigger than 6MB",

                accept: function(file, done) {
                    console.log("Uploaded");
                    done();
                },

                init:function() {
                /*  var submitButton = document.querySelector('#submit-all')
                        myAwesomeDropzone = this;

                    submitButton.addEventListener("click", function(
                        myAwesomeDropzone.processQueue();
                    ));

                    this.on("addedfile", function(){
                        $('#submit-all').show();
                    });*/

                },
                success: function(file,done){
                    console.log("All files done!");
                }
        }
        });
    </script>
</code>```

web.php

```<code>Route::get('/gallery', 'PagesController@Gallery');
Route::post('/file-upload', 'ImagesController@uploadImages');
</code>```

ImagesController.php

```<code><?php

namespace App\Http\Controllers;

use App\User;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ImagesController extends Controller
{
    public function __construct() {
        $this->middleware('auth');
    }

    public function uploadImages(Image $request) {
        $images = request()->file('files');
        dd($images);
        return view('Gallery');
    }
}
</code>```

Anything inside the uploadImages function is not running. Why?

答:
Change this

```<code>public function uploadImages(Image $request) {
        $images = request()->file('files');
        dd($images);
        return view('Gallery');
    }
</code>```

to and replace request() with $request since your using eloquent.

```<code>public function uploadImages(Request $request) {
        $images = $request->file('files');
        dd($images);
        return view('Gallery');
    }
</code>```

For more detailed integration with laravel dropzone you can refer to this tutorial Integrating Dropzone.js in Laravel 5 applications

Title: Dropzone.js post request in laravel 5.4

Body:
I am not receiving any request at controller's uploadGallery method. Although, the post request is received correctly.

gallery.blade.php

    <form action="{{ url('file-upload') }}" method="post" class="dropzone" id="my-awesome-dropzone">
                            {{ csrf_field() }}

Drop images here or click to upload.

                        </form>

web.php

Route::get('/gallery', 'PagesController@Gallery');
Route::post('/file-upload', 'ImagesController@uploadImages');

ImagesController.php

<?php

namespace App\Http\Controllers;

use App\User;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ImagesController extends Controller
{
    public function __construct() {
        $this->middleware('auth');
    }

    public function uploadImages(Image $request) {
        $images = request()->file('files');
        dd($images);
        return view('Gallery');
    }
}

Anything inside the uploadImages function is not running. Why?

Body:
Change this

public function uploadImages(Image $request) {
        $images = request()->file('files');
        dd($images);
        return view('Gallery');
    }

to and replace request() with $request since your using eloquent.

public function uploadImages(Request $request) {
        $images = $request->file('files');
        dd($images);
        return view('Gallery');
    }

For more detailed integration with laravel dropzone you can refer to this tutorial Integrating Dropzone.js in Laravel 5 applications


问:
Using Python scripts in Android for image processing
I have some python scripts which are doing image processing work using its own numpy and scipy libraries. How can I use/call these scripts in Android application providing image input from camera captures and saving the images after processed. Is there some native support for Python like C++. What performance implications would be there if I compare with using C++ as a native support. Any help would be greatly appreciated.</p>

答: You need a Python Interpreter to run Python scripts,Pydroid Gives you access to compile  Python scipts and comes with pip,So you could Install new Python Modules,it's the only app that gives a real Experience of Programming using python.</p>


问:
php html show large dynamic table data in one tv dashboard
I have one TV Dashboard (without touch). I want to display some information dynamically from database PHP/MySQL.
But here is a problem: when table rows exceed the height of screen i want to display automatically a second page and after 10 sec i want to auto go back on first page. All in loop mode. It is that possible?

Thank you.

I have code like this:

```<code><table class="table">
    <thead>
       <tr>
        <th id="th_left">Ticket ID</th>
        <th id="th_left">Device Model</th>
        <th id="th_left">Client Name</th>
       </tr>
    </thead>

                    <?php
                       for ($j=0; $j<count($to_display_list); $j++) {
                           $a = $to_display_list[$j]->status_id;
                    ?>
    <tbody>
      <tr>
        <td><strong><?php echo $to_display_list[$j]->ticket_id ?></strong></td>
        <td><strong><?php echo $to_display_list[$j]->device_model ?></strong></td>
        <td><strong><?php echo $to_display_list[$j]->client_name ?></strong></td>
      </tr>
    </tbody>
    <?php
    }
    ?>
</table>
</code>```

Can you help me please?

答:
<blockquote>
```<code>    Andreas, I have another question:
    If there is less rows, mean "<30", why I need to display page.php?p=2  ???
    Below is my working code based on your answer (testing)
    Thank you.
</code>```
</blockquote>

```<code><html>
<head>
    <?php
        $page = $_GET['p'];
        if($page == "1"){
            echo '<meta http-equiv="refresh" content="10; url=page.php?p=2">'; // replace page.php with your file name
        }else{
            echo '<meta http-equiv="refresh" content="10; url=page.php?p=1">'; // replace page.php with your file name
        }
    ?>
</head>
<body>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>NUMBER</th>
                <th>MODEL</th>
                <th>NAME</th>
                <th>IN</th>
                <th>START</th>
                <th>PRICE</th>
                <th>WAITING</th>
                <th>DONE</th>
                <th>TIME</th>
            </tr>
        </thead>
        <tbody>
        <?php
            if($page == "1"){
                for ($x=0; $x<30/2; $x++) {
        ?>
            <tr>
                <td><strong><?php echo $x ?></strong></td>
                <td><strong>4545465</strong></td>
                <td><strong>ANY MODEL</strong></td>
                <td><strong>EMMET BROWN</strong></td>
                <td></td>
                <td></td>
                <td></td>
                <td>X</td>
                <td></td>
                <td>00:05:08</td>
            </tr>
        <?php } } else {
            for ($x=30/2; $x<30; $x++) {
        ?>
            <tr>
                <td><strong><?php echo $x ?></strong></td>
                <td><strong>4545465</strong></td>
                <td><strong>ANY MODEL</strong></td>
                <td><strong>EMMET BROWN</strong></td>
                <td></td>
                <td></td>
                <td></td>
                <td>X</td>
                <td></td>
                <td>00:05:08</td>
            </tr>
        <?php }} ?>
        </tbody>
    </table>
</body>
</html>
</code>```

Body:
I have one TV Dashboard (without touch). I want to display some information dynamically from database PHP/MySQL.
But here is a problem: when table rows exceed the height of screen i want to display automatically a second page and after 10 sec i want to auto go back on first page. All in loop mode. It is that possible?

Thank you.

I have code like this:

        Ticket ID
        Device Model
        Client Name

                    <?php
                       for ($j=0; $j<count($to_display_list); $j++) {
                           $a = $to_display_list[$j]->status_id;
                    ?>

        <?php echo $to_display_list[$j]->ticket_id ?>
        <?php echo $to_display_list[$j]->device_model ?>
        <?php echo $to_display_list[$j]->client_name ?>

    <?php
    }
    ?>

Can you help me please?

Body:
    Andreas, I have another question:
    If there is less rows, mean "<30", why I need to display page.php?p=2  ???
    Below is my working code based on your answer (testing)
    Thank you.

<html>
<head>
    <?php
        $page = $_GET['p'];
        if($page == "1"){
            echo '<meta http-equiv="refresh" content="10; url=page.php?p=2">'; // replace page.php with your file name
        }else{
            echo '<meta http-equiv="refresh" content="10; url=page.php?p=1">'; // replace page.php with your file name
        }
    ?>
</head>
<body>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>NUMBER</th>
                <th>MODEL</th>
                <th>NAME</th>
                <th>IN</th>
                <th>START</th>
                <th>PRICE</th>
                <th>WAITING</th>
                <th>DONE</th>
                <th>TIME</th>
            </tr>
        </thead>
        <tbody>
        <?php
            if($page == "1"){
                for ($x=0; $x<30/2; $x++) {
        ?>
            <tr>
                <td><strong><?php echo $x ?></strong></td>
                <td><strong>4545465</strong></td>
                <td><strong>ANY MODEL</strong></td>
                <td><strong>EMMET BROWN</strong></td>
                <td></td>
                <td></td>
                <td></td>
                <td>X</td>
                <td></td>
                <td>00:05:08</td>
            </tr>
        <?php } } else {
            for ($x=30/2; $x<30; $x++) {
        ?>
            <tr>
                <td><strong><?php echo $x ?></strong></td>
                <td><strong>4545465</strong></td>
                <td><strong>ANY MODEL</strong></td>
                <td><strong>EMMET BROWN</strong></td>
                <td></td>
                <td></td>
                <td></td>
                <td>X</td>
                <td></td>
                <td>00:05:08</td>
            </tr>
        <?php }} ?>
        </tbody>
    </table>
</body>
</html>


问:
Error My SQL in Java Language (Netbeans)
I have code:

```<code>private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    try {
        con = Connect.ConnectDB();
        if (PatientID.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Please retrieve Patient ID", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (txtNoOfDays.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Please enter no. of days", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (txtServiceCharges.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Please retrieve service charges", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (txtBillingDate.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Please enter billing date", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (txtTotalPaid.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Please enter total paid", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        double add1 = Double.parseDouble(txtRoomCharges.getText());
        double add = Double.parseDouble(txtNoOfDays.getText());
        double add2 = add * add1;
        txtTotalRoomCharges.setText(String.valueOf(add2));
        double add3 = Double.parseDouble(txtServiceCharges.getText());
        double add5 = ((add * add1) + add3);
        txtTotalCharges.setText(String.valueOf(add5));
        double paid = Double.parseDouble(txtTotalPaid.getText());
        txtTotalPaid.setText(String.valueOf(paid));
        if (add5 > paid) {
            double datadue = add5 - paid;
            txtDueCharges.setText(String.valueOf(datadue));
        }
        //double add1 = Double.parseDouble(txtTotalCharges.getText());
        //double add2 = Double.parseDouble(txtTotalPaid.getText());

        Statement stmt;
        stmt = con.createStatement();
        String sql1 = "Select DischargeID from bill_room where DischargeID= " + txtDischargeID.getText() + "";
        rs = stmt.executeQuery(sql1);
        if (rs.next()) {
            JOptionPane.showMessageDialog(this, "Record already exists", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String sql = "insert into bill_room(DischargeID,BillingDate,RoomCharges,ServiceCharges,PaymentMode,PaymentModeDetails,ChargesPaid,DueCharges,TotalCharges,NoOfDays,TotalRoomCharges) values(" + txtDischargeID.getText() + ",'" + txtBillingDate.getText() + "'," + txtRoomCharges.getText() + "," + txtServiceCharges.getText() + ",'" + cmbPaymentMode.getSelectedItem() + "','" + txtPaymentModeDetails.getText() + "'," + txtTotalPaid.getText() + "," + txtDueCharges.getText() + "," + txtTotalCharges.getText() + "," + txtNoOfDays.getText() + "," + txtTotalRoomCharges.getText() + ")";
        pst = con.prepareStatement(sql);
        pst.execute();
        JOptionPane.showMessageDialog(this, "Successfully saved", "Record", JOptionPane.INFORMATION_MESSAGE);
        btnSave.setEnabled(false);

    } catch (HeadlessException | SQLException ex) {
        JOptionPane.showMessageDialog(this, ex);
    }
</code>```

I have this code, when the execution runs (sometimes goes well, sometimes error.)
When error happen:

com.mysql.jdbc.exceptions.jbdc4.MySQLSyntaxErrorException" You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for right sysntax to use near
  '110800.0,9,10800.0); at line 1

When Run clearly

What is not quite right here?
I need your help or your suggest

答:
You already use PreparedStatement why you don't use it properly, so to avoid syntax error and SQL injection you can use :

```<code>String sql = "insert into bill_room(DischargeID, BillingDate, "
        + "RoomCharges, ServiceCharges, PaymentMode, PaymentModeDetails, "
        + "ChargesPaid, DueCharges, TotalCharges, NoOfDays, TotalRoomCharges) "
        + "values(?, ?, ?, ?, ?, ?,  ?, ?, ?, ?, ?)";

try (PreparedStatement insert = connection.prepareStatement(sql)) {

    insert.setInt(1, txtDischargeID.getText());
    insert.setString(2, txtBillingDate.getText());

    //...Set the the right type if int use setInt if string use setString ...

    insert.setDouble(11, Double.parseDouble(txtTotalRoomCharges.getText()));

    insert.executeUpdate();
}
</code>```

same thing with select.

Body:
I have code:

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    try {
        con = Connect.ConnectDB();
        if (PatientID.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Please retrieve Patient ID", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (txtNoOfDays.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Please enter no. of days", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (txtServiceCharges.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Please retrieve service charges", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (txtBillingDate.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Please enter billing date", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (txtTotalPaid.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Please enter total paid", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        double add1 = Double.parseDouble(txtRoomCharges.getText());
        double add = Double.parseDouble(txtNoOfDays.getText());
        double add2 = add * add1;
        txtTotalRoomCharges.setText(String.valueOf(add2));
        double add3 = Double.parseDouble(txtServiceCharges.getText());
        double add5 = ((add * add1) + add3);
        txtTotalCharges.setText(String.valueOf(add5));
        double paid = Double.parseDouble(txtTotalPaid.getText());
        txtTotalPaid.setText(String.valueOf(paid));
        if (add5 > paid) {
            double datadue = add5 - paid;
            txtDueCharges.setText(String.valueOf(datadue));
        }
        //double add1 = Double.parseDouble(txtTotalCharges.getText());
        //double add2 = Double.parseDouble(txtTotalPaid.getText());

        Statement stmt;
        stmt = con.createStatement();
        String sql1 = "Select DischargeID from bill_room where DischargeID= " + txtDischargeID.getText() + "";
        rs = stmt.executeQuery(sql1);
        if (rs.next()) {
            JOptionPane.showMessageDialog(this, "Record already exists", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String sql = "insert into bill_room(DischargeID,BillingDate,RoomCharges,ServiceCharges,PaymentMode,PaymentModeDetails,ChargesPaid,DueCharges,TotalCharges,NoOfDays,TotalRoomCharges) values(" + txtDischargeID.getText() + ",'" + txtBillingDate.getText() + "'," + txtRoomCharges.getText() + "," + txtServiceCharges.getText() + ",'" + cmbPaymentMode.getSelectedItem() + "','" + txtPaymentModeDetails.getText() + "'," + txtTotalPaid.getText() + "," + txtDueCharges.getText() + "," + txtTotalCharges.getText() + "," + txtNoOfDays.getText() + "," + txtTotalRoomCharges.getText() + ")";
        pst = con.prepareStatement(sql);
        pst.execute();
        JOptionPane.showMessageDialog(this, "Successfully saved", "Record", JOptionPane.INFORMATION_MESSAGE);
        btnSave.setEnabled(false);

    } catch (HeadlessException | SQLException ex) {
        JOptionPane.showMessageDialog(this, ex);
    }

I have this code, when the execution runs (sometimes goes well, sometimes error.)
When error happen:

com.mysql.jdbc.exceptions.jbdc4.MySQLSyntaxErrorException" You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for right sysntax to use near
  '110800.0,9,10800.0); at line 1

When Run clearly

What is not quite right here?
I need your help or your suggest

Body:
You already use PreparedStatement why you don't use it properly, so to avoid syntax error and SQL injection you can use :

String sql = "insert into bill_room(DischargeID, BillingDate, "
        + "RoomCharges, ServiceCharges, PaymentMode, PaymentModeDetails, "
        + "ChargesPaid, DueCharges, TotalCharges, NoOfDays, TotalRoomCharges) "
        + "values(?, ?, ?, ?, ?, ?,  ?, ?, ?, ?, ?)";

try (PreparedStatement insert = connection.prepareStatement(sql)) {

    insert.setInt(1, txtDischargeID.getText());
    insert.setString(2, txtBillingDate.getText());

    //...Set the the right type if int use setInt if string use setString ...

    insert.setDouble(11, Double.parseDouble(txtTotalRoomCharges.getText()));

    insert.executeUpdate();
}

same thing with select.


问:
I cannot seem to handle dropdown from Robot Framework. I am using Selenium2Library and Python2.7
I already tried *select from list* methods but to no avail (It always cannot find the element). Please see the screenshot here and help me in handling it. I want to select DELHI option from the Payment Location dropdown options

Similarly how to handle this dropdown here (Cost Center). The suggestion only comes when we type letters in it. I tried it with 'select from list by index 0'  but that did not help.

答:
Not having access to the actual code limits us in helping you. Screenshots, especially those not included but linked to, are a burden to work with. Use the  image functionality to add an inline image. However, copy and paste the actual code is always preferred.

When the specialized functions like select from list are not working you can always revert back to the basic steps of click element and xpath.

In this case I'm asuming that the options are already available in the DOM before clicking on the menu. If that is the case I think click element    xpath=//select[@id='id_location']/option[text() = 'Delhi'] should work for you. Otherwise, add a preceding click element    xpath=//select[@id='id_location'] to first click the menu, so that the items are loaded.

For the second menu you mention that this menu is only populated when text is typed into the box. Here I'd follow the same approach as above. Use input text xpath=//.... generating the menu items you seek and the proceed by click element   xpath=//... for the actual menu selection.


问:
How to use a Objective-C #define from Swift
I am migrating a UIViewController class to train a bit with Swift. I am successfully using Objective-C code via the bridging header but I have the need of importing a constants file that contains #define directives.

I have seen in Using Swift with Cocoa and Objective-C (Simple macros) the following:

Simple Macros

Where you typically used the #define directive to define a primitive constant in C and Objective-C, in Swift you use a global constant instead. For example, the constant definition #define FADE_ANIMATION_DURATION 0.35 can be better expressed in Swift with let FADE_ANIMATION_DURATION = 0.35. Because simple constant-like macros map directly to Swift global variables, the compiler automatically imports simple macros defined in C and Objective-C source files.

So, it seems it's possible. I have imported the file containing my constants into the bridging header, but I have no visibility from my .swift file, cannot be resolved.

What should I do to make my constants visible to Swift?

UPDATE:

It seems working with NSString constants, but not with booleans:

```<code>#define kSTRING_CONSTANT @"a_string_constant" // resolved from swift
#define kBOOL_CONSTANT YES // unresolved from swift
</code>```

答:
The alternative for macro can be global variable . We can declare global variable outside the class and access those without using class. Please find example below</p>

```<code>import Foundation
let BASE_URL = "www.google.com"

class test {

}
</code>```

Body:
I am migrating a UIViewController class to train a bit with Swift. I am successfully using Objective-C code via the bridging header but I have the need of importing a constants file that contains #define directives.

I have seen in Using Swift with Cocoa and Objective-C (Simple macros) the following:

Simple Macros

Where you typically used the #define directive to define a primitive constant in C and Objective-C, in Swift you use a global constant instead. For example, the constant definition #define FADE_ANIMATION_DURATION 0.35 can be better expressed in Swift with let FADE_ANIMATION_DURATION = 0.35. Because simple constant-like macros map directly to Swift global variables, the compiler automatically imports simple macros defined in C and Objective-C source files.

So, it seems it's possible. I have imported the file containing my constants into the bridging header, but I have no visibility from my .swift file, cannot be resolved.

What should I do to make my constants visible to Swift?

UPDATE:

It seems working with NSString constants, but not with booleans:

#define kSTRING_CONSTANT @"a_string_constant" // resolved from swift
#define kBOOL_CONSTANT YES // unresolved from swift

Body:
The alternative for macro can be global variable . We can declare global variable outside the class and access those without using class. Please find example below

import Foundation
let BASE_URL = "www.google.com"

class test {

}

ContentLicense: CC BY-SA 4.0


问:
adding click action to NSTextField
How do I attach a event to a NSTextField for when I click on it? Are there any examples out there?</p>

答:
```<code>NSClickGestureRecognizer *click = [[NSClickGestureRecognizer alloc] initWithTarget:self action:@selector(myTextFieldClicked:)];
[self.myTextField addGestureRecognizer:click];
</code>```

ContentLicense: CC BY-SA 2.5

Title: adding click action to NSTextField


问:
Initialize a stack which can find the minimum number. Java
I am using the code like this but there are errors while running... the system returns java.util.EmptyStackException..Can anybody help me?</p>

```<code>public class Solution {

    private Stack<Integer> val = new Stack<>();
    private Stack<Integer> stackMin = new Stack<>();
    Integer temp = null;

    public void push(int node) {
        this.val.push(node);
        if(this.stackMin == null){
            this.stackMin.push(node);
        }else if(node<=this.min()){
            this.stackMin.push(node);
        }
    }

    public void pop() {
        if (this.val==null) {
            throw new RuntimeException("Stack is empty.");
        }
        int value = this.val.pop();
        if(value == this.min()){
            this.stackMin.pop();
        }
    }

    public int top() {
        if(this.val!=null){
            return this.val.peek();
        }else{
            throw new RuntimeException("Stack is empty");
        }
    }

    public int min() {
        if(this.stackMin!=null){
            return this.stackMin.peek();
        }
       throw new RuntimeException("Stack is empty");
    }
}
</code>```

答:
I think that you should use stack.empty() instead of testing for null value. I changed some code and the exception doesn't occur like this.

```<code>import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Main m1 = new Main();
        m1.push(2);
        m1.push(1);
        m1.push(3);
        System.out.println(m1.min());
    }
    private Stack<Integer> val = new Stack<>();
    private Stack<Integer> stackMin = new Stack<>();
    Integer temp = null;

    public void push(int node) {
        this.val.push(node);
        if(this.stackMin.empty()){
            this.stackMin.push(node);
        }else if(node<=this.min()){
            this.stackMin.push(node);
        }
    }

    public void pop() {
        if (!this.val.empty()) {
            throw new RuntimeException("Stack is empty.");
        }
        int value = this.val.pop();
        if(value == this.min()){
            this.stackMin.pop();
        }
    }

    public int top() {
        if(!this.val.empty()){
            return this.val.peek();
        }else{
            throw new RuntimeException("Stack is empty");
        }
    }

    public int min() {
        if(!this.stackMin.empty()){
            return this.stackMin.peek();
        }
        throw new RuntimeException("Stack is empty");
    }
}
</code>```

Test outputs the minimum value

```<code>/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java Main
1

Process finished with exit code 0
</code>```

Body:
I am using the code like this but there are errors while running... the system returns java.util.EmptyStackException..Can anybody help me?

public class Solution {

    private Stack<Integer> val = new Stack<>();
    private Stack<Integer> stackMin = new Stack<>();
    Integer temp = null;

    public void push(int node) {
        this.val.push(node);
        if(this.stackMin == null){
            this.stackMin.push(node);
        }else if(node<=this.min()){
            this.stackMin.push(node);
        }
    }

    public void pop() {
        if (this.val==null) {
            throw new RuntimeException("Stack is empty.");
        }
        int value = this.val.pop();
        if(value == this.min()){
            this.stackMin.pop();
        }
    }

    public int top() {
        if(this.val!=null){
            return this.val.peek();
        }else{
            throw new RuntimeException("Stack is empty");
        }
    }

    public int min() {
        if(this.stackMin!=null){
            return this.stackMin.peek();
        }
       throw new RuntimeException("Stack is empty");
    }
}

Body:
I think that you should use stack.empty() instead of testing for null value. I changed some code and the exception doesn't occur like this.

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Main m1 = new Main();
        m1.push(2);
        m1.push(1);
        m1.push(3);
        System.out.println(m1.min());
    }
    private Stack<Integer> val = new Stack<>();
    private Stack<Integer> stackMin = new Stack<>();
    Integer temp = null;

    public void push(int node) {
        this.val.push(node);
        if(this.stackMin.empty()){
            this.stackMin.push(node);
        }else if(node<=this.min()){
            this.stackMin.push(node);
        }
    }

    public void pop() {
        if (!this.val.empty()) {
            throw new RuntimeException("Stack is empty.");
        }
        int value = this.val.pop();
        if(value == this.min()){
            this.stackMin.pop();
        }
    }

    public int top() {
        if(!this.val.empty()){
            return this.val.peek();
        }else{
            throw new RuntimeException("Stack is empty");
        }
    }

    public int min() {
        if(!this.stackMin.empty()){
            return this.stackMin.peek();
        }
        throw new RuntimeException("Stack is empty");
    }
}

Test outputs the minimum value

/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java Main
1

Process finished with exit code 0


问:
Base url in background image joomla
I am creating a template and someone has created the orignal slider using

```<code><div class="item active" style="background-image: url(../images/slider/bg1.jpg)">
</code>```

My question is I am using Joomla to create this template how do i echo in the above html so that I can output the full url of site for at min its not finding the image.

```<code><?php echo $this->baseurl ?>/
</code>```

答:
You can use

```<code>JUri::base()
</code>```

accepting an optional parameter (true or false)
to include the protocol and site name.

Title: Base url in background image joomla

Body:
I am creating a template and someone has created the orignal slider using

My question is I am using Joomla to create this template how do i echo in the above html so that I can output the full url of site for at min its not finding the image.

<?php echo $this->baseurl ?>/

Body:
You can use

JUri::base()

accepting an optional parameter (true or false)
to include the protocol and site name.


问:
starting CQ in Debug mode. What happens with forking
I am pretty much interested in knowing that what happens to JVM forking when we start CQ in debug mode. I have gone through Adobe websites, but i am not much clear.
Does we have to use -nofork option?? or it automatically does this.

As of now, i understand it as this-

start CQ in debug mode with command line using this parameter:
 java -Xmx8192M  -agentlib:jdwp=transport........ -jar cq-author-4502.jar( nofork is not used )

CQ is started.

CQ forks a new JVM process even if I have given too much of memory to this command.

i use -nofork, but i start getting outofmemory errors. Why???

can i get a good to understand  explaination about this?

答:
Do we have to use -nofork option?

No, but if you debug on a specific port it forces forking! (ensure Xmx is BEEG)

If you run java -jar << AEM >>.jar --help on the jar file you get the following:

```<code>-debug << port >> <br/>
Enable Java Debugging on port number; forces forking
</code>```

Lots of articles and overlaps, but hope this answers and gives food for thought.

Good article as well:

http://blogs.adobe.com/dmcmahon/2012/03/09/cq5-5-how-to-start-the-server-in-debug-mode/

Body:
Do we have to use -nofork option?

No, but if you debug on a specific port it forces forking! (ensure Xmx is BEEG)

If you run java -jar << AEM >>.jar --help on the jar file you get the following:

-debug << port >> <br/>
Enable Java Debugging on port number; forces forking

Lots of articles and overlaps, but hope this answers and gives food for thought.

Good article as well:

http://blogs.adobe.com/dmcmahon/2012/03/09/cq5-5-how-to-start-the-server-in-debug-mode/


问:
Tiling in groupby on dataframe
I have a data frame that contains returns, size and sedols for a couple of dates.

My goal is to identify the top and bottom values for a certain condition per date, i.e I want the top decile largest size entries and the bottom decile smallest size entries for each date and flag them in a new column by 'xx' and 'yy'.

I am confused how to apply the tiling while grouping as well as creating a new column, here is what I already have.

```<code>import pandas as pd
import numpy as np
import datetime as dt

from random import choice
from string import ascii_uppercase

def create_dummy_data(start_date, days, entries_pday):
    date_sequence_lst = [dt.datetime.strptime(start_date,'%Y-%m-%d') +
dt.timedelta(days=x) for x in range(0,days)]
    date_sequence_lst = date_sequence_lst * entries_pday
    returns_lst = [round(np.random.uniform(low=-0.10,high=0.20),2) for _ in range(entries_pday*days)]

    size_lst = [round(np.random.uniform(low=10.00,high=10000.00),0) for _ in range(entries_pday*days)]

    rdm_sedol_lst = [(''.join(choice(ascii_uppercase) for i in range(7))) for x in range(entries_pday)]
    rdm_sedol_lst = rdm_sedol_lst * days

    dates_returns_df = pd.DataFrame({'Date':date_sequence_lst , 'Sedols':rdm_sedol_lst, 'Returns':returns_lst,'Size':size_lst})
    dates_returns_df = dates_returns_df.sort_values('Date',ascending=True)
    dates_returns_df = dates_returns_df.reset_index(drop=True)
    return dates_returns_df

def order_df_by(df_in,column_name):
    df_out = df_in.sort_values(['Date',column_name],ascending=[True,False])
    return df_out

def get_ntile(df_in,ntile):
    df_in['Tiled'] = df_in.groupby(['Date'])['Size'].transform(lambda x : pd.qcut(x,ntile))
    return df_in

if __name__ == "__main__":
    # create dummy returns
    data_df = create_dummy_data('2001-01-01',31,10)
    # sort by attribute
    data_sorted_df = order_df_by(data_df,'Size')
    #ntile data per date
    data_ntiled = get_ntile(data_sorted_df, 10)

    for key, item in data_ntiled:
        print(data_ntiled.get_group(key))
</code>```

so far I would be expecting deciled results based on 'Size' for each date, the next step would be to filter only for decile 1 and decile 10 and flag the entries 'xx' and 'yy' respectively.

thanks

答:
Consider using transform on the pandas.qcut method with labels 1 through ntile+1 for a decile column, then conditionally set flag with np.where using decile values:

```<code>...
def get_ntile(df_in, ntile):
    df_in['Tiled'] = df_in.groupby(['Date'])['Size'].transform(lambda x: pd.qcut(x, ntile, labels=list(range(1, ntile+1))))
    return df_in

if __name__ == "__main__":
    # create dummy returns
    data_df = create_dummy_data('2001-01-01',31,10)
    # sort by attribute
    data_sorted_df = order_df_by(data_df,'Size')
    #ntile data per date
    data_ntiled = get_ntile(data_sorted_df, 10)

    data_ntiled['flag'] = np.where(data_ntiled['Tiled']==1.0, 'YY',
                                   np.where(data_ntiled['Tiled']==10.0, 'XX', np.nan))

    print(data_ntiled.reset_index(drop=True).head(15))

#          Date  Returns   Sedols    Size   Tiled flag
# 0  2001-01-01    -0.03  TEEADVJ  8942.0    10.0   XX
# 1  2001-01-01    -0.03  PDBWGBJ  7142.0     9.0  nan
# 2  2001-01-01     0.03  QNVVPIC  6995.0     8.0  nan
# 3  2001-01-01     0.04  NTKEAKB  6871.0     7.0  nan
# 4  2001-01-01     0.20  ZVVCLSJ  6541.0     6.0  nan
# 5  2001-01-01     0.12  IJKXLIF  5131.0     5.0  nan
# 6  2001-01-01     0.14  HVPDRIU  4490.0     4.0  nan
# 7  2001-01-01    -0.08  XNOGFET  3397.0     3.0  nan
# 8  2001-01-01    -0.06  JOARYWC  2582.0     2.0  nan
# 9  2001-01-01     0.12  FVKBQGU   723.0     1.0   YY
# 10 2001-01-02     0.03  ZVVCLSJ  9291.0    10.0   XX
# 11 2001-01-02     0.14  HVPDRIU  8875.0     9.0  nan
# 12 2001-01-02     0.08  PDBWGBJ  7496.0     8.0  nan
# 13 2001-01-02     0.02  FVKBQGU  7307.0     7.0  nan
# 14 2001-01-02    -0.01  QNVVPIC  7159.0     6.0  nan
</code>```

Title: Tiling in groupby on dataframe

Body:
I have a data frame that contains returns, size and sedols for a couple of dates.

My goal is to identify the top and bottom values for a certain condition per date, i.e I want the top decile largest size entries and the bottom decile smallest size entries for each date and flag them in a new column by 'xx' and 'yy'.

I am confused how to apply the tiling while grouping as well as creating a new column, here is what I already have.

import pandas as pd
import numpy as np
import datetime as dt

from random import choice
from string import ascii_uppercase

def create_dummy_data(start_date, days, entries_pday):
    date_sequence_lst = [dt.datetime.strptime(start_date,'%Y-%m-%d') +
dt.timedelta(days=x) for x in range(0,days)]
    date_sequence_lst = date_sequence_lst * entries_pday
    returns_lst = [round(np.random.uniform(low=-0.10,high=0.20),2) for _ in range(entries_pday*days)]

    size_lst = [round(np.random.uniform(low=10.00,high=10000.00),0) for _ in range(entries_pday*days)]

    rdm_sedol_lst = [(''.join(choice(ascii_uppercase) for i in range(7))) for x in range(entries_pday)]
    rdm_sedol_lst = rdm_sedol_lst * days

    dates_returns_df = pd.DataFrame({'Date':date_sequence_lst , 'Sedols':rdm_sedol_lst, 'Returns':returns_lst,'Size':size_lst})
    dates_returns_df = dates_returns_df.sort_values('Date',ascending=True)
    dates_returns_df = dates_returns_df.reset_index(drop=True)
    return dates_returns_df

def order_df_by(df_in,column_name):
    df_out = df_in.sort_values(['Date',column_name],ascending=[True,False])
    return df_out

def get_ntile(df_in,ntile):
    df_in['Tiled'] = df_in.groupby(['Date'])['Size'].transform(lambda x : pd.qcut(x,ntile))
    return df_in

if __name__ == "__main__":
    # create dummy returns
    data_df = create_dummy_data('2001-01-01',31,10)
    # sort by attribute
    data_sorted_df = order_df_by(data_df,'Size')
    #ntile data per date
    data_ntiled = get_ntile(data_sorted_df, 10)

    for key, item in data_ntiled:
        print(data_ntiled.get_group(key))

so far I would be expecting deciled results based on 'Size' for each date, the next step would be to filter only for decile 1 and decile 10 and flag the entries 'xx' and 'yy' respectively.

thanks

Body:
Consider using transform on the pandas.qcut method with labels 1 through ntile+1 for a decile column, then conditionally set flag with np.where using decile values:

...
def get_ntile(df_in, ntile):
    df_in['Tiled'] = df_in.groupby(['Date'])['Size'].transform(lambda x: pd.qcut(x, ntile, labels=list(range(1, ntile+1))))
    return df_in

if __name__ == "__main__":
    # create dummy returns
    data_df = create_dummy_data('2001-01-01',31,10)
    # sort by attribute
    data_sorted_df = order_df_by(data_df,'Size')
    #ntile data per date
    data_ntiled = get_ntile(data_sorted_df, 10)

    data_ntiled['flag'] = np.where(data_ntiled['Tiled']==1.0, 'YY',
                                   np.where(data_ntiled['Tiled']==10.0, 'XX', np.nan))

    print(data_ntiled.reset_index(drop=True).head(15))

#          Date  Returns   Sedols    Size   Tiled flag
# 0  2001-01-01    -0.03  TEEADVJ  8942.0    10.0   XX
# 1  2001-01-01    -0.03  PDBWGBJ  7142.0     9.0  nan
# 2  2001-01-01     0.03  QNVVPIC  6995.0     8.0  nan
# 3  2001-01-01     0.04  NTKEAKB  6871.0     7.0  nan
# 4  2001-01-01     0.20  ZVVCLSJ  6541.0     6.0  nan
# 5  2001-01-01     0.12  IJKXLIF  5131.0     5.0  nan
# 6  2001-01-01     0.14  HVPDRIU  4490.0     4.0  nan
# 7  2001-01-01    -0.08  XNOGFET  3397.0     3.0  nan
# 8  2001-01-01    -0.06  JOARYWC  2582.0     2.0  nan
# 9  2001-01-01     0.12  FVKBQGU   723.0     1.0   YY
# 10 2001-01-02     0.03  ZVVCLSJ  9291.0    10.0   XX
# 11 2001-01-02     0.14  HVPDRIU  8875.0     9.0  nan
# 12 2001-01-02     0.08  PDBWGBJ  7496.0     8.0  nan
# 13 2001-01-02     0.02  FVKBQGU  7307.0     7.0  nan
# 14 2001-01-02    -0.01  QNVVPIC  7159.0     6.0  nan


问:
Gotchas with template argument deduction for class templates
I was reading the paper regarding template argument deduction for class templates here http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0091r3.html.  This feature is in the C++17 standard, and some things had confused me.

```<code>template <typename T>
class Something {
public:

    // delete the copy and move constructors for simplicity
    Something(const Something&) = delete;
    Something(Something&&) = delete;

    explicit Something(T&&) { ... }
    explicit Something(const T&) { ... }

    template <typename U, typename EnableIfNotT<U, T>* = nullptr>
    Something(U&&) { ... }
};
</code>```

Given the above code, if someone tries to instantiate an instance of the above template like this

```<code>auto something = Something{std::shared_ptr<int>{}};
</code>```

will the rvalue reference overload always be called?  Since the overload set considered for deduction is

```<code>template <typename T>
Something<T> F(T&&) { ... }
template <typename T>
Something<T> F(const T&) { ... }
template <typename T, typename U, typename EnableIfNotT<U, T>*>
Something<T> F(U&&) { ... }
</code>```

The second overload will never be preferred over the first one (since that is now a forwarding reference overload, instead of being an rvalue reference overload), so what is supposed to happen here?

And it seems like the last one can never be called without explicitly specifying the T parameter, is this the intended behavior?

Also are there any other gotchas or style guidelines that one should keep in mind when using template argument deduction for class templates?

Further are user defined deduction guides required to be after the class definition?  For example, can you have the trailing return type in the declaration of the class constructor within the class definition itself? (Unlike the iterator constructor here http://en.cppreference.com/w/cpp/language/class_template_deduction)

答:
The second overload will never be preferred over the first one (since that is now a forwarding reference overload, instead of being an rvalue reference overload), so what is supposed to happen here?

No, it is not a forwarding reference. This is a key distinction. From [temp.deduct.call]:

A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template (during class template argument deduction ([over.match.class.deduct])).

Your candidates are:

```<code>template <typename T>
Something<T> F(T&&);       // this ONLY matches non-const rvalues

template <typename T>
Something<T> F(const T&);  // this matches everything

template <typename T, typename U, typename EnableIfNotT<U, T>*>
Something<T> F(U&&);       // this matches nothing
</code>```

When you write:

```<code>auto something = Something{std::shared_ptr<int>{}};
</code>```

The T&& constructor is preferred, with T=std::shared_ptr<int>, so you end up with Something<std::shared_ptr<int>> as your class template specialization. If had instead written:

```<code>std::shared_ptr<int> p;
auto something = Something{p};
</code>```

then the T const& constructor is preferred (indeed it is the only viable candidate). Although we end up in the same place: Something<std::shared_ptr<int>>.

And it seems like the last one can never be called without explicitly specifying the T parameter, is this the intended behavior?

Correct, T is a non-deduced context. This makes sense - this constructor exists to do conversions, but you need to specify what you're converting to in order to do the conversion. It would never make sense to have this "just work" for you.

Further are user defined deduction guides required to be after the class definition?

Yes. That's just where they go, by rule. It doesn't make sense to have trailing return type in the constructor - the constructor doesn't "return" anything.

Body:
I was reading the paper regarding template argument deduction for class templates here http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0091r3.html.  This feature is in the C++17 standard, and some things had confused me.

template <typename T>
class Something {
public:

    // delete the copy and move constructors for simplicity
    Something(const Something&) = delete;
    Something(Something&&) = delete;

    explicit Something(T&&) { ... }
    explicit Something(const T&) { ... }

    template <typename U, typename EnableIfNotT* = nullptr>
    Something(U&&) { ... }
};

Given the above code, if someone tries to instantiate an instance of the above template like this

auto something = Something{std::shared_ptr<int>{}};

will the rvalue reference overload always be called?  Since the overload set considered for deduction is

template <typename T>
Something<T> F(T&&) { ... }
template <typename T>
Something<T> F(const T&) { ... }
template <typename T, typename U, typename EnableIfNotT*>
Something<T> F(U&&) { ... }

The second overload will never be preferred over the first one (since that is now a forwarding reference overload, instead of being an rvalue reference overload), so what is supposed to happen here?

And it seems like the last one can never be called without explicitly specifying the T parameter, is this the intended behavior?

Also are there any other gotchas or style guidelines that one should keep in mind when using template argument deduction for class templates?

Further are user defined deduction guides required to be after the class definition?  For example, can you have the trailing return type in the declaration of the class constructor within the class definition itself? (Unlike the iterator constructor here http://en.cppreference.com/w/cpp/language/class_template_deduction)

Body:
The second overload will never be preferred over the first one (since that is now a forwarding reference overload, instead of being an rvalue reference overload), so what is supposed to happen here?

No, it is not a forwarding reference. This is a key distinction. From [temp.deduct.call]:

A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template (during class template argument deduction ([over.match.class.deduct])).

Your candidates are:

template <typename T>
Something<T> F(T&&);       // this ONLY matches non-const rvalues

template <typename T>
Something<T> F(const T&);  // this matches everything

template <typename T, typename U, typename EnableIfNotT<U, T>*>
Something<T> F(U&&);       // this matches nothing

When you write:

auto something = Something{std::shared_ptr<int>{}};

The T&& constructor is preferred, with T=std::shared_ptr<int>, so you end up with Something<std::shared_ptr<int>> as your class template specialization. If had instead written:

std::shared_ptr<int> p;
auto something = Something{p};

then the T const& constructor is preferred (indeed it is the only viable candidate). Although we end up in the same place: Something<std::shared_ptr<int>>.

And it seems like the last one can never be called without explicitly specifying the T parameter, is this the intended behavior?

Correct, T is a non-deduced context. This makes sense - this constructor exists to do conversions, but you need to specify what you're converting to in order to do the conversion. It would never make sense to have this "just work" for you.

Further are user defined deduction guides required to be after the class definition?

Yes. That's just where they go, by rule. It doesn't make sense to have trailing return type in the constructor - the constructor doesn't "return" anything.


问:
Identify a method and it's scope while reading a source code with a file reader?
I am trying to search a specific string in the source code so that I can identify the string is found in which method.I tried file reader. But failed . How to identify a method and it's scope while reading a source code with a file reader? Is there any other way to get the method and it's scope / method and it's declaration?

I took another approach where I could manage to get name of methods of the file using classloader. But again failed to get the method declaration.

Any help will be appreciated. TIA.

答:
UPDATED VERSION

Sorry for posting a second answer, but I just want to ascertain that you get notified of this answer.

This is the code for the file:

```<code>File file = new File("FilePath");
FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);
String t = "";

while((t = br.readLine()) != null)
{
    str = str + t + "\n";
}
</code>```

This is the regex:

```<code>Pattern p = Pattern.compile(".*\\s+(.+\\(.*?\\))\\s*\\{(.*"+keyword+"[^\\w*].*)\\}.*\\}$", Pattern.DOTALL);
Matcher m = p.matcher(str);
boolean notFound = true;
while(m.find())
{
    System.out.println("Scope of keyword: " + m.group(1));
    notFound = false;
}

if(notFound)
{
    System.out.println("NOT FOUND");
}
</code>```

Since you wanted the scope of the keyword, it is the nearest brace brackets within which it is declared, so I have assumed you have written its data type and the variable name in the keyword. I'll see if I can handle more exceptions later :)

.*\\s+ - Takes in everything until the method name

(.+\\(.*?\\))\\s*\\{ - Stores the method name and parameters (In case there are overloaded methods)

(.*"+keyword+" - Finds if the keyword is present after some other code

[^\\w*] Ensures that the keyword exists by itself (Otherwise if the keyword is double x, and double xy is present, then it would be a match)

.*)\\}.*\\}$ - Sees if there are two Braces after the keyword is found (one to end the method or block [in case of if, else if, switch etc.], one to end the class)

Body:
UPDATED VERSION

Sorry for posting a second answer, but I just want to ascertain that you get notified of this answer.

This is the code for the file:

File file = new File("FilePath");
FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);
String t = "";

while((t = br.readLine()) != null)
{
    str = str + t + "\n";
}

This is the regex:

Pattern p = Pattern.compile(".*\\s+(.+\\(.*?\\))\\s*\\{(.*"+keyword+"[^\\w*].*)\\}.*\\}$", Pattern.DOTALL);
Matcher m = p.matcher(str);
boolean notFound = true;
while(m.find())
{
    System.out.println("Scope of keyword: " + m.group(1));
    notFound = false;
}

if(notFound)
{
    System.out.println("NOT FOUND");
}

Since you wanted the scope of the keyword, it is the nearest brace brackets within which it is declared, so I have assumed you have written its data type and the variable name in the keyword. I'll see if I can handle more exceptions later :)

.*\\s+ - Takes in everything until the method name

(.+\\(.*?\\))\\s*\\{ - Stores the method name and parameters (In case there are overloaded methods)

(.*"+keyword+" - Finds if the keyword is present after some other code

[^\\w*] Ensures that the keyword exists by itself (Otherwise if the keyword is double x, and double xy is present, then it would be a match)

.*)\\}.*\\}$ - Sees if there are two Braces after the keyword is found (one to end the method or block [in case of if, else if, switch etc.], one to end the class)


问:
Change Pimple with Symfony dependency injection
Is there a way to swap Pimple with Symfony dependency injection?

I can use Symfony dependency injection as a standalone package with Silex but i need to swap Pimple with it because i can't access controllers registered with Symfony dependency injection from Silex like:

```<code>$app->get('/route', 'testController:indexAction');
</code>```

答:
No you can't. Silex does not allow to change the container as the Silex main class extends from Pimple itself. If you need the Symfony container you should go with Symfony and not with Silex.

You could hack up a solution in which every call to Pimple is forwarded to DIC (Pimple would be a kind of proxy service only), but I wouldn't go that route.

Keep in mind that with the upcoming Symfony 4 (due on November, but there is a preview already aviable) the framework is going to be more like Silex: instead of having it all and remove the parts you don't use, you'll start small and add components/bundles/libraries into your project (check out Symfony flex).

Finally, as a side note/fun fact, there was a project from igorw (one of the coauthors of Silex) which replaced Pimple with Symfony DIC component, but it was more an academic exercise rather than a ready to use framework (it did work)

Body:
Is there a way to swap Pimple with Symfony dependency injection?

I can use Symfony dependency injection as a standalone package with Silex but i need to swap Pimple with it because i can't access controllers registered with Symfony dependency injection from Silex like:

$app->get('/route', 'testController:indexAction');


问:
Dropzone.JS in form with Laravel 5.2 not saving file
enctype="multipart/form-data" been stuck on this issue with saving the uploaded file to the Database using DropzoneJS.

The error in this case is that it's posting all the other form data except for the uploaded file which returns an empty response although I'm not sure what I'm missing here.

If anyone can manage to spot the error, it would be greatly appreciated!

View

```<code><form action="{{url('/save_information')}}" method="POST" enctype="multipart/form-data" class="form-horizontal" role="form">
<meta name="csrf-token" content="{{csrf_token()}}" />
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
    <legend></legend>
</div>

<label for="title">Title</label>
<input type="text" name="title" id="input-title" class="form-control">

<label for="description">Description</label>
<input type="text" name="description" id="input-description" class="form-control">

<div class="dropzone dropzone-previews" id="my-awesome-dropzone">
    <input name="_token" type="hidden" value="{{ csrf_token() }}">
</div>
</code>```

Jquery

```<code><script type="text/javascript">
        Dropzone.autoDiscover = false;
        var myDropzone = new Dropzone("#my-awesome-dropzone",{
            url: "/save_information",
            uploadMultiple: true,
            autoProcessQueue: false,
            addRemoveLinks: true,
            paramName: "file", // The name that will be used to transfer the file
            maxFilesize: 10, // MB
            sending: function(file, xhr, formData) {
                formData.append("_token", "{{ csrf_token() }}");
            }
        });

        $('#submit-all').click(function(){
            e.preventDefault();
            myDropzone.processQueue();
        });
</code>```

controller function

```<code> if (Request::hasFile('filename')) {
        $image = Request::file('filename');
        $location = public_path('images/');
        $filename = time() . '.' . $image->getClientOriginalExtension();
            $image->move($location, $filename);

            $trustDocument->image = $filename;

        } else {
        dd('no image found');
    }

$trustDocument->save();
</code>```

答:
The paramName you set is "file" but in your controller you are referencing to "filename".

Replace "filename" to "file" in your controller.

For more detailed integration with laravel dropzone you can refer to this tutorial Integrating Dropzone.js in Laravel 5 applications

Body:
enctype="multipart/form-data" been stuck on this issue with saving the uploaded file to the Database using DropzoneJS.

The error in this case is that it's posting all the other form data except for the uploaded file which returns an empty response although I'm not sure what I'm missing here.

If anyone can manage to spot the error, it would be greatly appreciated!

View

<form action="{{url('/save_information')}}" method="POST" enctype="multipart/form-data" class="form-horizontal" role="form">
<meta name="csrf-token" content="{{csrf_token()}}" />
<input type="hidden" name="_token" value="{{ csrf_token() }}">

    <legend></legend>

Title
<input type="text" name="title" id="input-title" class="form-control">

Description
<input type="text" name="description" id="input-description" class="form-control">

    <input name="_token" type="hidden" value="{{ csrf_token() }}">

Jquery


问:
NoClassDefFoundError on Kotlin class in JUnit test at runtime
My Kotlin class compiles and runs on an emulator without a problem. But when I test it, Android Studio says the class is not found.

Here's the Kotlin class and an example of using it:

```<code>// Product.kt
data class Product(
    val id: Int,
    val name: String,
    val manufacturer: String)

// MainActivity.java
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Product product = new Product(0, "foo", "bar");
        TextView textView = findViewById(R.id.textView);
        textView.setText(product.getName());
    }
}
</code>```

However when I write a JUnit test for the Kotlin class:

```<code>// ProductTest.java
public class ProductTest {
    @Test
    public void getName() throws Exception {
        Product p = new Product(0, "foo", "bar");
        assertThat(p.getName(), equalTo("foo"));
    }
}
</code>```

Android Studio compiles the code, but refuses to run the test:

```<code>java.lang.NoClassDefFoundError: com/example/Product

  at com.example.ProductTest.getName(ProductTest.java:15)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
  at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
  at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
  at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
Caused by: java.lang.ClassNotFoundException: com.example.Product
  at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  ... 28 more
</code>```

Here comes the dependencies section in the module-level build.gradle:

```<code>dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
    testCompile 'junit:junit:4.12'
}
</code>```

What did I do wrong?

答: Someone confirmed this bug has been fixed in Android Studio 3 Canary 3: https://issuetracker.google.com/issues/38454212</p>

Body:
My Kotlin class compiles and runs on an emulator without a problem. But when I test it, Android Studio says the class is not found.

Here's the Kotlin class and an example of using it:

// Product.kt
data class Product(
    val id: Int,
    val name: String,
    val manufacturer: String)

// MainActivity.java
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Product product = new Product(0, "foo", "bar");
        TextView textView = findViewById(R.id.textView);
        textView.setText(product.getName());
    }
}

However when I write a JUnit test for the Kotlin class:

// ProductTest.java
public class ProductTest {
    @Test
    public void getName() throws Exception {
        Product p = new Product(0, "foo", "bar");
        assertThat(p.getName(), equalTo("foo"));
    }
}

Android Studio compiles the code, but refuses to run the test:

java.lang.NoClassDefFoundError: com/example/Product

  at com.example.ProductTest.getName(ProductTest.java:15)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
  at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
  at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
  at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
Caused by: java.lang.ClassNotFoundException: com.example.Product
  at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  ... 28 more

Here comes the dependencies section in the module-level build.gradle:

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
    testCompile 'junit:junit:4.12'
}

What did I do wrong?


问:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Let x be a NumPy array. The following:

```<code>(x > 1) and (x < 3)
</code>```

Gives the error message:

ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

How do I fix this?

答:
The reason for the exception is that and implicitly calls bool. First on the left operand and (if the left operand is True) then on the right operand. So x and y is equivalent to bool(x) and bool(y).

However the bool on a numpy.ndarray (if it contains more than one element) will throw the exception you have seen:

```<code>>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

The bool() call is implicit in and, but also in if, while, or, so any of the following examples will also fail:

```<code>>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

There are more functions and statements in Python that hide bool calls, for example 2 < x < 10 is just another way of writing 2 < x and x < 10. And the and will call bool: bool(2 < x) and bool(x < 10).

The element-wise equivalent for and would be the np.logical_and function, similarly you could use np.logical_or as equivalent for or.

For boolean arrays - and comparisons like <, <=, ==, !=, >= and > on NumPy arrays return boolean NumPy arrays - you can also use the element-wise bitwise functions (and operators): np.bitwise_and (& operator)

```<code>>>> np.logical_and(arr > 1, arr < 3)
array([False,  True, False], dtype=bool)

>>> np.bitwise_and(arr > 1, arr < 3)
array([False,  True, False], dtype=bool)

>>> (arr > 1) & (arr < 3)
array([False,  True, False], dtype=bool)
</code>```

and bitwise_or (| operator):

```<code>>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False,  True], dtype=bool)

>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False,  True], dtype=bool)

>>> (arr <= 1) | (arr >= 3)
array([ True, False,  True], dtype=bool)
</code>```

A complete list of logical and binary functions can be found in the NumPy documentation:

"Logic functions"

"Binary operations"

Body:
Let x be a NumPy array. The following:

(x > 1) and (x < 3)

Gives the error message:

ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

How do I fix this?

Body:
The reason for the exception is that and implicitly calls bool. First on the left operand and (if the left operand is True) then on the right operand. So x and y is equivalent to bool(x) and bool(y).

However the bool on a numpy.ndarray (if it contains more than one element) will throw the exception you have seen:

>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The bool() call is implicit in and, but also in if, while, or, so any of the following examples will also fail:

>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

There are more functions and statements in Python that hide bool calls, for example 2 < x < 10 is just another way of writing 2 < x and x < 10. And the and will call bool: bool(2 < x) and bool(x < 10).

The element-wise equivalent for and would be the np.logical_and function, similarly you could use np.logical_or as equivalent for or.

For boolean arrays - and comparisons like <, <=, ==, !=, >= and > on NumPy arrays return boolean NumPy arrays - you can also use the element-wise bitwise functions (and operators): np.bitwise_and (& operator)

>>> np.logical_and(arr > 1, arr < 3)
array([False,  True, False], dtype=bool)

>>> np.bitwise_and(arr > 1, arr < 3)
array([False,  True, False], dtype=bool)

>>> (arr > 1) & (arr < 3)
array([False,  True, False], dtype=bool)

and bitwise_or (| operator):

>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False,  True], dtype=bool)

>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False,  True], dtype=bool)

>>> (arr <= 1) | (arr >= 3)
array([ True, False,  True], dtype=bool)

A complete list of logical and binary functions can be found in the NumPy documentation:

"Logic functions"

"Binary operations"


问:
How to make same height of all responsive images in a row
The first image of the row doesn't have the same height as the other ones. I am using Bootstrap .img-responsive.

HTML

```<code><div class="row">
    <div class="down-content">
        <div class="haber">
            <!--HABER 1-->
            <div class="col-sm-3">
                <div id="haber1">
                    <div id="haberimg1">
                        <img class="img-responsive" src="http://www.avukatwebsite.net/public/_uploads/photos/temalar/avukat-web-site-tema-1.jpg" >
                    </div>
                    <div id="haberyazi1">
                        <h3>Kanser Affetmedi...</h3>
                        <p>Sanssiz genc Kanser yüzünden öldü...</p>
                        <button type="button" class="btn">Devamini Oku...</button>
                    </div>
                </div>
            </div>
            <!--HABER 2-->
            <div class="col-sm-3">
                <div id="haber2">
                    <div id="haberimg2">
                        <img class="img-responsive" src="http://medicare.bold-themes.com/clinic/wp-content/uploads/sites/2/2015/12/shutterstock_288977717-1200x800.jpg" >
                    </div>
                    <div id="haberyazi2">
                        <h3>Sizofreni Salgini</h3>
                        <p>Türkiyede ki Sizofren sayisinda artis görüldü...</p>
                        <button type="button" class="btn">Devamini Oku...</button>
                    </div>
                </div>
            </div>
            /* we deleted the other parts because of mostly code problem */
        </div>
        <!--HABER BÖLÜMÜ BITIS-->
    </div>
</div>
</code>```

Bootstrap CSS

```<code>.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
    display: block;
    max-width: 100%;
    height: auto;
}
</code>```

This is the issue:

答:
Just give your images same class and add height.

Trick: avoid of giving height with pixels because getting issue in small screen instead give height with rem or
percentage

Body:
The first image of the row doesn't have the same height as the other ones. I am using Bootstrap .img-responsive.

HTML

Kanser Affetmedi...

Sanssiz genc Kanser yüzünden öldü...

                        <button type="button" class="btn">Devamini Oku...</button>

Sizofreni Salgini

Türkiyede ki Sizofren sayisinda artis görüldü...

                        <button type="button" class="btn">Devamini Oku...</button>

            /* we deleted the other parts because of mostly code problem */

Bootstrap CSS

.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
    display: block;
    max-width: 100%;
    height: auto;
}

This is the issue:


问:
Assigning DateRangePicker value to a Text box using jquery
I wanted to assign daterangepicker value to a text box in order to store the new selected date to a database. Though i tried this but didn't work as i expected.

HTML

```<code><input type="text" id="" name="docrcvd" value="<?php echo $res->doc_date; ?>" class="form-control col-md-12" disabled="disabled">
                               <input type="text" id="birthday1" class="fa fa-calendar date-picker ">
</code>```

This works fine and it populate the date stored in database and the second input filed display the datepicker.

But the problem is once i selected new date it won't assign the newly selected date to the first input field.

Jquery

```<code>$(document).ready(function() {
                      $('#birthday1').daterangepicker({
                            onSelect: function(dateText, inst) {
                               $('#docrcvd').val(dateText);
                            }
                         });
                  });
</code>```

Any help or suggestion would appreciated. Thank you!

答:
You are missing the ID for your input field.

```<code><input type="text" id="" name="docrcvd" value="<?php echo $res->doc_date; ?>" class="form-control col-md-12" disabled="disabled">
                           <input type="text" id="birthday1" class="fa fa-calendar date-picker ">
</code>```

has to look like this

```<code><input type="text" id="docrcvd" name="docrcvd" value="<?php echo $res->doc_date; ?>" class="form-control col-md-12" disabled="disabled">
                           <input type="text" id="birthday1" class="fa fa-calendar date-picker ">
</code>```

You are using the ID Selector '#elementId'

```<code>$('#docrcvd').val(dateText);
</code>```

But you did not assign that id to your element so your code would never find your input field to fill it.

Body:
I wanted to assign daterangepicker value to a text box in order to store the new selected date to a database. Though i tried this but didn't work as i expected.

HTML

<input type="text" id="" name="docrcvd" value="<?php echo $res->doc_date; ?>" class="form-control col-md-12" disabled="disabled">
                               <input type="text" id="birthday1" class="fa fa-calendar date-picker ">

This works fine and it populate the date stored in database and the second input filed display the datepicker.

But the problem is once i selected new date it won't assign the newly selected date to the first input field.

Jquery

$(document).ready(function() {
                      $('#birthday1').daterangepicker({
                            onSelect: function(dateText, inst) {
                               $('#docrcvd').val(dateText);
                            }
                         });
                  });

Any help or suggestion would appreciated. Thank you!

Body:
You are missing the ID for your input field.

<input type="text" id="" name="docrcvd" value="<?php echo $res->doc_date; ?>" class="form-control col-md-12" disabled="disabled">
                           <input type="text" id="birthday1" class="fa fa-calendar date-picker ">

has to look like this

<input type="text" id="docrcvd" name="docrcvd" value="<?php echo $res->doc_date; ?>" class="form-control col-md-12" disabled="disabled">
                           <input type="text" id="birthday1" class="fa fa-calendar date-picker ">

You are using the ID Selector '#elementId'

$('#docrcvd').val(dateText);

But you did not assign that id to your element so your code would never find your input field to fill it.