问:
Send data between Android and Arduino via Wifi
I program my Arduino and when in my tablet type 192.168.4.1 arduino send me Html page but when I use this code I cant receive any data and I get this error:

java.net.MalformedURLException: Protocol not found: 192.168.4.1

How can I solve this problem?

```<code>private void getdata(){

    try {
        URL url = new URL("192.168.4.1");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        InputStream inputStream = conn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String data = "", line = "";
        StringBuffer buffer = new StringBuffer();
        while ((line = bufferedReader.readLine()) != null) {
            // data += line + "\n";
            buffer.append(line + "\n");
        }
        Thread.sleep(4000);
    } //end try

    Log.e("errrorrrrrrrrrrrr", e.toString());
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
</code>```

答:
try to add http:// to your url :

```<code>URL url = new URL("http://192.168.4.1");
</code>```

Body:
I program my Arduino and when in my tablet type 192.168.4.1 arduino send me Html page but when I use this code I cant receive any data and I get this error:

java.net.MalformedURLException: Protocol not found: 192.168.4.1

How can I solve this problem?

private void getdata(){

    try {
        URL url = new URL("192.168.4.1");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        InputStream inputStream = conn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String data = "", line = "";
        StringBuffer buffer = new StringBuffer();
        while ((line = bufferedReader.readLine()) != null) {
            // data += line + "\n";
            buffer.append(line + "\n");
        }
        Thread.sleep(4000);
    } //end try

    Log.e("errrorrrrrrrrrrrr", e.toString());
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Body:
try to add http:// to your url :

URL url = new URL("http://192.168.4.1");


来源: stackexchange

问:
How can I fake a cookie in a web request that's generated dynamically?
I need to get some public data from a link, but this is a second time I encounter a Cookie that I cannot replicate as some values in it are dynamic. How can I get this cookie before doing an actual request to get my data?

Example link:

```<code>https://www.blackrock.com/ca/individual/en/products/239832/ishares-sptsx-60-index-etf/1464253357804.ajax?tab=chart
</code>```

Example headers:

```<code>Host: www.blackrock.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: https://www.blackrock.com/ca/individual/en/products/239832/ishares-sptsx-60-index-etf
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cookie: JSESSION_amer-retail01=EA5A098E120F4E3FAD2C994A64F292E4.03; ts-ca-one-locale=en_CA; FIRSTPAGE_ca_ca-one=page-class-home; blkUserType-ca-one=individual; ipe_s=0d9c807a-04cc-ae5b-e459-d89bddd2faab; ca-one-recent-funds=239832; __utmt=1; __utma=17023466.874636303.1499433731.1499433731.1499433731.1; __utmb=17023466.5.10.1499433731; __utmc=17023466; __utmz=17023466.1499433731.1.1.utmcsr=google|utmgclid=CJjax_ah99QCFZxMDQodKQ4NxQ|utmgclsrc=aw.ds|utmccn=(not%20set)|utmcmd=(not%20set)|utmctr=(not%20provided); _bizo_bzid=0688d0c2-d203-488b-b128-94c0406b5568; _bizo_cksm=B16C1965883E71EB; _bizo_np_stats=14%3D243%2C; ipe.20668.pageViewedCount=3; utag_main=v_id:015d1d3702f6001b054da00951140407300ad06b00bd0$_sn:1$_ss:0$_pn:6%3Bexp-session$_st:1499436924463$ses_id:1499433730806%3Bexp-session; s_pers=%20s_fid%3D5295C92DBD9DC781-0177F2F787EC9066%7C1562507124793%3B%20gpv%3Dca-one%257Cca%257Cfund%257Cishares%2520s%2526p%252Ftsx%252060%2520index%2520etf%257Cxiu%7C1499436924795%3B%20s_nr%3D1499435124796-New%7C1530971124796%3B%20s_pers_eVar17%3Dprospect%7C1502027124797%3B%20s_pers_prop19%3Danonymous%7C1502027124799%3B; s_sess=%20s_campaign%3Dppc%253Ablackrock_ca%253Agoogle%253Ablackrock%3B%20s_cc%3Dtrue%3B%20s_sq%3D%3B; s_vi=[CS]v1|2CAFC5818507C33B-6000011540002202[CE]
</code>```

答:
You can instantiate a CookieContainer and set it to the CookieContainer property of your HttpWebRequest. Then make an initial request and after you GetResponse the cookie container will be populated with any cookies returned.

Then reuse the CookieContainer in subsequent requests and all the previous returned cookies will be sent.

ContentLicense: CC BY-SA 3.0

Body:
I need to get some public data from a link, but this is a second time I encounter a Cookie that I cannot replicate as some values in it are dynamic. How can I get this cookie before doing an actual request to get my data?

Example link:

https://www.blackrock.com/ca/individual/en/products/239832/ishares-sptsx-60-index-etf/1464253357804.ajax?tab=chart

Example headers:

Host: www.blackrock.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: https://www.blackrock.com/ca/individual/en/products/239832/ishares-sptsx-60-index-etf
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cookie: JSESSION_amer-retail01=EA5A098E120F4E3FAD2C994A64F292E4.03; ts-ca-one-locale=en_CA; FIRSTPAGE_ca_ca-one=page-class-home; blkUserType-ca-one=individual; ipe_s=0d9c807a-04cc-ae5b-e459-d89bddd2faab; ca-one-recent-funds=239832; __utmt=1; __utma=17023466.874636303.1499433731.1499433731.1499433731.1; __utmb=17023466.5.10.1499433731; __utmc=17023466; __utmz=17023466.1499433731.1.1.utmcsr=google|utmgclid=CJjax_ah99QCFZxMDQodKQ4NxQ|utmgclsrc=aw.ds|utmccn=(not%20set)|utmcmd=(not%20set)|utmctr=(not%20provided); _bizo_bzid=0688d0c2-d203-488b-b128-94c0406b5568; _bizo_cksm=B16C1965883E71EB; _bizo_np_stats=14%3D243%2C; ipe.20668.pageViewedCount=3; utag_main=v_id:015d1d3702f6001b054da00951140407300ad06b00bd0$_sn:1$_ss:0$_pn:6%3Bexp-session$_st:1499436924463$ses_id:1499433730806%3Bexp-session; s_pers=%20s_fid%3D5295C92DBD9DC781-0177F2F787EC9066%7C1562507124793%3B%20gpv%3Dca-one%257Cca%257Cfund%257Cishares%2520s%2526p%252Ftsx%252060%2520index%2520etf%257Cxiu%7C1499436924795%3B%20s_nr%3D1499435124796-New%7C1530971124796%3B%20s_pers_eVar17%3Dprospect%7C1502027124797%3B%20s_pers_prop19%3Danonymous%7C1502027124799%3B; s_sess=%20s_campaign%3Dppc%253Ablackrock_ca%253Agoogle%253Ablackrock%3B%20s_cc%3Dtrue%3B%20s_sq%3D%3B; s_vi=[CS]v1|2CAFC5818507C33B-6000011540002202[CE]


问:
Not able to set text ellipsis for input placeholder in IE11
I'm able to set the color of input placeholder text in IE11 (Windows 7) but I'm not able to set text overflow to ellipsis for input placeholder text.

Here is the jsfiddle to reproduce this issue (Please open this fiddle link in IE11 on windows 7) ,

https://jsfiddle.net/1nku0aty/3/

HTML

```<code><input type="text" placeholder="longtextlongtextlongtextlongtextlongtext">
</code>```

CSS

```<code>input {
  margin: 2em;
}
input:-ms-input-placeholder {
  text-overflow: ellipsis;
  overflow: hidden;
  color: red;
}
</code>```

Can some one help on solving this?

答:
There is a better answer to this question about IE10:

Placeholder text-overflow:ellipsis in IE10 not working

Basically, apparently it doesn't work unless you make the input field readonly, it is possible to do some hacky javascript to make it readonly except when you click it, but if you have the option of going 'eh whatever, it's IE11 and a minor glitch, who cares' you should probably take that...

Body:
I'm able to set the color of input placeholder text in IE11 (Windows 7) but I'm not able to set text overflow to ellipsis for input placeholder text.

Here is the jsfiddle to reproduce this issue (Please open this fiddle link in IE11 on windows 7) ,

https://jsfiddle.net/1nku0aty/3/

HTML

<input type="text" placeholder="longtextlongtextlongtextlongtextlongtext">

CSS

input {
  margin: 2em;
}
input:-ms-input-placeholder {
  text-overflow: ellipsis;
  overflow: hidden;
  color: red;
}

Can some one help on solving this?


问:
reload a page with list menu option javascript
Hello i'm searching the best way to reload a page withe list menu.

I know how to reload a page with simple code or by the meta but from a list menu it not easy.

Example :

List :

none

5 seconds

10 seconds
30 seconds

1 minutes

2 minutes

5 minutes

When an option is selected the page will be automatically reload from the option selected.

Do someone have an idea how to make a simple code ?

@mplungjan my code :

```<code><SCRIPT type="text/javascript">
function refresh()
{
document.location.reload();
 }
setTimeout(refresh,theForm.submit();
</SCRIPT>

<FORM NAME="reloadForm" >
<SELECT NAME="sec" OnChange="refresh()">
<OPTION VALUE="0" SELECTED>None
<OPTION VALUE="5" >Every 5 secondes
<OPTION VALUE="10" >Every 10 secondes
<OPTION VALUE="30" >Every 30 secondes
<OPTION VALUE="60" >Every  minutes
<OPTION VALUE="90" >Every  minutes and half
<OPTION VALUE="120" >Every  2 minutes
<OPTION VALUE="180" >Every  3 minutes
<OPTION VALUE="300" >Every  5 minutes
</SELECT>
</code>```

答:
define the time variable as a value of option you have then use setTimeOut function to reload the page according to that variable , here the page reload after 6 seconds , this is the idea.</p>

```<code>var time = 6000
setTimeout(function(){ location.reload(); }, time);
</code>```

Body:
Hello i'm searching the best way to reload a page withe list menu.

I know how to reload a page with simple code or by the meta but from a list menu it not easy.

Example :

List :

none

5 seconds

10 seconds
30 seconds

1 minutes

2 minutes

5 minutes

When an option is selected the page will be automatically reload from the option selected.

Do someone have an idea how to make a simple code ?

@mplungjan my code :

<FORM NAME="reloadForm" >
<SELECT NAME="sec" OnChange="refresh()">
<OPTION VALUE="0" SELECTED>None
<OPTION VALUE="5" >Every 5 secondes
<OPTION VALUE="10" >Every 10 secondes
<OPTION VALUE="30" >Every 30 secondes
<OPTION VALUE="60" >Every  minutes
<OPTION VALUE="90" >Every  minutes and half
<OPTION VALUE="120" >Every  2 minutes
<OPTION VALUE="180" >Every  3 minutes
<OPTION VALUE="300" >Every  5 minutes
</SELECT>

Body:
define the time variable as a value of option you have then use setTimeOut function to reload the page according to that variable , here the page reload after 6 seconds , this is the idea.

var time = 6000
setTimeout(function(){ location.reload(); }, time);


问:
HTML CSS Menu with Sub Menus
I am trying to create a custom navigation bar with sub menus with very simple coding to keep it light but its not working properly. Please have a look at this code and fiddle link. Fiddle https://jsfiddle.net/tjmkf9sb/

As you can see that I want to create a hoverable sub menu but the sub menus are not obeying display: none property right now. Please help.

CSS

```<code>.menu {
    border: 1px solid aliceblue;
    margin-top: 55px;
    margin-left: auto;
}
.menu li {
    list-style: none;
    padding: 15px;
    border-radius: 5px;
    color: #fff;
    background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #1fc8db, #2cb5e8); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #1fc8db, #2cb5e8); /* Standard syntax */
    display: inline;
}
.menu li:hover {
    background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #26cfe3, #1aade4); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #26cfe3, #1aade4); /* Standard syntax */
}
.menu a:hover {
    text-decoration: none;
}
.menu li ul {
    display: block;
}
.submenu ul {
  display: none;
  position: absolute;
}
</code>```

HTML

```<code><div class="menu">
  <ul>
    <a href="dashboard.php"><li>Dashboard</li></a>
    <a href="dashboard.php">
      <li class="submenu">
        Licence Orders
        <ul class="dropdown">
          <li>Paid Orders</li>
          <li>Unpaid Orders</li>
        </ul>
      </li>
    </a>
    <a href="dashboard.php"><li>Dashboard</li></a>
    <a href="logout.php"><li>Logout</li></a>
  </ul>
</div>
</code>```

Please help me. I have been stuck on this for quite some time now.

答:
Add:

```<code>.menu li ul {
    display: none;
}

.menu li:hover ul {
    display: block;
}
</code>```

.menu {
 border: 1px solid aliceblue;
 margin-top: 55px;
 margin-left: auto;
}
.menu li {
 list-style: none;
 padding: 15px;
 border-radius: 5px;
 color: #fff;
 background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #1fc8db, #2cb5e8); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #1fc8db, #2cb5e8); /* Standard syntax */
 display: inline;
}
.menu li:hover {
 background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #26cfe3, #1aade4); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #26cfe3, #1aade4); /* Standard syntax */
}
.menu a:hover {
 text-decoration: none;
}
.menu li ul {
 display: none;
}

.menu li:hover ul {
  display: block;
}
.submenu ul {
  display: none;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
  <ul>
    <li>Dashboard<li>
    <li class="submenu">
      Licence Orders
      <ul class="dropdown">
        <li>Paid Orders</li>
        <li>Unpaid Orders</li>
      </ul>
    </li>
    <li>Dashboard</li>
    <li>Logout</li>
  </ul>
</div></code>```

Style with your rules.

Edit: Only li can be descendent from ul

Title: HTML CSS Menu with Sub Menus

Body:
I am trying to create a custom navigation bar with sub menus with very simple coding to keep it light but its not working properly. Please have a look at this code and fiddle link. Fiddle https://jsfiddle.net/tjmkf9sb/

As you can see that I want to create a hoverable sub menu but the sub menus are not obeying display: none property right now. Please help.

CSS

.menu {
    border: 1px solid aliceblue;
    margin-top: 55px;
    margin-left: auto;
}
.menu li {
    list-style: none;
    padding: 15px;
    border-radius: 5px;
    color: #fff;
    background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #1fc8db, #2cb5e8); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #1fc8db, #2cb5e8); /* Standard syntax */
    display: inline;
}
.menu li:hover {
    background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #26cfe3, #1aade4); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #26cfe3, #1aade4); /* Standard syntax */
}
.menu a:hover {
    text-decoration: none;
}
.menu li ul {
    display: block;
}
.submenu ul {
  display: none;
  position: absolute;
}

HTML

Dashboard

        Licence Orders

Paid Orders

Unpaid Orders

Dashboard

Logout

Please help me. I have been stuck on this for quite some time now.

Body:
Add:

.menu li ul {
    display: none;
}

.menu li:hover ul {
    display: block;
}

.menu {
 border: 1px solid aliceblue;
 margin-top: 55px;
 margin-left: auto;
}
.menu li {
 list-style: none;
 padding: 15px;
 border-radius: 5px;
 color: #fff;
 background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #1fc8db, #2cb5e8); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #1fc8db, #2cb5e8); /* Standard syntax */
 display: inline;
}
.menu li:hover {
 background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #26cfe3, #1aade4); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #26cfe3, #1aade4); /* Standard syntax */
}
.menu a:hover {
 text-decoration: none;
}
.menu li ul {
 display: none;
}

.menu li:hover ul {
  display: block;
}
.submenu ul {
  display: none;
  position: absolute;
}

<div class="menu">
  <ul>
    <li><a href="dashboard.php">Dashboard</a><li>
    <li class="submenu">
      <a href="dashboard.php">Licence Orders</a>
      <ul class="dropdown">
        <li>Paid Orders</li>
        <li>Unpaid Orders</li>
      </ul>
    </li>
    <li><a href="dashboard.php">Dashboard</a></li>
    <li><a href="logout.php">Logout</a></li>
  </ul>
</div>

Style with your rules.

Edit: Only li can be descendent from ul


问:
Auto calculate value including decimals
I have a html form where users add hours to 5 input fields (days of the week).

The total hours is then displayed at the bottom of the form.

This is working fine for rounded hours, but when adding something like 7.4 the total is rounding it to 7

See below:
Is there a way to add the decimals too?

$(document).ready(function() {
  $('.calc').change(function() {
    var total = 0;
    $('.calc').each(function() {
      if ($(this).val() != '') {
        total += parseInt($(this).val());
      }
    });
    $('#total').html(total);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control  calc" name='mon'>
<input type="text" class="form-control  calc" name='tue'>
<span id="total"></span></code>```

答: As @MysterX pointed out, you are converting the user's input into integer(whole number) form. parseFloat will account for decimal places.

Title: Auto calculate value including decimals

Body:
I have a html form where users add hours to 5 input fields (days of the week).

The total hours is then displayed at the bottom of the form.

This is working fine for rounded hours, but when adding something like 7.4 the total is rounding it to 7

See below:
Is there a way to add the decimals too?

$(document).ready(function() {
  $('.calc').change(function() {
    var total = 0;
    $('.calc').each(function() {
      if ($(this).val() != '') {
        total += parseInt($(this).val());
      }
    });
    $('#total').html(total);
  });
});

<input type="text" class="form-control  calc" name='mon'>
<input type="text" class="form-control  calc" name='tue'>


问:
Programatically triggering event into the $timeout cause infinite loop
I have template that looks like this (with many instances in template like this):

```<code><span>
  <button type="button" ng-click="uploadPdf($event)">
    <i class="fa fa-file"></i>
    <input type="file" class="pdfDoc" ng-show="false">
  </button>
</span>
</code>```

The idea is when user click on button, the input[type="file"] should be triggered (clicked).

I tried firstly to make It like this:

```<code>$scope.uploadPdf = function(e) {
  e.currentTarget.lastElementChild.click();
};
</code>```

And It works, but console yell on me that $apply is still in progress, so I found solution where usage of $timeout is suggested, so I wrapped code above to $timeout

```<code>$scope.uploadPdf = function(e) {
  $timeout(function() {
    e.currentTarget.lastElementChild.click();
  }, 0, false);
};
</code>```

And this for some reason runs infinitely.

Does anyone why is that happening and any another possible solution ?

Thanks.

答:
1) You click the button with onclick UploadPdf

2) You trigger a click inside the button (on its child element)

