问:
Java - how to read a string OR that the user hit enter
scanner doesn't seem capable of letting me know the user hit enter rather than keying something in - my program just hangs forever on scanner.

I know I used to code something else a few years ago that worked, but I lost all my old code and am reinventing the wheel and I have searched and searched for a couple of hours and everyone is hooked on scanner.

Here is my code - I guess I'll have to change it so when the user is done they enter something like NO - because this doesn't work when they just hit enter, otherwise it works fine. (like if I comment out the scanner and just have the answer = "" when I was going to just hit enter - that works fine).

```<code>*/
 public static void main(String[] args) {
...
Scanner scanner = new Scanner(System.in);
...
System.out.println("\nIf you are guessing(know) any letters, now enter the CRYPTO letter you are guessing (not what it is)");
    System.out.println("Just hit Enter if you are not entering any");

    // get their input as a String
    String answer = scanner.next();
    while (answer.length() > 0) {
        code = new WordChars(answer.toUpperCase());
        System.out.println("\nNOW enter the real letter you are guessing or know " + code.theWord + " is");
        answer = scanner.next();
        //answer = "p";
        if (answer.length() < 1) {
            System.out.println("\nIf you hit enter again we are cancelling that character map, else enter the character");
            answer = scanner.next();
            //answer = "";
        } else {
            letter = new WordChars(answer.toUpperCase());
            for (int j = 0; j < i; j++) {
                for (int k = 0; k < theTemplate[j].theChars.length; k++) {
                    if (theTemplate[j].theChars[k] == code.theChars[0]) {
                        theTemplate[j].theKnownChars[k] = letter.theChars[0];
                    }
                }
            }
            code = null;
            letter = null;
            System.out.println("\nIf you are guessing(know) any MORE letters, now enter the CRYPTO letter you are guessing (not what it is)");
            System.out.println("Just hit enter is you are not entering any");
            answer = scanner.next();
            //answer = "";
        }
    }
</code>```

...

So basically all works EXCEPT for stopping the whole thing but just hitting enter when prompted, and then answer being empty.  I know there is (a somewhat lengthier) way of coding this but I've forgotten what it is.

答:
Here's one way to check if the user presses a letter, number, or enter:

```<code>Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (s.matches("[a-zA-z]")) {
    System.out.println("You pressed a letter");
} else if(s.matches("[1-9]")){
    System.out.println("You pressed a number");
} else {
    System.out.println("You pressed enter");
}
in.close();
</code>```

To read enter, all you have to do is use scanner.nextLine(), instead of scanner.next().

Body:
scanner doesn't seem capable of letting me know the user hit enter rather than keying something in - my program just hangs forever on scanner.

I know I used to code something else a few years ago that worked, but I lost all my old code and am reinventing the wheel and I have searched and searched for a couple of hours and everyone is hooked on scanner.

Here is my code - I guess I'll have to change it so when the user is done they enter something like NO - because this doesn't work when they just hit enter, otherwise it works fine. (like if I comment out the scanner and just have the answer = "" when I was going to just hit enter - that works fine).

