问:
Dynamic JavaScript time counter
I'm trying to make a dynamic time counter/timer in JavaScript.

Why dynamic? Well I would like to display days/hours/minutes/seconds if the time stamp is bigger enough to display days or hours and so on.

In case the timestamp is less than a day I would like that the script dynamically displays only the hours.

```<code>1D 0H 59M 59S
23H 59M 59S
59M 59S
59S
MESSAGE
</code>```

Here is the code I try to make it work.

```<code><center>
<script>
    var countDownDate = new Date("2017-11-17T20:10:30Z").getTime();
    var x = setInterval(function() {
        var now = new Date().getTime();
        var distance = countDownDate - now;

        // Seconds
        if (distance < 1000){
            document.getElementById("count1").innerHTML = seconds + "s ";
        }
        // Minutes
        if (distance < 60000){
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            document.getElementById("count1").innerHTML = minutes + "m " + seconds + "s ";
        }
        // Hours
        if (distance < 3600000){
            var hours = Math.floor(distance / (1000 * 60 * 60 * 1));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            document.getElementById("count1").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
        }
        // Days
        if(distance > 3600001){
            var days = Math.floor(distance / (1000 * 60 * 60 * 24));
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            document.getElementById("count1").innerHTML = days + "d " + hours + "h " + minutes + "m " $
        }

        if (distance < 0) {
            clearInterval(x);
            document.getElementById("count1").innerHTML = "You will be redirected now";
        }
    }, 1000);
</script>

<p id="count1"></p>
</center>
</code>```

I think that my problem is related with math confusion in milliseconds but I can't find out what is wrong.

答:
These changes made it work for me:

```<code>      <center>
<script>

    var countDownDate = new Date("2017-11-17T21:30:30Z").getTime();
    var x = setInterval(function () {
        var now = new Date().getTime();
        var distance = countDownDate - now;

        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // Seconds
        if (distance <= 60000) {
            document.getElementById("count1").innerHTML = seconds + "s ";
        }
        // Minutes
        else if (distance <= 3600000) {
            document.getElementById("count1").innerHTML = minutes + "m " + seconds + "s ";
        }
        // Hours
        else if (distance <= 86400000) {
            document.getElementById("count1").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
        }
        // Days
        else if (distance > 86400000) {
            document.getElementById("count1").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
        }

        if (distance < 0) {
            clearInterval(x);
            document.getElementById("count1").innerHTML = "You will be redirected now";
        }
    }, 1000);
</script>

<p id="count1"></p>
</code>```

I changed the milliseconds accordingly, and in your days you had a "$" so i changed that.

I changed the date around and got the effect I think you were going for.

Title: Dynamic JavaScript time counter

Body:
I'm trying to make a dynamic time counter/timer in JavaScript.

Why dynamic? Well I would like to display days/hours/minutes/seconds if the time stamp is bigger enough to display days or hours and so on.

In case the timestamp is less than a day I would like that the script dynamically displays only the hours.

1D 0H 59M 59S
23H 59M 59S
59M 59S
59S
MESSAGE

Here is the code I try to make it work.

I think that my problem is related with math confusion in milliseconds but I can't find out what is wrong.

Body:
These changes made it work for me:

      <center>
<script>

    var countDownDate = new Date("2017-11-17T21:30:30Z").getTime();
    var x = setInterval(function () {
        var now = new Date().getTime();
        var distance = countDownDate - now;

        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // Seconds
        if (distance <= 60000) {
            document.getElementById("count1").innerHTML = seconds + "s ";
        }
        // Minutes
        else if (distance <= 3600000) {
            document.getElementById("count1").innerHTML = minutes + "m " + seconds + "s ";
        }
        // Hours
        else if (distance <= 86400000) {
            document.getElementById("count1").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
        }
        // Days
        else if (distance > 86400000) {
            document.getElementById("count1").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
        }

        if (distance < 0) {
            clearInterval(x);
            document.getElementById("count1").innerHTML = "You will be redirected now";
        }
    }, 1000);
</script>

<p id="count1"></p>

I changed the milliseconds accordingly, and in your days you had a "$" so i changed that.

I changed the date around and got the effect I think you were going for.


来源: stackexchange

问:
Some mouse clicks don't register in Selenium
I've got a rather Javascript-heavy page with lots of contents generated via AJAX or other scripts. On some of these elements Selenium can record mouse clicks, while on others it ignores them. I haven't found any correlation. Perhaps there are some known common scenarios where Selenium cannot intercept mouse clicks?</p>

答:
I'm a 100% selenium noob, but I had the same problem and solved it through the following workaround:

Right-click the to-be-clicked item

Choose a random command that has the entire locator text, e.g. assertText //div[2]/div[5]/table/tbody/tr[1]/td[1]/div IR or something. Look inside "Show all available commands" too.

In the Selenium IDE, change the command to "click" and remove the 2nd argument (the Value field; if any)

Hacky, and should be easily improved with a custom command in the right-click menu, but for now this works fine for me.

ContentLicense: CC BY-SA 2.5


问:
Hide horizontal off-screen overflow of a div that has a large width
How do I hide the horizontal, off-screen overflow of a
 that has a large width set on it? For example:

HTML:

```<code><div class="example">
</div>
</code>```

CSS:

```<code>.example {
  height: 100px;
  width: 10000px;
  background-color: black;
  position: absolute;
  overflow: hidden;
}
</code>```

Here is an example fiddle that shows the scrollbar appearing, I wish for that to not happen if the div is very large like this.

Edit: Adding hidden overflow-x on the parent element does not work on small width iOS devices.

答:
You can set overflow: hidden on the elements container.  In this case it's the body.

```<code>body {
  overflow: hidden;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I hide the horizontal, off-screen overflow of a
 that has a large width set on it? For example:

HTML:

CSS:

.example {
  height: 100px;
  width: 10000px;
  background-color: black;
  position: absolute;
  overflow: hidden;
}

Here is an example fiddle that shows the scrollbar appearing, I wish for that to not happen if the div is very large like this.

Edit: Adding hidden overflow-x on the parent element does not work on small width iOS devices.

Body:
You can set overflow: hidden on the elements container.  In this case it's the body.

body {
  overflow: hidden;
}


问:
Servlet with no answer
Is it possible to create a servlet that let's the browser of the client stay in that particular page, while at the same time changing a value of a session wide variable?

Basically I have a button on my webpage, which is encapsulated in an form that calls an servlet on submit. On that servlet I now want to increase a counter for that session by 1, but I don't want the page of the client to change, in case the user wants to press the button several times.

How can I program the servlet to not send back a response to the user, or if that's not possible, how do I sent a response that basically says: Don't do anything, stay where you are.

I tried simply not sending the response with .forward(), but the browser is then stuck on a blank page. I also tried .setContentType(null), but still nothing. Is this even doable?

答:
Do an AJAX call to that servlet in client's browser using XMLHttpResponse object like var xhr = new XMLHttpResponse()

just google about AJAX request

Title: Servlet with no answer


问:
javascript object variable and method scope problems using navigator.geolocation.watchPosition
I'm trying to move from my old procedural approach to javascript coding to a more object based approach. One of the pieces of code I'm trying to migrate is my location tracker as shown here:

```<code>var gps = new geolocation();