3) The click event bubbles back up to the button

4) Go to point 1 :)

And the solution can be

```<code>ng-click="$event.stopPropagation();"
</code>```

applied to the input element

Body:
I have template that looks like this (with many instances in template like this):

  <button type="button" ng-click="uploadPdf($event)">

    <input type="file" class="pdfDoc" ng-show="false">
  </button>

The idea is when user click on button, the input[type="file"] should be triggered (clicked).

I tried firstly to make It like this:

$scope.uploadPdf = function(e) {
  e.currentTarget.lastElementChild.click();
};

And It works, but console yell on me that $apply is still in progress, so I found solution where usage of $timeout is suggested, so I wrapped code above to $timeout

$scope.uploadPdf = function(e) {
  $timeout(function() {
    e.currentTarget.lastElementChild.click();
  }, 0, false);
};

And this for some reason runs infinitely.

Does anyone why is that happening and any another possible solution ?

Thanks.

Body:
1) You click the button with onclick UploadPdf

2) You trigger a click inside the button (on its child element)

3) The click event bubbles back up to the button

4) Go to point 1 :)

And the solution can be

ng-click="$event.stopPropagation();"

applied to the input element


问:
Conversion from 'char' to non-scalar type 'Vector<char>' error thrown unknown reason
Error Thrown Unknown Reason

```<code>#include "std_lib_facilities.h"

int main()
{
    vector<char> shape = ('a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a');
    return(0);
}
</code>```

that one line with the vector throws this error that I've never seen before nor can figure out...

:: g++ TicTacToe.cpp -o TTT

TicTacToe.cpp: In function int main()':

TicTacToe.cpp:5: error: conversion fromchar' to non-scalar type `Vector' requested

See in each tic-tac-toe box it will start as _ and then go to either X or O, I'm doing this without a graphics library so its terminal graphics.

答:
The vector class has the following constructor:

```<code>explicit vector( size_type n, const T& value= T(), const Allocator&=Allocator());
</code>```

Using which you can do:

```<code>vector<char> shape (9,'a');
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Error Thrown Unknown Reason

#include "std_lib_facilities.h"

int main()
{
    vector<char> shape = ('a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a');
    return(0);
}

that one line with the vector throws this error that I've never seen before nor can figure out...

:: g++ TicTacToe.cpp -o TTT

TicTacToe.cpp: In function int main()':

TicTacToe.cpp:5: error: conversion fromchar' to non-scalar type `Vector' requested

See in each tic-tac-toe box it will start as _ and then go to either X or O, I'm doing this without a graphics library so its terminal graphics.

Body:
The vector class has the following constructor:

explicit vector( size_type n, const T& value= T(), const Allocator&=Allocator());

Using which you can do:

vector<char> shape (9,'a');


问:
When to choose multiple loops over single loop with if-statements
I have to process each element of an array the same way once and have to modify each by an unpredictable pattern afterwards aswell.

Is there any difference in performance between these snippets and why, if so?

```<code>std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];

    if(nums[i] < 10){
        nums[i] = 0;
    }
}
</code>```

```<code>std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
}

for(unsigned int i = 0; i < nums.size(); ++i){
    if(nums[i] < 10){
        nums[i] = 0;
    }
}
</code>```

Would a different approach like this improve anything?

```<code>std::vector<int> nums;
//fill nums array

std::vector<int> flags;
flags.resize(nums.size());

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
    flags[i] = nums[i] < 10;
}

for(unsigned int i = 0; i < flags.size(); ++i){
   nums[i] = (!flags[i]) * nums[i]; //!flags[i] is 0 if nums[i] < 10
}
</code>```

答:
In Algorithm analysis
First pattern: time complexity is size of array O(n)
Second pattern: time complexity is max between 2 loops
O(n) and O(n) so it will be O(n) also.

First and second patterns are a same.

Third pattern not improve any thing.

Conclusion: 3 patterns are techniques not more.

Body:
I have to process each element of an array the same way once and have to modify each by an unpredictable pattern afterwards aswell.

Is there any difference in performance between these snippets and why, if so?

std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];

    if(nums[i] < 10){
        nums[i] = 0;
    }
}

std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
}

for(unsigned int i = 0; i < nums.size(); ++i){
    if(nums[i] < 10){
        nums[i] = 0;
    }
}

Would a different approach like this improve anything?

std::vector<int> nums;
//fill nums array

std::vector<int> flags;
flags.resize(nums.size());

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
    flags[i] = nums[i] < 10;
}

for(unsigned int i = 0; i < flags.size(); ++i){
   nums[i] = (!flags[i]) * nums[i]; //!flags[i] is 0 if nums[i] < 10
}


问:
Apollo subscription not working
I have a graphql server and I'm attempting to trigger an event whenever the status of an entity is updated. I have a mutation for updating the entity, which uses graphql-subscriptions to publish the update for the subscriber to listen to. However, pubsub.subscribe(EVENT_NAME) picked up the change, but when I integrate that into the subscription resolver, it doesn't trigger the update.

I've redacted parts of the code not relevant to the issue for brevity.

My resolver:

```<code>Mutation: {
  updateStatus(_, { id, status, hash }) {
    return repository.updateStatus(id, status, hash);
  }
},
Subscription: {
  updatedStatus: {
    subscribe: () => pubsub.asyncIterator('updatedStatus'),
  }
},
</code>```

My repository:

```<code>export const updateStatus = async function(id: String, status: String, hash: String) {
  try {
    const res = await fetch(`${baseURL}/article/${id}/status?publish_hash=${hash}`, {
      headers,
      method: 'PATCH',
      body: JSON.stringify({ status })
    });

    const article = await fetchSingleArticle(id, 'XML', headers.channel, false);

    await pubsub.publish('updatedStatus', article);
    return article;
  } catch (e) {
    console.log(e.message);
  }
}
</code>```

My schema:

```<code>type Mutation {
  updateStatus(id: ID!, status: PublishingStatus = PUBLISHING, hash: String): Article
}

type Subscription {
  updatedStatus(id: ID!): Article
}

schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}
</code>```

To test this, I'm just using graphiql, which is picking up the websocket connection fine.

I've attempted the publish using both article (as shown) and { updatedStatus: article }, neither seem to get picked up.

As mentioned previously pubsub.subscribe('updatedStatus') does pick up the change. So the issue seems to be related to the Subscription resolver.

I'm going off the following docs: http://dev.apollodata.com/tools/graphql-subscriptions/setup.html#setup

答: Turns out I was using an out of date graphql package! Updating to the latest version fixed this problem.</p>

Title: Apollo subscription not working

Body:
I have a graphql server and I'm attempting to trigger an event whenever the status of an entity is updated. I have a mutation for updating the entity, which uses graphql-subscriptions to publish the update for the subscriber to listen to. However, pubsub.subscribe(EVENT_NAME) picked up the change, but when I integrate that into the subscription resolver, it doesn't trigger the update.

I've redacted parts of the code not relevant to the issue for brevity.

My resolver:

Mutation: {
  updateStatus(_, { id, status, hash }) {
    return repository.updateStatus(id, status, hash);
  }
},
Subscription: {
  updatedStatus: {
    subscribe: () => pubsub.asyncIterator('updatedStatus'),
  }
},

My repository:

export const updateStatus = async function(id: String, status: String, hash: String) {
  try {
    const res = await fetch(`${baseURL}/article/${id}/status?publish_hash=${hash}`, {
      headers,
      method: 'PATCH',
      body: JSON.stringify({ status })
    });

    const article = await fetchSingleArticle(id, 'XML', headers.channel, false);

    await pubsub.publish('updatedStatus', article);
    return article;
  } catch (e) {
    console.log(e.message);
  }
}

My schema:

type Mutation {
  updateStatus(id: ID!, status: PublishingStatus = PUBLISHING, hash: String): Article
}

type Subscription {
  updatedStatus(id: ID!): Article
}

schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}

To test this, I'm just using graphiql, which is picking up the websocket connection fine.

I've attempted the publish using both article (as shown) and { updatedStatus: article }, neither seem to get picked up.

As mentioned previously pubsub.subscribe('updatedStatus') does pick up the change. So the issue seems to be related to the Subscription resolver.

I'm going off the following docs: http://dev.apollodata.com/tools/graphql-subscriptions/setup.html#setup


问:
How to use a directive as an entry point when using angular's bootstrap function?
I have an angular 1 app that's being bootstrapped onto a Java web page (legacy app) using ng-app tags. I'm trying to create a hybrid app using Angular 2's downgrade capabilities.

In order to do this I need to remove ng-app tags and use the UpgradeModule from @angular/upgrade/static and bootstrap using the upgrade.bootstrap(document.body, ['myapp']). However, most of the components of the app, including the entry point of the app, are just plain old angular 1.2 directives.

From the examples I've seen, they are using the controller="MenuCtrl" syntax to add components to the page. Is it possible to use directives as the entry point to the app? e.g.

Currently, nothing is showing up in the app since I've removed the ng-app tags, but the app is definitely being bootstrapped. I'm just not seeing any of the directives.

答:
Fixed this by wrapping the bootstrap statement in angular.element() like so:

```<code>angular.element(function() {
  upgrade.bootstrap(document.body, ['myApp'], { strictDi: true });
});
</code>```

Body:
Fixed this by wrapping the bootstrap statement in angular.element() like so:

angular.element(function() {
  upgrade.bootstrap(document.body, ['myApp'], { strictDi: true });
});


问:
better way of handling nested list
```<code>my_list = [ [1,2,3,4,5,6], [1,3,4],[34,56,56,56]]
for item in my_list:
    var1,var2,var3,var4,var5,var6 = None
     if len(item) ==1:
          var1 = item[0]
     if len(item) == 2:
          var1 = item[0]
          var2  = item[1]
     if len(item) == 3:
         var1 = item[0]
         var2 = item[1]
         var3 = item[2]
     if len(item) == 4:
        var1 = item[0]
        var2 = item[1]
        var3 = item[2]
        var4 = item[3]
    fun(var1,var2,var3,var4,var5,var6)
</code>```

I have a function

```<code>def fun(var1, var2 = None, var3 = None, var4 = None, var5=None, var6= None)
</code>```

Depending upon the values in my inner list. I am passing it to function.
I hope I made it clear.

Thanks

答:
See Calls and Function definitions in the Python documentation, specifically:

If the syntax *expression appears in
  the function call, expression must
  evaluate to a sequence. Elements from
  this sequence are treated as if they
  were additional positional
  arguments....

If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments....

...A function call always assigns values
  to all parameters mentioned in the
  parameter list, either from position
  arguments, from keyword arguments, or
  from default values. If the form
  “*identifier” is present, it is
  initialized to a tuple receiving any
  excess positional parameters,
  defaulting to the empty tuple. If the
  form “**identifier” is present, it is
  initialized to a new dictionary
  receiving any excess keyword
  arguments, defaulting to a new empty
  dictionary.

Example 1

You most likely need the following, since your arguments are simple integers:

```<code>my_list = [[1,2,3,4,5,6],[1,3,4],[34,56,56,56]]

def func(*var):
    for arg in var:
        print arg,
    print

for args in my_list:
    func(*args)
</code>```

Output 1

```<code>1 2 3 4 5 6
1 3 4
34 56 56 56
</code>```

Example 2

The next example shows you can fill in any number of arguments to a function with defaults:

```<code>my_list = [[1,2,3,4,5,6],[1,3,4],[34,56,56,56]]

def func(var1=None,var2=None,var3=None,var4=None,var5=None,var6=None):
    print var1,var2,var3,var4,var5,var6

for args in my_list:
    func(*args)
</code>```

Output 2

```<code>1 2 3 4 5 6
1 3 4 None None None
34 56 56 56 None None
</code>```

Example 3

You can even fill them in out-of-order with the ** syntax:

```<code>my_list = [dict(var1=1,var5=5,var6=6),dict(var2=2,var4=4)]

def func(var1=None,var2=None,var3=None,var4=None,var5=None,var6=None):
    print var1,var2,var3,var4,var5,var6

for args in my_list:
    func(**args)
</code>```

Output 3

```<code>1 None None None 5 6
None 2 None 4 None None
</code>```

Title: better way of handling nested list

Body:
my_list = [ [1,2,3,4,5,6], [1,3,4],[34,56,56,56]]
for item in my_list:
    var1,var2,var3,var4,var5,var6 = None
     if len(item) ==1:
          var1 = item[0]
     if len(item) == 2:
          var1 = item[0]
          var2  = item[1]
     if len(item) == 3:
         var1 = item[0]
         var2 = item[1]
         var3 = item[2]
     if len(item) == 4:
        var1 = item[0]
        var2 = item[1]
        var3 = item[2]
        var4 = item[3]
    fun(var1,var2,var3,var4,var5,var6)

I have a function

def fun(var1, var2 = None, var3 = None, var4 = None, var5=None, var6= None)

Depending upon the values in my inner list. I am passing it to function.
I hope I made it clear.

Thanks

Body:
See Calls and Function definitions in the Python documentation, specifically:

If the syntax *expression appears in
  the function call, expression must
  evaluate to a sequence. Elements from
  this sequence are treated as if they
  were additional positional
  arguments....