*/
 public static void main(String[] args) {
...
Scanner scanner = new Scanner(System.in);
...
System.out.println("\nIf you are guessing(know) any letters, now enter the CRYPTO letter you are guessing (not what it is)");
    System.out.println("Just hit Enter if you are not entering any");

    // get their input as a String
    String answer = scanner.next();
    while (answer.length() > 0) {
        code = new WordChars(answer.toUpperCase());
        System.out.println("\nNOW enter the real letter you are guessing or know " + code.theWord + " is");
        answer = scanner.next();
        //answer = "p";
        if (answer.length() < 1) {
            System.out.println("\nIf you hit enter again we are cancelling that character map, else enter the character");
            answer = scanner.next();
            //answer = "";
        } else {
            letter = new WordChars(answer.toUpperCase());
            for (int j = 0; j < i; j++) {
                for (int k = 0; k < theTemplate[j].theChars.length; k++) {
                    if (theTemplate[j].theChars[k] == code.theChars[0]) {
                        theTemplate[j].theKnownChars[k] = letter.theChars[0];
                    }
                }
            }
            code = null;
            letter = null;
            System.out.println("\nIf you are guessing(know) any MORE letters, now enter the CRYPTO letter you are guessing (not what it is)");
            System.out.println("Just hit enter is you are not entering any");
            answer = scanner.next();
            //answer = "";
        }
    }

...

So basically all works EXCEPT for stopping the whole thing but just hitting enter when prompted, and then answer being empty.  I know there is (a somewhat lengthier) way of coding this but I've forgotten what it is.

Body:
Here's one way to check if the user presses a letter, number, or enter:

Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (s.matches("[a-zA-z]")) {
    System.out.println("You pressed a letter");
} else if(s.matches("[1-9]")){
    System.out.println("You pressed a number");
} else {
    System.out.println("You pressed enter");
}
in.close();

To read enter, all you have to do is use scanner.nextLine(), instead of scanner.next().


来源: stackexchange

问:
UIAlertController button function not working
```<code>let location =  CLLocationCoordinate2D(latitude: 32.075300, longitude: 34.782563)

    @IBAction func DirectionsTolocationButton(_ sender: Any) {
        // Create the AlertController and add its actions like button in ActionSheet
        let ActionSheet = UIAlertController(title: "Please Select A Navigation Service.", message: nil, preferredStyle: .actionSheet)

        let AppleMapsButton = UIAlertAction(title: "Apple Maps", style: .default) { action -> Void in

            let destinationName = (self.barNameTemplate )
            self.openMapsAppWithDirections(to: self.CoordinatesTemplate, destinationName: destinationName)
            print("Apple Map Chosen!")

        }
        let WazeButton = UIAlertAction(title: "Waze", style: .default) { action -> Void in

            func openWaze(location : CLLocationCoordinate2D) {
                if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                    // Waze is installed. Launch Waze and start navigation
                    let urlStr: String = "waze://?ll=\(location.latitude),\(location.longitude)&navigate=yes"
                    UIApplication.shared.openURL(URL(string: urlStr)!)
                }
                else {
                    // Waze is not installed. Launch AppStore to install Waze app
                    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
                }
            }
            print("Waze Chosen!")
        }
</code>```

When i choose WazeButton nothing happens... as Waze says in their API iv added this to my Plist as well :

```<code><key>LSApplicationQueriesSchemes</key>
<array>
        <string>waze</string>
</array>
</code>```

why it doesn't work for me?

答:
You need to add function out side the function and call as below.

```<code>func openWaze(location : CLLocationCoordinate2D) {
                if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                    // Waze is installed. Launch Waze and start navigation
                    let urlStr: String = "waze://?ll=\(location.latitude),\(location.longitude)&navigate=yes"
                    UIApplication.shared.openURL(URL(string: urlStr)!)
                }
                else {
                    // Waze is not installed. Launch AppStore to install Waze app
                    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
                }
            }
</code>```

Calling as below

```<code>let WazeButton = UIAlertAction(title: "Waze", style: .default) { action -> Void in

            self. openWaze(location : your corrdinates)// call here your function
            print("Waze Chosen!")
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
let location =  CLLocationCoordinate2D(latitude: 32.075300, longitude: 34.782563)

    @IBAction func DirectionsTolocationButton(_ sender: Any) {
        // Create the AlertController and add its actions like button in ActionSheet
        let ActionSheet = UIAlertController(title: "Please Select A Navigation Service.", message: nil, preferredStyle: .actionSheet)

        let AppleMapsButton = UIAlertAction(title: "Apple Maps", style: .default) { action -> Void in

            let destinationName = (self.barNameTemplate )
            self.openMapsAppWithDirections(to: self.CoordinatesTemplate, destinationName: destinationName)
            print("Apple Map Chosen!")

        }
        let WazeButton = UIAlertAction(title: "Waze", style: .default) { action -> Void in

            func openWaze(location : CLLocationCoordinate2D) {
                if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                    // Waze is installed. Launch Waze and start navigation
                    let urlStr: String = "waze://?ll=\(location.latitude),\(location.longitude)&navigate=yes"
                    UIApplication.shared.openURL(URL(string: urlStr)!)
                }
                else {
                    // Waze is not installed. Launch AppStore to install Waze app
                    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
                }
            }
            print("Waze Chosen!")
        }

When i choose WazeButton nothing happens... as Waze says in their API iv added this to my Plist as well :

<key>LSApplicationQueriesSchemes</key>
<array>
        <string>waze</string>
</array>

why it doesn't work for me?

Body:
You need to add function out side the function and call as below.

func openWaze(location : CLLocationCoordinate2D) {
                if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                    // Waze is installed. Launch Waze and start navigation
                    let urlStr: String = "waze://?ll=\(location.latitude),\(location.longitude)&navigate=yes"
                    UIApplication.shared.openURL(URL(string: urlStr)!)
                }
                else {
                    // Waze is not installed. Launch AppStore to install Waze app
                    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
                }
            }

Calling as below

let WazeButton = UIAlertAction(title: "Waze", style: .default) { action -> Void in

            self. openWaze(location : your corrdinates)// call here your function
            print("Waze Chosen!")
        }


问:
Socket.io User Sessions With Redis and JWT
Could anyone please help me understand a this part of code:

```<code>  var auth = function(cb) {
return _.wrap(cb, function(fn, data) {
  redis.get(email, function(err, id){
    if (!err) throw err;
    if (!id) return socket.disconnect('unauthorized');
    fn(data);
   });
 });
};
</code>```

that I got from this article.

I don't understand what's happening there, even though I navigated to the lodash documentation and read about 'wrap' method. I'm confused, especially because I can't see where in the article this 'auth' is further used! (I think that is defined to be used somewhere after all).
Thank you in advance.

答:
So, let's break that down. First, we are assigning a function that takes a cb parameter to auth. What does that function do, well, it returns the result of _.wrap. Looking at the docs, _.wrap is a currying function, so it takes an arg (cb) and a function, and returns a new function where the first parameter is bound to the arg, and the rest of the parameters are unbound. In fact, the _.wrap part:

```<code>return _.wrap(cb, function(fn, data) {
  /* code */
  fn(data); // inside of the redis scope
})
</code>```

is probably overkill, since you are in a closure from the outer function, so you could just do:

```<code>return function(data) {
  /* code */
  cb(data) // in the redis callbak scope, but that is still in the closed over scope
}
</code>```

I'm honestly not sure why they didn't just do that (hammer/nail?).

Let's go on.

So, we've determined that auth is a function that takes a cb parameter and returns a function that takes a data parameter. That function is now calling redis.get to find the value associated with the key stored in email (which is pulled in from the surrounding scope). It then calls the passed in callback function (the one taking an err and id) validates the parameters (disconnecting the websocket if the email isn't associated in redis, and finally calls the orginal cb callback with the passed in data parameter.

I'm not sure where it is used in the code, but the idea is that you can call it as:

```<code>let authCb = auth((data) => { console.log(data) })
authCb('test')
</code>```

and if the email is found in redis, then test should be logged to the console. In the context of the article, you would use this to validate the connection before you actually started communicating with the socket (in the cb function)

Body:
Could anyone please help me understand a this part of code:

  var auth = function(cb) {
return _.wrap(cb, function(fn, data) {
  redis.get(email, function(err, id){
    if (!err) throw err;
    if (!id) return socket.disconnect('unauthorized');
    fn(data);
   });
 });
};

that I got from this article.

I don't understand what's happening there, even though I navigated to the lodash documentation and read about 'wrap' method. I'm confused, especially because I can't see where in the article this 'auth' is further used! (I think that is defined to be used somewhere after all).
Thank you in advance.

Body:
So, let's break that down. First, we are assigning a function that takes a cb parameter to auth. What does that function do, well, it returns the result of _.wrap. Looking at the docs, _.wrap is a currying function, so it takes an arg (cb) and a function, and returns a new function where the first parameter is bound to the arg, and the rest of the parameters are unbound. In fact, the _.wrap part:

return _.wrap(cb, function(fn, data) {
  /* code */
  fn(data); // inside of the redis scope
})

is probably overkill, since you are in a closure from the outer function, so you could just do:

return function(data) {
  /* code */
  cb(data) // in the redis callbak scope, but that is still in the closed over scope
}

I'm honestly not sure why they didn't just do that (hammer/nail?).

Let's go on.

So, we've determined that auth is a function that takes a cb parameter and returns a function that takes a data parameter. That function is now calling redis.get to find the value associated with the key stored in email (which is pulled in from the surrounding scope). It then calls the passed in callback function (the one taking an err and id) validates the parameters (disconnecting the websocket if the email isn't associated in redis, and finally calls the orginal cb callback with the passed in data parameter.

I'm not sure where it is used in the code, but the idea is that you can call it as:

let authCb = auth((data) => { console.log(data) })
authCb('test')

and if the email is found in redis, then test should be logged to the console. In the context of the article, you would use this to validate the connection before you actually started communicating with the socket (in the cb function)


问:
How to get path to add number of Images that are in the resource to be displayed in the WebView in objective-c
I am added image to my application but I want to display them into my web view. I tried but not succeeded. how can I set the path for those images in html in image tag and how to display them.

Please help me out of this.

Thank you,
Madan Mohan.

答:
Are you just displaying the images individually or do you have an HTML file that references them?

To get a URL to the files directly:

```<code>NSString *pathForImage = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
NSURL *URL = [NSURL fileURLWithPath:pathForImage];
</code>```

If you're loading an HTML file that references the images (such as by including an , with no path info) then:

```<code>[webView loadHTMLString:htmlString
    baseURL:[[NSBundle mainBundle] resourceURL]];
</code>```

EDIT: so, supposing you had image.png in your application bundle as a resource, then you could do:

```<code>[webView loadHTMLString:@"<html><body><img src=\"image.png\"></body></html>"
    baseURL:[[NSBundle mainBundle] resourceURL]];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Are you just displaying the images individually or do you have an HTML file that references them?

To get a URL to the files directly:

NSString *pathForImage = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
NSURL *URL = [NSURL fileURLWithPath:pathForImage];

If you're loading an HTML file that references the images (such as by including an <img src="image.png">, with no path info) then:

[webView loadHTMLString:htmlString
    baseURL:[[NSBundle mainBundle] resourceURL]];

EDIT: so, supposing you had image.png in your application bundle as a resource, then you could do:

[webView loadHTMLString:@"<html><body><img src=\"image.png\"></body></html>"
    baseURL:[[NSBundle mainBundle] resourceURL]];


问:
Display 12digit double or int as full instead of 3.23223e+9 on QLabel
C++ is displaying a number 3232235975 on QLabel as 3.23223e+9, while on QCustomPlot axis as 3.23223*10^9. I am not involving stream such as std::cout, that is why std::setprecision doesn't work for my case.

Am actually working with QCustomPlot to plot graph with 12digit numbers on the axis. Is this C++ issue or is it QCustomPlot mechanism issue? How can I display all the digits of the number?

Thanks

EDIT: After receiving hint of setNumberPrecision() from @saeed, now the coordination is still showing in 2.88798e+9 format. Now that the axis is already showing 4000000000, I want the coordination QLabel (shown in the image I attached)  also display 2887984335.

I am getting the coordination and setting it to a QLabel like this.

```<code>double x2 = ui->widget_graph2->xAxis->pixelToCoord(_mouseEvent->pos().x());
double y2 = ui->widget_graph2->yAxis-pixelToCoord(_mouseEvent->pos().y());
ui->label_xcoord_2->setNum(x2);
ui->label_ycoord_2->setNum(y2);
</code>```

And I'm setting the plot data using setData() like this

```<code>QVector<double> x2(i), y2(i);
for(int o = 0; o <= i; o++){
    double dSec = arrayIPxTime[o][0] - startSecond;
    double dMin = dSec/60;
    double ipv4addr = arrayIPxTime[o][1];
    x2[o] = dMin;
    y2[o] = ipv4addr;
}
ui->widget_graph2->addGraph(0);
ui->widget_graph2->graph(0)->setData(x2, y2);
ui->widget_graph2->installEventFilter(this);
</code>```

答: I'm guessing you want std::setprecision.</p>

Body:
C++ is displaying a number 3232235975 on QLabel as 3.23223e+9, while on QCustomPlot axis as 3.23223*10^9. I am not involving stream such as std::cout, that is why std::setprecision doesn't work for my case.

Am actually working with QCustomPlot to plot graph with 12digit numbers on the axis. Is this C++ issue or is it QCustomPlot mechanism issue? How can I display all the digits of the number?

Thanks

EDIT: After receiving hint of setNumberPrecision() from @saeed, now the coordination is still showing in 2.88798e+9 format. Now that the axis is already showing 4000000000, I want the coordination QLabel (shown in the image I attached)  also display 2887984335.

I am getting the coordination and setting it to a QLabel like this.

double x2 = ui->widget_graph2->xAxis->pixelToCoord(_mouseEvent->pos().x());
double y2 = ui->widget_graph2->yAxis-pixelToCoord(_mouseEvent->pos().y());
ui->label_xcoord_2->setNum(x2);
ui->label_ycoord_2->setNum(y2);

And I'm setting the plot data using setData() like this

QVector<double> x2(i), y2(i);
for(int o = 0; o <= i; o++){
    double dSec = arrayIPxTime[o][0] - startSecond;
    double dMin = dSec/60;
    double ipv4addr = arrayIPxTime[o][1];
    x2[o] = dMin;
    y2[o] = ipv4addr;
}
ui->widget_graph2->addGraph(0);
ui->widget_graph2->graph(0)->setData(x2, y2);
ui->widget_graph2->installEventFilter(this);


问:
Empty MySQL-entries from PHP form despite of $isset?
I am working on a form to enter customer data. Works fine so far, but have a problem. Every day, five times a day, there are empty double entries and I don't know why. I checked the submit-button of the form, added $isset to prevent from adding empty posts. But still get empty entries.

Now I have no clue why. Though the way how it appears looks like a bot or else, but am not sure.

TimeStamp screen.

```<code>    <body>

        <div class="container">
        <!-- Example row of columns -->
            <div class="row">
    <h2>Customer Database - Insert</h2>
                <form action=""  method="post"> <!--action="insert.php" -->
                <h4>Kunde</h4>
                <div class="col-md-12 dbstyle">
                    <div class="col-md-3">
                    <span>
                        <label for="firstName">Vorname:</label>
                        <input type="text" name="firstname" id="firstName">
                    </span>
                    </div>
                    <div class="col-md-3">
                    <span>
                        <label for="lastName">Nachname:</label>
                        <input type="text" name="lastname" id="lastName">
                    </span>
                    </div>
                    <div class="col-md-3">
                    <span>
                        <label for="customerNumber">Kundennummer:</label>
                        <input type="number" name="customernumber" id="customerNumber">
                        <p>Kundennummer in <b>DEINEM</b> Kundenstamm</p>
                    </span>
                    </div>
                    <div class="col-md-3">
                    <span>
                            <label for="birthDate">Geburtsdatum:</label>
                            <input type="date" name="birthdate" id="birthDate">
                            <p>Format: <i>YYYY/MM/DD</i></p>
                    </span>
                    </div>
                </div>

                <h4>Vertragsdaten</h4>
                <div class="col-md-12 dbstyle">
                    <div class="col-md-3">
                        <span>
                            <label for="company">Anbieter:</label>
                            <input type="text" name="company" id="company">
                        </span>
                    </div>
                    <div class="col-md-3">
                        <span>
                            <label for="contractNumber">Vertrags-/Kundennummer:</label>
                            <input type="number" name="contractnumber" id="contractNumber">
                        </span>
                    </div>
                    <div class="col-md-3">
                        <span>
                            <label for="quitDate">Kündigungsdatum:</label>
                            <input type="date" name="quitdate" id="quitDate">
                            <p>Format: <i>YYYY/MM/DD</i></p>

                        </span>
                    </div>
                    <div class="col-md-3">
                        <span>
                            <label for="quit">Kündigungsfrist in Wochen:</label>
                            <select name="quit" id="quit">
                              <option value="4">4</option>
                              <option value="5">5</option>
                              <option value="6">6</option>
                              <option value="7">7</option>
                              <option value="8">8</option>
                              <option value="9">9</option>
                              <option value="10">10</option>
                              <option value="11">11</option>
                              <option value="12">12</option>
                              <option value="13">13</option>
                              <option value="14">14</option>
                              <option value="15">15</option>
                              <option value="16">16</option>
                              <option value="17">17</option>
                              <option value="18">18</option>
                              <option value="19">19</option>
                              <option value="20">20</option>
                            </select>
                        </span>
                    </div>

                </div>

                <div class="col-md-12 dbstyle">
                    <div class="col-md-3">
                        <span>
                            <label for="quitDate">Lieferbeginn:</label>
                            <input type="date" name="deliverydate" id="deliveryDate">
                            <p>Format: <i>YYYY/MM/DD</i></p>

                        </span>
                    </div>
                </div>

                <h4>Kontaktdaten</h4>

                <div class="col-md-12 dbstyle">
                    <div class="col-md-4">
                        <span>
                            <label for="landline">Festnetz:</label>
                            <input type="tel" name="landline" id="landline">
                        </span>
                    </div>

                    <div class="col-md-4">
                        <span>
                            <label for="cellphone">Mobilfunk:</label>
                            <input type="tel" name="cellphone" id="cellphone">
                        </span>
                    </div>

                    <div class="col-md-4">
                        <span>
                            <label for="emailAddress">Email:</label>
                            <input type="email" name="email" id="emailAddress">
                        </span>
                    </div>
                </div>

                <div class="col-md-12 dbstyle">
                    <div class="col-md-4">
                        <span>
                        <label for="address">Straße, Nr.:</label>
                        <input type="text" name="address" id="address">
                        </span>
                    </div>

                    <div class="col-md-4">
                        <span>
                            <label for="location">Ort:</label>
                            <input type="text" name="location" id="location">
                        </span>
                    </div>

                    <div class="col-md-4">
                        <span>
                            <label for="postal">PLZ:</label>
                            <input type="number" name="postal" id="postal">
                        </span>
                    </div>
                </div>
                    <input type="submit" name ="submit" value="submit">
                </form>
            </div>
            </div>
        </div>
<?php

/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("name", "name", "pw", "other data");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$birthdate = mysqli_real_escape_string($link, $_POST['birthdate']);
$company = mysqli_real_escape_string($link, $_POST['company']);
$contractnumber = mysqli_real_escape_string($link, $_POST['contractnumber']);
$customernumber = mysqli_real_escape_string($link, $_POST['customernumber']);
$quit = mysqli_real_escape_string($link, $_POST['quit']);
$quitdate = mysqli_real_escape_string($link, $_POST['quitdate']);
$landline = mysqli_real_escape_string($link, $_POST['landline']);
$delivery = mysqli_real_escape_string($link, $_POST['deliverydate']);
$qd = $quit * 7;
$cell = mysqli_real_escape_string($link, $_POST['cellphone']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
$address = mysqli_real_escape_string($link, $_POST['address']);
$location = mysqli_real_escape_string($link, $_POST['location']);
$postal = mysqli_real_escape_string($link, $_POST['postal']);
//$alert = mysqli_real_escape_string($link, date('Y-m-d', strtotime($quitdate. ' - $qd days')));
//$alert = date('Y-m-d', strtotime($quitdate. " + $qd days"));
$alert = mysqli_real_escape_string($link, date('Y-m-d', strtotime($quitdate. " - $qd days")));

echo $qd;
echo "<br>";
echo $alert;
echo "<br>";
echo $quitdate;
echo "<br>";
$dromedar = date('Y-m-d', strtotime($quitdate. ' - $qd days'));
echo $dromedar;

// attempt insert query execution
if(isset($_POST['submit']))
{

    if(!empty($customernumber) || !empty($contractnumber) ){

        $sql = "INSERT INTO customer (name, surname, birthdate, company, contractnumber, custnumber, unsubscription, quit,landline, cell, email, street, town, postal, delivery, alert) VALUES ('$first_name', '$last_name', '$birthdate', '$company', '$contractnumber', '$customernumber','$quitdate', '$qd','$landline','$cell', '$email_address','$address', '$location', '$postal','$delivery','$alert')";

            if(mysqli_query($link, $sql)){
                echo "";
            } else{
                echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
            }

    } else {
        echo "ERROR: Nicht gespeichert. Kundennummer oder Vertragsnummer fehlen!";
    }

}
// close connection
mysqli_close($link);
</code>```

One info on the structure: because it is for a friend I try to keep it all on a single page, so that he can make multiple inserts at once.

Hope somebody can help me. Thanks in advance.

Edit: Found out that this is happening:

```<code>*domain* anon-119-0-0-209.ip6.invalid - - [31/May/2017:07:56:47 +0200] "GET /database/input_form.php HTTP/1.1" 200 7116 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4"

*domain* anon-119-0-0-7.ip6.invalid - - [31/May/2017:17:37:39 +0200] "POST /database/input_form.php HTTP/1.1" 200 7060 "http://n-tec24.de/database/input_form.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4"
</code>```

So I see that it's something with the POST. And I'd assume it's about bots, because it's returning, but today I used a robots.txt and it still doesn't help.

答: Problem solved. It was my fault, because I had an older file on the server which began to insert automatically. Here I used to read the logs to find it out.</p>

Body:
I am working on a form to enter customer data. Works fine so far, but have a problem. Every day, five times a day, there are empty double entries and I don't know why. I checked the submit-button of the form, added $isset to prevent from adding empty posts. But still get empty entries.

Now I have no clue why. Though the way how it appears looks like a bot or else, but am not sure.

TimeStamp screen.

Customer Database - Insert

                <form action=""  method="post">

Kunde

                        Vorname:
                        <input type="text" name="firstname" id="firstName">

                        Nachname:
                        <input type="text" name="lastname" id="lastName">

                        Kundennummer:
                        <input type="number" name="customernumber" id="customerNumber">

Kundennummer in DEINEM Kundenstamm

                            Geburtsdatum:
                            <input type="date" name="birthdate" id="birthDate">

Format: YYYY/MM/DD

Vertragsdaten

                            Anbieter:
                            <input type="text" name="company" id="company">

                            Vertrags-/Kundennummer:
                            <input type="number" name="contractnumber" id="contractNumber">

                            Kündigungsdatum:
                            <input type="date" name="quitdate" id="quitDate">

Format: YYYY/MM/DD

                            Kündigungsfrist in Wochen:
                            <select name="quit" id="quit">
                              <option value="4">4</option>
                              <option value="5">5</option>
                              <option value="6">6</option>
                              <option value="7">7</option>
                              <option value="8">8</option>
                              <option value="9">9</option>
                              <option value="10">10</option>
                              <option value="11">11</option>
                              <option value="12">12</option>
                              <option value="13">13</option>
                              <option value="14">14</option>
                              <option value="15">15</option>
                              <option value="16">16</option>
                              <option value="17">17</option>
                              <option value="18">18</option>
                              <option value="19">19</option>
                              <option value="20">20</option>
                            </select>

                            Lieferbeginn:
                            <input type="date" name="deliverydate" id="deliveryDate">

Format: YYYY/MM/DD

Kontaktdaten

                            Festnetz:
                            <input type="tel" name="landline" id="landline">

                            Mobilfunk:
                            <input type="tel" name="cellphone" id="cellphone">

                            Email:
                            <input type="email" name="email" id="emailAddress">

                        Straße, Nr.:
                        <input type="text" name="address" id="address">

                            Ort:
                            <input type="text" name="location" id="location">

                            PLZ:
                            <input type="number" name="postal" id="postal">

                    <input type="submit" name ="submit" value="submit">
                </form>

<?php

/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("name", "name", "pw", "other data");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$birthdate = mysqli_real_escape_string($link, $_POST['birthdate']);
$company = mysqli_real_escape_string($link, $_POST['company']);
$contractnumber = mysqli_real_escape_string($link, $_POST['contractnumber']);
$customernumber = mysqli_real_escape_string($link, $_POST['customernumber']);
$quit = mysqli_real_escape_string($link, $_POST['quit']);
$quitdate = mysqli_real_escape_string($link, $_POST['quitdate']);
$landline = mysqli_real_escape_string($link, $_POST['landline']);
$delivery = mysqli_real_escape_string($link, $_POST['deliverydate']);
$qd = $quit * 7;
$cell = mysqli_real_escape_string($link, $_POST['cellphone']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
$address = mysqli_real_escape_string($link, $_POST['address']);
$location = mysqli_real_escape_string($link, $_POST['location']);
$postal = mysqli_real_escape_string($link, $_POST['postal']);
//$alert = mysqli_real_escape_string($link, date('Y-m-d', strtotime($quitdate. ' - $qd days')));
//$alert = date('Y-m-d', strtotime($quitdate. " + $qd days"));
$alert = mysqli_real_escape_string($link, date('Y-m-d', strtotime($quitdate. " - $qd days")));

echo $qd;
echo "
";
echo $alert;
echo "
";
echo $quitdate;
echo "
";
$dromedar = date('Y-m-d', strtotime($quitdate. ' - $qd days'));
echo $dromedar;

// attempt insert query execution
if(isset($_POST['submit']))
{

    if(!empty($customernumber) || !empty($contractnumber) ){

        $sql = "INSERT INTO customer (name, surname, birthdate, company, contractnumber, custnumber, unsubscription, quit,landline, cell, email, street, town, postal, delivery, alert) VALUES ('$first_name', '$last_name', '$birthdate', '$company', '$contractnumber', '$customernumber','$quitdate', '$qd','$landline','$cell', '$email_address','$address', '$location', '$postal','$delivery','$alert')";

            if(mysqli_query($link, $sql)){
                echo "";
            } else{
                echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
            }

    } else {
        echo "ERROR: Nicht gespeichert. Kundennummer oder Vertragsnummer fehlen!";
    }

}
// close connection
mysqli_close($link);

One info on the structure: because it is for a friend I try to keep it all on a single page, so that he can make multiple inserts at once.

Hope somebody can help me. Thanks in advance.

Edit: Found out that this is happening:

*domain* anon-119-0-0-209.ip6.invalid - - [31/May/2017:07:56:47 +0200] "GET /database/input_form.php HTTP/1.1" 200 7116 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4"

*domain* anon-119-0-0-7.ip6.invalid - - [31/May/2017:17:37:39 +0200] "POST /database/input_form.php HTTP/1.1" 200 7060 "http://n-tec24.de/database/input_form.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4"

So I see that it's something with the POST. And I'd assume it's about bots, because it's returning, but today I used a robots.txt and it still doesn't help.


问:
select union does not summarize selection
If I select 1 post from table posts

plus (union) 11 posts form table parchive

the final count is not 12 but 11:

```<code>$stmt = $db->query("SELECT * FROM posts where status='public' order by inde asc limit 12 offset " . $offset);
    $count1 = $stmt->rowCount(); // echo: 1
    if ($count1 < 12){
        $diff = 12 - $count1;
        $stmt = $db->query("(select * from posts where status='public' order by inde asc limit 12 offset " . $offset . ")
        union (select * from parchive where status='public' order by date desc limit " . $diff .")");
        $count2 = $stmt->rowCount(); // echo 11
    }
</code>```

So if $count1 is 1 and $diff is 11

$count2 should be 12 (1+11) and not 11 !

答:
If you need  all the result and not remove duplicated  values use union ALL</p>

```<code>$stmt = $db->query("(select *
        from posts where status='public' order by inde asc limit 12 offset " . $offset . ")
 union all  (select *
  from parchive where status='public' order by date desc limit " . $diff .")");
</code>```

Body:
If I select 1 post from table posts

plus (union) 11 posts form table parchive

the final count is not 12 but 11:

$stmt = $db->query("SELECT * FROM posts where status='public' order by inde asc limit 12 offset " . $offset);
    $count1 = $stmt->rowCount(); // echo: 1
    if ($count1 < 12){
        $diff = 12 - $count1;
        $stmt = $db->query("(select * from posts where status='public' order by inde asc limit 12 offset " . $offset . ")
        union (select * from parchive where status='public' order by date desc limit " . $diff .")");
        $count2 = $stmt->rowCount(); // echo 11
    }

So if $count1 is 1 and $diff is 11

$count2 should be 12 (1+11) and not 11 !

Body:
If you need  all the result and not remove duplicated  values use union ALL

$stmt = $db->query("(select *
        from posts where status='public' order by inde asc limit 12 offset " . $offset . ")
 union all  (select *
  from parchive where status='public' order by date desc limit " . $diff .")");


问:
Handling Special Characters in a Splunk Scripted Input
I've set up some python scripted inputs which work great for numerical values, but I'm having trouble when dealing with special characters.

The output of my script looks like:

```<code>fieldname1="60", fieldname2="abc", ...
</code>```

When I start dealing with text input that may contain special characters, I might have fields like:

```<code>fieldname3=""\", fieldname4="<3", fieldname5=""8===D"
</code>```

What is the best way to handle special characters, including quoted, commas, and equals signs?

答:
Depends
What's the source of those special characters?
You'll surely find an python module which will help you with that specific data
Recently had to clean html flags from a Sharepoint list in the customer engagement used the HTMLParser module
So you'd need to tell us more about your data</p>

Body:
I've set up some python scripted inputs which work great for numerical values, but I'm having trouble when dealing with special characters.

The output of my script looks like:

fieldname1="60", fieldname2="abc", ...

When I start dealing with text input that may contain special characters, I might have fields like:

fieldname3=""\", fieldname4="<3", fieldname5=""8===D"

What is the best way to handle special characters, including quoted, commas, and equals signs?


问:
is not a field of struct type hugolib.SiteInfo in
I tried adding a new property to my theme/partials/footer.html template, and adding that property to my /config.toml file, but I keep getting the error:

ERROR: 2017/07/09 template: theme/partials/footer.html:16:40: executing "theme/partials/footer.html" at <.Site.CopyrightStart...>: CopyrightStartYear is not a field of struct type *hugolib.SiteInfo in theme/partials/footer.html

Example from my partial template file:

```<code><span>© {{.Site.copyrightStartYear}}</span>
</code>```

答:
The template engine in Hugo will look for all site params under the [Params] block in the config.toml file (must be a quoted string for this example). These can be referenced via the .Site.Params.<paramName> lookup in partial templates.

e.g.

```<code># config.toml
...
[Params]
    myParam = "weeee!"
...
</code>```

And use it in your HTML fragment:

```<code># somePartial.html
<span>{{ .Site.Params.myParam }}</span>
...
</code>```

Body:
I tried adding a new property to my theme/partials/footer.html template, and adding that property to my /config.toml file, but I keep getting the error:

ERROR: 2017/07/09 template: theme/partials/footer.html:16:40: executing "theme/partials/footer.html" at <.Site.CopyrightStart...>: CopyrightStartYear is not a field of struct type *hugolib.SiteInfo in theme/partials/footer.html

Example from my partial template file:

© {{.Site.copyrightStartYear}}

Body:
The template engine in Hugo will look for all site params under the [Params] block in the config.toml file (must be a quoted string for this example). These can be referenced via the .Site.Params.<paramName> lookup in partial templates.

e.g.

# config.toml
...
[Params]
    myParam = "weeee!"
...

And use it in your HTML fragment:

# somePartial.html
<span>{{ .Site.Params.myParam }}</span>
...


问:
Checkerboard colouring of HTML elements on screen size change
I have several elements on a web page that's intended to be responsive to screen size. There is always an even number of the elements, and they're always the same height and width, so that when there are four of them, on a desktop screen, each will be one quarter of the width of the screen. To distinguish the elements to the viewer, I have them alternate colour, like this:

When the screen size changes, my CSS automatically reduces the number of elements per row, moving them to multiple rows. On a thin screen, this looks something like this:

However, when the screen size is a tiny bit wider, but still smaller than desktop, I want there to be two elements per row. Here's the problem: When I do that, instead of forming a checkerboard pattern, which would keep the elements distinguished from each other, they of course form columns of the same colour:

This is a problem, since when the elements aren't separated by a margin, you can't tell the rows apart in each column. My question, then, is how you would get the elements to always automatically form a checkerboard pattern, whether they're all in one row, one column, or in multiple rows and columns?

Right now, I'm generating the elements with PHP, so each element is assigned a class denoting its colour. I am open to a solution using PHP, CSS, or JavaScript, but it should work no matter the screen size, and should automatically change the elements' colour to fit the checkerboard pattern whenever the screen resizes.

答:
You should not define the actual colour, but eg the number. If you are dealing with 4, 2 and 1 per row, than use numbers 0-3 like this:

```<code>for ($i=0; $i < 20; $i++) {
  echo '<div class="box box-'.($i % 4).'">...</div>';
}
</code>```

Now you can use CSS media queries to define the colors for each screen width you want to change them.

For desktop:

```<code>.box-0, .box-2 { color: blue; }
.box-1, .box-3 { color: red; }
</code>```

For the 2-by-2 layout:

```<code>.box-0, .box-3 { color: blue; }
.box-1, .box-2 { color: red; }
</code>```

Body:
You should not define the actual colour, but eg the number. If you are dealing with 4, 2 and 1 per row, than use numbers 0-3 like this:

for ($i=0; $i < 20; $i++) {
  echo '<div class="box box-'.($i % 4).'">...</div>';
}

Now you can use CSS media queries to define the colors for each screen width you want to change them.

For desktop:

.box-0, .box-2 { color: blue; }
.box-1, .box-3 { color: red; }

For the 2-by-2 layout:

.box-0, .box-3 { color: blue; }
.box-1, .box-2 { color: red; }


问:
How to separate words from a row individually using php and mysql
I have a mysql database with a table called keywords -- see below

**** As you can see the row has more than one word listed inside.

MY QUESTION
Is there a way to separate each word on it's own using mysql and php. Right now it combines all the words as one instead of individually.

The picture below is showing you words but one button may contain 3 or more words.

I need for the words to be unique and on their own. Can this be done in MYSQL? If so can you please provide the php coding, thank you.

答:
As you didn't share any code, i can give you a simple guess so you can proceed further :-

Get data from your table with php and use explode function to separate each word.


问:
Issue with d3.js bar graph
I am porting a bar graph using json data and d3.js
But I am not able to do so. I have tried many ways.
Any help would be appreciated.

Here is my code,

```<code><!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
font: 10px sans-serif;
}

.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}

.bar {
fill: steelblue;
}

.x.axis path {
 display: none;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
.rangeRound([height, 0]);

var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));

var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var data = [
        {
        "State": "AL",
        "Under 5 Years": 310504,
        "5 to 13 Years": 552339,
        "14 to 17 Years": 259034
        },
        {
        "State": "PA",
        "Under 5 Years": 737462,
        "5 to 13 Years": 1345341,
        "14 to 17 Years": 679201
        },
        {
        "State": "RI",
        "Under 5 Years": 60934,
        "5 to 13 Years": 111408,
        "14 to 17 Years": 56198
        },
        {
        "State": "SC",
        "Under 5 Years": 303024,
        "5 to 13 Years": 517803,
        "14 to 17 Years": 245400
        },
        {
        "State": "SD",
        "Under 5 Years": 58566,
        "5 to 13 Years": 94438,
        "14 to 17 Years": 45305
        },
        {
        "State": "TN",
        "Under 5 Years": 416334,
        "5 to 13 Years": 725948,
        "14 to 17 Years": 336312
        },
        {
        "State": "TX",
        "Under 5 Years": 2027307,
        "5 to 13 Years": 3277946,
        "14 to 17 Years": 1420518
        },
        {
        "State": "WY",
        "Under 5 Years": 38253,
        "5 to 13 Years": 60890,
        "14 to 17 Years": 29314
        }
    ];

d3.json.parse(data, function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "State"; }));

data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
d.total = d.ages[d.ages.length - 1].y1;
});

x.domain(data.map(function(d) { return d.State; }));
y.domain([0, d3.max(data, function(d) { return d.total; })]);

 svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

 svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
 .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Population");

 var state = svg.selectAll(".state")
  .data(data)
 .enter().append("g")
  .attr("class", "g")
  .attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });

 state.selectAll("rect")
  .data(function(d) { return d.ages; })
 .enter().append("rect")
  .attr("width", x.rangeBand())
  .attr("y", function(d) { return y(d.y1); })
  .attr("height", function(d) { return y(d.y0) - y(d.y1); })
  .style("fill", function(d) { return color(d.name); });

 var legend = svg.selectAll(".legend")
  .data(color.domain().slice().reverse())
 .enter().append("g")
  .attr("class", "legend")
  .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
  .attr("x", width - 18)
  .attr("width", 18)
  .attr("height", 18)
  .style("fill", color);

  legend.append("text")
  .attr("x", width - 24)
  .attr("y", 9)
  .attr("dy", ".35em")
  .style("text-anchor", "end")
  .text(function(d) { return d; });

 });

 </script>
</code>```

答:
This may help,

Take your data and stick it in an external json file.

For example, "mydata.json"

Instead of

```<code>d3.json.parse(data, function(error, data)
</code>```

Remove parse and replace your data with the path to your external json file.

```<code> d3.json(path/mydata.json, function(error, data)
</code>```

Make sure the external file is in the correct json format

Title: Issue with d3.js bar graph

Body:
I am porting a bar graph using json data and d3.js
But I am not able to do so. I have tried many ways.
Any help would be appreciated.

Here is my code,

<!DOCTYPE html>
<meta charset="utf-8">

Body:
This may help,

Take your data and stick it in an external json file.

For example, "mydata.json"

Instead of

d3.json.parse(data, function(error, data)

Remove parse and replace your data with the path to your external json file.

 d3.json(path/mydata.json, function(error, data)

Make sure the external file is in the correct json format


问:
Use java8 streams to read in 1 file and write out 3 files based on some critera
To be clear - the goal here is to use input AND output streams, so that I am not building up huge lists for output later.  I just want java to open the input file, and run through it, writing to the output files in semi-realtime as it goes through.

I am totally new to streams.  I understand the basic idea of streams, and lamba's etc, but don't know the details of implementation and syntax, etc.  (For instance I am confused by the :: syntax I see in some examples)...

In any case - below is an example that gets done basically what I want to do...

I'd like to know how to do it with stream interface so that the main file (which could be quite large) doesn't need to be in memory all at the same time.

Thanks!

```<code>        Set<String> set1 = fileToSet(file1);
        Set<String> set2 = fileToSet(file2);

        List<String> output1 = new ArrayList<>();
        List<String> output2 = new ArrayList<>();
        List<String> output3 = new ArrayList<>();

        for (String line : Files.readAllLines(inputPath)) {
                String subString = line.substring(0,10);

                if (set1.contains(subString)) {
                    output1.add(line);
                }
                else if (set2.contains(subString)) {
                    output2.add(line);
                }
                else {
                    output3.add(line);
                }
        }
//write out all 3 files from the collected lists
</code>```

答:
Something like that should work:

```<code>    Files.lines(Paths.get(inputPath)).forEach(line -> {
        // do your logic with line
        ...
    });
</code>```

You should also consider to write the filtered data directly into output files and do not collect it in the memory. Output files might be open prior the file reading.

Body:
To be clear - the goal here is to use input AND output streams, so that I am not building up huge lists for output later.  I just want java to open the input file, and run through it, writing to the output files in semi-realtime as it goes through.

I am totally new to streams.  I understand the basic idea of streams, and lamba's etc, but don't know the details of implementation and syntax, etc.  (For instance I am confused by the :: syntax I see in some examples)...

In any case - below is an example that gets done basically what I want to do...

I'd like to know how to do it with stream interface so that the main file (which could be quite large) doesn't need to be in memory all at the same time.

Thanks!

        Set<String> set1 = fileToSet(file1);
        Set<String> set2 = fileToSet(file2);

        List<String> output1 = new ArrayList<>();
        List<String> output2 = new ArrayList<>();
        List<String> output3 = new ArrayList<>();

        for (String line : Files.readAllLines(inputPath)) {
                String subString = line.substring(0,10);

                if (set1.contains(subString)) {
                    output1.add(line);
                }
                else if (set2.contains(subString)) {
                    output2.add(line);
                }
                else {
                    output3.add(line);
                }
        }
//write out all 3 files from the collected lists

Body:
Something like that should work:

    Files.lines(Paths.get(inputPath)).forEach(line -> {
        // do your logic with line
        ...
    });

You should also consider to write the filtered data directly into output files and do not collect it in the memory. Output files might be open prior the file reading.


问:
Golang listenUDP multiple ports blocking with BigTable connection
I'm creating a simple udp client that listens on multiple ports and saves the request to bigtable.

It's essential to listen on different ports before you ask.

Everything was working nicely until I included bigtable. After doing so, the listeners block completely.

My stripped down code, without bigtable, looks like this:

```<code>func flow(port string) {

    protocol := "udp"
    udpAddr, err := net.ResolveUDPAddr(protocol, "0.0.0.0:"+port)
    if err != nil {
        fmt.Println("Wrong Address")
        return
    }

    udpConn, err := net.ListenUDP(protocol, udpAddr)
    if err != nil {
        fmt.Println(err)
    }
    defer udpConn.Close()

    for {
        Publish(udpConn, port)
    }
}

func main() {

    fmt.Print("Starting server.........")
    for i := *Start; i <= *End; i++ {
        x := strconv.Itoa(i)
        go flow(x)
    }
}
</code>```

This works fine however, as soon as I add the following for bigtable, the whole thing blocks. If I remove the go routine that creates the listener (which means I can't listen on multiple ports) it works.

```<code>func createBigTable() {
    ctx := context.Background()

    client, err := bigtable.NewClient(ctx, *ProjectID, *Instance)
    if err != nil {
        log.Fatal("Bigtable NewClient:", err)
    }

    Table = client.Open("x")

}
</code>```

I managed to get it working by adding a query in the createBigTable func but the program still blocks later on.

I have no idea if this is an issue with bigtable, grpc or just the way I'm doing it.

Would really appreciate some advise about how to fix.

--- UPDATE ---

I've discovered the issue isn't just with BigTable - I also have the same issue when I call gcloud pubsub.

--- UPDATE 2 ---

createBigtable is called in the init function (BEFORE THE MAIN FUNCTION):

```<code>func init() {
    createBigTable
}
</code>```

--- Update 3 ---

Output from sigquit can be found here:

https://pastebin.com/fzixqmiA

答:
In your playground example, you're using for {} to keep the server running for forever.
This seems to deprive the goroutines from ever getting to run.
Try using e.g. a WaitGroup to yield control from the main() routine and let the flow() routines handle the incoming UDP packets.

```<code>import (
    ...
    "sync"
    ...
)

...

func main() {

    fmt.Print("Starting server.")
    for i := *Start; i <= *End; i++ {
        x := strconv.Itoa(i)
        go flow(x)
    }

    var wg sync.WaitGroup
    wg.Add(1)
    wg.Wait()
}
</code>```

Body:
I'm creating a simple udp client that listens on multiple ports and saves the request to bigtable.

It's essential to listen on different ports before you ask.

Everything was working nicely until I included bigtable. After doing so, the listeners block completely.

My stripped down code, without bigtable, looks like this:

func flow(port string) {

    protocol := "udp"
    udpAddr, err := net.ResolveUDPAddr(protocol, "0.0.0.0:"+port)
    if err != nil {
        fmt.Println("Wrong Address")
        return
    }

    udpConn, err := net.ListenUDP(protocol, udpAddr)
    if err != nil {
        fmt.Println(err)
    }
    defer udpConn.Close()

    for {
        Publish(udpConn, port)
    }
}

func main() {

    fmt.Print("Starting server.........")
    for i := *Start; i <= *End; i++ {
        x := strconv.Itoa(i)
        go flow(x)
    }
}

This works fine however, as soon as I add the following for bigtable, the whole thing blocks. If I remove the go routine that creates the listener (which means I can't listen on multiple ports) it works.

func createBigTable() {
    ctx := context.Background()

    client, err := bigtable.NewClient(ctx, *ProjectID, *Instance)
    if err != nil {
        log.Fatal("Bigtable NewClient:", err)
    }

    Table = client.Open("x")

}

I managed to get it working by adding a query in the createBigTable func but the program still blocks later on.

I have no idea if this is an issue with bigtable, grpc or just the way I'm doing it.

Would really appreciate some advise about how to fix.

--- UPDATE ---

I've discovered the issue isn't just with BigTable - I also have the same issue when I call gcloud pubsub.

--- UPDATE 2 ---

createBigtable is called in the init function (BEFORE THE MAIN FUNCTION):

func init() {
    createBigTable
}

--- Update 3 ---

Output from sigquit can be found here:

https://pastebin.com/fzixqmiA

Body:
In your playground example, you're using for {} to keep the server running for forever.
This seems to deprive the goroutines from ever getting to run.
Try using e.g. a WaitGroup to yield control from the main() routine and let the flow() routines handle the incoming UDP packets.

import (
    ...
    "sync"
    ...
)

...

func main() {

    fmt.Print("Starting server.")
    for i := *Start; i <= *End; i++ {
        x := strconv.Itoa(i)
        go flow(x)
    }

    var wg sync.WaitGroup
    wg.Add(1)
    wg.Wait()
}


问:
Replacing bluebird with node.js native promises breaks Promise.reject
The following code works perfectly fine when I use bluebird promises:

```<code>import * as Promise from 'bluebird';

getAccount(id) {
    var account = find(accounts, ['id', id]);
    return account ?
        Promise.resolve(account) :
        Promise.reject(new NotFoundError());
}
</code>```

NotFoundError is defined as follows:

```<code>export function NotFoundError(message = 'Not Found') {
    this.name = 'NotFoundError';
    this.message = message;
    this.stack = (new Error()).stack;
}
NotFoundError.prototype = Object.create(Error.prototype);
NotFoundError.prototype.constructor = NotFoundError;
</code>```

However, if I remove the import of bluebird in getAccount() and let node.js take over promises, the code fails inside the NotFoundError() constructor because this is not defined. Specifically, the constructor is called twice, once correctly from the getAccount() code shown above and a second time by node.js's _tickCallback() function with this as undefined:

```<code>NotFoundError (errors.js:13)
runMicrotasksCallback (internal/proces…ext_tick.js:58)
_combinedTickCallback (internal/proces…ext_tick.js:67)
_tickCallback (internal/proces…ext_tick.js:98)
</code>```

Why is node.js calling the NotFoundError() constructor a second time and that too incorrectly!!!

Please help.

答:
The issue is caused by this line:

```<code>.catch(NotFoundError, function() { ... })
</code>```

Native promises don't have an option to pass a specific error class to a catch method, so what happens is that when an error occurs, NotFoundError is called (without a new in front of it) because it's presumed to be the catch handler.

Body:
The following code works perfectly fine when I use bluebird promises:

import * as Promise from 'bluebird';

getAccount(id) {
    var account = find(accounts, ['id', id]);
    return account ?
        Promise.resolve(account) :
        Promise.reject(new NotFoundError());
}

NotFoundError is defined as follows:

export function NotFoundError(message = 'Not Found') {
    this.name = 'NotFoundError';
    this.message = message;
    this.stack = (new Error()).stack;
}
NotFoundError.prototype = Object.create(Error.prototype);
NotFoundError.prototype.constructor = NotFoundError;

However, if I remove the import of bluebird in getAccount() and let node.js take over promises, the code fails inside the NotFoundError() constructor because this is not defined. Specifically, the constructor is called twice, once correctly from the getAccount() code shown above and a second time by node.js's _tickCallback() function with this as undefined:

NotFoundError (errors.js:13)
runMicrotasksCallback (internal/proces…ext_tick.js:58)
_combinedTickCallback (internal/proces…ext_tick.js:67)
_tickCallback (internal/proces…ext_tick.js:98)

Why is node.js calling the NotFoundError() constructor a second time and that too incorrectly!!!

Please help.

Body:
The issue is caused by this line:

.catch(NotFoundError, function() { ... })

Native promises don't have an option to pass a specific error class to a catch method, so what happens is that when an error occurs, NotFoundError is called (without a new in front of it) because it's presumed to be the catch handler.


问:
in App purchase showing "Environment Sandbox" even after status changed to "ready for sale"
My iPhone application  and in App purchase  status become "ready for Sale" yesterday. But when am running my In App Purchase , i am getting "[Environment Sandbox]" in "Do you want to buy .... push notifications"  .How can i change my in app purchase from test environment ?</p>

答: Your app is getting "resigned" with a different certificate when it gets processed for the AppStore so it won't use the Sandbox after a user downloads it from the AppStore.</p>


问:
SL4J setup with spring webapp using tomcat not logging?
I'm stuck in a loop and cant quite figure out why when my war is deployed to tomcat there is no output logs - however if i run unit tests locally through intellij the log file is populated as expected.

Web.xml contains:

```<code><context-param>
    <param-name>logbackConfigLocation</param-name>
    <param-value>/WEB-INF/logback.xml</param-value>
</context-param>
</code>```

src/main/java/resources/logback.xml (also have it in web-inf/logback.xml)

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

```<code><appender name="FILE-AUDIT"
          class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>storagedebug.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
        </Pattern>
    </encoder>

    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- rollover daily -->
        <fileNamePattern>storagedebug.%d{yyyy-MM-dd}.%i.log
        </fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>

</appender>

<logger name="com.app.storage" level="debug"
        additivity="false">
    <appender-ref ref="FILE-AUDIT" />
</logger>

<root level="error">
    <appender-ref ref="FILE-AUDIT" />
</root>

</configuration>
</code>```

Finally relevant dependencies:

```<code>compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.7'
compile group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.25'
compile group: 'ch.qos.logback', name: 'logback-core', version:'1.1.2'
compile group: 'ch.qos.logback', name: 'logback-classic',
version:'1.1.2'
</code>```

And i have included the following with my spring dependencies:

```<code>configurations.all {
    exclude group: "commons-logging", module: "commons-logging"
}
</code>```

答: For <file>storagedebug.log</file> can you try putting absolute path for log file? Since at present,this is relative to tomcat bin directory. Also don't forget to update absolute path at <fileNamePattern>storagedebug.%d{yyyy-MM-dd}.%i.log also

Body:
I'm stuck in a loop and cant quite figure out why when my war is deployed to tomcat there is no output logs - however if i run unit tests locally through intellij the log file is populated as expected.

Web.xml contains:

<context-param>
    <param-name>logbackConfigLocation</param-name>
    <param-value>/WEB-INF/logback.xml</param-value>
</context-param>

src/main/java/resources/logback.xml (also have it in web-inf/logback.xml)

<?xml version="1.0" encoding="UTF-8"?>

<appender name="FILE-AUDIT"
          class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>storagedebug.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
        </Pattern>
    </encoder>

    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

        <fileNamePattern>storagedebug.%d{yyyy-MM-dd}.%i.log
        </fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>

</appender>

<logger name="com.app.storage" level="debug"
        additivity="false">
    <appender-ref ref="FILE-AUDIT" />
</logger>

<root level="error">
    <appender-ref ref="FILE-AUDIT" />
</root>

</configuration>

Finally relevant dependencies:

compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.7'
compile group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.25'
compile group: 'ch.qos.logback', name: 'logback-core', version:'1.1.2'
compile group: 'ch.qos.logback', name: 'logback-classic',
version:'1.1.2'

And i have included the following with my spring dependencies:

configurations.all {
    exclude group: "commons-logging", module: "commons-logging"
}


问:
Saving multiple params in a single array with ajax and rails
When a card is dragged inside a list, I'm using thejQueryUI sortable plugin's update callback to send the new position of each card to my controller. This AJAX request posts the position attribute of every card in whichever list the dragged card was released in.

```<code>$(".js-Sortable").sortable({
    connectWith: ".js-Sortable",
    items: ".js-CardContainer",
    update: function( event, ui ) {
        if (this === ui.item.parent()[0]) {

            var data = $(this).sortable('serialize');

            $.ajax({
                url: "/c/sort",
                type: "POST",
                dataType: "script",
                data: data,
                success: function(resp){
                    console.log('Yay');
                }
            });
        }
    }
});
</code>```

This sends params which look something like this

```<code>Parameters: {"card"=>["39", "2", "1", "6", "40", "5", "18", "3", "16", "7", "17", "8", "15", "9", "10", "11", "12", "13", "14", "4"]}
</code>```

I'm then updating each affected card's position attribute in my controller action like this:

```<code>def sort
    params[:card].each_with_index do |id, index|
        card = Card.find(id)
        card.update_attribute(:position, index) if card
    end

    head :ok
end
</code>```

The view looks like this:

```<code><ul class="js-CardsContainer js-Sortable">
  <% list.cards.order(:position).where(archived: false).each do |card| %>
    <li class="js-CardContainer" id="card-<%= card.id %>">
      <%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true do %>
        <span><%= card.title %></span>
      <% end %>
    </li>
  <% end %>
</ul>
</code>```

This is all working so far. The problem is, cards can be moved across different lists. So, I need to somehow get the id of whichever list the dragged card was released in and post that with the AJAX request too.

I can get the list_id as a variable, but how can I add this list_id to the array in the AJAX request?

答:
As I mentioned in the previous comment, at least one of the objects sent on an event like sorting (and in other jquery UI events like draggable) will usually contain a reference to the previous element.

In this case, the ui object contains a sender array which will include a reference at index 0 to the most recent sender: ui.sender[0]

I've given an example here of how this could be used in your case:

http://jsfiddle.net/6npx24uf/

Body:
When a card is dragged inside a list, I'm using thejQueryUI sortable plugin's update callback to send the new position of each card to my controller. This AJAX request posts the position attribute of every card in whichever list the dragged card was released in.

$(".js-Sortable").sortable({
    connectWith: ".js-Sortable",
    items: ".js-CardContainer",
    update: function( event, ui ) {
        if (this === ui.item.parent()[0]) {

            var data = $(this).sortable('serialize');

            $.ajax({
                url: "/c/sort",
                type: "POST",
                dataType: "script",
                data: data,
                success: function(resp){
                    console.log('Yay');
                }
            });
        }
    }
});

This sends params which look something like this

Parameters: {"card"=>["39", "2", "1", "6", "40", "5", "18", "3", "16", "7", "17", "8", "15", "9", "10", "11", "12", "13", "14", "4"]}

I'm then updating each affected card's position attribute in my controller action like this:

def sort
    params[:card].each_with_index do |id, index|
        card = Card.find(id)
        card.update_attribute(:position, index) if card
    end

    head :ok
end

The view looks like this:

  <% list.cards.order(:position).where(archived: false).each do |card| %>
    <li class="js-CardContainer" id="card-<%= card.id %>">
      <%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true do %>
        <%= card.title %>
      <% end %>

  <% end %>

This is all working so far. The problem is, cards can be moved across different lists. So, I need to somehow get the id of whichever list the dragged card was released in and post that with the AJAX request too.

I can get the list_id as a variable, but how can I add this list_id to the array in the AJAX request?


答:
You could use a forEach to handle each line and apply your actual logic in
and you could also use a BufferedWriter to write the content of the line that matches with your logic :

```<code>try (Stream<String> lines = Files.lines(path);
     BufferedWriter writer1 = new BufferedWriter(new FileWriter("file1"));
     BufferedWriter writer2 = new BufferedWriter(new FileWriter("file2"));
     BufferedWriter writer3 = new BufferedWriter(new FileWriter("file3"))) {

        lines.forEach((line) -> {

            String subString = line.substring(0, 10);

            try {
                BufferedWriter writerToUse;
                if (set1.contains(subString)) {
                    writerToUse = writer1;
                } else if (set2.contains(subString)) {
                    writerToUse = writer2;
                } else {
                    writerToUse = writer3;
                }
                writerToUse.append(line);
                writerToUse.newLine();

              // lambda cannot throw checked exception not declared in the
              // functional interface. So you have to catch IO exception in
            } catch (IOException e) {
                // TODO error processing
            }

        });
}
</code>```

Title: Use java8 streams to read in 1 file and write out 3 files based on some critera

Body:
You could use a forEach to handle each line and apply your actual logic in
and you could also use a BufferedWriter to write the content of the line that matches with your logic :

try (Stream<String> lines = Files.lines(path);
     BufferedWriter writer1 = new BufferedWriter(new FileWriter("file1"));
     BufferedWriter writer2 = new BufferedWriter(new FileWriter("file2"));
     BufferedWriter writer3 = new BufferedWriter(new FileWriter("file3"))) {

        lines.forEach((line) -> {

            String subString = line.substring(0, 10);

            try {
                BufferedWriter writerToUse;
                if (set1.contains(subString)) {
                    writerToUse = writer1;
                } else if (set2.contains(subString)) {
                    writerToUse = writer2;
                } else {
                    writerToUse = writer3;
                }
                writerToUse.append(line);
                writerToUse.newLine();

              // lambda cannot throw checked exception not declared in the
              // functional interface. So you have to catch IO exception in
            } catch (IOException e) {
                // TODO error processing
            }

        });
}


问:
Id is not getting perfect values, Get id based on name from spinner onitemselected
I'm trying to load Some data from JSON to Android spinner, the data is loading perfectly but when I'm trying to get id for the selected item its showing the last name id value whatever the item is selected.

Here's my JSON response

```<code> [{"name":"aaa","id":"1"},
  {"name":"bbb","id":"2"},
 {"name":"ccc", "id":"3"},
{"name":"ddd",  "id":"4"}]
</code>```

Mainactivity.java

```<code>protected void receivedata(final String result){
    final ArrayList<String> list = new ArrayList<>();
    final ArrayList<GetDataAdapter> datalist = new ArrayList<>();
    list.clear();
    try{
        GetDataAdapter GetDatadp = new GetDataAdapter();
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
            JSONObject jsonObject=jArray.getJSONObject(i);
            GetDatadp.setName(jsonObject.getString("name"));
            GetDatadp.setId(jsonObject.getString("id"));
            datalist.add(GetDatadp);

            list.add(jsonObject.getString("name"));
        }
    }
    catch(JSONException e){
        e.printStackTrace();
    }

    final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.spinner_layout, R.id.txt, list);
    sp.setAdapter(adapter);
    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
            public void onItemSelected(AdapterView<?> arg0, View view, int position, long row_id) {
            String id = datalist.get(position).getId();

            Toast.makeText(getApplicationContext(),"Value   " +id , Toast.LENGTH_LONG).show();

        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            //Do something
        }
    }
    );
}
</code>```

GetDataAdapte.java

```<code>public class GetDataAdapter {
String name;
String id;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
}
</code>```

So when I'm trying to select names aaa/bbb or whatever it is showing the id value 4.how to get display the correct id.

答:
To avoid a naming confusion between Adapter and DTO (model class)

Adapter:

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.

However, you problem as I understood because you only created a one object which is GetDataAdapter in your case, so in order to get a valid list of GetDataAdapter objects you have to create a new instance in the loop, take a look for the updated code below :

```<code> try{
    GetDataAdapter GetDatadp ;
    JSONObject jsonObject;
    JSONArray jArray = new JSONArray(result);

    for(int i=0;i<jArray.length();i++){

        jsonObject=jArray.getJSONObject(i);

        GetDatadp = new GetDataAdapter();
        GetDatadp.setName(jsonObject.getString("name"));
        GetDatadp.setId(jsonObject.getString("id"));
        datalist.add(GetDatadp);

        list.add(jsonObject.getString("name"));
    }
}
catch(JSONException e){
    e.printStackTrace();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to load Some data from JSON to Android spinner, the data is loading perfectly but when I'm trying to get id for the selected item its showing the last name id value whatever the item is selected.

Here's my JSON response

 [{"name":"aaa","id":"1"},
  {"name":"bbb","id":"2"},
 {"name":"ccc", "id":"3"},
{"name":"ddd",  "id":"4"}]

Mainactivity.java

protected void receivedata(final String result){
    final ArrayList<String> list = new ArrayList<>();
    final ArrayList<GetDataAdapter> datalist = new ArrayList<>();
    list.clear();
    try{
        GetDataAdapter GetDatadp = new GetDataAdapter();
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
            JSONObject jsonObject=jArray.getJSONObject(i);
            GetDatadp.setName(jsonObject.getString("name"));
            GetDatadp.setId(jsonObject.getString("id"));
            datalist.add(GetDatadp);

            list.add(jsonObject.getString("name"));
        }
    }
    catch(JSONException e){
        e.printStackTrace();
    }

    final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.spinner_layout, R.id.txt, list);
    sp.setAdapter(adapter);
    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
            public void onItemSelected(AdapterView<?> arg0, View view, int position, long row_id) {
            String id = datalist.get(position).getId();

            Toast.makeText(getApplicationContext(),"Value   " +id , Toast.LENGTH_LONG).show();

        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            //Do something
        }
    }
    );
}

GetDataAdapte.java

public class GetDataAdapter {
String name;
String id;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
}

So when I'm trying to select names aaa/bbb or whatever it is showing the id value 4.how to get display the correct id.

Body:
To avoid a naming confusion between Adapter and DTO (model class)

Adapter:

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.

However, you problem as I understood because you only created a one object which is GetDataAdapter in your case, so in order to get a valid list of GetDataAdapter objects you have to create a new instance in the loop, take a look for the updated code below :

 try{
    GetDataAdapter GetDatadp ;
    JSONObject jsonObject;
    JSONArray jArray = new JSONArray(result);

    for(int i=0;i<jArray.length();i++){

        jsonObject=jArray.getJSONObject(i);

        GetDatadp = new GetDataAdapter();
        GetDatadp.setName(jsonObject.getString("name"));
        GetDatadp.setId(jsonObject.getString("id"));
        datalist.add(GetDatadp);

        list.add(jsonObject.getString("name"));
    }
}
catch(JSONException e){
    e.printStackTrace();
}


问:
Examine logs from the past with logcat?
I'd like to examine stack traces from the last hours. I haven't found a proper logcat command. Does Android "forget" those logs?

First story:

When I find an unhandled exception in my co-workers Iphone App, he connects the iphone to his computer and reads the stack trace into x-code. X-Code also visualizes the exception in a nice way.
Is there a smth. similar in Android?

答:
You probably won't be able to see those logs from the past hours. Imagine that your phone stores all logs, how much space will it consume in a couple of days?

So, this is what I do:

I'm in the autobus, and suddenly the app I'm working on crashes!

I'd like to see what's the logcat output to analyze it at home

I just launch the Android log collector app, and send myself an email with the logcat output

I get home, have dinner, feed the dogs and then I can start working on the logtrace I emailed hours ago.

Title: Examine logs from the past with logcat?


问:
Makefile builds everything each time
I have the following Makefile (reduced to ignore irrelevant stuff):

```<code>BUILD_DIR=./build
OBJS = \
  $(BUILD_DIR)/main.o \
  $(BUILD_DIR)/common.o \
  ...

roo: $(OBJS)
    $(CXX) -o $@ $(OBJS) $(LFLAGS)

.PHONY: $(BUILD_DIR)
$(BUILD_DIR):
    mkdir -p $(BUILD_DIR)/passes

$(BUILD_DIR)/%.o: src/%.cpp $(BUILD_DIR)
    $(CXX) -o $@ -c $< $(CFLAGS)
</code>```

However, every object file is recompiled every time, even thought I'm following the rule to directly use $@ in each non-phony target.

I don't think this is a duplicate of this because I'm applying the subdirectory in the rule rather than in the recipe, but I may be wrong? How do I get Make to correctly track the dependencies in the build directory?

答:
You've stated that $(BUILD_DIR)/%.o depends on $(BUILD_DIR), but that directory will be touched every time a file is added to that directory (for example by this rule itself).  That is, $(BUILD_DIR) will always be newer than its target.

It looks like you want to create the build directory automatically.  The best way to do that, I think, is

```<code>$(BUILD_DIR)/%.o: src/%.cpp
    mkdir -p $(BUILD_DIR)/passes
    $(CXX) -o $@ -c $< $(CFLAGS)
</code>```

Title: Makefile builds everything each time

Body:
I have the following Makefile (reduced to ignore irrelevant stuff):

BUILD_DIR=./build
OBJS = \
  $(BUILD_DIR)/main.o \
  $(BUILD_DIR)/common.o \
  ...

roo: $(OBJS)
    $(CXX) -o $@ $(OBJS) $(LFLAGS)

.PHONY: $(BUILD_DIR)
$(BUILD_DIR):
    mkdir -p $(BUILD_DIR)/passes

$(BUILD_DIR)/%.o: src/%.cpp $(BUILD_DIR)
    $(CXX) -o $@ -c $< $(CFLAGS)

However, every object file is recompiled every time, even thought I'm following the rule to directly use $@ in each non-phony target.

I don't think this is a duplicate of this because I'm applying the subdirectory in the rule rather than in the recipe, but I may be wrong? How do I get Make to correctly track the dependencies in the build directory?

Body:
You've stated that $(BUILD_DIR)/%.o depends on $(BUILD_DIR), but that directory will be touched every time a file is added to that directory (for example by this rule itself).  That is, $(BUILD_DIR) will always be newer than its target.

It looks like you want to create the build directory automatically.  The best way to do that, I think, is

$(BUILD_DIR)/%.o: src/%.cpp
    mkdir -p $(BUILD_DIR)/passes
    $(CXX) -o $@ -c $< $(CFLAGS)


问:
execute final mongoose query after loop completes
I want to run a loop of mongoose queries to update a database based on an array called dateStarts. Then after that, I want to execute a final command, but I want it to use the databases as they after all that updating. As written, the final query seems to be running before the loop is done. How do I fix that?

```<code>dateStarts.forEach(function(datevalue)
        {
            var conditions = {//conditions};
            var update     = {//updates};
            titleRecords.update(conditions, update, options, function(err, data)
            {
                if (err) throw err;
            });
        }) //end of forEach loop
        titleRecords.remove({//finalcondition});
</code>```

答:
The function update is an asynchronous operation, that is why remove is execute before of the updates. You can build an array of promises and use Promise.all to resolve all of the updates before doing that remove:

```<code>var updatePromises = dateStarts.map((datevalue) => {
    var conditions = {//conditions};
    var update     = {//updates};
    return titleRecords.update(conditions, update, options);
});

Promise.all(updatePromises)
  .then(() => titleRecords.remove({//finalcondition}))
  .catch((error) => ...);
</code>```

To make mongoose use the native promise (node version 6 or higher), you can do this at the top:

```<code>mongoose.Promise = global.Promise;
</code>```

Body:
I want to run a loop of mongoose queries to update a database based on an array called dateStarts. Then after that, I want to execute a final command, but I want it to use the databases as they after all that updating. As written, the final query seems to be running before the loop is done. How do I fix that?

dateStarts.forEach(function(datevalue)
        {
            var conditions = {//conditions};
            var update     = {//updates};
            titleRecords.update(conditions, update, options, function(err, data)
            {
                if (err) throw err;
            });
        }) //end of forEach loop
        titleRecords.remove({//finalcondition});

Body:
The function update is an asynchronous operation, that is why remove is execute before of the updates. You can build an array of promises and use Promise.all to resolve all of the updates before doing that remove:

var updatePromises = dateStarts.map((datevalue) => {
    var conditions = {//conditions};
    var update     = {//updates};
    return titleRecords.update(conditions, update, options);
});

Promise.all(updatePromises)
  .then(() => titleRecords.remove({//finalcondition}))
  .catch((error) => ...);

To make mongoose use the native promise (node version 6 or higher), you can do this at the top:

mongoose.Promise = global.Promise;


问:
PHP version is not changing after write statement into bash-profile
I tried to make the xampp php version as a default php instance. At the moment the build in php version is default. In the nano .bash_profile I write the statement

```<code>export PATH=/Applications/XAMPP/xamppfiles/bin:$PATH
</code>```

and this is no stored in the bash_profil. But when I check the php version via php -v I get the older one. Any idea?

答: exec "$SHELL" to load your recently changed .bash_profile. That should do it.

Body:
I tried to make the xampp php version as a default php instance. At the moment the build in php version is default. In the nano .bash_profile I write the statement

export PATH=/Applications/XAMPP/xamppfiles/bin:$PATH

and this is no stored in the bash_profil. But when I check the php version via php -v I get the older one. Any idea?


问:
How can I make an unordered_multimap in C++ between an int and a pair?
When trying to run the following code I get this compiling error
"error: type/value mismatch at argument 2 in template parameter list for ‘template class std::unordered_multimap’ unordered_multimap m;"

Is there any way I can setup an  multimap? If not how can I do what I want to do? Thanks!

```<code>#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#include <map>
#include <unordered_map>
#include <utility>

using namespace std;

int main(){

int n = 100;
unordered_multimap<int, pair> m; //Error is in this line

for (int a = 0; a <= n; ++a)
    for (int b = 0; b <= n; ++b)
    {
        int result = (a*a*a) + (b*b*b);
        pair<int,int> p = {a,b};
        pair<int,pair> p2 = {result,p};
        m.insert(p2);
    }
return 0;
}
</code>```

答:
A std::pair isn't a type by itself, it's a template that "generates" types. You need to specify what type you want to "make" by specifying the 2 template argument types that it asks for.

Your use case shows that you want to have two ints as a pair so you should specify that everywhere:

```<code>unordered_multimap<int, pair<int, int>> m;
</code>```

and

```<code>pair<int,pair<int, int>> p2 = {result,p};
</code>```

Body:
When trying to run the following code I get this compiling error
"error: type/value mismatch at argument 2 in template parameter list for ‘template class std::unordered_multimap’ unordered_multimap m;"

Is there any way I can setup an  multimap? If not how can I do what I want to do? Thanks!

#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#include <map>
#include <unordered_map>
#include <utility>

using namespace std;

int main(){

int n = 100;
unordered_multimap<int, pair> m; //Error is in this line

for (int a = 0; a <= n; ++a)
    for (int b = 0; b <= n; ++b)
    {
        int result = (a*a*a) + (b*b*b);
        pair<int,int> p = {a,b};
        pair<int,pair> p2 = {result,p};
        m.insert(p2);
    }
return 0;
}

Body:
A std::pair isn't a type by itself, it's a template that "generates" types. You need to specify what type you want to "make" by specifying the 2 template argument types that it asks for.

Your use case shows that you want to have two ints as a pair so you should specify that everywhere:

unordered_multimap<int, pair<int, int>> m;

and

pair<int,pair<int, int>> p2 = {result,p};