function geolocation() {
  this.watchID;
  this.position;

  this.success = function(p) {
    this.position = p;
  };

  this.failure = function(error) {
    var errmsg;

    // convert the error code to a readable message
    switch(error.code)
    {
        case error.PERMISSION_DENIED:
          errmsg="App doesn't have permission to access your location.";
          break;
        case error.POSITION_UNAVAILABLE:
          errmsg="Your location information is unavailable to App.";
          break;
        case error.TIMEOUT:
          errmsg="App's request to get your location timed out.";
          break;
        case error.UNKNOWN_ERROR:
          errmsg="An unknown GPS error occurred.";
          break;
    }
    console.log(errmsg);
  };

  this.watchPosition = function() {
    if(!this.watchID)
    {
      this.watchID = navigator.geolocation.watchPosition(this.success, this.failure, { maximumAge: 1000, timeout: 15000, enableHighAccuracy: true });
    }
  };

  this.getPosition = function() {
    return(this.position);
  };

  this.clearWatch = function() {
    if(this.watchID)
    {
      // turn off the watch
      navigator.geolocation.clearWatch(this.watchID);
      this.watchID = null;
      console.log("GPS WatchID was cleared.", "GPS Status");
    }
  };
};
</code>```

I can access all the methods in this object. When I start gps.watchPosition(); this.watchID gets set. However, when I use:

```<code>var p = gps.getPosition();
</code>```

I get p as 'undefined' and running through the debugger shows this.position is also undefined.

If I break this code back out to it's procedural state, it works fine. Obviously, I'm missing something but I just can't figure out what.

(note: I did some minimizing of this code before posting)

答:
the answer lies in "this" - as apparently keeping up with the "this" is a bit too complicated for the javascript engineers so inside your object you have to make a copy of "this" and then use the copy to reference items in your object.</p>

```<code>function geolocation() {
  var self = this;
  this.watchID;
  this.position;

  this.success = function(p) {
    self.position = p;
  };
</code>```

Body:
I'm trying to move from my old procedural approach to javascript coding to a more object based approach. One of the pieces of code I'm trying to migrate is my location tracker as shown here:

var gps = new geolocation();

function geolocation() {
  this.watchID;
  this.position;

  this.success = function(p) {
    this.position = p;
  };

  this.failure = function(error) {
    var errmsg;

    // convert the error code to a readable message
    switch(error.code)
    {
        case error.PERMISSION_DENIED:
          errmsg="App doesn't have permission to access your location.";
          break;
        case error.POSITION_UNAVAILABLE:
          errmsg="Your location information is unavailable to App.";
          break;
        case error.TIMEOUT:
          errmsg="App's request to get your location timed out.";
          break;
        case error.UNKNOWN_ERROR:
          errmsg="An unknown GPS error occurred.";
          break;
    }
    console.log(errmsg);
  };

  this.watchPosition = function() {
    if(!this.watchID)
    {
      this.watchID = navigator.geolocation.watchPosition(this.success, this.failure, { maximumAge: 1000, timeout: 15000, enableHighAccuracy: true });
    }
  };

  this.getPosition = function() {
    return(this.position);
  };

  this.clearWatch = function() {
    if(this.watchID)
    {
      // turn off the watch
      navigator.geolocation.clearWatch(this.watchID);
      this.watchID = null;
      console.log("GPS WatchID was cleared.", "GPS Status");
    }
  };
};

I can access all the methods in this object. When I start gps.watchPosition(); this.watchID gets set. However, when I use:

var p = gps.getPosition();

I get p as 'undefined' and running through the debugger shows this.position is also undefined.

If I break this code back out to it's procedural state, it works fine. Obviously, I'm missing something but I just can't figure out what.

(note: I did some minimizing of this code before posting)

Body:
the answer lies in "this" - as apparently keeping up with the "this" is a bit too complicated for the javascript engineers so inside your object you have to make a copy of "this" and then use the copy to reference items in your object.

function geolocation() {
  var self = this;
  this.watchID;
  this.position;

  this.success = function(p) {
    self.position = p;
  };


问:
PHP: javascript alert, with value from sql query, into IF condition
With the following code, a popup table should appear with sql query data, only when retrieved records are greater than 1.

```<code>$sql = "SELECT * FROM pt_locations WHERE country = ('$countryCode') AND location = ('$cityCode')";
$result = $conn->query($sql);

$rowcount=mysqli_num_rows($result);

$message = "Records found: " . $rowcount . "<br /><br />";

if ($rowcount > 1) {

echo '<script language="javascript">';
echo 'alert' .$message;

foreach($result as $val){

$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;

echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
echo '</script>';
}
</code>```

Recording counts are done correctly, but I can not make the popup appear in any way.

答:
There are some errors, because for logic you must put the alert at the end of the table complete, just for logic and after you put alert something without brakets and you open a script before the foreach loop and after the foreach loop you close the script, this is absolutley wrong, another error is in the $message, you are using br inside an alert javascript that isn't recognize as html but just like characters at the least you can use unicode \n\t not br, i used also a setTimeout,but works also without setTimeout.
Sometimes can result essential use javascript injection inside the php for example to autofill of some forms and input select or to call a change event from external compilation of other application that pass variables in get and need to autofill a form, but i think in this case is not necessary do a javascript injection you can print the total Records just in the page, btw...
The code under works
Bye</p>

```<code>        $message = "Records found: " . $rowcount." \\n\t\\n\t";
        if ($rowcount > 1) {

            foreach($result as $val){
                //var_dump($val);
                $id_country = $val["country"] ;
                $id_code = $val["code"] ;
                $id_location = $val["location"] ;
                $id_latitude = $val["latitude"] ;
                $id_longitude = $val["longitude"] ;

                echo "<table border='1' cellpadding='5'>";
                echo "<tr>";
                echo "<td><i><strong>ID Code</strong></i></td><td>";
                echo $id_code."</td>";
                echo "<td><i><strong>Country</strong></i></td><td>";
                echo $id_country."</td>";
                echo "<td><i><strong>Code</strong></i></td><td>";
                echo $code."</td>";
                echo "<td><i><strong>Location</strong></i></td><td>";
                echo $id_location."</td>";
                echo "<td><i><strong>Latitude</strong></i></td><td>";
                echo $id_latitude."</td>";
                echo "<td><i><strong>Longitude</strong></i></td><td>";
                echo $id_longitude."</td>";
                echo "</tr>";
                echo "</table><br /><br />";
            }
            $jvsVar = "<script type='text/javascript'>;setTimeout(function(){alert('$message');},100)</script>";
        echo $jvsVar;
        }
</code>```

Body:
With the following code, a popup table should appear with sql query data, only when retrieved records are greater than 1.

$sql = "SELECT * FROM pt_locations WHERE country = ('$countryCode') AND location = ('$cityCode')";
$result = $conn->query($sql);

$rowcount=mysqli_num_rows($result);

$message = "Records found: " . $rowcount . "

";

if ($rowcount > 1) {

echo '';
}

Recording counts are done correctly, but I can not make the popup appear in any way.

Body:
There are some errors, because for logic you must put the alert at the end of the table complete, just for logic and after you put alert something without brakets and you open a script before the foreach loop and after the foreach loop you close the script, this is absolutley wrong, another error is in the $message, you are using br inside an alert javascript that isn't recognize as html but just like characters at the least you can use unicode \n\t not br, i used also a setTimeout,but works also without setTimeout.
Sometimes can result essential use javascript injection inside the php for example to autofill of some forms and input select or to call a change event from external compilation of other application that pass variables in get and need to autofill a form, but i think in this case is not necessary do a javascript injection you can print the total Records just in the page, btw...
The code under works
Bye

        $message = "Records found: " . $rowcount." \\n\t\\n\t";
        if ($rowcount > 1) {

            foreach($result as $val){
                //var_dump($val);
                $id_country = $val["country"] ;
                $id_code = $val["code"] ;
                $id_location = $val["location"] ;
                $id_latitude = $val["latitude"] ;
                $id_longitude = $val["longitude"] ;

                echo "<table border='1' cellpadding='5'>";
                echo "<tr>";
                echo "<td><i><strong>ID Code</strong></i></td><td>";
                echo $id_code."</td>";
                echo "<td><i><strong>Country</strong></i></td><td>";
                echo $id_country."</td>";
                echo "<td><i><strong>Code</strong></i></td><td>";
                echo $code."</td>";
                echo "<td><i><strong>Location</strong></i></td><td>";
                echo $id_location."</td>";
                echo "<td><i><strong>Latitude</strong></i></td><td>";
                echo $id_latitude."</td>";
                echo "<td><i><strong>Longitude</strong></i></td><td>";
                echo $id_longitude."</td>";
                echo "</tr>";
                echo "</table><br /><br />";
            }
            $jvsVar = "<script type='text/javascript'>;setTimeout(function(){alert('$message');},100)</script>";
        echo $jvsVar;
        }


问:
Resetting the state of flex and/or bison
As part of a toy project I've been trying to make a small modification of someone else's parser based on flex/bison. I'm really not experienced with either. You can find the original parser here.

I've been trying to put together a simple function that accepts a string and returns a parse tree, so I can expose this via FFI for use in another programming language. What I have is mostly based on the main() function in the original program, my butchered version is below:

```<code>TreeNode* parse_string(char *s)
{
    FILE *in = fmemopen(s, strlen(s), "r");
    lex2_initialise();
    parse_file(in);
    fclose(in);
    preprocess_tokens();
    yyparse();
    return top;
}
</code>```

This actually works fine, at least the first time I call it. The second time it complains about misparsed tokens, and the error reporting function used appears to be called from somewhere inside a maze of goto statements within the generated parser during the call to yyparse(), at which point I don't understand what's going on anymore.

The original program itself only appears to be designed to take all its input upfront and then exit, so it doesn't leave me with much clue of what I'm missing. Putting aside the not-altogether-outlandish idea some old state is being retained elsewhere in the rest of the program, my main questions are:

Do either Flex or Bison maintain global state between calls to yyparse()

Is there some simple function call I could put at the end of the function above to wipe it all and reset everything back to the initial state?

答:
Even if you are using a non-reentrant parser, you can use yylex_destroy (without arguments) after lexing to force an initialisation, the next time the the lexer is invoked:

extern int yylex_destroy(void);
...
// do parsing here
...
yylex_destroy()
```

For reentrant parsers see here.

Body:
As part of a toy project I've been trying to make a small modification of someone else's parser based on flex/bison. I'm really not experienced with either. You can find the original parser here.

I've been trying to put together a simple function that accepts a string and returns a parse tree, so I can expose this via FFI for use in another programming language. What I have is mostly based on the main() function in the original program, my butchered version is below:

TreeNode* parse_string(char *s)
{
    FILE *in = fmemopen(s, strlen(s), "r");
    lex2_initialise();
    parse_file(in);
    fclose(in);
    preprocess_tokens();
    yyparse();
    return top;
}

This actually works fine, at least the first time I call it. The second time it complains about misparsed tokens, and the error reporting function used appears to be called from somewhere inside a maze of goto statements within the generated parser during the call to yyparse(), at which point I don't understand what's going on anymore.

The original program itself only appears to be designed to take all its input upfront and then exit, so it doesn't leave me with much clue of what I'm missing. Putting aside the not-altogether-outlandish idea some old state is being retained elsewhere in the rest of the program, my main questions are:

Do either Flex or Bison maintain global state between calls to yyparse()

Is there some simple function call I could put at the end of the function above to wipe it all and reset everything back to the initial state?

Body:
Even if you are using a non-reentrant parser, you can use yylex_destroy (without arguments) after lexing to force an initialisation, the next time the the lexer is invoked:

extern int yylex_destroy(void);
...
// do parsing here
...
yylex_destroy()

For reentrant parsers see here.


问:
Pass data to TabBar Controller
I want pass data between two ViewControllers throw the TabBarController.
Inside the first ViewController I located textField and button.
Inside the second I located Label.
When I write some text in textField and push button, I expect that this text appear in the Label in the second ViewController. But nothing happens.

And my code:

First ViewController:

```<code>import UIKit

class FirstViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    @IBAction func enter(_ sender: Any) {
        if textField.text != "" {
            if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController, let second = tabBarController.viewControllers?.first as? SecondViewController {
                second.label.text = textField.text
                tabBarController.selectedIndex = 0
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

Second ViewController:

```<code>import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    var myString = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = myString
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

答:
I think the problem is in

```<code>tabBarController.viewControllers?.first as? SecondViewController
</code>```

You probably want to do this instead:

```<code>tabBarController.viewControllers?[1] as? SecondViewController
</code>```

Don't forget arrays are indexed from 0, so viewControllers?[1] actually returns the second element in the array.

Title: Pass data to TabBar Controller

Body:
I want pass data between two ViewControllers throw the TabBarController.
Inside the first ViewController I located textField and button.
Inside the second I located Label.
When I write some text in textField and push button, I expect that this text appear in the Label in the second ViewController. But nothing happens.

And my code:

First ViewController:

import UIKit

class FirstViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    @IBAction func enter(_ sender: Any) {
        if textField.text != "" {
            if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController, let second = tabBarController.viewControllers?.first as? SecondViewController {
                second.label.text = textField.text
                tabBarController.selectedIndex = 0
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Second ViewController:

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    var myString = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = myString
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Body:
I think the problem is in

tabBarController.viewControllers?.first as? SecondViewController

You probably want to do this instead:

tabBarController.viewControllers?[1] as? SecondViewController

Don't forget arrays are indexed from 0, so viewControllers?[1] actually returns the second element in the array.


问:
Move file that is in use
I have this problem: I process a file and after I need to move into another folder:
actually I do this:

```<code>FileInfo file = new FileInfo(BW_FullPathPhoto);
file.MoveTo(sFolderCopy + "\\" + System.IO.Path.GetFileName(BW_FullPathPhoto));
</code>```

but sometimes give me the error that the file is current in use and is not able to move...

I know that if I rename a file that is in use, windows let me do this... it's possible rename a file without moving (I think that a move performs a copy and after a deletion)

答:
```<code>public static class Pathy
{
  internal enum MoveFileFlags
  {
    MOVEFILE_REPLACE_EXISTING = 0x1
    , MOVEFILE_COPY_ALLOWED = 0x02
    , MOVEFILE_DELAY_UNTIL_REBOOT = 0x04
    , MOVEFILE_CREATE_HARDLINK = 0x10
    , MOVEFILE_WRITE_THROUGH = 0x8
    , MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20
  }
  [System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "MoveFileEx")]
  internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);

  public bool MoveOrReboot(FileInfo fi, DirectoryInfo di)
  {
    fi?.Refresh();
    if (!(di?.Exists ?? false)) throw new DirectoryNotFoundException(di.FullName);
    if (fi?.Exists ?? false)
    {
      try
      {
        fi.MoveTo(di.FullName + System.IO.Path.DirectorySeparatorChar + fi.Name);
        return true;
      }
      catch (IOException e)
      {
        switch (e.HResult)
        {
          case -2147024864:  //equivalent 'file in use' error
            if (MoveFileEx(fi.FullName, di.FullName + System.IO.Path.DirectorySeparatorChar + fi.Name, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT))
            {
              return false;
            }
            break;

          default:
            throw e;
        }
      }
      catch (Exception e)
      {
        throw e;
      }
    }
    else throw new FileNotFoundException(fi.FullName);
  }
}
</code>```

EDIT: Placed the function into a class and added a return value to gate whether the OS needs to be rebooted or not.

Usage:

```<code>try
{
  if (!Pathy.MoveOrReboot(fi,di)) reboot_needed = true;
}
catch (Exception e)
{
  //...
}
</code>```

Title: Move file that is in use

Body:
I have this problem: I process a file and after I need to move into another folder:
actually I do this:

FileInfo file = new FileInfo(BW_FullPathPhoto);
file.MoveTo(sFolderCopy + "\\" + System.IO.Path.GetFileName(BW_FullPathPhoto));

but sometimes give me the error that the file is current in use and is not able to move...

I know that if I rename a file that is in use, windows let me do this... it's possible rename a file without moving (I think that a move performs a copy and after a deletion)

Body:
public static class Pathy
{
  internal enum MoveFileFlags
  {
    MOVEFILE_REPLACE_EXISTING = 0x1
    , MOVEFILE_COPY_ALLOWED = 0x02
    , MOVEFILE_DELAY_UNTIL_REBOOT = 0x04
    , MOVEFILE_CREATE_HARDLINK = 0x10
    , MOVEFILE_WRITE_THROUGH = 0x8
    , MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20
  }
  [System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "MoveFileEx")]
  internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);

  public bool MoveOrReboot(FileInfo fi, DirectoryInfo di)
  {
    fi?.Refresh();
    if (!(di?.Exists ?? false)) throw new DirectoryNotFoundException(di.FullName);
    if (fi?.Exists ?? false)
    {
      try
      {
        fi.MoveTo(di.FullName + System.IO.Path.DirectorySeparatorChar + fi.Name);
        return true;
      }
      catch (IOException e)
      {
        switch (e.HResult)
        {
          case -2147024864:  //equivalent 'file in use' error
            if (MoveFileEx(fi.FullName, di.FullName + System.IO.Path.DirectorySeparatorChar + fi.Name, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT))
            {
              return false;
            }
            break;

          default:
            throw e;
        }
      }
      catch (Exception e)
      {
        throw e;
      }
    }
    else throw new FileNotFoundException(fi.FullName);
  }
}

EDIT: Placed the function into a class and added a return value to gate whether the OS needs to be rebooted or not.

Usage:

try
{
  if (!Pathy.MoveOrReboot(fi,di)) reboot_needed = true;
}
catch (Exception e)
{
  //...
}


问:
Generate all combinations from multiple lists
Given an unknown amount of lists, each with an unknown length, I need to generate a singular list with all possible unique combinations.
For example, given the following lists:

```<code>X: [A, B, C]
Y: [W, X, Y, Z]
</code>```

Then I should be able to generate 12 combinations:

```<code>[AW, AX, AY, AZ, BW, BX, BY, BZ, CW, CX, CY, CZ]
</code>```

If a third list of 3 elements were added, I'd have 36 combinations, and so forth.

Any ideas on how I can do this in Java?

(pseudo code would be fine too)

答:
Here is a sample using bit mask. No recursion and multiple lists</p>

```<code>static List<Integer> allComboMatch(List<Integer> numbers, int target) {
    int sz = (int)Math.pow(2, numbers.size());
    for (int i = 1; i < sz; i++) {
        int sum = 0;
        ArrayList<Integer> result = new ArrayList<Integer>();
        for (int j = 0; j < numbers.size(); j++) {
            int x = (i >> j) & 1;
            if (x == 1) {
                sum += numbers.get(j);
                result.add(j);
            }
        }
        if (sum == target) {
            return result;
        }
    }
    return null;
}
</code>```

Body:
Given an unknown amount of lists, each with an unknown length, I need to generate a singular list with all possible unique combinations.
For example, given the following lists:

X: [A, B, C]
Y: [W, X, Y, Z]

Then I should be able to generate 12 combinations:

[AW, AX, AY, AZ, BW, BX, BY, BZ, CW, CX, CY, CZ]

If a third list of 3 elements were added, I'd have 36 combinations, and so forth.

Any ideas on how I can do this in Java?

(pseudo code would be fine too)

Body:
Here is a sample using bit mask. No recursion and multiple lists

static List<Integer> allComboMatch(List<Integer> numbers, int target) {
    int sz = (int)Math.pow(2, numbers.size());
    for (int i = 1; i < sz; i++) {
        int sum = 0;
        ArrayList<Integer> result = new ArrayList<Integer>();
        for (int j = 0; j < numbers.size(); j++) {
            int x = (i >> j) & 1;
            if (x == 1) {
                sum += numbers.get(j);
                result.add(j);
            }
        }
        if (sum == target) {
            return result;
        }
    }
    return null;
}


问:
Error: [$controller:ctrlreg] The controller with the name 'ToDoCtrl' is not registered
I have a page like this using AngularJS 1.6.6:

```<code><!DOCTYPE html>
<html ng-app lang="en">
  <head>
    <title>AngularJS Test Page</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="angular.js"></script>
    <script src="app.js"></script>
    <link rel="stylesheet" href="bootstrap.css"/>
    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>
  </head>
  <body ng-controller="ToDoCtrl">
    <div class="page-header">
      <h1>{{todo.user}}'s To-Do List</h1>
    </div>

    <!-- Rest omitted for brevity -->
  </body>
</html>
</code>```

app.js is literally nothing more than the following:

```<code>var model = {
  user: 'Adam',
  items: [{ action: 'Buy Flowers', done: false },
          { action: 'Get Shoes', done: false },
          { action: 'Collect Tickets', done: true },
          { action: 'Call Joe', done: false }]
};

var todoApp = angular.module('todoApp', []);

angular.module('todoApp').controller('ToDoCtrl', function ($scope) {
  $scope.todo = model;
});
</code>```

Without fail I get the following error on the console:

```<code>Error: [$controller:ctrlreg] The controller with the name 'ToDoCtrl' is not registered.
</code>```

...despite very obviously having registered the controller. Not a good start for my AngularJS journey. If you want full code, you can get it here:

https://github.com/readyready15728/infernal-angularjs

Please don't request a fiddle or the like; I'm obviously not in the position to set one up for AngularJS yet.

答:
First of all i recommend to read angular-styleguide.

If you have a design pattern you won't get an error like this. So you can use your code like:

```<code><!DOCTYPE html>
<html ng-app="app" lang="en">
  <head>
    <title>AngularJS Test Page</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="bootstrap.css"/>
  </head>
  <body ng-controller="TodoController">
    <div class="page-header">
      <h1>{{vm.todo.user}}'s To-Do List</h1>
    </div>
    <script src="angular.js"></script>
    <script src="app.module.js"></script>
    <script src="todo.controller.js"></script>

    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>
    <!-- Rest omitted for brevity -->
  </body>
</html>
</code>```

app.module.js

```<code>(function() {
    'use strict';

    angular
        .module('app', []);
})();
</code>```

todo.controller.js

```<code>(function() {
    'use strict';
    angular
        .module('app')
        .controller('TodoController', TodoController);

    function TodoController($scope) {
        var vm = this;
        vm.todo = {
                      user: 'Adam',
                      items: [{ action: 'Buy Flowers', done: false },
                              { action: 'Get Shoes', done: false },
                              { action: 'Collect Tickets', done: true },
                              { action: 'Call Joe', done: false }]};
    }

})();
</code>```

Body:
I have a page like this using AngularJS 1.6.6:

<!DOCTYPE html>

    <title>AngularJS Test Page</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="bootstrap.css"/>

{{todo.user}}'s To-Do List

app.js is literally nothing more than the following:

var model = {
  user: 'Adam',
  items: [{ action: 'Buy Flowers', done: false },
          { action: 'Get Shoes', done: false },
          { action: 'Collect Tickets', done: true },
          { action: 'Call Joe', done: false }]
};

var todoApp = angular.module('todoApp', []);

angular.module('todoApp').controller('ToDoCtrl', function ($scope) {
  $scope.todo = model;
});

Without fail I get the following error on the console:

Error: [$controller:ctrlreg] The controller with the name 'ToDoCtrl' is not registered.

...despite very obviously having registered the controller. Not a good start for my AngularJS journey. If you want full code, you can get it here:

https://github.com/readyready15728/infernal-angularjs

Please don't request a fiddle or the like; I'm obviously not in the position to set one up for AngularJS yet.

Body:
First of all i recommend to read angular-styleguide.

If you have a design pattern you won't get an error like this. So you can use your code like:

<!DOCTYPE html>
<html ng-app="app" lang="en">
  <head>
    <title>AngularJS Test Page</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="bootstrap.css"/>
  </head>
  <body ng-controller="TodoController">
    <div class="page-header">
      <h1>{{vm.todo.user}}'s To-Do List</h1>
    </div>
    <script src="angular.js"></script>
    <script src="app.module.js"></script>
    <script src="todo.controller.js"></script>

    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>
    <!-- Rest omitted for brevity -->
  </body>
</html>

app.module.js

(function() {
    'use strict';

    angular
        .module('app', []);
})();

todo.controller.js

(function() {
    'use strict';
    angular
        .module('app')
        .controller('TodoController', TodoController);

    function TodoController($scope) {
        var vm = this;
        vm.todo = {
                      user: 'Adam',
                      items: [{ action: 'Buy Flowers', done: false },
                              { action: 'Get Shoes', done: false },
                              { action: 'Collect Tickets', done: true },
                              { action: 'Call Joe', done: false }]};
    }

})();


问:
Implement Twitter timeline partway through View Controller?
I'm using Twitter Kit and am trying to implement the timeline partway through the main View Controller like so.

Twitter Timeline plus Scroll View 1

Twitter Timeline plus Scrol View 2

Essentially have a scroll view and underneath that the Twitter timeline.
I have the code for the timeline as a separate view, but I'm having trouble implementing it alongside another class.

```<code>let client = TWTRAPIClient()
    self.dataSource = TWTRListTimelineDataSource(listSlug: "surfing", listOwnerScreenName: "stevenhepting", apiClient: client)
</code>```

Edit from comments: I tried implementing the Twitter timeline as a table view object within the View Controller, which didn't work. I'm guessing that is not permitted within TWTRTimelineViewController.

答:
Lets say we have a regular viewcontroller which contains both the tweet section and the other stuff, now you can make your UI but instead of the timeline part you add an UIContainerView (drag it in in storyboard) and make the embedded viewcontroller the TWTRTimelineViewController.

This way you can use the standard viewcontroller and still have it embedded somewhere.

I hope I understood your problem well.

Body:
I'm using Twitter Kit and am trying to implement the timeline partway through the main View Controller like so.

Twitter Timeline plus Scroll View 1

Twitter Timeline plus Scrol View 2

Essentially have a scroll view and underneath that the Twitter timeline.
I have the code for the timeline as a separate view, but I'm having trouble implementing it alongside another class.

let client = TWTRAPIClient()
    self.dataSource = TWTRListTimelineDataSource(listSlug: "surfing", listOwnerScreenName: "stevenhepting", apiClient: client)

Edit from comments: I tried implementing the Twitter timeline as a table view object within the View Controller, which didn't work. I'm guessing that is not permitted within TWTRTimelineViewController.


问:
font-awesome icons not showing up in Chrome 61
I've downloaded font-awesome icons in my project and imported font-awesome.min.css as

```<code><link rel="stylesheet" href="resources/font-awesome/css/font-awesome.min.css">
</code>```

And used them simply like

```<code><i class="fa fa-user-o" aria-hidden="true"></i>
</code>```

The stylesheet was loaded so there was no problem with the path.

The icons worked fine in Firefox, but didn't show up in Chrome 61 at all,  neither in Win 10 nor Linux, so I guess it has nothing to do with OS.

I don't have any plugin in Chrome that would be conflicting.

I've also tried <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> but nothing changed.

Does anyone know what might cause this problem? Thanks!

答:
If you have any kind of AdBlock turned on, you need to disable it first.
I also have the same problem that font-awesome icons appear in Firefox but not in Chrome, and I figured out that my Chrome AdBlock blocked it.</p>

Body:
I've downloaded font-awesome icons in my project and imported font-awesome.min.css as

<link rel="stylesheet" href="resources/font-awesome/css/font-awesome.min.css">

And used them simply like

The stylesheet was loaded so there was no problem with the path.

The icons worked fine in Firefox, but didn't show up in Chrome 61 at all,  neither in Win 10 nor Linux, so I guess it has nothing to do with OS.

I don't have any plugin in Chrome that would be conflicting.

I've also tried <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> but nothing changed.

Does anyone know what might cause this problem? Thanks!


问:
C# JsonConverter JSONArray to string w/ separator and back
I want to implement a custom JsonConverter to use as such,

```<code>    [JsonConverter(typeof(ArrayString))]
    public string ServiceCodes { get; set; }
</code>```

The purpose is to convert a JSON array to a string with separators, e.g.,
["this", "is", "my", "json", "array"] should become "this;is;my;json;array" (or whatever separator).  Likewise, the reverse should be possible.

I struggle to understand overriding the WriteJson method of JsonConverter.

To provide some context, I ServiceCodes is a property on an Entity (I'm using EF6).  I think it's easier to do what I'm asking for my case than other one to many implementations.  One question I have, however, is when is the JsonConverter called?

I only want the the get to give json when the getter desires json, namely, when the object which contains this property is being return as JSON from my API.  I don't want this converter to called when I'm writing LINQ, for example.

Any help would be appreciated, thank you.

EDIT - info added

Here's the class and some moc data.

```<code>    [ComplexType]
    public class TerminalDuties
    {
        public string TerminalCode { get; set; }

        public string TransportationCode { get; set; }

        [JsonConverter(typeof(ArrayString))]
        public string ServiceCodes { get; set; }
    }
</code>```

"Origin": {
    "TerminalCode": "MIA",
    "TransportationCode": "GT",
    "ServiceCodes": ["WH", "HL"]
}

I tried @felix-b's answer, but it was not mapping.  The object was null.  I had breakpoints in the ArrayString class but they were not hit.  Presumably it did not try to map because the property is a string.  What is the workaround?

Here's how it's exposed in my Web API Controller (inherits from ApiController)

```<code>    [HttpPost]
    public void DoStuff([FromBody]Thing t)
    {
        someMngr.Add(t);
    }

    public class Thing : ParentClass
    {
        properties...
        public TerminalDuties Origin { get; set; }
    }
</code>```

答:
Tested with .NET Framework 4.6.1, ASP.NET Web API 2, Entity Framework 6.1.3, Newtonsoft.Json 10.0.3.

UPDATE

My answer originally required [JsonConverter(typeof(ArrayString), ';')] to be specified, as opposed to [JsonConverter(typeof(ArrayString))] in the question.

I added default constructor to the converter class, so that delimiter configuration is optional, and semicolon will be used if not specified. Now [JsonConverter(typeof(ArrayString))] works either.

ORIGINAL ANSWER

The converter will only be invoked during serialization and deserialization of your entity through JSON.NET. It doesn't influence getting or setting property value from code, neither LINQ queries and DB operations.

Here is converter implementation:

```<code>public class ArrayString : JsonConverter
{
    private readonly char _delimiter;

    // UPDATE -- added default constructor, so that
    // JsonConverter attribute can be specified without the
    // delimiter parameter, in which case semicolon will be used
    public ArrayString() : this(';')
    {
    }

    public ArrayString(char delimiter)
    {
        _delimiter = delimiter;
    }

    public override bool CanRead => true;
    public override bool CanWrite => true;

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType != JsonToken.StartArray)
        {
            return null;
        }

        var stringValue = new StringBuilder();

        while (reader.Read() && reader.TokenType == JsonToken.String)
        {
            if (stringValue.Length > 0)
            {
                stringValue.Append(_delimiter);
            }
            stringValue.Append((string)reader.Value);
        }

        return stringValue.ToString();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var stringValue = value?.ToString();

        if (stringValue == null)
        {
            writer.WriteNull();
            return;
        }

        var arrayValue = stringValue.Split(_delimiter);

        writer.WriteStartArray();

        foreach (var item in arrayValue)
        {
            writer.WriteValue(item);
        }

        writer.WriteEndArray();
    }
}
</code>```

Here is how you can specify a delimiter character (semicolon in this example):

```<code>[JsonConverter(typeof(ArrayString), ';')]
public string ServiceCodes { get; set; }
</code>```

Body:
I want to implement a custom JsonConverter to use as such,

    [JsonConverter(typeof(ArrayString))]
    public string ServiceCodes { get; set; }

The purpose is to convert a JSON array to a string with separators, e.g.,
["this", "is", "my", "json", "array"] should become "this;is;my;json;array" (or whatever separator).  Likewise, the reverse should be possible.

I struggle to understand overriding the WriteJson method of JsonConverter.

To provide some context, I ServiceCodes is a property on an Entity (I'm using EF6).  I think it's easier to do what I'm asking for my case than other one to many implementations.  One question I have, however, is when is the JsonConverter called?

I only want the the get to give json when the getter desires json, namely, when the object which contains this property is being return as JSON from my API.  I don't want this converter to called when I'm writing LINQ, for example.

Any help would be appreciated, thank you.

EDIT - info added

Here's the class and some moc data.

    [ComplexType]
    public class TerminalDuties
    {
        public string TerminalCode { get; set; }

        public string TransportationCode { get; set; }

        [JsonConverter(typeof(ArrayString))]
        public string ServiceCodes { get; set; }
    }

"Origin": {
    "TerminalCode": "MIA",
    "TransportationCode": "GT",
    "ServiceCodes": ["WH", "HL"]
}

I tried @felix-b's answer, but it was not mapping.  The object was null.  I had breakpoints in the ArrayString class but they were not hit.  Presumably it did not try to map because the property is a string.  What is the workaround?

Here's how it's exposed in my Web API Controller (inherits from ApiController)

    [HttpPost]
    public void DoStuff([FromBody]Thing t)
    {
        someMngr.Add(t);
    }

    public class Thing : ParentClass
    {
        properties...
        public TerminalDuties Origin { get; set; }
    }

Body:
Tested with .NET Framework 4.6.1, ASP.NET Web API 2, Entity Framework 6.1.3, Newtonsoft.Json 10.0.3.

UPDATE

My answer originally required [JsonConverter(typeof(ArrayString), ';')] to be specified, as opposed to [JsonConverter(typeof(ArrayString))] in the question.

I added default constructor to the converter class, so that delimiter configuration is optional, and semicolon will be used if not specified. Now [JsonConverter(typeof(ArrayString))] works either.

ORIGINAL ANSWER

The converter will only be invoked during serialization and deserialization of your entity through JSON.NET. It doesn't influence getting or setting property value from code, neither LINQ queries and DB operations.

Here is converter implementation:

public class ArrayString : JsonConverter
{
    private readonly char _delimiter;

    // UPDATE -- added default constructor, so that
    // JsonConverter attribute can be specified without the
    // delimiter parameter, in which case semicolon will be used
    public ArrayString() : this(';')
    {
    }

    public ArrayString(char delimiter)
    {
        _delimiter = delimiter;
    }

    public override bool CanRead => true;
    public override bool CanWrite => true;

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType != JsonToken.StartArray)
        {
            return null;
        }

        var stringValue = new StringBuilder();

        while (reader.Read() && reader.TokenType == JsonToken.String)
        {
            if (stringValue.Length > 0)
            {
                stringValue.Append(_delimiter);
            }
            stringValue.Append((string)reader.Value);
        }

        return stringValue.ToString();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var stringValue = value?.ToString();

        if (stringValue == null)
        {
            writer.WriteNull();
            return;
        }

        var arrayValue = stringValue.Split(_delimiter);

        writer.WriteStartArray();

        foreach (var item in arrayValue)
        {
            writer.WriteValue(item);
        }

        writer.WriteEndArray();
    }
}

Here is how you can specify a delimiter character (semicolon in this example):

[JsonConverter(typeof(ArrayString), ';')]
public string ServiceCodes { get; set; }


问:
Golang: calculate diff between two array of bytes and patch an array
I'm trying to find the difference between two byte ararys and store the delta.

I've read this documentation https://golang.org/pkg/bytes/ but I didn't find anything that show how to find the diff.

Thanks.

答:
Sounds like you just want a function which takes two byte slices and returns a new slice containing the difference of each element in the input slice. The example function below asserts that the input slices are both non-nil and have the same length. It also returns a slice of int16s since the range of difference in bytes is [-255,255].

```<code>package main

import "fmt"

func main() {
  bs1 := []byte{0, 2, 255, 0}
  bs2 := []byte{0, 1, 0, 255}
  delta, err := byteDiff(bs1, bs2)
  if err != nil {
    panic(err)
  }
  fmt.Printf("OK: delta=%v\n", delta)
  // OK: delta=[0 1 255 -255]
}

func byteDiff(bs1, bs2 []byte) ([]int16, error) {
  // Ensure that we have two non-nil slices with the same length.
  if (bs1 == nil) || (bs2 == nil) {
    return nil, fmt.Errorf("expected a byte slice but got nil")
  }
  if len(bs1) != len(bs2) {
    return nil, fmt.Errorf("mismatched lengths, %d != %d", len(bs1), len(bs2))
  }

  // Populate and return the difference between the two.
  diff := make([]int16, len(bs1))
  for i := range bs1 {
    diff[i] = int16(bs1[i]) - int16(bs2[i])
  }
  return diff, nil
}
</code>```

Body:
Sounds like you just want a function which takes two byte slices and returns a new slice containing the difference of each element in the input slice. The example function below asserts that the input slices are both non-nil and have the same length. It also returns a slice of int16s since the range of difference in bytes is [-255,255].

package main

import "fmt"

func main() {
  bs1 := []byte{0, 2, 255, 0}
  bs2 := []byte{0, 1, 0, 255}
  delta, err := byteDiff(bs1, bs2)
  if err != nil {
    panic(err)
  }
  fmt.Printf("OK: delta=%v\n", delta)
  // OK: delta=[0 1 255 -255]
}

func byteDiff(bs1, bs2 []byte) ([]int16, error) {
  // Ensure that we have two non-nil slices with the same length.
  if (bs1 == nil) || (bs2 == nil) {
    return nil, fmt.Errorf("expected a byte slice but got nil")
  }
  if len(bs1) != len(bs2) {
    return nil, fmt.Errorf("mismatched lengths, %d != %d", len(bs1), len(bs2))
  }

  // Populate and return the difference between the two.
  diff := make([]int16, len(bs1))
  for i := range bs1 {
    diff[i] = int16(bs1[i]) - int16(bs2[i])
  }
  return diff, nil
}


问:
How can I compare rows for multiple columns if they are identical
I have one pandas DataFrame and I want to check the rows are identical. This shall work for 3 columns out of the dataframe.

```<code>A B C ...
1 1 1 ...
1 2 3 ...
1 4 4 ...
</code>```

This should bring up a mask with

```<code>True
False
False
</code>```

答:
Or you can use nunique

```<code>df.nunique(1).eq(1)
Out[1155]:
0     True
1    False
2    False
dtype: bool
</code>```

Body:
I have one pandas DataFrame and I want to check the rows are identical. This shall work for 3 columns out of the dataframe.

A B C ...
1 1 1 ...
1 2 3 ...
1 4 4 ...

This should bring up a mask with

True
False
False

Body:
Or you can use nunique

df.nunique(1).eq(1)
Out[1155]:
0     True
1    False
2    False
dtype: bool


问:
If username is set and password is not, display me an error message
```<code>    <div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="username" required />
<input type="password" name="password" placeholder="password" required />
<input name="submit" type="submit" value="Login" />
</form>

<?php
      if (isset($_POST['username']) && !isset($_POST['password']))  {
    echo "Please enter your password.";
}?>
</code>```

I just want to display an error message IF username IS set and password field is not filled with any character after click on "submit", this is how I tried but now working for me.

答:
Below your form enter the following:

```<code>if ((isset($_POST['username'])) == true && (isset($_POST['password'])) == false ){
   echo "please enter your password";
}
</code>```

This means that if the username is set and the password is NOT set it will display the error message of: "please enter you password".
You can change this and use it as a template:

```<code>if ((isset($_POST['value'])) == true && (isset($_POST['value2'])) == false{
   echo "error message!";
}
</code>```

Body:
Log In

<form action="" method="post" name="login">
<input type="text" name="username" placeholder="username" required />
<input type="password" name="password" placeholder="password" required />
<input name="submit" type="submit" value="Login" />
</form>

<?php
      if (isset($_POST['username']) && !isset($_POST['password']))  {
    echo "Please enter your password.";
}?>

I just want to display an error message IF username IS set and password field is not filled with any character after click on "submit", this is how I tried but now working for me.

Body:
Below your form enter the following:

if ((isset($_POST['username'])) == true && (isset($_POST['password'])) == false ){
   echo "please enter your password";
}

This means that if the username is set and the password is NOT set it will display the error message of: "please enter you password".
You can change this and use it as a template:

if ((isset($_POST['value'])) == true && (isset($_POST['value2'])) == false{
   echo "error message!";
}


问:
Transactional wrapped method doesn't persist or remove
I have a problem with a CDI Named Bean which is @Transactional.

I use the WildFly 11.1.0.Final.

Here the Code: https://gist.github.com/stefanwendelmann/7a1f8352900067d5a59826d6ee205044

This is the persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="QuoLoco" transaction-type="JTA">
    <description>Verbindung zur QuoLoco Datenbank</description>
    <jta-data-source>java:/QUOLOCO_NORM</jta-data-source>
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <properties>
      <property name="hibernate.format_sql" value="false"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
      <property name="hibernate.id.new_generator_mappings" value="false"/>
    </properties>
  </persistence-unit>
</persistence>
</code>```

When I call the method "doChange" and only edited Empfangseinheittypenparameter, the em.remove and em.persist doesn't trigger a flush.

When I call the method "doChange" and edited some of the main  Empfangseinheittypen empfangseinheittyp, I make a find on the Empfangseinheittypenparameter don't need a flush

What am a doing wrong?

Both methods are public.

Please see a picture of the Application attached

Thanks in advance for your help

答:
According to the comments, doChange is called from the same bean.
The problem is similar to @Transactional method called from another method doesn't obtain a transaction which means, that the transaction will not end with doChange, so you can not expect a flush to be done when returning from the method.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with a CDI Named Bean which is @Transactional.

I use the WildFly 11.1.0.Final.

Here the Code: https://gist.github.com/stefanwendelmann/7a1f8352900067d5a59826d6ee205044

This is the persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="QuoLoco" transaction-type="JTA">
    <description>Verbindung zur QuoLoco Datenbank</description>
    <jta-data-source>java:/QUOLOCO_NORM</jta-data-source>
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <properties>
      <property name="hibernate.format_sql" value="false"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
      <property name="hibernate.id.new_generator_mappings" value="false"/>
    </properties>
  </persistence-unit>
</persistence>

When I call the method "doChange" and only edited Empfangseinheittypenparameter, the em.remove and em.persist doesn't trigger a flush.

When I call the method "doChange" and edited some of the main  Empfangseinheittypen empfangseinheittyp, I make a find on the Empfangseinheittypenparameter don't need a flush

What am a doing wrong?

Both methods are public.

Please see a picture of the Application attached

Thanks in advance for your help


问:
Delete all files being ignored within a Subversion checkout
How can I delete all files that are being ignored within a Subversion checkout?  Effectively to bring it back to the equivalent of a pristine checkout.</p>

答:
karoberts' solution doesn't work on Mac OS X (Snow Leopard). Neither does another command I found on a blog

I get

xargs: illegal option -- i

and

xargs: illegal option -- d

respectively.

This works on Mac (adapted from karoberts'):

```<code>svn status | awk '$1=="?"||$1=="I" { print $2 }' | xargs rm -rf
</code>```

Body:
karoberts' solution doesn't work on Mac OS X (Snow Leopard). Neither does another command I found on a blog

I get

xargs: illegal option -- i

and

xargs: illegal option -- d

respectively.

This works on Mac (adapted from karoberts'):

svn status | awk '$1=="?"||$1=="I" { print $2 }' | xargs rm -rf


问:
How to reset iPhone simulator
My app uses the location service. To test what is happening when the user presses 'Don't allow' when the simulator asks for the permission to access the location service (when the app is started for the first time) I need to reset the simulator. This because the question was answered at the beginning of the development process with allow. So no more questions are asked.

Resetting the Simulator with "Resetting Content and Settings.." don't bring back the question at the start. What I am doing wrong?

答:
I tried "Erase All Content and Settings" in Simulator 10.0, but it didn't work. What worked for me is that in Simulator 10.0, the Settings app is built in. You can reset by:

Clicking on the Settings app to start it.

Click General.

Click Reset.

Click Reset Location & Privacy.

Click Reset Warnings.

Then your authorization status will be reset to .notDetermined.

Title: How to reset iPhone simulator


问:
Is it possible to mix Java 8 and Java 9 source code in the same project without using compiler flags?
In Java 9, you can optionally package a source directory as a module by adding a module-info.java, which defines the things packages that it exports, and which other modules it depends on.

Once you do that, however, you must list ALL dependencies in the module descriptor - and the dependencies must all themselves be modules. Therefore, by extension, if you modularize a single source directory, you must modularize every single source directory company wide.

Furthermore, you cannot define modules in Java 8 or earlier, meaning that in addition to modularizing every single Java source directory, you must convert everything to Java 9. At the same time.

This seems catastrophic if you work in a company with a large base of code that is shared by many different projects.

For now, I can work around the problem by just setting a bunch of compiler flags to avoid defining modules, but that seems like a very poor solution.

I hope that I am understanding this incorrectly?

答:
Once you do that, however, you must list ALL dependencies in the module descriptor

True.

and the dependencies must all themselves be modules.

Technically true, but it doesn't imply what you think it does.

Therefore, by extension, if you modularize a single source directory, you must modularize every single source directory company wide.

No, because you can let the module system turn regular old JARs into automatic modules, which will get a name based on a manifest entry or their file name - you can find that out with:

```<code># jar command from Java 9
jar --describe-module --file $JAR_FILE
</code>```

Furthermore, you cannot define modules in Java 8 or earlier, meaning that in addition to modularizing every single Java source directory, you must convert everything to Java 9. At the same time.

Again, fortunately that's not quite right. You can add a module-info.class to a JAR built for Java 8 and it will work on both Java 8 (which ignores that file) and Java 9 (which can of course execute Java 8 bytecode).

Body:
Once you do that, however, you must list ALL dependencies in the module descriptor

True.

and the dependencies must all themselves be modules.

Technically true, but it doesn't imply what you think it does.

Therefore, by extension, if you modularize a single source directory, you must modularize every single source directory company wide.

No, because you can let the module system turn regular old JARs into automatic modules, which will get a name based on a manifest entry or their file name - you can find that out with:

# jar command from Java 9
jar --describe-module --file $JAR_FILE

Furthermore, you cannot define modules in Java 8 or earlier, meaning that in addition to modularizing every single Java source directory, you must convert everything to Java 9. At the same time.

Again, fortunately that's not quite right. You can add a module-info.class to a JAR built for Java 8 and it will work on both Java 8 (which ignores that file) and Java 9 (which can of course execute Java 8 bytecode).


问:
openParentApplication method is missing from watch os 4
how do I awake parent app from watch app when parent app is not running state. </p>

答:
That method is only available in watchOS1 as the documentation clearly states.

From watchOS2+, Watch apps are no longer considered just extensions of the iOS app and hence you cannot open the connected iOS application from your Watch app.


问:
Dynamic JavaScript time counter
I'm trying to make a dynamic time counter/timer in JavaScript.

Why dynamic? Well I would like to display days/hours/minutes/seconds if the time stamp is bigger enough to display days or hours and so on.

In case the timestamp is less than a day I would like that the script dynamically displays only the hours.

```<code>1D 0H 59M 59S
23H 59M 59S
59M 59S
59S
MESSAGE
</code>```

Here is the code I try to make it work.

```<code><center>
<script>
    var countDownDate = new Date("2017-11-17T20:10:30Z").getTime();
    var x = setInterval(function() {
        var now = new Date().getTime();
        var distance = countDownDate - now;

        // Seconds
        if (distance < 1000){
            document.getElementById("count1").innerHTML = seconds + "s ";
        }
        // Minutes
        if (distance < 60000){
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            document.getElementById("count1").innerHTML = minutes + "m " + seconds + "s ";
        }
        // Hours
        if (distance < 3600000){
            var hours = Math.floor(distance / (1000 * 60 * 60 * 1));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            document.getElementById("count1").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
        }
        // Days
        if(distance > 3600001){
            var days = Math.floor(distance / (1000 * 60 * 60 * 24));
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            document.getElementById("count1").innerHTML = days + "d " + hours + "h " + minutes + "m " $
        }

        if (distance < 0) {
            clearInterval(x);
            document.getElementById("count1").innerHTML = "You will be redirected now";
        }
    }, 1000);
</script>

<p id="count1"></p>
</center>
</code>```

I think that my problem is related with math confusion in milliseconds but I can't find out what is wrong.

答:
It looks like you're doing this the absolute hardest way possible, and also reinventing the wheel. There are a lot of great references to built in javascript functions (like MDN) that you should really take a look at.

If you're doing this as an intellectual exercise think about restructuring your code into something like this (obviously just psuedocode):

```<code>let dateHTML = "";
if (time1.seconds - time2.seconds > 0) {
    dateHTML = (time1.seconds - time2.seconds) + "s";
}
if (time1.minutes-time2.minutes > 0) {
    dateHTML = (time1.minutes-time2.minutes) + "m " + dateHTML;
}
//So on and so forth for the maximum interval you want to account for.
document.getElementById("count1").innerHTML = dateHTML;
</code>```

You can probably get really clever with null operators, putting the time unit distances into an array to clean up the syntax and avoid doing calculations twice etc. but this should cut down on what you're doing significantly.

Do keep in mind that there are JS libraries built to do this exact sort of thing really well, so if you're working on a "real" project consider that.

Title: Dynamic JavaScript time counter

Body:
I'm trying to make a dynamic time counter/timer in JavaScript.

Why dynamic? Well I would like to display days/hours/minutes/seconds if the time stamp is bigger enough to display days or hours and so on.

In case the timestamp is less than a day I would like that the script dynamically displays only the hours.

1D 0H 59M 59S
23H 59M 59S
59M 59S
59S
MESSAGE

Here is the code I try to make it work.

I think that my problem is related with math confusion in milliseconds but I can't find out what is wrong.

Body:
It looks like you're doing this the absolute hardest way possible, and also reinventing the wheel. There are a lot of great references to built in javascript functions (like MDN) that you should really take a look at.

If you're doing this as an intellectual exercise think about restructuring your code into something like this (obviously just psuedocode):

let dateHTML = "";
if (time1.seconds - time2.seconds > 0) {
    dateHTML = (time1.seconds - time2.seconds) + "s";
}
if (time1.minutes-time2.minutes > 0) {
    dateHTML = (time1.minutes-time2.minutes) + "m " + dateHTML;
}
//So on and so forth for the maximum interval you want to account for.
document.getElementById("count1").innerHTML = dateHTML;

You can probably get really clever with null operators, putting the time unit distances into an array to clean up the syntax and avoid doing calculations twice etc. but this should cut down on what you're doing significantly.

Do keep in mind that there are JS libraries built to do this exact sort of thing really well, so if you're working on a "real" project consider that.


问:
space between inline text and input items in JADE?
How to give space between inline text and input items in JADE?

```<code>div(data-role="horizontal", data-theme="a", data-overlay-theme="a", data-inline="true",class="ui-bar ui-grid-c")
                        div(class='ui-block-a')
                            div(data-role='fieldcontain')
                                label(for='memberaddress') Address Proof
                                textarea(id='memberaddress',name='memberaddress')
                        div(class='ui-block-b')
                            div(data-role="fieldcontain")
                                label(for="proof") Proof ID
                                select(name='proof', id='proof', data-theme='a', data-icon='bank', data-inline='true', data-native-menu="false")
                                    option(value='0') Select Proof
                                    option(value='1') Voter ID
                                    option(value='2') Driving Licence
                                    option(value='3') PANCARD
                                    option(value='4') Ration Card
                        div(class='ui-block-c')
                            div(data-role="fieldcontain")
                                input(type='checkbox', name='addressmatchedCheck', id='addressmatchedCheck', data-inline="true")
                                label(for='addressmatchedCheck') Address Matched
</code>```

My output is:

I am not able to get space between label and textarea.

答:
Option 1 (my choice)

```<code>input(type='button')
|
input(type='button')
</code>```

Option 2

```<code>input(type='button')
= ' '
input(type='button')
</code>```

Option 3

```<code>input(type='button')
|
input(type='button')
</code>```

There are others though....

Body:
How to give space between inline text and input items in JADE?

div(data-role="horizontal", data-theme="a", data-overlay-theme="a", data-inline="true",class="ui-bar ui-grid-c")
                        div(class='ui-block-a')
                            div(data-role='fieldcontain')
                                label(for='memberaddress') Address Proof
                                textarea(id='memberaddress',name='memberaddress')
                        div(class='ui-block-b')
                            div(data-role="fieldcontain")
                                label(for="proof") Proof ID
                                select(name='proof', id='proof', data-theme='a', data-icon='bank', data-inline='true', data-native-menu="false")
                                    option(value='0') Select Proof
                                    option(value='1') Voter ID
                                    option(value='2') Driving Licence
                                    option(value='3') PANCARD
                                    option(value='4') Ration Card
                        div(class='ui-block-c')
                            div(data-role="fieldcontain")
                                input(type='checkbox', name='addressmatchedCheck', id='addressmatchedCheck', data-inline="true")
                                label(for='addressmatchedCheck') Address Matched

My output is:

I am not able to get space between label and textarea.

Body:
Option 1 (my choice)

input(type='button')
| &nbsp;
input(type='button')

Option 2

input(type='button')
= ' '
input(type='button')

Option 3

input(type='button')
|
input(type='button')

There are others though....


问:
Facing an exception with Scanner in Java
i'm trying to execute this simple code but it gives me this exception and i can't resolve it , i've tried some solutions in others posts but with no result , so please some help </p>

```<code>import java.text.DecimalFormat;
import java.util.*;

class test{

   public static void main(String args[]){

            Scanner sc = new Scanner(System.in);

            for(int i=0;i<4;i++){

                int a = sc.nextInt();
                String s = sc.next();
                int b = sc.nextInt();

                if(s.equals("*")){
                    System.out.println(a*b);
                }
                else if(s.equals("+")){
                    System.out.println(a+b);
                }
                else if(s.equals("-")){
                    System.out.println(a-b);
                }

                else if(s.equals("/")){
                    double a1 = a;
                    double b1 = b;

                    System.out.println(new DecimalFormat("##.##").format(a1/b1));
                }

        }
    }
}
</code>```

<p>the exception  : </p>

```<code>Exception in thread "main" java.util.NoSuchElementException

at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at test.main(test.java:14)
</code>```

答:
you problem is the method next. it is expecting a deliminator. you can define it using the useDeliminator method.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()</p>

Body:
i'm trying to execute this simple code but it gives me this exception and i can't resolve it , i've tried some solutions in others posts but with no result , so please some help

import java.text.DecimalFormat;
import java.util.*;

class test{

   public static void main(String args[]){

            Scanner sc = new Scanner(System.in);

            for(int i=0;i<4;i++){

                int a = sc.nextInt();
                String s = sc.next();
                int b = sc.nextInt();

                if(s.equals("*")){
                    System.out.println(a*b);
                }
                else if(s.equals("+")){
                    System.out.println(a+b);
                }
                else if(s.equals("-")){
                    System.out.println(a-b);
                }

                else if(s.equals("/")){
                    double a1 = a;
                    double b1 = b;

                    System.out.println(new DecimalFormat("##.##").format(a1/b1));
                }

        }
    }
}

the exception  :

Exception in thread "main" java.util.NoSuchElementException

at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at test.main(test.java:14)


问:
Java: Declaring array with do... while
My school homework is to declare array with 100 variables.

The actual task is: Declare array with 100 variables. Use do.. while loop to read the data to array. Reading data should be finished when array will be full or when user will enter a negative number.

So far I got:

```<code>public static void runTask1() {

    Scanner read = new Scanner(System.in);
    int[] tab = new int [100];
    for (int i = 0; i < tab.length; i++);
    System.out.println("Enter number for array ");
    tab [] = read.nextInt();
</code>```

Please help. I'm a total newbie in programming.

答:
Try that</p>

```<code>  public static void main(String[] args) {
          Scanner read = new Scanner(System.in);
          int[] tab = new int [100];
          int index = 0;
        while(index < tab.length){
          System.out.println("Enter number for array ");
          tab[index]= read.nextInt();

            if(tab[index]<1) break;
            index++;
          }
         System.out.println(Arrays.toString(tab));
     }
</code>```

Title: Java: Declaring array with do... while

Body:
My school homework is to declare array with 100 variables.

The actual task is: Declare array with 100 variables. Use do.. while loop to read the data to array. Reading data should be finished when array will be full or when user will enter a negative number.

So far I got:

public static void runTask1() {

    Scanner read = new Scanner(System.in);
    int[] tab = new int [100];
    for (int i = 0; i < tab.length; i++);
    System.out.println("Enter number for array ");
    tab [] = read.nextInt();

Please help. I'm a total newbie in programming.

Body:
Try that

  public static void main(String[] args) {
          Scanner read = new Scanner(System.in);
          int[] tab = new int [100];
          int index = 0;
        while(index < tab.length){
          System.out.println("Enter number for array ");
          tab[index]= read.nextInt();

            if(tab[index]<1) break;
            index++;
          }
         System.out.println(Arrays.toString(tab));
     }


问:
Access VBA round by the quarter of the hour
I want to be able to round time by the quarter of the hour, so when it is 3 minutes past the quarter of the hour it rounds up and when it's within the 3 minutes it rounds down.  Like below:

```<code>08:01 (will be 08:00)
08:03 (will be 08:00)
08:04 (will be 08:15)
</code>```

Managed to get it working in excel but cannot get it working in Access.

Here is the excel formula:

```<code>=(TRUNC((VALUE("08:03")+VALUE("00:11"))*96)*VALUE("00:15"))
</code>```

答:
Try the following:  </p>

```<code>Option Compare Database
Option Explicit

Sub Test_time()
Dim i   As Integer
Dim dTime   As Date
    dTime = #8:00:00 AM#
    For i = 0 To 75
        dTime = DateAdd("n", 1, dTime)
        Debug.Print dTime & vbTab & Format(Trunc(dTime), "hh:mm")
    Next i
End Sub

Function Trunc(vTime As Date) As Date
Dim iHr, iMin As Integer
Dim iQtr    As Integer
Dim MyTime  As Date
    iHr = Hour(vTime)
    iMin = Minute(vTime)
    iQtr = Int(iMin / 15)
    If iMin - (iQtr * 15) < 4 Then
        MyTime = DateAdd("h", iHr, 0)
        MyTime = DateAdd("n", iQtr * 15, MyTime)
    Else
        MyTime = DateAdd("h", iHr, 0)
        MyTime = DateAdd("n", (iQtr + 1) * 15, MyTime)
    End If
    Trunc = MyTime
End Function
</code>```

Body:
I want to be able to round time by the quarter of the hour, so when it is 3 minutes past the quarter of the hour it rounds up and when it's within the 3 minutes it rounds down.  Like below:

08:01 (will be 08:00)
08:03 (will be 08:00)
08:04 (will be 08:15)

Managed to get it working in excel but cannot get it working in Access.

Here is the excel formula:

=(TRUNC((VALUE("08:03")+VALUE("00:11"))*96)*VALUE("00:15"))

Body:
Try the following:

Option Compare Database
Option Explicit

Sub Test_time()
Dim i   As Integer
Dim dTime   As Date
    dTime = #8:00:00 AM#
    For i = 0 To 75
        dTime = DateAdd("n", 1, dTime)
        Debug.Print dTime & vbTab & Format(Trunc(dTime), "hh:mm")
    Next i
End Sub

Function Trunc(vTime As Date) As Date
Dim iHr, iMin As Integer
Dim iQtr    As Integer
Dim MyTime  As Date
    iHr = Hour(vTime)
    iMin = Minute(vTime)
    iQtr = Int(iMin / 15)
    If iMin - (iQtr * 15) < 4 Then
        MyTime = DateAdd("h", iHr, 0)
        MyTime = DateAdd("n", iQtr * 15, MyTime)
    Else
        MyTime = DateAdd("h", iHr, 0)
        MyTime = DateAdd("n", (iQtr + 1) * 15, MyTime)
    End If
    Trunc = MyTime
End Function


答:
Using diff

```<code>df.diff(axis=1).fillna(0).eq(0).all(1)

0     True
1    False
2    False
dtype: bool
</code>```

Using shift

```<code>df.eq(df.shift(axis=1)).iloc[:, 1:].all(1)

0     True
1    False
2    False
dtype: bool
</code>```

Using std (inspired by @Wen)

```<code>df.std(1).eq(0)

0     True
1    False
2    False
dtype: bool
</code>```

Inspired by @MaxU with a healthy amount of obnoxious sprinkled in.

```<code>(lambda v, j: pd.Series((v == v[:, [0]]).all(1), j))(df.values, df.index)

0     True
1    False
2    False
dtype: bool
</code>```

Now with less obnoxious

```<code>v = df.values
pd.Series((v == v[:, [0]]).all(1), df.index)
</code>```

Title: How can I compare rows for multiple columns if they are identical

Body:
Using diff

df.diff(axis=1).fillna(0).eq(0).all(1)

0     True
1    False
2    False
dtype: bool

Using shift

df.eq(df.shift(axis=1)).iloc[:, 1:].all(1)

0     True
1    False
2    False
dtype: bool

Using std (inspired by @Wen)

df.std(1).eq(0)

0     True
1    False
2    False
dtype: bool

Inspired by @MaxU with a healthy amount of obnoxious sprinkled in.

(lambda v, j: pd.Series((v == v[:, [0]]).all(1), j))(df.values, df.index)

0     True
1    False
2    False
dtype: bool

Now with less obnoxious

v = df.values
pd.Series((v == v[:, [0]]).all(1), df.index)


问:
How to change Angular CLI favicon
How can I change the default favicon that is set by the Angular CLI?

I have tried many things, but it always shows the Angular logo as the favicon,
even though I have deleted that icon (favicon.ico in src folder). It still shows, and I don't know from where it's loaded from.

I have replaced that icon with another icon, but it still show the Angular logo:

<link rel="icon" type="image/x-icon" href="favicon.ico">
```

答:
I had the same problem.

If you are using a Mac, you will need to empty the Cache (Option+⌘+E) and reload the page in addition to restarting the app (and of course changing the path in index.html).

Title: How to change Angular CLI favicon


问:
Are Margin and Padding implemented by ContentControl?
I am developing a custom control derived from System.Windows.Controls.ContentControl. In the controls default template (themes\generic.xaml), I use a Border element that wraps the actual content.

Does my custom control already implement margin and padding (i.e., shrink the border according to the padding set on the custom control) or do/can I decide myself, where margin and padding are applied (i.e., set the margin and padding properties on the border element to {TemplateBinding Margin} etc.

Thanks in advance!

答: Margin is implemented I believe all the way down in Framework element. However Padding is not. ContentControl has the "PaddingProperty" but by default it doesn't do anything. Basically you bind the MarginProperty of the Content to the Padding property of the content control.</p>

OwnerDisplayName: SealedSun

OwnerDisplayName: Micah


问:
Compare values of two columns then select the larger value
I need to query a table and select 3 of the values of 4 columns. I need to compare the values of the 3rd column and the fourth column and select the larger value.

For example:

```<code>column1  column2  column3  column4
 hello    hello      3        5
 hi       hi         7        1
</code>```

I need to return:

```<code>column1  column2  Hybrid
 hello    hello     5
 hi       hi        7
</code>```

I have been trying to use IF/ELSE but I just can't seem to get the syntax correct

答:
Just so we don't return null:

```<code>SELECT  IIF( a > b, a, COALESCE( a, b )) -- coalesce or isnull
FROM wherever
</code>```

Here's a query to test it:

```<code>with whatever as (
  select null as a, 1 as b
  UNION
  select 1 as a, null as b
  union
  select 1 as a, 0 as b
  union
  select 0 as a, 1 as b
  union
  select null as a, null as b
)
select( iif( a > b, a, isnull( b, a )))
from whatever
</code>```

Should return

```<code>null
1
1
1
1
</code>```

Body:
I need to query a table and select 3 of the values of 4 columns. I need to compare the values of the 3rd column and the fourth column and select the larger value.

For example:

column1  column2  column3  column4
 hello    hello      3        5
 hi       hi         7        1

I need to return:

column1  column2  Hybrid
 hello    hello     5
 hi       hi        7

I have been trying to use IF/ELSE but I just can't seem to get the syntax correct

Body:
Just so we don't return null:

SELECT  IIF( a > b, a, COALESCE( a, b )) -- coalesce or isnull
FROM wherever

Here's a query to test it:

with whatever as (
  select null as a, 1 as b
  UNION
  select 1 as a, null as b
  union
  select 1 as a, 0 as b
  union
  select 0 as a, 1 as b
  union
  select null as a, null as b
)
select( iif( a > b, a, isnull( b, a )))
from whatever

Should return

null
1
1
1
1


问:
Multiple where clauses and elimination
I'm trying to generate the count of unique drivers who have completed their trip and never cancel on the client. If a driver has ever canceled on any client they should be removed from the results.

I'm wondering if a subquery is needed here or not.
The data that I am working with is shown here and while rudimentary, it's simply to test my query.

```<code>id  driver_id   client_id   city_id status
1   1011        9004        546     completed
1   1011        9008        323     completed
2   1011        9001        546     completed
3   1011        9006        323     completed
3   1011        9007        154     cancelled_by_client
1   1012        9001        546     cancelled_by_client
2   1012        9003        123     cancelled_by_driver
2   1012        9002        789     completed
2   1013        9007        546     cancelled_by_driver
4   1013        9006        546     cancelled_by_driver
2   1015        9001        546     completed
3   1015        9006        323     completed
3   1015        9007        154     cancelled_by_client
</code>```

What I am after as my expected result is a count of the unique driver IDs that have both completed their trips and never canceled on the client (canceled_by_driver).

```<code>driver_id    non_driver_cancels
1011         1
1015         1
</code>```

I have a GROUP BY in here to show the data with more detail and I am seeing that driver 1012 has a canceled_by_driver but they are still in my results. From there I believe I can simply count the driver_id's and finish this task.

Any help is greatly appreciated.

http://sqlfiddle.com/#!9/ad7cca/7

答:
You can do this with group by and having:

```<code>select driver_id, sum(status = 'cancelled_by_client') as client_cancels
from t
group by driver_id
having sum(status = 'cancelled_by_driver') = 0;
</code>```

This assumes that the only other type of  cancellation is "cancelled_by_client", as shown in your data.

Title: Multiple where clauses and elimination

Body:
I'm trying to generate the count of unique drivers who have completed their trip and never cancel on the client. If a driver has ever canceled on any client they should be removed from the results.

I'm wondering if a subquery is needed here or not.
The data that I am working with is shown here and while rudimentary, it's simply to test my query.

id  driver_id   client_id   city_id status
1   1011        9004        546     completed
1   1011        9008        323     completed
2   1011        9001        546     completed
3   1011        9006        323     completed
3   1011        9007        154     cancelled_by_client
1   1012        9001        546     cancelled_by_client
2   1012        9003        123     cancelled_by_driver
2   1012        9002        789     completed
2   1013        9007        546     cancelled_by_driver
4   1013        9006        546     cancelled_by_driver
2   1015        9001        546     completed
3   1015        9006        323     completed
3   1015        9007        154     cancelled_by_client

What I am after as my expected result is a count of the unique driver IDs that have both completed their trips and never canceled on the client (canceled_by_driver).

driver_id    non_driver_cancels
1011         1
1015         1

I have a GROUP BY in here to show the data with more detail and I am seeing that driver 1012 has a canceled_by_driver but they are still in my results. From there I believe I can simply count the driver_id's and finish this task.

Any help is greatly appreciated.

http://sqlfiddle.com/#!9/ad7cca/7

Body:
You can do this with group by and having:

select driver_id, sum(status = 'cancelled_by_client') as client_cancels
from t
group by driver_id
having sum(status = 'cancelled_by_driver') = 0;

This assumes that the only other type of  cancellation is "cancelled_by_client", as shown in your data.