If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments....

...A function call always assigns values
  to all parameters mentioned in the
  parameter list, either from position
  arguments, from keyword arguments, or
  from default values. If the form
  “*identifier” is present, it is
  initialized to a tuple receiving any
  excess positional parameters,
  defaulting to the empty tuple. If the
  form “**identifier” is present, it is
  initialized to a new dictionary
  receiving any excess keyword
  arguments, defaulting to a new empty
  dictionary.

Example 1

You most likely need the following, since your arguments are simple integers:

my_list = [[1,2,3,4,5,6],[1,3,4],[34,56,56,56]]

def func(*var):
    for arg in var:
        print arg,
    print

for args in my_list:
    func(*args)

Output 1

1 2 3 4 5 6
1 3 4
34 56 56 56

Example 2

The next example shows you can fill in any number of arguments to a function with defaults:

my_list = [[1,2,3,4,5,6],[1,3,4],[34,56,56,56]]

def func(var1=None,var2=None,var3=None,var4=None,var5=None,var6=None):
    print var1,var2,var3,var4,var5,var6

for args in my_list:
    func(*args)

Output 2

1 2 3 4 5 6
1 3 4 None None None
34 56 56 56 None None

Example 3

You can even fill them in out-of-order with the ** syntax:

my_list = [dict(var1=1,var5=5,var6=6),dict(var2=2,var4=4)]

def func(var1=None,var2=None,var3=None,var4=None,var5=None,var6=None):
    print var1,var2,var3,var4,var5,var6

for args in my_list:
    func(**args)

Output 3

1 None None None 5 6
None 2 None 4 None None


问:
Apache Tomcat Maven plugin war not found
I'm following the documentation here but I end up with a jar that doesn't find the war to execute. Here's the error:

```<code>java.io.FileNotFoundException: C:\Users\ortizj\Documents\NetBeansProjects\valida
tion-manager\Validation-Manager-Web\target\.extract\webapps\ROOT.war (The system
 cannot find the file specified)
</code>```

For some reason the war file is not added to the jar so it fails when it's extracting it.

ROOT.war exists and is present in the target folder.

Here's the relevant POM contents:

POM Project:

```<code> <profile>
        <id>installer</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <executions>
                        <execution>
                            <id>tomcat-run</id>
                            <goals>
                                <goal>exec-war-only</goal>
                            </goals>
                            <phase>package</phase>
                            <configuration>
                                <warRunDependency>
                                    <dependency>
                                        <groupId>${project.groupId}</groupId>
                                        <artifactId>Validation-Manager-Web</artifactId>
                                        <version>${project.version}</version>
                                        <type>war</type>
                                    </dependency>
                                    <charset>utf-8</charset>
                                    <httpPort>9078</httpPort>
                                    <contextPath>/</contextPath>
                                </warRunDependency>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</code>```

答:
How about adding this to your pom.xml file..</p>

```<code>                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-war-plugin</artifactId>
                        <version>${maven-war-plugin.version}</version>
                        <configuration>
                            <warSourceDirectory>src/main/webapp</warSourceDirectory>
                            <warName>your-war-name</warName>
                            <failOnMissingWebXml>false</failOnMissingWebXml>
                            <outputDirectory>${deploy-path}</outputDirectory>
                        </configuration>
                    </plugin>
</code>```

Body:
I'm following the documentation here but I end up with a jar that doesn't find the war to execute. Here's the error:

java.io.FileNotFoundException: C:\Users\ortizj\Documents\NetBeansProjects\valida
tion-manager\Validation-Manager-Web\target\.extract\webapps\ROOT.war (The system
 cannot find the file specified)

For some reason the war file is not added to the jar so it fails when it's extracting it.

ROOT.war exists and is present in the target folder.

Here's the relevant POM contents:

POM Project:

 <profile>
        <id>installer</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <executions>
                        <execution>
                            <id>tomcat-run</id>
                            <goals>
                                <goal>exec-war-only</goal>
                            </goals>
                            <phase>package</phase>
                            <configuration>
                                <warRunDependency>
                                    <dependency>
                                        <groupId>${project.groupId}</groupId>
                                        <artifactId>Validation-Manager-Web</artifactId>
                                        <version>${project.version}</version>
                                        <type>war</type>
                                    </dependency>
                                    <charset>utf-8</charset>
                                    <httpPort>9078</httpPort>
                                    <contextPath>/</contextPath>
                                </warRunDependency>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>

Body:
How about adding this to your pom.xml file..

                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-war-plugin</artifactId>
                        <version>${maven-war-plugin.version}</version>
                        <configuration>
                            <warSourceDirectory>src/main/webapp</warSourceDirectory>
                            <warName>your-war-name</warName>
                            <failOnMissingWebXml>false</failOnMissingWebXml>
                            <outputDirectory>${deploy-path}</outputDirectory>
                        </configuration>
                    </plugin>


问:
Bootstrap 4 tabs - Only one isn't working
I'm trying to build an admin section for a site where admins can go in and change things about the site. I've split this page up into different sections using tabs and they've been working up until I added the most recent one and as soon as I did, one of the ones that was already there, stopped working.
Here's the code - The one that isn't working is the "Historical Fact of The Day" tab:

```<code><!-- This is within a .container-fluid -->
<ul class="nav nav-tabs">
    <li class="nav-item">
        <a href="#potd" data-toggle="tab" role="tab" class="nav-link active">Photo of the Day</a>
    </li>
    <li class="nav-item">
        <a href="#users" data-toggle="tab" role="tab" class="nav-link">Users</a>
    </li>
    <li class="nav-item">
        <a href="#forum" data-toggle="tab" role="tab" class="nav-link">Forum</a>
    </li>
    <li class="nav-item">
        <a href="#hfotd" data-toggle="tab" role="tab" class="nav-link">Historical Fact of The Day</a>
    </li>
    <li class="nav-item">
        <a href="#cntdwn" data-toggle="tab" role="tab" class="nav-link">Countdown</a>
    </li>
</ul>

<div class="tab-content">
    <div class="tab-pane active" id="potd">
        <h3>Add a Photo of The Day</h3>
        <?php include 'create_potd.php'; ?>
        <h3>View Upcoming Photos of the Day</h3>
        <?php include 'view_potd.php'; ?>
    </div>
    <div class="tab-pane" id="forum">
        <h3>Create a category</h3>
        <?php include 'create_cat.php'; ?>
    </div>
    <div class="tab-pane" id="users">
        <h3>User List</h3>
        <?php include 'user_list.php'; ?>
    </div>
    <div class="tab-pane" id="hfotd">
        <h3>Add a Historical Fact of The Day</h3>
        <?php include 'create_hfotd.php'; ?>
        <h3>View Upcoming Historical Facts of the Day</h3>
        <?php include 'view_hfotd.php'; ?>
    </div>
    <div class="tab-pane" id="cntdwn">
        <h3>Change the current countdown</h3>
    </div>
</div>
</code>```

I really have no idea what the problem is. Thanks in advance!

答:
Sorry everybody! Realised I was using the #hfotd in a JavaScript function in my footer...
What a numpty.</p>

Body:
I'm trying to build an admin section for a site where admins can go in and change things about the site. I've split this page up into different sections using tabs and they've been working up until I added the most recent one and as soon as I did, one of the ones that was already there, stopped working.
Here's the code - The one that isn't working is the "Historical Fact of The Day" tab:

        Photo of the Day

        Users

        Forum

        Historical Fact of The Day

        Countdown

Add a Photo of The Day

        <?php include 'create_potd.php'; ?>

View Upcoming Photos of the Day

        <?php include 'view_potd.php'; ?>

Create a category

        <?php include 'create_cat.php'; ?>

User List

        <?php include 'user_list.php'; ?>

Add a Historical Fact of The Day

        <?php include 'create_hfotd.php'; ?>

View Upcoming Historical Facts of the Day

        <?php include 'view_hfotd.php'; ?>

Change the current countdown

I really have no idea what the problem is. Thanks in advance!


问:
Angular 4 Observables mouse coordinates
I want to know how it's possible to get mouse coordinates X and Y using only Observables without http service using Angular 4.</p>

答:
Http module is not a dependency for RxJS observables, so you don't have to use it. In fact, Http module itself uses RxJS to empower Http operands with reactive capabilities.

In order to subscribe to events like mousemove, you would simply import fromEvent and Observable and subscribe to its event emitter. Something like this should work:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';

Observable.fromEvent(document.body, 'mousemove').subscribe(e => {
  console.log(e.pageX, e.pageY)
})
```

Of course, use the appropriate event source (instead of document.body).

Title: Angular 4 Observables mouse coordinates

Body:
Http module is not a dependency for RxJS observables, so you don't have to use it. In fact, Http module itself uses RxJS to empower Http operands with reactive capabilities.

In order to subscribe to events like mousemove, you would simply import fromEvent and Observable and subscribe to its event emitter. Something like this should work:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';

Observable.fromEvent(document.body, 'mousemove').subscribe(e => {
  console.log(e.pageX, e.pageY)
})

Of course, use the appropriate event source (instead of document.body).

ContentLicense: CC BY-SA 4.0


问:
How does app know if it started from a crash
Whenever I start the app I want to know if the app recovered from a crash. Can I store it in a flag ?

Do the crash and regular app exit scenario go through the same steps(lifecycle) in android ?

答:
You can override your crash exception by using Thread.setDefaultUncaughtExceptionHandler. But do not forget, If you would not close your application it will freeze the screen by OS.

Example code :

```<code>//variable that inside the application class
private Thread.UncaughtExceptionHandler defaultUEH;
public void onCreate(){
    super.onCreate();
    defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                handleUncaughtException(t,e);
                defaultUEH.uncaughtException(thread,e);
            }
        });
}

private void handleUncaughtException(Thread thread,Throwable e){
      //do whatever you like!

}
</code>```

NOTE : There is no way to understand how is your program is opened

Body:
You can override your crash exception by using Thread.setDefaultUncaughtExceptionHandler. But do not forget, If you would not close your application it will freeze the screen by OS.

Example code :

//variable that inside the application class
private Thread.UncaughtExceptionHandler defaultUEH;
public void onCreate(){
    super.onCreate();
    defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                handleUncaughtException(t,e);
                defaultUEH.uncaughtException(thread,e);
            }
        });
}

private void handleUncaughtException(Thread thread,Throwable e){
      //do whatever you like!

}

NOTE : There is no way to understand how is your program is opened


问:
UrlRewriteFilter: www and https redirect
I am using Tuckey UrlRewriteFilter to force users to go to the 'www' and 'https' version of my web. I mean next 3 URLs must redirect to https://www.myweb.com

http://www.myweb.com

http://myweb.com

https://myweb.com

The problem comes with the last one, I cannot find the solution to put 'www' for 'https'. I have the next rule that makes 2 first cases work without problems:

```<code>  <rule>
    <name>Domain Name Check</name>
    <condition name="host" operator="equal">myweb.com$</condition>
    <condition type="scheme" operator="equal">^http$</condition>
    <from>^(.*)$</from>
    <to type="permanent-redirect">https://www.myweb.com$1</to>
  </rule>
</code>```

This one of course does not apply for the third case. If I try a similar rule for the third case like the following, it doesn't work either (I don't know why):

```<code>  <rule>
    <name>Domain Name Check</name>
    <condition name="host" operator="equal">myweb.com$</condition>
    <condition type="scheme" operator="equal">^https$</condition>
    <from>^(.*)$</from>
    <to type="permanent-redirect">https://www.myweb.com$1</to>
  </rule>
</code>```

Could you please help me to figure out the rule for the third case?

Thank you.

答:
The problem was not the filter but my certificate. I issued my certificate for www.myweb.com but not for myweb.com so https://myweb.com request didn't reach my server, the browser detected the certificate was not valid and blocked the process.

I just issued my certificate for https://myweb.com and modified my Tuckey rule as you can see below. Now https://www.myweb.com is the only URL users can use.

```<code>  <rule>
    <name>Domain Name Check</name>
    <condition type="request-url" operator="equal">(^http://myweb.com|^http://www.myweb.com|^https://myweb.com)</condition>
    <from>^(.*)$</from>
    <to type="redirect">https://www.myweb.com$1</to>
  </rule>
</code>```

Body:
I am using Tuckey UrlRewriteFilter to force users to go to the 'www' and 'https' version of my web. I mean next 3 URLs must redirect to https://www.myweb.com

http://www.myweb.com

http://myweb.com

https://myweb.com

The problem comes with the last one, I cannot find the solution to put 'www' for 'https'. I have the next rule that makes 2 first cases work without problems:

  <rule>
    <name>Domain Name Check</name>
    <condition name="host" operator="equal">myweb.com$</condition>
    <condition type="scheme" operator="equal">^http$</condition>
    <from>^(.*)$</from>
    <to type="permanent-redirect">https://www.myweb.com$1</to>
  </rule>

This one of course does not apply for the third case. If I try a similar rule for the third case like the following, it doesn't work either (I don't know why):

  <rule>
    <name>Domain Name Check</name>
    <condition name="host" operator="equal">myweb.com$</condition>
    <condition type="scheme" operator="equal">^https$</condition>
    <from>^(.*)$</from>
    <to type="permanent-redirect">https://www.myweb.com$1</to>
  </rule>

Could you please help me to figure out the rule for the third case?

Thank you.

Body:
The problem was not the filter but my certificate. I issued my certificate for www.myweb.com but not for myweb.com so https://myweb.com request didn't reach my server, the browser detected the certificate was not valid and blocked the process.

I just issued my certificate for https://myweb.com and modified my Tuckey rule as you can see below. Now https://www.myweb.com is the only URL users can use.

  <rule>
    <name>Domain Name Check</name>
    <condition type="request-url" operator="equal">(^http://myweb.com|^http://www.myweb.com|^https://myweb.com)</condition>
    <from>^(.*)$</from>
    <to type="redirect">https://www.myweb.com$1</to>
  </rule>


问:
Loop over Json using Jquery
Below is my Json Data received from Ajax response.

```<code>{
    "error": {
        "errorCode": "0001",
        "errorText": "SUCCESS"
    },
    "responselist": [
        {
            "count": 2,
            "event": [
                {
                    "startDate": null,
                    "eventId": 1234,
                    "eventName": "Interview",
                    "modifiedUser": "User",
                    "eventTypeCode": "1",
                    "eventVenue": null,
                    "eventSpecialInst": "isnsdf",
                    "eventStatusCode": "OP",
                    "eventLangCode": "Eng",
                    "eventDesc": "sdfsadfsd",
                    "fromEmailId": "Abcd@apple.com",
                    "rsvpDeadline": 5,
                    "canceledInd": "yes",
                    "canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
                    "daysToWaitlistLastCall": 5,
                    "daysToReminderAdmin": 6,
                    "daysToReminderEvent": 3,
                    "daysToReminderInvitation": 2,
                    "endDate": null,
                    "venueAddrLine1": null,
                    "venueAddrLine2": null,
                    "venueAddrLine3": null,
                    "cityCode": null,
                    "stateCode": null,
                    "appId": null,
                    "modifiedDate": "2010-12-16",
                    "countryCode": null,
                    "zipCode": null,
                    "user_id": null,
                    "updateFlag": "R"
                },
                {
                    "startDate": null,
                    "eventId": 4321,
                    "eventName": "Seasonal Hiring",
                    "modifiedUser": "User",
                    "eventTypeCode": "1",
                    "eventVenue": null,
                    "eventSpecialInst": "isnsdf",
                    "eventStatusCode": "OP",
                    "eventLangCode": "Eng",
                    "eventDesc": "sdfsadfsd",
                    "fromEmailId": "Abcd@apple.com",
                    "rsvpDeadline": 5,
                    "canceledInd": "yes",
                    "canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
                    "daysToWaitlistLastCall": 5,
                    "daysToReminderAdmin": 6,
                    "daysToReminderEvent": 3,
                    "daysToReminderInvitation": 2,
                    "endDate": null,
                    "venueAddrLine1": "KFC",
                    "venueAddrLine2": "The Forum",
                    "venueAddrLine3": "Koramangala",
                    "cityCode": "Bangalore",
                    "stateCode": "Karnataka",
                    "appId": null,
                    "modifiedDate": "2010-12-16",
                    "countryCode": "India",
                    "zipCode": "560040",
                    "user_id": null,
                    "updateFlag": "R"
                }
            ]
        }
    ]
}
</code>```

Using below code to extract information inside event object. But I am not able to do it. Need guidance.

```<code>$.ajax({ url:"<%=request.getContextPath()%>/service/showInvitedEvents/21",

         dataType:"json",
         success: function(jsonData)
         {
           alert("Inside response success");

           $.each(jsonData.responselist.event,function(i,item)
          $.each(Employees,function(i,item)
           {
             alert('Iteration is' + i);
            var teventName = item.eventName;

            var teventVenue = item.eventVenue;
            var tstartDate = item.startDate;
            var tendDate = item.endDate;
            var tstarend = tstartDate +" - "+ tendDate ;

            $("#eventTable tbody").append("<tr><td><a id="+teventName+i+" href=<%=request.getContextPath()%>/service/session/1234>"+teventName+"</a></td><td>"+teventVenue+"</td><td>"+tstarend+"</td></tr>");

           });
</code>```

答:
What is the purpose of the following line in your code:?

```<code>$.each(Employees,function(i,item)
</code>```

Try removing it and see what happens.

Title: Loop over Json using Jquery

Body:
Below is my Json Data received from Ajax response.

{
    "error": {
        "errorCode": "0001",
        "errorText": "SUCCESS"
    },
    "responselist": [
        {
            "count": 2,
            "event": [
                {
                    "startDate": null,
                    "eventId": 1234,
                    "eventName": "Interview",
                    "modifiedUser": "User",
                    "eventTypeCode": "1",
                    "eventVenue": null,
                    "eventSpecialInst": "isnsdf",
                    "eventStatusCode": "OP",
                    "eventLangCode": "Eng",
                    "eventDesc": "sdfsadfsd",
                    "fromEmailId": "Abcd@apple.com",
                    "rsvpDeadline": 5,
                    "canceledInd": "yes",
                    "canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
                    "daysToWaitlistLastCall": 5,
                    "daysToReminderAdmin": 6,
                    "daysToReminderEvent": 3,
                    "daysToReminderInvitation": 2,
                    "endDate": null,
                    "venueAddrLine1": null,
                    "venueAddrLine2": null,
                    "venueAddrLine3": null,
                    "cityCode": null,
                    "stateCode": null,
                    "appId": null,
                    "modifiedDate": "2010-12-16",
                    "countryCode": null,
                    "zipCode": null,
                    "user_id": null,
                    "updateFlag": "R"
                },
                {
                    "startDate": null,
                    "eventId": 4321,
                    "eventName": "Seasonal Hiring",
                    "modifiedUser": "User",
                    "eventTypeCode": "1",
                    "eventVenue": null,
                    "eventSpecialInst": "isnsdf",
                    "eventStatusCode": "OP",
                    "eventLangCode": "Eng",
                    "eventDesc": "sdfsadfsd",
                    "fromEmailId": "Abcd@apple.com",
                    "rsvpDeadline": 5,
                    "canceledInd": "yes",
                    "canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
                    "daysToWaitlistLastCall": 5,
                    "daysToReminderAdmin": 6,
                    "daysToReminderEvent": 3,
                    "daysToReminderInvitation": 2,
                    "endDate": null,
                    "venueAddrLine1": "KFC",
                    "venueAddrLine2": "The Forum",
                    "venueAddrLine3": "Koramangala",
                    "cityCode": "Bangalore",
                    "stateCode": "Karnataka",
                    "appId": null,
                    "modifiedDate": "2010-12-16",
                    "countryCode": "India",
                    "zipCode": "560040",
                    "user_id": null,
                    "updateFlag": "R"
                }
            ]
        }
    ]
}

Using below code to extract information inside event object. But I am not able to do it. Need guidance.

$.ajax({ url:"<%=request.getContextPath()%>/service/showInvitedEvents/21",

         dataType:"json",
         success: function(jsonData)
         {
           alert("Inside response success");

           $.each(jsonData.responselist.event,function(i,item)
          $.each(Employees,function(i,item)
           {
             alert('Iteration is' + i);
            var teventName = item.eventName;

            var teventVenue = item.eventVenue;
            var tstartDate = item.startDate;
            var tendDate = item.endDate;
            var tstarend = tstartDate +" - "+ tendDate ;

            $("#eventTable tbody").append("
<a id="+teventName+i+" href=<%=request.getContextPath()%>/service/session/1234>"+teventName+"	"+teventVenue+"	"+tstarend+"
");

           });

Body:
What is the purpose of the following line in your code:?

$.each(Employees,function(i,item)

Try removing it and see what happens.


问:
Show TimePicker with minutes intervals in android
My application show a TimePickerDialog to set a time.
I want that the timePickerDialog show the minutes with an interval of 5 minutes.

This works fine with this code:

```<code>private final int TIME_PICKER_INTERVAL=5;
private boolean mIgnoreEvent=false;
…
    public TimePickerDialogs(Context arg0, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
    super(arg0, callBack, hourOfDay, minute, is24HourView);

    formato=Statics.formato;
}

@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
    //super.onTimeChanged(arg0, arg1, arg2);

    if (mIgnoreEvent)
        return;
    if (minute%TIME_PICKER_INTERVAL!=0){
        int minuteFloor=minute-(minute%TIME_PICKER_INTERVAL);
        minute=minuteFloor + (minute==minuteFloor+1 ? TIME_PICKER_INTERVAL : 0);
        if (minute==60)
            minute=0;
        mIgnoreEvent=true;
        view.setCurrentMinute(minute);
        mIgnoreEvent=false;
    }
}
</code>```

Although only minutes can be selected with an interval of five minutes, the timepickerdialog looks like:

do not know how the minutes also show the range of 5 minutes, as in this picture:

I have searched but can not find the solution.

答:
The answer above works really fine for older version of Android, but it didn't work for me in Android 7 Nougat, basically the date picker is changed completely to use the Clock mode... I kind of merge the code proposed here with https://gist.github.com/jeffdgr8/6bc5f990bf0c13a7334ce385d482af9f, then it set by default the mode of the TimePickerDialog to show the Spinner controls, and it runs the code to show only 15minuts intervals in my case.

The code is posted here https://gist.github.com/smaugho/14dae83f3284fa05455ee0a9e4f13099

```<code>public class CustomTimePickerDialog extends TimePickerDialog {

private final static int TIME_PICKER_INTERVAL = 15;
private TimePicker timePicker;
private final OnTimeSetListener callback;

  public HorekoTimePicker(Context context,
        OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
      super(context, callBack, hourOfDay, minute/TIME_PICKER_INTERVAL, is24HourView);
      this.callback = callBack;
    fixSpinner(context, hourOfDay, minute, is24HourView);
  }

/**
 * Workaround for this bug: https://code.google.com/p/android/issues/detail?id=222208
 * In Android 7.0 Nougat, spinner mode for the TimePicker in TimePickerDialog is
 * incorrectly displayed as clock, even when the theme specifies otherwise, such as:
 *
 *  <resources>
 *      <style name="Theme.MyApp" parent="Theme.AppCompat.Light.NoActionBar">
 *          <item name="android:timePickerStyle">@style/Widget.MyApp.TimePicker</item>
 *      </style>
 *
 *      <style name="Widget.MyApp.TimePicker" parent="android:Widget.Material.TimePicker">
 *          <item name="android:timePickerMode">spinner</item>
 *      </style>
 *  </resources>
 *
 * May also pass TimePickerDialog.THEME_HOLO_LIGHT as an argument to the constructor,
 * as this theme has the TimePickerMode set to spinner.
 *
 * Taken from: https://gist.github.com/jeffdgr8/6bc5f990bf0c13a7334ce385d482af9f
 */
private void fixSpinner(Context context, int hourOfDay, int minute, boolean is24HourView) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // android:timePickerMode spinner and clock began in Lollipop
        try {

            // Get the theme's android:timePickerMode
            final int MODE_SPINNER = 1;
            Class<?> styleableClass = Class.forName("com.android.internal.R$styleable");
            Field timePickerStyleableField = styleableClass.getField("TimePicker");
            int[] timePickerStyleable = (int[]) timePickerStyleableField.get(null);
            final TypedArray a = context.obtainStyledAttributes(null, timePickerStyleable, android.R.attr.timePickerStyle, 0);
            Field timePickerModeStyleableField = styleableClass.getField("TimePicker_timePickerMode");
            int timePickerModeStyleable = timePickerModeStyleableField.getInt(null);
            final int mode = a.getInt(timePickerModeStyleable, MODE_SPINNER);
            a.recycle();

            if (mode == MODE_SPINNER) {

                timePicker = (TimePicker) findField(TimePickerDialog.class, TimePicker.class, "mTimePicker").get(this);
                Class<?> delegateClass = Class.forName("android.widget.TimePicker$TimePickerDelegate");
                Field delegateField = findField(TimePicker.class, delegateClass, "mDelegate");
                Object delegate = delegateField.get(timePicker);
                Class<?> spinnerDelegateClass;
                if (Build.VERSION.SDK_INT != Build.VERSION_CODES.LOLLIPOP) {
                    spinnerDelegateClass = Class.forName("android.widget.TimePickerSpinnerDelegate");
                } else {
                    // TimePickerSpinnerDelegate was initially misnamed TimePickerClockDelegate in API 21!
                    spinnerDelegateClass = Class.forName("android.widget.TimePickerClockDelegate");
                }

                // In 7.0 Nougat for some reason the timePickerMode is ignored and the delegate is TimePickerClockDelegate
                if (delegate.getClass() != spinnerDelegateClass) {
                    delegateField.set(timePicker, null); // throw out the TimePickerClockDelegate!
                    timePicker.removeAllViews(); // remove the TimePickerClockDelegate views
                    Constructor spinnerDelegateConstructor = spinnerDelegateClass.getConstructor(TimePicker.class, Context.class, AttributeSet.class, int.class, int.class);
                    spinnerDelegateConstructor.setAccessible(true);
                    // Instantiate a TimePickerSpinnerDelegate
                    delegate = spinnerDelegateConstructor.newInstance(timePicker, context, null, android.R.attr.timePickerStyle, 0);
                    delegateField.set(timePicker, delegate); // set the TimePicker.mDelegate to the spinner delegate
                    // Set up the TimePicker again, with the TimePickerSpinnerDelegate
                    timePicker.setIs24HourView(is24HourView);
                    timePicker.setCurrentHour(hourOfDay);
                    timePicker.setCurrentMinute(minute);
                    timePicker.setOnTimeChangedListener(this);
                }

                setTimeIntervals();
            }

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

private static Field findField(Class objectClass, Class fieldClass, String expectedName) {
    try {
        Field field = objectClass.getDeclaredField(expectedName);
        field.setAccessible(true);
        return field;
    } catch (NoSuchFieldException e) {} // ignore
    // search for it if it wasn't found under the expected ivar name
    for (Field searchField : objectClass.getDeclaredFields()) {
        if (searchField.getType() == fieldClass) {
            searchField.setAccessible(true);
            return searchField;
        }
    }
    return null;
}

  @Override
protected void onStop() { }

/*
 * Feature #363: (Un)availability times in 15min interval
 * https://abix.webhop.net/redmine/issues/363
 * Solution extracted from
 * http://stackoverflow.com/questions/20214547/show-timepicker-with-minutes-intervals-in-android
 */

@Override
public void onClick(DialogInterface dialog, int which) {
    super.onClick(dialog, which);

    if (callback != null && timePicker != null) {
        timePicker.clearFocus();
        callback.onTimeSet(timePicker, timePicker.getCurrentHour(),
            timePicker.getCurrentMinute()*TIME_PICKER_INTERVAL);
    }
}

private void setTimeIntervals() {
    try {
        Class<?> classForid = Class.forName("com.android.internal.R$id");
        Field field = classForid.getField("minute");

        NumberPicker mMinuteSpinner = (NumberPicker) timePicker.findViewById(field.getInt(null));
        mMinuteSpinner.setMinValue(0);
        mMinuteSpinner.setMaxValue((60 / TIME_PICKER_INTERVAL) - 1);
        List<String> displayedValues = new ArrayList<String>();
        for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            displayedValues.add(String.format("%02d", i));
        }
        mMinuteSpinner.setDisplayedValues(displayedValues.toArray(new String[0]));

    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

}

Body:
My application show a TimePickerDialog to set a time.
I want that the timePickerDialog show the minutes with an interval of 5 minutes.

This works fine with this code:

private final int TIME_PICKER_INTERVAL=5;
private boolean mIgnoreEvent=false;
…
    public TimePickerDialogs(Context arg0, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
    super(arg0, callBack, hourOfDay, minute, is24HourView);

    formato=Statics.formato;
}

@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
    //super.onTimeChanged(arg0, arg1, arg2);

    if (mIgnoreEvent)
        return;
    if (minute%TIME_PICKER_INTERVAL!=0){
        int minuteFloor=minute-(minute%TIME_PICKER_INTERVAL);
        minute=minuteFloor + (minute==minuteFloor+1 ? TIME_PICKER_INTERVAL : 0);
        if (minute==60)
            minute=0;
        mIgnoreEvent=true;
        view.setCurrentMinute(minute);
        mIgnoreEvent=false;
    }
}

Although only minutes can be selected with an interval of five minutes, the timepickerdialog looks like:

do not know how the minutes also show the range of 5 minutes, as in this picture:

I have searched but can not find the solution.

Body:
The answer above works really fine for older version of Android, but it didn't work for me in Android 7 Nougat, basically the date picker is changed completely to use the Clock mode... I kind of merge the code proposed here with https://gist.github.com/jeffdgr8/6bc5f990bf0c13a7334ce385d482af9f, then it set by default the mode of the TimePickerDialog to show the Spinner controls, and it runs the code to show only 15minuts intervals in my case.

The code is posted here https://gist.github.com/smaugho/14dae83f3284fa05455ee0a9e4f13099

public class CustomTimePickerDialog extends TimePickerDialog {

private final static int TIME_PICKER_INTERVAL = 15;
private TimePicker timePicker;
private final OnTimeSetListener callback;

  public HorekoTimePicker(Context context,
        OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
      super(context, callBack, hourOfDay, minute/TIME_PICKER_INTERVAL, is24HourView);
      this.callback = callBack;
    fixSpinner(context, hourOfDay, minute, is24HourView);
  }

/**
 * Workaround for this bug: https://code.google.com/p/android/issues/detail?id=222208
 * In Android 7.0 Nougat, spinner mode for the TimePicker in TimePickerDialog is
 * incorrectly displayed as clock, even when the theme specifies otherwise, such as:
 *
 *  <resources>
 *      <style name="Theme.MyApp" parent="Theme.AppCompat.Light.NoActionBar">
 *          <item name="android:timePickerStyle">@style/Widget.MyApp.TimePicker</item>
 *      </style>
 *
 *      <style name="Widget.MyApp.TimePicker" parent="android:Widget.Material.TimePicker">
 *          <item name="android:timePickerMode">spinner</item>
 *      </style>
 *  </resources>
 *
 * May also pass TimePickerDialog.THEME_HOLO_LIGHT as an argument to the constructor,
 * as this theme has the TimePickerMode set to spinner.
 *
 * Taken from: https://gist.github.com/jeffdgr8/6bc5f990bf0c13a7334ce385d482af9f
 */
private void fixSpinner(Context context, int hourOfDay, int minute, boolean is24HourView) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // android:timePickerMode spinner and clock began in Lollipop
        try {

            // Get the theme's android:timePickerMode
            final int MODE_SPINNER = 1;
            Class<?> styleableClass = Class.forName("com.android.internal.R$styleable");
            Field timePickerStyleableField = styleableClass.getField("TimePicker");
            int[] timePickerStyleable = (int[]) timePickerStyleableField.get(null);
            final TypedArray a = context.obtainStyledAttributes(null, timePickerStyleable, android.R.attr.timePickerStyle, 0);
            Field timePickerModeStyleableField = styleableClass.getField("TimePicker_timePickerMode");
            int timePickerModeStyleable = timePickerModeStyleableField.getInt(null);
            final int mode = a.getInt(timePickerModeStyleable, MODE_SPINNER);
            a.recycle();

            if (mode == MODE_SPINNER) {

                timePicker = (TimePicker) findField(TimePickerDialog.class, TimePicker.class, "mTimePicker").get(this);
                Class<?> delegateClass = Class.forName("android.widget.TimePicker$TimePickerDelegate");
                Field delegateField = findField(TimePicker.class, delegateClass, "mDelegate");
                Object delegate = delegateField.get(timePicker);
                Class<?> spinnerDelegateClass;
                if (Build.VERSION.SDK_INT != Build.VERSION_CODES.LOLLIPOP) {
                    spinnerDelegateClass = Class.forName("android.widget.TimePickerSpinnerDelegate");
                } else {
                    // TimePickerSpinnerDelegate was initially misnamed TimePickerClockDelegate in API 21!
                    spinnerDelegateClass = Class.forName("android.widget.TimePickerClockDelegate");
                }

                // In 7.0 Nougat for some reason the timePickerMode is ignored and the delegate is TimePickerClockDelegate
                if (delegate.getClass() != spinnerDelegateClass) {
                    delegateField.set(timePicker, null); // throw out the TimePickerClockDelegate!
                    timePicker.removeAllViews(); // remove the TimePickerClockDelegate views
                    Constructor spinnerDelegateConstructor = spinnerDelegateClass.getConstructor(TimePicker.class, Context.class, AttributeSet.class, int.class, int.class);
                    spinnerDelegateConstructor.setAccessible(true);
                    // Instantiate a TimePickerSpinnerDelegate
                    delegate = spinnerDelegateConstructor.newInstance(timePicker, context, null, android.R.attr.timePickerStyle, 0);
                    delegateField.set(timePicker, delegate); // set the TimePicker.mDelegate to the spinner delegate
                    // Set up the TimePicker again, with the TimePickerSpinnerDelegate
                    timePicker.setIs24HourView(is24HourView);
                    timePicker.setCurrentHour(hourOfDay);
                    timePicker.setCurrentMinute(minute);
                    timePicker.setOnTimeChangedListener(this);
                }

                setTimeIntervals();
            }

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

private static Field findField(Class objectClass, Class fieldClass, String expectedName) {
    try {
        Field field = objectClass.getDeclaredField(expectedName);
        field.setAccessible(true);
        return field;
    } catch (NoSuchFieldException e) {} // ignore
    // search for it if it wasn't found under the expected ivar name
    for (Field searchField : objectClass.getDeclaredFields()) {
        if (searchField.getType() == fieldClass) {
            searchField.setAccessible(true);
            return searchField;
        }
    }
    return null;
}

  @Override
protected void onStop() { }

/*
 * Feature #363: (Un)availability times in 15min interval
 * https://abix.webhop.net/redmine/issues/363
 * Solution extracted from
 * http://stackoverflow.com/questions/20214547/show-timepicker-with-minutes-intervals-in-android
 */

@Override
public void onClick(DialogInterface dialog, int which) {
    super.onClick(dialog, which);

    if (callback != null && timePicker != null) {
        timePicker.clearFocus();
        callback.onTimeSet(timePicker, timePicker.getCurrentHour(),
            timePicker.getCurrentMinute()*TIME_PICKER_INTERVAL);
    }
}

private void setTimeIntervals() {
    try {
        Class<?> classForid = Class.forName("com.android.internal.R$id");
        Field field = classForid.getField("minute");

        NumberPicker mMinuteSpinner = (NumberPicker) timePicker.findViewById(field.getInt(null));
        mMinuteSpinner.setMinValue(0);
        mMinuteSpinner.setMaxValue((60 / TIME_PICKER_INTERVAL) - 1);
        List<String> displayedValues = new ArrayList<String>();
        for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            displayedValues.add(String.format("%02d", i));
        }
        mMinuteSpinner.setDisplayedValues(displayedValues.toArray(new String[0]));

    } catch (Exception e) {
        e.printStackTrace();
    }

}

}


问:
Stitch multiple images using OpenCV (Python)
Hi have seen a lot of tutorials how to do simple image stitching using two photos and that is no problem.

But what to do when I want to make a panorama from 4-6 images or more?

I have code that takes in list of image files(the images are in order from the first image in the sequence to the last). Then for each image I compute the SIFT feature descriptors
. But then I am stuck, for two images I would set up a matcher using FLANN kd-tree and find matches between the images and calculate the Homography. Similar to this tutorial http://docs.opencv.org/trunk/doc/py_tutorials/py_feature2d/py_feature_homography/py_feature_homography.html#py-feature-homography

But in stead of showing the lines between feature points at the end I have used this https://stackoverflow.com/a/20355545/622194 function to make a panorama from 2 images. But I am not sure what to do when I want to add the third and the fourth image to the panorama.

EDIT:

From the answers I have tried to implement my image stitching script to calculate a homography matrix between images that are next to each other in the image sequence. So if I have I1 I2 I3 and I4 I now have H_12, H_23 and H_34. Then I start by stitching I1 and I2 using H_12. Then I want to find cumulative homography to stitch I3 to the current panorama. I fing H_13 = H_12*H_23 and stitch the image 3 to the current panorama but here I get very apparent gap in my panorama image and when next image is stitched it is even bigger gap and the images is very stretched.

Can anyone tell me if I am using right approach for this or can someone spot the error or see what I am doing wrong.

答:
I had the similar problem with gaps between images.
The first thing you should do is to init your accumulated homography matrix to identity at first frame.
Then, with every new frame you should multiply it by homography matrix between current and next frame. Be aware to use numpy matrices and not numpy arrays. IDK why but they have different multiplication routines.

Here is my code:

```<code>def addFramePair(self, images, ratio=0.75, reprojThresh=4.0, showMatches=False):
    (imageA, imageB) = images
    (kpsA, featuresA) = self.detectAndDescribe(imageA)
    (kpsB, featuresB) = self.detectAndDescribe(imageB)

    H = self.matchKeypoints(kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh)
    self.accHomography *= np.asmatrix(H)
    result = cv2.warpPerspective(imageA, np.linalg.inv(self.accHomography), (1600, 900))
    return result
</code>```

imageA is current, imageB is the next one.

Hope this helps.

Body:
I had the similar problem with gaps between images.
The first thing you should do is to init your accumulated homography matrix to identity at first frame.
Then, with every new frame you should multiply it by homography matrix between current and next frame. Be aware to use numpy matrices and not numpy arrays. IDK why but they have different multiplication routines.

Here is my code:

def addFramePair(self, images, ratio=0.75, reprojThresh=4.0, showMatches=False):
    (imageA, imageB) = images
    (kpsA, featuresA) = self.detectAndDescribe(imageA)
    (kpsB, featuresB) = self.detectAndDescribe(imageB)

    H = self.matchKeypoints(kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh)
    self.accHomography *= np.asmatrix(H)
    result = cv2.warpPerspective(imageA, np.linalg.inv(self.accHomography), (1600, 900))
    return result

imageA is current, imageB is the next one.

Hope this helps.


问:
Bower packages don't install
I am trying to install bower packages, in the site of bower is written I must install them following way:

```<code>bower install <package>
</code>```

But it doesn't want to install this kinda way. Instead,it tells me something like:

```<code>ENOGIT git is not installed or not in the PATH
</code>```

How to deal with this kinda problem?

Thank you.

答: you have to install git, some package in bower depend on git to be installed</p>

Title: Bower packages don't install

Body:
I am trying to install bower packages, in the site of bower is written I must install them following way:

bower install <package>

But it doesn't want to install this kinda way. Instead,it tells me something like:

ENOGIT git is not installed or not in the PATH

How to deal with this kinda problem?

Thank you.


问:
How to link commands between user control and main in MVVM
I have a user control which have one TextBox and one Button called View. The TextBox takes index values.

On my Main view, I have one list view which will display all lines in a file.
An ObservableCollection is Bind to this.

What I need is, when index value is entered in the TextBox and View Button is clicked(in the user control), the SelecedIndex of the ListView(in the Main) should be changed to the index value.

How can I achieve this using MVVM?

Also, Please provide the proper approach to do this if I am doing it wrong.

Here is my UserControl Code:

XAML

```<code><UserControl.DataContext>
    <VM:IndexView_VM ></VM:IndexView_VM>
</UserControl.DataContext>
<Grid Background="White">
    <TextBlock Margin="10,12,168,9" Text="Index : "/>
    <TextBox Text="{Binding Index}" x:Name="TB_Index" Margin="53,11,90,8" />
    <Button Command="{Binding View_CMD}" x:Name="BT_View" Content="View" Margin="136,11,10,8" />
</Grid>
</code>```

ViewModel

```<code>public class IndexView_VM : ViewModelBase
{
    public IndexView_VM()
    {
        View_CMD = new RelayCommand(_View_CMD);
    }

    int _Index;
    public int Index
    {
        get { return _Index; }
        set
        {
            _Index = value;
            RaisePropertyChanged();
        }
    }

    public RelayCommand View_CMD { get; set; }
    internal void _View_CMD(object Parameter)
    {
        // What to write here?
    }
}
</code>```

Here is the Main View:

XAML

```<code><UserControl.DataContext>
        <VM:MainView_VM></VM:MainView_VM>
    </UserControl.DataContext>
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="111*"/>
            <ColumnDefinition Width="100*"/>
        </Grid.ColumnDefinitions>
        <StackPanel>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
        </StackPanel>
        <ListView ItemsSource="{Binding FileData}" x:Name="listView" Grid.Column="1" >
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Data" Width="100"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</code>```

View Model

```<code>public class MainView_VM : ViewModelBase
{
    public MainView_VM()
    {
        ReadFile();
    }

    public ObservableCollection<string> FileData { get; set; }

    void ReadFile()
    {
        //I will read file here.
    }
}
</code>```

答:
Not sure if I understand this right. You want to set the selected item of your ListBox using the index value you type in that TextBox, is this right?

If this is is right then I have the following considerations:

In this scenario a UserControl is probably overkill. Especially if you are going to never re-use it somewhere else in your UI.

Given the first consideration, all you have to do is move that TextBox to your main view, give it a name and bind the .Text Property to your ListView's SelectedIndex Property.

Example:

```<code><ListView SelectedIndex="{Binding ElementName=txtIndex, Path=Text, Converter={StaticResource StringToIntConverter}, UpdateSourceTrigger=PropertyChanged}" />
</code>```

That converter (which you would need to implement) is needed because converting a string to an int won't probably happen automatically. UpdateSourceTrigger=PropertyChanged will update the target Property as soon as you type, removing the need for a button.

At that point you should be done.

If you absolutely need that UserControl, you could add a DependencyProperty exposing the TextBox's value. Then you could bind to that Property as in the example above.

Body:
I have a user control which have one TextBox and one Button called View. The TextBox takes index values.

On my Main view, I have one list view which will display all lines in a file.
An ObservableCollection is Bind to this.

What I need is, when index value is entered in the TextBox and View Button is clicked(in the user control), the SelecedIndex of the ListView(in the Main) should be changed to the index value.

How can I achieve this using MVVM?

Also, Please provide the proper approach to do this if I am doing it wrong.

Here is my UserControl Code:

XAML

<UserControl.DataContext>
    <VM:IndexView_VM ></VM:IndexView_VM>
</UserControl.DataContext>
<Grid Background="White">
    <TextBlock Margin="10,12,168,9" Text="Index : "/>
    <TextBox Text="{Binding Index}" x:Name="TB_Index" Margin="53,11,90,8" />
    <Button Command="{Binding View_CMD}" x:Name="BT_View" Content="View" Margin="136,11,10,8" />
</Grid>

ViewModel

public class IndexView_VM : ViewModelBase
{
    public IndexView_VM()
    {
        View_CMD = new RelayCommand(_View_CMD);
    }

    int _Index;
    public int Index
    {
        get { return _Index; }
        set
        {
            _Index = value;
            RaisePropertyChanged();
        }
    }

    public RelayCommand View_CMD { get; set; }
    internal void _View_CMD(object Parameter)
    {
        // What to write here?
    }
}

Here is the Main View:

XAML

<UserControl.DataContext>
        <VM:MainView_VM></VM:MainView_VM>
    </UserControl.DataContext>
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="111*"/>
            <ColumnDefinition Width="100*"/>
        </Grid.ColumnDefinitions>
        <StackPanel>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
        </StackPanel>
        <ListView ItemsSource="{Binding FileData}" x:Name="listView" Grid.Column="1" >
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Data" Width="100"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

View Model

public class MainView_VM : ViewModelBase
{
    public MainView_VM()
    {
        ReadFile();
    }

    public ObservableCollection<string> FileData { get; set; }

    void ReadFile()
    {
        //I will read file here.
    }
}

Body:
Not sure if I understand this right. You want to set the selected item of your ListBox using the index value you type in that TextBox, is this right?

If this is is right then I have the following considerations:

In this scenario a UserControl is probably overkill. Especially if you are going to never re-use it somewhere else in your UI.

Given the first consideration, all you have to do is move that TextBox to your main view, give it a name and bind the .Text Property to your ListView's SelectedIndex Property.

Example:

<ListView SelectedIndex="{Binding ElementName=txtIndex, Path=Text, Converter={StaticResource StringToIntConverter}, UpdateSourceTrigger=PropertyChanged}" />

That converter (which you would need to implement) is needed because converting a string to an int won't probably happen automatically. UpdateSourceTrigger=PropertyChanged will update the target Property as soon as you type, removing the need for a button.

At that point you should be done.

If you absolutely need that UserControl, you could add a DependencyProperty exposing the TextBox's value. Then you could bind to that Property as in the example above.


问:
jQuery selectors not working in .load() complete callback
I am using nakupanda bootstrap3-dialog library for modals. Below is the code for creating and showing dialog:

```<code>function createIncommingCallDialog(msg){
  offermsg = msg;
  incommingCallDialog = new BootstrapDialog({
      message: $('<div></div>').load('./RemoteDialog.html', function() {
        //this code is not working. Neither .text() nor .click() has any
        //affect.
        $('.caller').text(offermsg.from);
        $('.incomming').text('incoming call');
        $('#accept').click(function(){
          incommingCallDialog.close();
        });
        $('#decline').click(function(){
          incommingCallDialog.close();
        });
      }),
      closable: false,
  });
  incommingCallDialog.realize();
  incommingCallDialog.getModalFooter().hide();
  incommingCallDialog.getModalHeader().hide();
  incommingCallDialog.getModalBody().css('background-color', '#1A1A1A');
  incommingCallDialog.getModalBody().css('color', '#fff');
  incommingCallDialog.open();
}
</code>```

I am loading a remote html in the dialog using jquery's .load() method and when it completes i am setting text and listeners of divs and buttons. But nothing happens. Neither .text() nor .click() has any affect inside the complete callback and there is no error in console. What's wrong?

答:
I just figured out the problem. This code

```<code>message: $('<div></div>').load('./RemoteDialog.html', function() {
    //this code is not working. Neither .text() nor .click() has any
    //affect.
    $('.caller').text(offermsg.from);
    $('.incomming').text('incoming call');
    $('#accept').click(function(){
      incommingCallDialog.close();
    });
    $('#decline').click(function(){
      incommingCallDialog.close();
    });
  }),
</code>```

was searching for the DOM elements (.caller, .incomming, #accept etc.) in main document and sometimes it couldn't find them because they were loaded inside $('

') and not yet attached to the main document. So i changed the code to this:

```<code>message: $('<div></div>').load('./RemoteDialog.html', function() {
        $(this).find('.caller').text(offermsg.from);
        $(this).find('.incomming').text('incoming call');
        $(this).find('#accept').click(function(){
          incommingCallDialog.close();
        });
        $(this).find('#decline').click(function(){
          incommingCallDialog.close();
        });
      }),
</code>```

Now it works...

Body:
I am using nakupanda bootstrap3-dialog library for modals. Below is the code for creating and showing dialog:

function createIncommingCallDialog(msg){
  offermsg = msg;
  incommingCallDialog = new BootstrapDialog({
      message: $('

').load('./RemoteDialog.html', function() {
        //this code is not working. Neither .text() nor .click() has any
        //affect.
        $('.caller').text(offermsg.from);
        $('.incomming').text('incoming call');
        $('#accept').click(function(){
          incommingCallDialog.close();
        });
        $('#decline').click(function(){
          incommingCallDialog.close();
        });
      }),
      closable: false,
  });
  incommingCallDialog.realize();
  incommingCallDialog.getModalFooter().hide();
  incommingCallDialog.getModalHeader().hide();
  incommingCallDialog.getModalBody().css('background-color', '#1A1A1A');
  incommingCallDialog.getModalBody().css('color', '#fff');
  incommingCallDialog.open();
}

I am loading a remote html in the dialog using jquery's .load() method and when it completes i am setting text and listeners of divs and buttons. But nothing happens. Neither .text() nor .click() has any affect inside the complete callback and there is no error in console. What's wrong?

Body:
I just figured out the problem. This code

message: $('<div></div>').load('./RemoteDialog.html', function() {
    //this code is not working. Neither .text() nor .click() has any
    //affect.
    $('.caller').text(offermsg.from);
    $('.incomming').text('incoming call');
    $('#accept').click(function(){
      incommingCallDialog.close();
    });
    $('#decline').click(function(){
      incommingCallDialog.close();
    });
  }),

was searching for the DOM elements (.caller, .incomming, #accept etc.) in main document and sometimes it couldn't find them because they were loaded inside $('<div></div>') and not yet attached to the main document. So i changed the code to this:

message: $('<div></div>').load('./RemoteDialog.html', function() {
        $(this).find('.caller').text(offermsg.from);
        $(this).find('.incomming').text('incoming call');
        $(this).find('#accept').click(function(){
          incommingCallDialog.close();
        });
        $(this).find('#decline').click(function(){
          incommingCallDialog.close();
        });
      }),

Now it works...


问:
get first business day of last month in panda DataFrame column
My DataSet ranges from 1989-1-03 to present date. It looks something like this. I have Column R which has Dates at certain points which matches the Index of the DataFrame.

```<code> Index     R
1989-01-24      NaT

1989-01-25      NaT

1989-01-26      NaT

1989-01-27      NaT

1989-01-30      NaT

1989-01-31      NaT

1989-02-01     1989-02-01

1989-02-02      NaT

1989-02-03      NaT
</code>```

I want find rows from Column R which are not NaT, subtract one month from them and find the value of the first business day for that month and Store into a new column RI in the DataFrame.

The Final Data Frame should look something like this:

```<code>Index       R           RI

1989-01-02   NaT       1989-01-02

----

1989-02-01  1989-02-01      NaT

1989-02-02    NaT           NaT

1989-02-03    NaT           NaT
</code>```

Can someone help me ? I am really weak at DateTime handling.

答:
You specifically asked about a pandas dataframe so you should look into pandas Business Date Range functions.

One such solution would be:

```<code>import pandas as pd
pd.bdate_range(start='2017-07-01',periods=1)[0]
# returns Timestamp('2017-07-03 00:00:00', freq='B')
</code>```

Body:
My DataSet ranges from 1989-1-03 to present date. It looks something like this. I have Column R which has Dates at certain points which matches the Index of the DataFrame.

 Index     R
1989-01-24      NaT

1989-01-25      NaT

1989-01-26      NaT

1989-01-27      NaT

1989-01-30      NaT

1989-01-31      NaT

1989-02-01     1989-02-01

1989-02-02      NaT

1989-02-03      NaT

I want find rows from Column R which are not NaT, subtract one month from them and find the value of the first business day for that month and Store into a new column RI in the DataFrame.

The Final Data Frame should look something like this:

Index       R           RI

1989-01-02   NaT       1989-01-02

----

1989-02-01  1989-02-01      NaT

1989-02-02    NaT           NaT

1989-02-03    NaT           NaT

Can someone help me ? I am really weak at DateTime handling.

Body:
You specifically asked about a pandas dataframe so you should look into pandas Business Date Range functions.

One such solution would be:

import pandas as pd
pd.bdate_range(start='2017-07-01',periods=1)[0]
# returns Timestamp('2017-07-03 00:00:00', freq='B')