问:
momentjs change string mm/yyyy format to yyyy-mm
I have a date string 11/2004 that comes to me via an API and on mobile I am trying to display this on a date field.

If i try to render this as it is I see the following warning on console

The specified value "11/2004" does not conform to the required format.
  The format is "yyyy-MM" where yyyy is year in four or more digits, and
  MM is 01-12.

so using momentjs i thought this should be easy to change to date or month format but i am struggling with it as i cant seem to get the output i want.

I tried the following code but that give me invalid date

```<code>moment('11/2004').format('yyyy-MM')
</code>```

What am i doing wrong here? How do i display the date on an input field in the correct format? I cant change the field type to anything else as its a date picker field on mobile.

答:
Looking at the documentation on parsing what you need to do is created your moment object with the format specified.

```<code>moment('11/2004','MM/YYYY')
</code>```

This will set the day to the first, but the month and the year to the ones specified.

Also, your format is wrong, the yyyy should be capital YYYY

So your final code should look like this

```<code>moment('11/2004', 'MM/YYYY').format('YYYY-MM')
</code>```

Body:
I have a date string 11/2004 that comes to me via an API and on mobile I am trying to display this on a date field.

If i try to render this as it is I see the following warning on console

The specified value "11/2004" does not conform to the required format.
  The format is "yyyy-MM" where yyyy is year in four or more digits, and
  MM is 01-12.

so using momentjs i thought this should be easy to change to date or month format but i am struggling with it as i cant seem to get the output i want.

I tried the following code but that give me invalid date

moment('11/2004').format('yyyy-MM')

What am i doing wrong here? How do i display the date on an input field in the correct format? I cant change the field type to anything else as its a date picker field on mobile.

Body:
Looking at the documentation on parsing what you need to do is created your moment object with the format specified.

moment('11/2004','MM/YYYY')

This will set the day to the first, but the month and the year to the ones specified.

Also, your format is wrong, the yyyy should be capital YYYY

So your final code should look like this

moment('11/2004', 'MM/YYYY').format('YYYY-MM')


来源: stackexchange

问:
Photon or Smartfox for a quiz game with Unity
I'm starting a new project and it's a quiz, which be written with Unity.

Right now, i have to make a choice between Smartfox and Photon. One of the requirements is to contain a database with questions and answers for the quiz.
I ask to share experience, and help to make the right decision)).

Which of the two tools would you recommend?

答:
I will go for smartfoxserver, as it is the leading multiplayer server and a very sophisticated server side java api as well. You can write your algorithms and turn based logic on server that way it will be secure, robust and manageable and will be called through extensions calls from client side.

You can find many examples on their website, with server side extensions introduction and details as well. And a very good helping community forum.

For questions and answers that will be stored in a database. One of the best thing with smartfoxserver is, it can connect to database and than it will be a local access to database and you can execute queries and call stored procedures directly from server side API and manipulate results in just next line. Make it more secure and flexible.

Also your questions will be coming from server directly which is connected to your database. No need to handle API calls on client side.

It is a perfect scenario for multiplayer quiz game.

Hope it helps !

ContentLicense: CC BY-SA 3.0


问:
How to install module libphp5.so in Apache serve CentOS 7
I have installed php 5.6.27 in Cent OS 7. Also I uncommented configurtion line in:

```<code>LoadModule php5_module       modules/libphp5.so
</code>```

But I does not have this file in directory modules/.

How can I install this?

答:
The exact source and name of the PHP version installed is important. I too had this problem and had installed php56.x86_64 from remi-safe repo. However it wasn't until I installed php.x86_64 from remi-php56 repo that things worked (and libphp5.so showed up).

I recommend revisiting the version installed and repo source (yum list installed), and then look for an alternative of one or the other, or both (version/repo source).

Body:
I have installed php 5.6.27 in Cent OS 7. Also I uncommented configurtion line in:

LoadModule php5_module       modules/libphp5.so

But I does not have this file in directory modules/.

How can I install this?


问:
Microsoft Graph APIs: conditional access policies
A follow up on my earlier question - Are there any APIs available to manage conditional access policies for a tenant?

I'm using the API (https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/policy_list) to retrieve the list of policies created for my tenant and have been running into permissions issues.

According to the documentation this API requires a scope of Directory.AccessAsUser.All. On the Azure AD portal, I set the permissions for my test App to include "Read and write directory data" and "Access the directory as a signed-in user". I set these permissions on both Windows Azure Active Directory and Microsoft Graph APIs. When I make a call to https://graph.microsoft.com/beta/policies, I keep getting 403 Forbidden with the error message "Insufficient privileges to complete the operation.". The other operations like getting the users in the directory, getting identityRiskEvents, etc all work fine.

Am I missing anything here?

Thanks in advance!

答:
No, There is a REST API List policies of Operations on policy described in Graph API reference, which you can use it to list all policies for your tenant.

Edit: This article lists only Token Policy's are being returned at this moment: https://learn.microsoft.com/nl-nl/graph/api/resources/policy?view=graph-rest-beta

ContentLicense: CC BY-SA 4.0


问:
Apache Camel - ftp component - need to use absolute path
I am trying to upgrade a product that uses an older camel version (2.15.1).
I am trying to upgrade the camel version to 2.17.5

In the code base, camel ftp component is used with absolute paths. After upgrade we saw that, files could not be consumed due to the following error:

SftpComponent doesn't support absolute paths, "xxx" will be converted to "yyy". After Camel 2.16, absolute paths will be invalid.

I can see that absolute paths are not supported starting with 2.16:

http://camel.apache.org/ftp.html

For our case, it will be very costly to change the existing code base.

My question : Is there any possibility to force  camel ftp 2.17.5 to support absolute paths as before in 2.15.1 (via config or other setting)?

答: It seems it's not possibble. Commit: https://github.com/apache/camel/commit/ca6d74205815269b7b3caf32ca57cb73c1a7299a</p>


问:
Logging out via a link in Laravel
I have a "Logout" link in my top navigation bar. I'm wondering how I can make it so that while I'm logged in, it'll log me out when I click on it and return me to the homepage.

To be specific, what changes to which files do I make in Laravel? Also, what code do I need to write in the view, which currently contains just HTML, to trigger this?

答:
Use the logout() method:

```<code>auth()->logout();
</code>```

Or:

```<code>Auth::logout();
</code>```

To log users out of your application, you may use the logout method on the Auth facade. This will clear the authentication information in the user's session.

Title: Logging out via a link in Laravel

Body:
Use the logout() method:

auth()->logout();

Or:

Auth::logout();

To log users out of your application, you may use the logout method on the Auth facade. This will clear the authentication information in the user's session.


问:
Prevent new row insert for each page refresh
I have to tables and I am appending an json file to them.

```<code><table id="userdata" border="2">
    <thead>
    <th>Id</th>
    <th>Title</th>
    <th>TotalUnresolvedItems</th>
    </thead>
    <tbody></tbody>
</table>
<strong>Item2:</strong>
<table id="userdata2" border="2">
    <thead>
    <th>Id</th>
    <th>FullName</th>
    <th>TotalUnresolvedItems</th>
    </thead>
    <tbody></tbody>
</table>
</code>```

Every time setInterval triggers it adds new rows but i would like to remove exist rows and replace it with new one.
I have tried .remove() from different places but its removing forever :(
My code looks like this.

```<code><script type="text/javascript">
    $(document).ready(function () {
        refreshStatus();
        setInterval(refreshStatus, 30000);
    });
    function refreshStatus() {
        $.ajax({
            type: "GET",
            url: "refreshTicketStatus",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(),
            dataType: "json",
            success: function (data) {
                repopulateTable(data);
            },
            error: function (errorThrown){
                alert(errorThrown);
            }
        })
    }
    function repopulateTable(data) {
        var parsedData = JSON.parse(data);
        console.log(parsedData);
        var dashboard = [];
        dashboard.push(JSON.parse(data));
        dashboard.forEach(function (value, index) {;
            for (var key in value) {
                if (value.hasOwnProperty(key)) {
                    if (key === 'Item1') {
                        value[key].forEach(function (val) {
                            //$('#userdata tbody').remove(9000);
                            var tblRow = "<tr>" + "<td>" + val.Id + "</td>" + "<td>" + val.Title + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
                            $(tblRow).appendTo("#userdata tbody");
                        })
                    }
                    if (key === 'Item2') {
                        value[key].forEach(function (val) {
                            //$('#userdata2 tbody').remove(9000);
                            var tblRow = "<tr>" + "<td>" + val.Id + "</td>" + "<td>" + val.FullName + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
                            $(tblRow).appendTo("#userdata2 tbody");
                        })
                    }
                }
            }
        });
    }
  </script>
</code>```

答:
I would change your repopulateDataTable function to the following. Basically I'm creating two empty variables, pass all the rows html in them and then replace all the html only once per interval.</p>

```<code>function repopulateTable(data) {
    var parsedData = JSON.parse(data);
    console.log(parsedData);
    var dashboard = [];
    dashboard.push(JSON.parse(data));
    dashboard.forEach(function (value, index) {;
        var table1Rows  = "";
        var table2Rows  = "";
        for (var key in value) {
            if (value.hasOwnProperty(key)) {
                if (key === 'Item1') {
                    value[key].forEach(function (val) {
                        //$('#userdata tbody').remove(9000);
                        var tbl1Row = "<tr>" + "<td>" + val.Id + "</td>" + "<td>" + val.Title + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
                        table1Rows   += tbl1Row;
                    })
                }
                if (key === 'Item2') {
                    value[key].forEach(function (val) {
                        //$('#userdata2 tbody').remove(9000);
                        var tbl2Row = "<tr>" + "<td>" + val.Id + "</td>" + "<td>" + val.FullName + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
                        table2Rows   += tbl2Row;
                    })
                }
            }
        }
        $("#userdata tbody").html(table1Rows);
        $("#userdata2 tbody").html(table2Rows);
    });
}
</code>```

Body:
I have to tables and I am appending an json file to them.

    Id
    Title
    TotalUnresolvedItems

Item2:

    Id
    FullName
    TotalUnresolvedItems

Every time setInterval triggers it adds new rows but i would like to remove exist rows and replace it with new one.
I have tried .remove() from different places but its removing forever :(
My code looks like this.

Body:
I would change your repopulateDataTable function to the following. Basically I'm creating two empty variables, pass all the rows html in them and then replace all the html only once per interval.

function repopulateTable(data) {
    var parsedData = JSON.parse(data);
    console.log(parsedData);
    var dashboard = [];
    dashboard.push(JSON.parse(data));
    dashboard.forEach(function (value, index) {;
        var table1Rows  = "";
        var table2Rows  = "";
        for (var key in value) {
            if (value.hasOwnProperty(key)) {
                if (key === 'Item1') {
                    value[key].forEach(function (val) {
                        //$('#userdata tbody').remove(9000);
                        var tbl1Row = "<tr>" + "<td>" + val.Id + "</td>" + "<td>" + val.Title + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
                        table1Rows   += tbl1Row;
                    })
                }
                if (key === 'Item2') {
                    value[key].forEach(function (val) {
                        //$('#userdata2 tbody').remove(9000);
                        var tbl2Row = "<tr>" + "<td>" + val.Id + "</td>" + "<td>" + val.FullName + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
                        table2Rows   += tbl2Row;
                    })
                }
            }
        }
        $("#userdata tbody").html(table1Rows);
        $("#userdata2 tbody").html(table2Rows);
    });
}


问:
Regex replace url with links
I need a little help with some regex I have. Basically I have a shout box that only shows text. I would like to replace urls with links and image urls with the image. I've got the basics working, it just when I try to name a link that I have problems, well if there is more than one link... check out the demo.

Named link format {name}:url should become name. The problem I am having is with shout #5 where the regex doesn't split the two urls properly.

HTML

```<code><ul>
 <li>Shout #1 and a link to google: http://www.google.com</li>
 <li>Shout #2 with an image: http://i201.photobucket.com/albums/aa236/Mottie1/SMRT.jpg</li>
 <li>Shout #3 with two links: http://www.google.com and http://www.yahoo.com</li>
 <li>Shout #4 with named link: {google}:http://www.google.com</li>
 <li>Shout #5 with two named links: {google}:http://www.google.com and {yahoo}:http://www.yahoo.com and {google}:http://www.google.com</li>
</ul>
</code>```

Script

```<code>var rex1 = /(\{(.+)\}:)?(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g,
  rex2 = /(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g;

 $('ul li').each(function(i){
  var shout = $(this);
  shout.html(function(i,h){
   var p = h.split(rex1),
    img = h.match(rex2),
    typ = (p[2] !== '') ? '<a href="$3">$2</a>' : '<a href="$3">link</a>';
   if (img !== null) {
    shout.addClass('shoutWithImage')
    typ = '<img src="' + img + '" alt="" />';
   }
   return h.replace(rex1, typ);
  });
 });
</code>```

Update: I figured it out thanks to Brad helping me with the regex. In case anyone needs it, here is the updated demo and code (Now works in IE!!):

```<code>var rex1 = /(\{(.+?)\}:)?(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g,
rex2 = /(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g;

$('ul li').each(function(i) {
  var shout = $(this);
  shout.html(function(i, h) {
    var txt, url = h.split(' '),
    img = h.match(rex2);
    if (img !== null) {
      shout.addClass('shoutWithImage');
      $.each(img, function(i, image) {
        h = h.replace(image, '<img src="' + image + '"  alt=""  />');
      });
    } else {
      $.each(url, function(i, u) {
        if (rex1.test(u)) {
          txt = u.split(':')[0] || ' ';
          if (txt.indexOf('{') >= 0) {
            u = u.replace(txt + ':', '');
            txt = txt.replace(/[\{\}]/g, '');
          } else {
            txt = '';
          }
          url[i] = '<a href="' + u + '">' + ((txt == '') ? 'link' : txt) + '</a>';
        }
      });
      h = url.join(' ');
    }
    return h;
  });
});
</code>```

答:
```<code>(\{(.+?)\}:)
</code>```

you need the ? to make the regex become "ungreedy" and not just find the next brace.

EDIT

However, if you remove the {yahoo}: the second link becomes null too (seems to populate the anchor tag, just no attribute within). This almost seems to be a victim of using a split instead of a replace. I would almost recommend doing a once-over looking for links first, then go back around looking for images (I don't see any harm in off-linking directly to the image, unless that's not a desired result?)

ContentLicense: CC BY-SA 2.5

Title: Regex replace url with links

Body:
I need a little help with some regex I have. Basically I have a shout box that only shows text. I would like to replace urls with links and image urls with the image. I've got the basics working, it just when I try to name a link that I have problems, well if there is more than one link... check out the demo.

Named link format {name}:url should become name. The problem I am having is with shout #5 where the regex doesn't split the two urls properly.

HTML

Shout #1 and a link to google: http://www.google.com

Shout #2 with an image: http://i201.photobucket.com/albums/aa236/Mottie1/SMRT.jpg

Shout #3 with two links: http://www.google.com and http://www.yahoo.com

Shout #4 with named link: {google}:http://www.google.com

Shout #5 with two named links: {google}:http://www.google.com and {yahoo}:http://www.yahoo.com and {google}:http://www.google.com

Script

var rex1 = /(\{(.+)\}:)?(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g,
  rex2 = /(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g;

 $('ul li').each(function(i){
  var shout = $(this);
  shout.html(function(i,h){
   var p = h.split(rex1),
    img = h.match(rex2),
    typ = (p[2] !== '') ? '$2' : 'link';
   if (img !== null) {
    shout.addClass('shoutWithImage')
    typ = '';
   }
   return h.replace(rex1, typ);
  });
 });

Update: I figured it out thanks to Brad helping me with the regex. In case anyone needs it, here is the updated demo and code (Now works in IE!!):

var rex1 = /(\{(.+?)\}:)?(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g,
rex2 = /(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g;

$('ul li').each(function(i) {
  var shout = $(this);
  shout.html(function(i, h) {
    var txt, url = h.split(' '),
    img = h.match(rex2);
    if (img !== null) {
      shout.addClass('shoutWithImage');
      $.each(img, function(i, image) {
        h = h.replace(image, '');
      });
    } else {
      $.each(url, function(i, u) {
        if (rex1.test(u)) {
          txt = u.split(':')[0] || ' ';
          if (txt.indexOf('{') >= 0) {
            u = u.replace(txt + ':', '');
            txt = txt.replace(/[\{\}]/g, '');
          } else {
            txt = '';
          }
          url[i] = '' + ((txt == '') ? 'link' : txt) + '';
        }
      });
      h = url.join(' ');
    }
    return h;
  });
});

Body:
(\{(.+?)\}:)

you need the ? to make the regex become "ungreedy" and not just find the next brace.

EDIT

However, if you remove the {yahoo}: the second link becomes null too (seems to populate the anchor tag, just no attribute within). This almost seems to be a victim of using a split instead of a replace. I would almost recommend doing a once-over looking for links first, then go back around looking for images (I don't see any harm in off-linking directly to the image, unless that's not a desired result?)


问:
trying to make a React dropdown with checkbox options in it and its not working properly
I am trying to make a simple dropdown with dropdown items as checkbox inputs. Currently I have this :

```<code>import React, { Component } from 'react'
export default class Sort extends Component {
  constructor() {
    super()
    this.state= { expanded : false}

  }
  showCheckboxes() {
      var checkboxes = document.getElementById("checkboxes");
      if (!expanded) {
          checkboxes.style.display = "block";
          this.state.expanded = true;
      } else {
          checkboxes.style.display = "none";
          this.state.expanded = false;
      }
  }
  render() {
    return (
      <form>
        <div class="multiselect">
            <div class="selectBox" onclick="showCheckboxes()">
                <select>
                    <option>Select an option</option>
                </select>
                <div class="overSelect"></div>
            </div>
            <div id="checkboxes">
                <label for="one"><input type="checkbox" id="one"/>First checkbox</label>
                <label for="two"><input type="checkbox" id="two"/>Second checkbox </label>
                <label for="three"><input type="checkbox" id="three"/>Third checkbox</label>
            </div>
        </div>
      </form>
    )
  }
}
</code>```

But It ends up having an empty dropdown with multiple checkbox fields under the dropdown, I would like to have it within the dropdown if possible.

答:
We can create it by using bootstrap in reactJS

code below

HTML:

    <button className="selectbox" id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true"
        aria-expanded="false">
        Select
    </button>

            <input type="checkbox" id="valuePot" value="Value Pot" name="Value Pot" />
            Value Pot

            <input type="checkbox" id="payback" value="Payback" name="Payback" />
            Payback

            <input type="checkbox" id="writeOff" value="Write-off" name="Write-off" />
            Write-off

            <input type="checkbox" id="offset" value="Offset" name="Offset" />
            Offset

            <input type="checkbox" id="genValuePot" value="Gen Value Pot" name="Gen Value Pot" />
            Gen Value Pot

            <input type="checkbox" id="mancValuePot" value="Manc Value Pot" name="Manc Value Pot" />
            Manc Value Pot

```

<p><strong>CSS:</strong> </p>

```#valueItemDrop .dropdown-menu {
    padding: 0 10px;
    top: 22px;
    width: 100%;
    box-shadow: none;
    border-radius: none;
}
#valueItemDrop .checkbox label:before {
 content: "";
 display: inline-block;
 width: 16px;
 height: 16px;
 margin-right: 10px;
 position: absolute;
 left: 0;
 bottom: 4px;
 background-color: transparent;
 border: 1px solid #ccc;
}

#valueItemDrop .checkbox input[type=checkbox] {
 display: none;
}

#valueItemDrop .checkbox label {
    padding-left: 25px;
    font-weight: bold;
}

#valueItemDrop .checkbox label:before {
    border: 1px solid #ccc;
 border-radius: 3px;
}

#valueItemDrop .checkbox input[type=checkbox]:checked + label:before {
 content: "\2714";
 font-size: 15px;
 color: #4A90E2;
 text-align: center;
 line-height: 14px;
 padding: 0px;
 font-weight: normal;
}

#valueItemDrop .selectbox {
    border-radius: 5px;
    padding: 3px 5px;
    width: 100%;
    border: 1px solid #A4A4A4;
    float: right;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    cursor: pointer;
    background: url('../images/ExpandArrowDown.svg');
    background-repeat: no-repeat;
    background-position: 163px 8px;
    background-color: white;
}
```

Body:
I am trying to make a simple dropdown with dropdown items as checkbox inputs. Currently I have this :

import React, { Component } from 'react'
export default class Sort extends Component {
  constructor() {
    super()
    this.state= { expanded : false}

  }
  showCheckboxes() {
      var checkboxes = document.getElementById("checkboxes");
      if (!expanded) {
          checkboxes.style.display = "block";
          this.state.expanded = true;
      } else {
          checkboxes.style.display = "none";
          this.state.expanded = false;
      }
  }
  render() {
    return (
      <form>

                <select>
                    <option>Select an option</option>
                </select>

                <input type="checkbox" id="one"/>First checkbox
                <input type="checkbox" id="two"/>Second checkbox
                <input type="checkbox" id="three"/>Third checkbox

      </form>
    )
  }
}

But It ends up having an empty dropdown with multiple checkbox fields under the dropdown, I would like to have it within the dropdown if possible.

Body:
We can create it by using bootstrap in reactJS

code below

HTML:

<div className="dropdown" id="valueItemDrop">
    <button className="selectbox" id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true"
        aria-expanded="false">
        Select
    </button>
    <ul className="dropdown-menu" aria-labelledby="dLabel">
        <li className="checkbox form-group">
            <input type="checkbox" id="valuePot" value="Value Pot" name="Value Pot" />
            <label htmlFor="valuePot">Value Pot</label>
        </li>
        <li className="checkbox form-group">
            <input type="checkbox" id="payback" value="Payback" name="Payback" />
            <label htmlFor="payback">Payback</label>
        </li>
        <li className="checkbox form-group">
            <input type="checkbox" id="writeOff" value="Write-off" name="Write-off" />
            <label htmlFor="writeOff">Write-off</label>
        </li>
        <li className="checkbox form-group">
            <input type="checkbox" id="offset" value="Offset" name="Offset" />
            <label htmlFor="offset">Offset</label>
        </li>
        <li className="checkbox form-group">
            <input type="checkbox" id="genValuePot" value="Gen Value Pot" name="Gen Value Pot" />
            <label htmlFor="genValuePot">Gen Value Pot</label>
        </li>
        <li className="checkbox form-group">
            <input type="checkbox" id="mancValuePot" value="Manc Value Pot" name="Manc Value Pot" />
            <label htmlFor="mancValuePot">Manc Value Pot</label>
        </li>
    </ul>
</div>

CSS:

#valueItemDrop .dropdown-menu {
    padding: 0 10px;
    top: 22px;
    width: 100%;
    box-shadow: none;
    border-radius: none;
}
#valueItemDrop .checkbox label:before {
 content: "";
 display: inline-block;
 width: 16px;
 height: 16px;
 margin-right: 10px;
 position: absolute;
 left: 0;
 bottom: 4px;
 background-color: transparent;
 border: 1px solid #ccc;
}

#valueItemDrop .checkbox input[type=checkbox] {
 display: none;
}

#valueItemDrop .checkbox label {
    padding-left: 25px;
    font-weight: bold;
}

#valueItemDrop .checkbox label:before {
    border: 1px solid #ccc;
 border-radius: 3px;
}

#valueItemDrop .checkbox input[type=checkbox]:checked + label:before {
 content: "\2714";
 font-size: 15px;
 color: #4A90E2;
 text-align: center;
 line-height: 14px;
 padding: 0px;
 font-weight: normal;
}

#valueItemDrop .selectbox {
    border-radius: 5px;
    padding: 3px 5px;
    width: 100%;
    border: 1px solid #A4A4A4;
    float: right;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    cursor: pointer;
    background: url('../images/ExpandArrowDown.svg');
    background-repeat: no-repeat;
    background-position: 163px 8px;
    background-color: white;
}


问:
can't open oracle enterprise manager with firefox version 45
when my oracle enterprise manager starts it is not visible on browser and when I'm trying to attempt it through Firefox i get the this error :

An error occurred during a connection to oracle2017:5500. The server certificate included a public key that was too weak. Error code: SSL_ERROR_WEAK_SERVER_CERT_KEY

please help me

答:
This is only a security warning. Firefox rejects sites with weak SSL security.

You must accept it as security exception. Raise a ticket to Oracle if you want better security.

Use the  More...  button you see or whatever link, and change your browser options for this site.
..

edit:

In the navigation bar:  about:config

Set security.tls.insecure_fallback_hosts = www.domain.com (substitute the domain you're having the problem with)

Reload the page


问:
Android, String.split (String regex) doesn't split all the string
I have a problem with String.split(String regex). I want to split my string in parts of 4 characters each.

```<code>String stringa = "1111110000000000"
String [] result = stringa.split("(?<=\\G....)")
</code>```

When I print result I expect 1111,1100,0000,0000 but result is 1111,110000000000.
How can I resolve? Thanks.

答:
Here a solution without regex -

You begin at the string's end, extract 4 or less characters and prepend them to a List:

```<code>public static void main (String[] args) {
    String stringa = "11111110000000000";
    List<String> result = new ArrayList<>();

    for (int endIndex = stringa.length(); endIndex  >= 0; endIndex  -= 4) {
        int beginIndex = Math.max(0, endIndex - 4);
        String str = stringa.substring(beginIndex, endIndex);
        result.add(0, str);
    }

    System.out.println(result);
}
</code>```

Which results in the output:

```<code>[1, 1111, 1100, 0000, 0000]
</code>```

Body:
I have a problem with String.split(String regex). I want to split my string in parts of 4 characters each.

String stringa = "1111110000000000"
String [] result = stringa.split("(?<=\\G....)")

When I print result I expect 1111,1100,0000,0000 but result is 1111,110000000000.
How can I resolve? Thanks.

Body:
Here a solution without regex -

You begin at the string's end, extract 4 or less characters and prepend them to a List:

public static void main (String[] args) {
    String stringa = "11111110000000000";
    List<String> result = new ArrayList<>();

    for (int endIndex = stringa.length(); endIndex  >= 0; endIndex  -= 4) {
        int beginIndex = Math.max(0, endIndex - 4);
        String str = stringa.substring(beginIndex, endIndex);
        result.add(0, str);
    }

    System.out.println(result);
}

Which results in the output:

[1, 1111, 1100, 0000, 0000]


问:
js/jquery - How to change existing iframe attribute from inside the iframe
I am working with TFS and I'm trying to upload an extension(web page) to the dashboard.
When the dashboard loads my extension it wrapps my it with Iframe.

TFS Iframe example

The iframe sandbox attribute missing the allow-same-origin which allow me to manipulate the page that contains my extension.
Is there a way to change the iframe attribute from my extension web page?
the whole page looks like:

```<code><html> // Tfs page
<body>
<div> // main page
    <iframe sandbox='allow-scripts ...'> // the iframe that wrapps my extension, missing 'allow-same-origin'
        <html> // my extension
        <body>
        ...
        </body>
        </html>
    </iframe>
</body>
</html>
</code>```

Thanks...

答: I think this is on purpose: you should use the SDK to interact with VSTS/TFS, otherwise it is easy to imagine a rogue Extension that sells a company's Intellectual Property in the deep web.</p>

Body:
I am working with TFS and I'm trying to upload an extension(web page) to the dashboard.
When the dashboard loads my extension it wrapps my it with Iframe.

TFS Iframe example

The iframe sandbox attribute missing the allow-same-origin which allow me to manipulate the page that contains my extension.
Is there a way to change the iframe attribute from my extension web page?
the whole page looks like:

 // Tfs page

 // main page
     // the iframe that wrapps my extension, missing 'allow-same-origin'
         // my extension

        ...

Thanks...


问:
Why are bit fields not allowed as static data members of a class
Can anyone explain the reason behind not allowing bit fields as static member of a class? For example, a class defined like:

```<code>class A{
public:
    A() {}
    ~A(){}
private:
    static int mem :10;
};
int A::mem;
</code>```

doesn't compile.

Compiling this class with different compilers:-

1- g++ throws error:-

error: static member 'mem' cannot be a bit-field

```<code>static int mem :10;
</code>```

error: ‘int A::mem’ is not a static data member of ‘class A’

int A::mem;

2- clang throws error:-

error: static member 'mem' cannot be a bit-field

```<code>static int mem :10;
</code>```

3-Visual Studio 15 throws error:-

'A::mem'::illegal storage class

'int A::mem':member function redeclaration not allowed

答:
The reason the standard prohibits it is because static data members need to be instantiated somewhere - in your example, a compilation unit somewhere would need to contain:

```<code>int A::mem :10;
</code>```

which is invalid, in the same way that a standalone non-member bitfield variable such as:

```<code>int foo :10;
</code>```

is invalid.

Of course one can ask why this is prohibited, but that's a wider question not related to it being a class member.

Body:
Can anyone explain the reason behind not allowing bit fields as static member of a class? For example, a class defined like:

class A{
public:
    A() {}
    ~A(){}
private:
    static int mem :10;
};
int A::mem;

doesn't compile.

Compiling this class with different compilers:-

1- g++ throws error:-

error: static member 'mem' cannot be a bit-field

static int mem :10;

error: ‘int A::mem’ is not a static data member of ‘class A’

int A::mem;

2- clang throws error:-

error: static member 'mem' cannot be a bit-field

static int mem :10;

3-Visual Studio 15 throws error:-

'A::mem'::illegal storage class

'int A::mem':member function redeclaration not allowed

Body:
The reason the standard prohibits it is because static data members need to be instantiated somewhere - in your example, a compilation unit somewhere would need to contain:

int A::mem :10;

which is invalid, in the same way that a standalone non-member bitfield variable such as:

int foo :10;

is invalid.

Of course one can ask why this is prohibited, but that's a wider question not related to it being a class member.


问:
After collapse SearchView disappear from toolbar
I create small example to show my issue.
Main layout with SearchView in toolbar and 3 buttons:
1) Set text - expand search view and set query
2) Expand - expand search view
3) Collapse - collapse search view

activity_main.xml

        android:fitsSystemWindows="true">

```<code>    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:orientation="vertical"
        tools:context="com.porn.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="368dp"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="0dp">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:contentInsetStartWithNavigation="0dp">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.AppBarLayout>

        <Button
            android:id="@+id/setTextBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Set text" />

        <Button
            android:id="@+id/expandBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Expand" />

        <Button
            android:id="@+id/collapseBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Collapse" />
    </LinearLayout>
</android.support.v4.widget.DrawerLayout>
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    private MenuItem toolbarSearchMenuItem;
    private SearchView toolbarSearchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        findViewById(R.id.expandBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toolbarSearchMenuItem.expandActionView();
            }
        });

        findViewById(R.id.collapseBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toolbarSearchMenuItem.collapseActionView();
            }
        });

        findViewById(R.id.setTextBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setToolbarSearchQuery("Text2");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toobar, menu);
        toolbarSearchMenuItem = menu.findItem(R.id.toolbar_action_search);
        toolbarSearchView = (SearchView) menu.findItem(R.id.toolbar_action_search).getActionView();
        init();
        return true;
    }

    public void init() {
        //In real app i get searchQuery from extra
        //String searchQuery = getIntent().getStringExtra(INTENT_EXTRA_SEARCH_QUERY_KEY);
        setToolbarSearchQuery("Text from intent");
    }

    private void setToolbarSearchQuery(String searchQuery) {
        if (!searchQuery.equals("")) {
            toolbarSearchMenuItem.expandActionView();
            toolbarSearchView.setQuery(searchQuery, false);
            toolbarSearchView.clearFocus();
        } else {
            toolbarSearchMenuItem.collapseActionView();
        }
    }

}
</code>```

My problem appears when i call method init() from onCreateOptionsMenu (In real app i init SearchView with text from intent extra). If i call setToolbarSearchQuery method from init and after i click collapse button SearchView collapsed and search icon disappear.

But if i will not call init method and will call same method setToolbarSearchQuery with set text button it works correctly (SearchView is collapsed and search icon shown in toolbar).

How i can solve this problem? And why icon disappear after collapse?

I understood that it happens when i expand SearchView from onCreateOptionsMenu. But how i can correct init SearchView from intent extra?

Screenshot how it looks after collapse

Screenshot how it must looks after collapse

答:
I found only one solution. Set text in init method delayed.

```<code>public void init() {
    //setToolbarSearchQuery("Text from intent");
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            toolbarSearchMenuItem.expandActionView();
            toolbarSearchView.setQuery("Text from intent", false);
        }
    }, 1000);
}
</code>```

But i don't like this solution. It looks like trick.

Body:
I create small example to show my issue.
Main layout with SearchView in toolbar and 3 buttons:
1) Set text - expand search view and set query
2) Expand - expand search view
3) Collapse - collapse search view

activity_main.xml

        android:fitsSystemWindows="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:orientation="vertical"
        tools:context="com.porn.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="368dp"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="0dp">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:contentInsetStartWithNavigation="0dp">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.AppBarLayout>

        <Button
            android:id="@+id/setTextBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Set text" />

        <Button
            android:id="@+id/expandBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Expand" />

        <Button
            android:id="@+id/collapseBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Collapse" />
    </LinearLayout>
</android.support.v4.widget.DrawerLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private MenuItem toolbarSearchMenuItem;
    private SearchView toolbarSearchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        findViewById(R.id.expandBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toolbarSearchMenuItem.expandActionView();
            }
        });

        findViewById(R.id.collapseBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toolbarSearchMenuItem.collapseActionView();
            }
        });

        findViewById(R.id.setTextBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setToolbarSearchQuery("Text2");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toobar, menu);
        toolbarSearchMenuItem = menu.findItem(R.id.toolbar_action_search);
        toolbarSearchView = (SearchView) menu.findItem(R.id.toolbar_action_search).getActionView();
        init();
        return true;
    }

    public void init() {
        //In real app i get searchQuery from extra
        //String searchQuery = getIntent().getStringExtra(INTENT_EXTRA_SEARCH_QUERY_KEY);
        setToolbarSearchQuery("Text from intent");
    }

    private void setToolbarSearchQuery(String searchQuery) {
        if (!searchQuery.equals("")) {
            toolbarSearchMenuItem.expandActionView();
            toolbarSearchView.setQuery(searchQuery, false);
            toolbarSearchView.clearFocus();
        } else {
            toolbarSearchMenuItem.collapseActionView();
        }
    }

}

My problem appears when i call method init() from onCreateOptionsMenu (In real app i init SearchView with text from intent extra). If i call setToolbarSearchQuery method from init and after i click collapse button SearchView collapsed and search icon disappear.

But if i will not call init method and will call same method setToolbarSearchQuery with set text button it works correctly (SearchView is collapsed and search icon shown in toolbar).

How i can solve this problem? And why icon disappear after collapse?

I understood that it happens when i expand SearchView from onCreateOptionsMenu. But how i can correct init SearchView from intent extra?

Screenshot how it looks after collapse

Screenshot how it must looks after collapse

Body:
I found only one solution. Set text in init method delayed.

public void init() {
    //setToolbarSearchQuery("Text from intent");
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            toolbarSearchMenuItem.expandActionView();
            toolbarSearchView.setQuery("Text from intent", false);
        }
    }, 1000);
}

But i don't like this solution. It looks like trick.


问:
Trying to use boundingRect in Qt
What is wrong with class Kwadrat? I have an error:

Invalid new-expression of abstract class type 'Kwadrat'

```<code>Kwadrat* kwadrat = new Kwadrat(20);
</code>```

I want a moving square on the screen (when it hit 370 on X or 370 on Y coordinate it comes back to middle).

when Kwadrat is classic QGraphicsRectItem I have a bug with (0,0) coordinate.

```<code>#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QPixmap>
#include "poruszanie.h"
#include <QRectF>
#include <QGraphicsRectItem>

class Kwadrat : public QGraphicsItem
{
    Q_OBJECT

public:
    Kwadrat(int size)
        : QGraphicsItem(NULL) // we could parent, but this may confuse at first
    {
        m_boundingRect = QRectF(0, 0, size, size);
    }

    QRectF boundingRect() const
    {
        return m_boundingRect;
    }

private:
    QRectF m_boundingRect;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene*scena=new QGraphicsScene();

   // Poruszanie*kwadrat=new Poruszanie();
   // kwadrat->setRect(0,0,20,20);
   // kwadrat->setBrush(QBrush(Qt::white));
   // scena->addItem(kwadrat);

    Kwadrat*kwadrat=new Kwadrat(20);
    kwadrat->setBrush(QBrush(Qt::white));
    scena->addItem(kwadrat);

    kwadrat->setFlag(QGraphicsItem::ItemIsFocusable);
    kwadrat->setFocus();

    QGraphicsView *widok=new QGraphicsView(scena);
    widok->setBackgroundBrush(QBrush(Qt::yellow));
    widok->setMinimumSize(400,400);
    widok->show();

    return a.exec();
}
</code>```

答:
To write your own graphics item, you first create a subclass of
  QGraphicsItem, and then start by implementing its two pure virtual
  public functions: boundingRect(), which returns an estimate of the
  area painted by the item, and paint(), which implements the actual
  painting.

From http://doc.qt.io/qt-5/qgraphicsitem.html#details

So you need to implement the pure virtual function paint to do the painting of your QGraphicsItem to get rid of the error, your compiler should have shown that, besides telling you that your class is abstract (because of the missing function implementation).

Title: Trying to use boundingRect in Qt

Body:
What is wrong with class Kwadrat? I have an error:

Invalid new-expression of abstract class type 'Kwadrat'

Kwadrat* kwadrat = new Kwadrat(20);

I want a moving square on the screen (when it hit 370 on X or 370 on Y coordinate it comes back to middle).

when Kwadrat is classic QGraphicsRectItem I have a bug with (0,0) coordinate.

#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QPixmap>
#include "poruszanie.h"
#include <QRectF>
#include <QGraphicsRectItem>

class Kwadrat : public QGraphicsItem
{
    Q_OBJECT

public:
    Kwadrat(int size)
        : QGraphicsItem(NULL) // we could parent, but this may confuse at first
    {
        m_boundingRect = QRectF(0, 0, size, size);
    }

    QRectF boundingRect() const
    {
        return m_boundingRect;
    }

private:
    QRectF m_boundingRect;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene*scena=new QGraphicsScene();

   // Poruszanie*kwadrat=new Poruszanie();
   // kwadrat->setRect(0,0,20,20);
   // kwadrat->setBrush(QBrush(Qt::white));
   // scena->addItem(kwadrat);

    Kwadrat*kwadrat=new Kwadrat(20);
    kwadrat->setBrush(QBrush(Qt::white));
    scena->addItem(kwadrat);

    kwadrat->setFlag(QGraphicsItem::ItemIsFocusable);
    kwadrat->setFocus();

    QGraphicsView *widok=new QGraphicsView(scena);
    widok->setBackgroundBrush(QBrush(Qt::yellow));
    widok->setMinimumSize(400,400);
    widok->show();

    return a.exec();
}


问:
Xamarin Forms navigation issue
I'm working on a Xamarin Forms app, and I've ran into an issue.

The navigation system seems to be off a bit. I'm using a root NavigationPage to host my pages, and it works fine all time, except...

I have a sub-page with a list of items. When tapped, each item should display information about itself, on a separate page (let it be modal or not).

However, it only works the first time. The second time I try to check an entry, it seemingly loads it twice (font is thicker and a bit ghosty), and when I press back, one layer stays behind while the other moves with the close animation (that's why I think it was loaded twice).

The code is the following:

public partial class NotesPage : ContentPage {
protected override void OnAppearing()
    {
        base.OnAppearing();

        NotesList.ItemsSource = VM.Notes; // VM is my ViewModel, NotesList is a ListView defined in XAML
        NotesList.ItemSelected += async (sender, e) =>
        {
            if (e.SelectedItem == null) return;
            await Navigation.PushAsync(new NoteDetails((Note)e.Item));
            ((ListView)sender).SelectedItem = null;
        };
    }
}
```

<pre class="lang-xml prettyprint-override"><code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="Views.Notes.NoteDetails">
  <StackLayout>
    <Label Text="{Binding Title}" />
    <Label Text="{Binding Date}" />
    <Label Text="{Binding Author}" />
    <Label Text="{Binding Content}" />
  </StackLayout>
</ContentPage>
</code>```

NoteDetails' class only sets the BindingContext to the Note object passed.
The Note class has four properties: a String Title, a String Date (its code-back field is a DateTime object, conversion happens in the getter-setter), a String Author and a String Content. All the details are displayed properly.

The only issue is this second-time checking - it simply refuses to work properly.
What can be the problem?

答:
you can also set a variable to check if the page is loaded for the first time.</p>

```<code>protected override void OnAppearing()
{
   if (_isFirstLoad) {
   //-- create your list
   //-- _isFirstLoad = true;
   }
}
</code>```

Title: Xamarin Forms navigation issue

Body:
I'm working on a Xamarin Forms app, and I've ran into an issue.

The navigation system seems to be off a bit. I'm using a root NavigationPage to host my pages, and it works fine all time, except...

I have a sub-page with a list of items. When tapped, each item should display information about itself, on a separate page (let it be modal or not).

However, it only works the first time. The second time I try to check an entry, it seemingly loads it twice (font is thicker and a bit ghosty), and when I press back, one layer stays behind while the other moves with the close animation (that's why I think it was loaded twice).

The code is the following:

public partial class NotesPage : ContentPage {
protected override void OnAppearing()
    {
        base.OnAppearing();

        NotesList.ItemsSource = VM.Notes; // VM is my ViewModel, NotesList is a ListView defined in XAML
        NotesList.ItemSelected += async (sender, e) =>
        {
            if (e.SelectedItem == null) return;
            await Navigation.PushAsync(new NoteDetails((Note)e.Item));
            ((ListView)sender).SelectedItem = null;
        };
    }
}

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="Views.Notes.NoteDetails">
  <StackLayout>

  </StackLayout>
</ContentPage>

NoteDetails' class only sets the BindingContext to the Note object passed.
The Note class has four properties: a String Title, a String Date (its code-back field is a DateTime object, conversion happens in the getter-setter), a String Author and a String Content. All the details are displayed properly.

The only issue is this second-time checking - it simply refuses to work properly.
What can be the problem?

Body:
you can also set a variable to check if the page is loaded for the first time.

protected override void OnAppearing()
{
   if (_isFirstLoad) {
   //-- create your list
   //-- _isFirstLoad = true;
   }
}


问:
NSURLConnection, using proxy server
I want to POST using an NSURLConnection, using a SOCKS proxy along the way.

From what I've read, NSURLConnection does support SOCKS and HTTP proxies. The question is, where do I configure it?
I couldn't find any suitable method on e.g. NSURLRequest for configuring which proxy server to use.

If this is a limitation, does anyone know of a good replacement that does support SOCKS?

答: Though I've never used it myself, from reading around the topic I think you need to use an NSOutputStream rather than an NSURLConnection, which is toll-free bridged with CFWriteStream. On that you can use CFWriteStreamSetProperty with the kCFStreamPropertySOCKSProxy key and a dictionary with corresponding entries for the various keys defined here.

Title: NSURLConnection, using proxy server


问:
How to add progress bar to FFMPEG android
I want add a progress bar during FFMPEG execution android.

When i start FFMPEG command then progress bar start with percentage progress.

答:
To Calculate ffmpeg progress in percentage

```<code>ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
            @Override
            public void onFailure(String s) {
                Log.d(TAG, "FAILED with output : " + s);
            }

            @Override
            public void onSuccess(String s) {
                Log.d(TAG, "SUCCESS with output : " + s);
            }

            @Override
            public void onProgress(String s) {
                Log.d(TAG, "Started command : ffmpeg " + Arrays.toString(command));
                Log.d(TAG, "progress : " + s);
                Pattern timePattern = Pattern.compile("(?<=time=)[\\d:.]*");
                Scanner sc = new Scanner(s);

                String match = sc.findWithinHorizon(timePattern, 0);
                if (match != null) {
                    String[] matchSplit = match.split(":");
                    if (totalDur != 0) {
                        float progress = (Integer.parseInt(matchSplit[0]) * 3600 +
                                Integer.parseInt(matchSplit[1]) * 60 +
                                Float.parseFloat(matchSplit[2])) / totalDur;
                        float showProgress = (progress * 100);
                        Log.d(TAG, "=======PROGRESS======== " + showProgress);
                    }
                }
            }

            @Override
            public void onStart() {
                Log.d(TAG, "Started command : ffmpeg " + Arrays.toString(command));
                progressDialog.setMessage("Processing...");
                progressDialog.show();
            }

            @Override
            public void onFinish() {
                Log.d(TAG, "Finished command : ffmpeg " + Arrays.toString(command));
                progressDialog.dismiss();
            }
        });
</code>```

totalDur=25; // for 25 Sec Video

But totalDur will change according to operation like for 2x Slow Video you have to give totalDur=2*25; //50 Sec Video

Body:
To Calculate ffmpeg progress in percentage

ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
            @Override
            public void onFailure(String s) {
                Log.d(TAG, "FAILED with output : " + s);
            }

            @Override
            public void onSuccess(String s) {
                Log.d(TAG, "SUCCESS with output : " + s);
            }

            @Override
            public void onProgress(String s) {
                Log.d(TAG, "Started command : ffmpeg " + Arrays.toString(command));
                Log.d(TAG, "progress : " + s);
                Pattern timePattern = Pattern.compile("(?<=time=)[\\d:.]*");
                Scanner sc = new Scanner(s);

                String match = sc.findWithinHorizon(timePattern, 0);
                if (match != null) {
                    String[] matchSplit = match.split(":");
                    if (totalDur != 0) {
                        float progress = (Integer.parseInt(matchSplit[0]) * 3600 +
                                Integer.parseInt(matchSplit[1]) * 60 +
                                Float.parseFloat(matchSplit[2])) / totalDur;
                        float showProgress = (progress * 100);
                        Log.d(TAG, "=======PROGRESS======== " + showProgress);
                    }
                }
            }

            @Override
            public void onStart() {
                Log.d(TAG, "Started command : ffmpeg " + Arrays.toString(command));
                progressDialog.setMessage("Processing...");
                progressDialog.show();
            }

            @Override
            public void onFinish() {
                Log.d(TAG, "Finished command : ffmpeg " + Arrays.toString(command));
                progressDialog.dismiss();
            }
        });

totalDur=25; // for 25 Sec Video

But totalDur will change according to operation like for 2x Slow Video you have to give totalDur=2*25; //50 Sec Video


答:
You probably are talking about function isBizday from timeDate package. So firstly you should read documentation of this function [here].
There is written that:

x is an object of class timeDate.

So you need to convert your dates:

```<code>d <- as.timeDate(Dates)
isBizday(d)
</code>```

Title: isBizday not working and returning an that is not an S4 object error

Body:
I'm not sure why my function isBizday is not working. The error I'm getting is:

Error in isBizday(Dates, holidayTSX()) :
    trying to get slot "Data" from an object (class "Date") that is not an S4 object

My code:

Dates[isBizday(Dates, holidayTSX())]

How should I go about correcting this error?

An example of my data:

Dates<-structure(c(15340, 15340, 15340, 15340, 15340, 15340, 15340,
15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340,
15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340,
15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340,
15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340,
15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340,
15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340,
15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340,
15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340,
15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340,
15340, 15340, 15340, 15340, 15340, 15340, 15340, 15340, 15341,
15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341,
15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341,
15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341,
15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341,
15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341,
15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341,
15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341,
15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341,
15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341,
15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341, 15341,
15341, 15341, 15341, 15341, 15341, 15342, 15342, 15342, 15342,
15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342,
15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342,
15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342,
15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342,
15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342,
15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342,
15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342,
15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342,
15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342,
15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342, 15342,
15342, 15342), class = "Date")

Body:
You probably are talking about function isBizday from timeDate package. So firstly you should read documentation of this function [here].
There is written that:

x is an object of class timeDate.

So you need to convert your dates:

d <- as.timeDate(Dates)
isBizday(d)


问:
A component required a bean named 'jpaTransactionManager' that could not be found
I'm developing a web app using Spring Boot, Hibernate 5 and MySQL DB. Trying to start an application I get such a message:

```<code>Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-03-29 09:36:59.862 ERROR 9312 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

A component required a bean named 'jpaTransactionManager' that could not be found.

Action:

Consider defining a bean named 'jpaTransactionManager' in your configuration.
</code>```

My configuration is as follows:

application.properties:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
</code>```

pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>zapisano</groupId>
    <artifactId>project-back-spring</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.googlecode.soundlibs</groupId>
            <artifactId>mp3spi</artifactId>
            <version>1.9.5-1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.9.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.2.3.Final</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.16</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Application.java:

```<code>package core;

import core.storage.StorageProperties;
import core.storage.StorageService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}
</code>```

I suppose there are few ways to declare a bean named 'jpaTransactionManager' explicitly. With Spring configuration in .xml or in application.properties.

I have 3 questions in that case:

What is the best way to declare a bean named 'jpaTransactionManager'?

Can it be done automatically?

And may I dispense with .xml?

答:
I am not sure it can be done automatically, I think that you need to declare it.
Good pratice would be to have your configuration in a separate @Configuration bean (no need for an xml config), in which you can define the jpaTransactionManager.

You can find such an example here.

Body:
I'm developing a web app using Spring Boot, Hibernate 5 and MySQL DB. Trying to start an application I get such a message:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-03-29 09:36:59.862 ERROR 9312 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

A component required a bean named 'jpaTransactionManager' that could not be found.

Action:

Consider defining a bean named 'jpaTransactionManager' in your configuration.

My configuration is as follows:

application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>zapisano</groupId>
    <artifactId>project-back-spring</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.googlecode.soundlibs</groupId>
            <artifactId>mp3spi</artifactId>
            <version>1.9.5-1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.9.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.2.3.Final</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.16</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Application.java:

package core;

import core.storage.StorageProperties;
import core.storage.StorageService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}

I suppose there are few ways to declare a bean named 'jpaTransactionManager' explicitly. With Spring configuration in .xml or in application.properties.

I have 3 questions in that case:

What is the best way to declare a bean named 'jpaTransactionManager'?

Can it be done automatically?

And may I dispense with .xml?


问:
How to strip HTML tags from div content using Javascript/jQuery?
I had made one div tag and stored its contents in a variable. If this tag contains p,b or any other tags then it should be removed from string. How can I achieve this?

答:
I would like to add a few things on top of the accepted answer which is suggesting the regex var regex = /(<([^>]+)>)/ig:

you don't need the i flag in your regex as you don't match any alphabetic character. See here: http://jsfiddle.net/66L6nfwt/2/

you don't need any pair of brackets as you just replace with nothing the whole match. See here: http://jsfiddle.net/66L6nfwt/3/

This regex can be improved as it will fail if you use both chars < and > in your text content. See here: http://jsfiddle.net/66L6nfwt/4/

So here is a regex improvement: /<\/?\w+[^>]*\/?>/g. See here: http://jsfiddle.net/66L6nfwt/5/

Final code:

```<code>var regex = /<\/?\w+[^>]*\/?>/g,
    body = "<sTrong><b>test<b></STRONG><b> sss</b><em> what if you write some maths: i < 2 && i > 4.</em>";

alert(body.replace(regex, ""));
</code>```

It can also be helpful to place the function in the built-in 'String' class so you can do this directly :

"test".stripTags()

```<code>String.prototype.stripTags = function()
{
    return this.replace(/<\/?\w+[^>]*\/?>/g, '');
};
</code>```

Eventually, if your string is a DOM node, you can do alert(element.innerText || element.textContent); which is built-in and even safer! See example here: http://jsfiddle.net/66L6nfwt/6/

Body:
I would like to add a few things on top of the accepted answer which is suggesting the regex var regex = /(<([^>]+)>)/ig:

you don't need the i flag in your regex as you don't match any alphabetic character. See here: http://jsfiddle.net/66L6nfwt/2/

you don't need any pair of brackets as you just replace with nothing the whole match. See here: http://jsfiddle.net/66L6nfwt/3/

This regex can be improved as it will fail if you use both chars < and > in your text content. See here: http://jsfiddle.net/66L6nfwt/4/

So here is a regex improvement: /<\/?\w+[^>]*\/?>/g. See here: http://jsfiddle.net/66L6nfwt/5/

Final code:

var regex = /<\/?\w+[^>]*\/?>/g,
    body = "<sTrong><b>test<b></STRONG><b> sss</b><em> what if you write some maths: i < 2 && i > 4.</em>";

alert(body.replace(regex, ""));

It can also be helpful to place the function in the built-in 'String' class so you can do this directly :

"<em>test</em>".stripTags()

String.prototype.stripTags = function()
{
    return this.replace(/<\/?\w+[^>]*\/?>/g, '');
};

Eventually, if your string is a DOM node, you can do alert(element.innerText || element.textContent); which is built-in and even safer! See example here: http://jsfiddle.net/66L6nfwt/6/


问:
Are there any charges for Google App Engine Push Queue HTTP calls within the same application
Google App Engine's documentation says that once tasks have been added to Push-Queue, the Push-Queue will initiate HTTP calls to the handler/url specified in the newly added task.

My question: Do the HTTP call charges, or any other charges apply to internal HTTP calls initiated by Push-Queue (HTTP calls that never leave GAE)?

My task creation code (in {root}.activities.service) looks roughly like this:

```<code>Queue taskQueue = QueueFactory.getQueue(QUEUENAME);
add(TaskOptions.Builder.withUrl("/activity").
     param("actor", Long.toString(activityDTO.getActor())).
     param("actorGroup", Long.toString(activityDTO.getActorGroup())).
     param("action", activityDTO.getAction()).
     param("object", activityDTO.getObject()).
     param("objectGroup", Long.toString(activityDTO.getObjectGroup())).
     method(TaskOptions.Method.GET)
);
</code>```

The receiving end-point in the controller (in {root}.activities.controller) looks like this:

```<code>@RestController
@RequestMapping("/activity")
public class ActivityController {
     .
     .
     .
  @RequestMapping(method = RequestMethod.GET)
  public ResponseEntity<GenericHTTPResponseDTO> recordActivity(ActivityDTO activityDTO) {

      activityService.recordActivity(activityDTO);

      return new ResponseEntity<>(HttpStatus.OK);
  }
}
</code>```

Once Task is added to Push-Queue the Push-queue will then make an HTTP call to the '/activity' end point, which will trigger the recordActivity() method.

答:
The Push Task Queue requests are billed like any other request: if you have an important number of requests, AppEngine will scale up the number of instances, and you will pay more.

BUT, according to the AppEngine documentation, the data stored in the task queues (ie. the request payload, etc ...) are also billed: $0.026/Gb/month (2017-03-29).

Source: https://cloud.google.com/appengine/pricing (section Other resources)

Body:
Google App Engine's documentation says that once tasks have been added to Push-Queue, the Push-Queue will initiate HTTP calls to the handler/url specified in the newly added task.

My question: Do the HTTP call charges, or any other charges apply to internal HTTP calls initiated by Push-Queue (HTTP calls that never leave GAE)?

My task creation code (in {root}.activities.service) looks roughly like this:

Queue taskQueue = QueueFactory.getQueue(QUEUENAME);
add(TaskOptions.Builder.withUrl("/activity").
     param("actor", Long.toString(activityDTO.getActor())).
     param("actorGroup", Long.toString(activityDTO.getActorGroup())).
     param("action", activityDTO.getAction()).
     param("object", activityDTO.getObject()).
     param("objectGroup", Long.toString(activityDTO.getObjectGroup())).
     method(TaskOptions.Method.GET)
);

The receiving end-point in the controller (in {root}.activities.controller) looks like this:

@RestController
@RequestMapping("/activity")
public class ActivityController {
     .
     .
     .
  @RequestMapping(method = RequestMethod.GET)
  public ResponseEntity<GenericHTTPResponseDTO> recordActivity(ActivityDTO activityDTO) {

      activityService.recordActivity(activityDTO);

      return new ResponseEntity<>(HttpStatus.OK);
  }
}

Once Task is added to Push-Queue the Push-queue will then make an HTTP call to the '/activity' end point, which will trigger the recordActivity() method.


问:
Program a 'Back' button to return to the previous activity
I am very new to all this so please be kind. I have searched and read a lot but I'm totally confused.
I have a number of activities say 1 thru to 10. I can go to activity 4 from both activity 3 and 8. However my 'Back' button on activity 4 always returns me to activity 3. I want it to take me back to the previous activity (3 or 8), please.

Here is the current java code:

```<code>public class Player_new extends AppCompatActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_4_new);
Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    }
public void sendBackMessage(View view) {
        Intent intent = new Intent(this, 3.class);
        startActivity(intent);
    }
}
</code>```

TIA
John

答:
Activity A:
startActivity(new Intent(A.this, B.class);

In activity B

 @Override
    public void onBackPressed() {
        finish();
    }```

Body:
I am very new to all this so please be kind. I have searched and read a lot but I'm totally confused.
I have a number of activities say 1 thru to 10. I can go to activity 4 from both activity 3 and 8. However my 'Back' button on activity 4 always returns me to activity 3. I want it to take me back to the previous activity (3 or 8), please.

Here is the current java code:

public class Player_new extends AppCompatActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_4_new);
Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    }
public void sendBackMessage(View view) {
        Intent intent = new Intent(this, 3.class);
        startActivity(intent);
    }
}

TIA
John


问:
change all checkboxes in one table-row
I want to uncheck all checkboxes that are in one table row.
I have this HTML code :

```<code><tr id="unlosta_line_1">
     <td>
        <input id="unlosta_prop_id_1" name="unlosta_prop_id[1]" value="1"  checked="checked" type="checkbox">
Feld 1
     </td>

     <td>
        <input id="unlosta_prop_id_2" name="unlosta_prop_id[2]" value="2"  type="checkbox">
Feld 2
     </td>

     <td>
        <input id="unlosta_prop_id_3" name="unlosta_prop_id[3]" value="3"  type="checkbox">
Feld 3
     </td>
     <td>...and so on
     <td>
</tr>
</code>```

What I have tried at now is this jquery code:

```<code>$("tr#unlosta_line_1").children("td").each(function(i) { $(i).prop("checked", false) } )
</code>```

答:
Problem with you implementation is that, You are setting checked property of TD element not checkbox.

You can directly use :checkbox selector, then set its checked property

```<code>$("#unlosta_line_1 :checkbox").prop("checked", false);
</code>```

Title: change all checkboxes in one table-row

Body:
I want to uncheck all checkboxes that are in one table row.
I have this HTML code :

        <input id="unlosta_prop_id_1" name="unlosta_prop_id[1]" value="1"  checked="checked" type="checkbox">
Feld 1

        <input id="unlosta_prop_id_2" name="unlosta_prop_id[2]" value="2"  type="checkbox">
Feld 2

        <input id="unlosta_prop_id_3" name="unlosta_prop_id[3]" value="3"  type="checkbox">
Feld 3

     ...and so on

What I have tried at now is this jquery code:

$("tr#unlosta_line_1").children("td").each(function(i) { $(i).prop("checked", false) } )

Body:
Problem with you implementation is that, You are setting checked property of TD element not checkbox.

You can directly use :checkbox selector, then set its checked property

$("#unlosta_line_1 :checkbox").prop("checked", false);


问:
How to Call Javascript method from a javascript file in the Iframe of aspx page?
I have an aspx page where I have a parent page xyz.aspx page where one js file(abc.js) mentioned in the  tag. I need to call a method written in abc.js in child aspx page on load based on some condition. I would like to know how to call this function in child aspx page under document.ready()/window.onload.

I tried using parent.methodname() under script tag but it didnt work.
Here is the code how it looks like:

```<code><script type="text/javascript">
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" :         decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    $(window).load(function () {
        var flgInsidePresentation = getParameterByName("flgInsidePresentation");
        if (flgInsidePresentation) { parent.updateButtons(null, 2, 1); }
    });

</script>
</code>```

If I write only Parent in my console i get the parent page(xyz.aspx) where the js file is mentioned under  tag.

PS: I have to call updateButtons method from deck.navigation.js file from my child.aspx page

```<code>(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  var updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);
</code>```

Please let me know if there is any other way. Thanks for the help in advance.

答:
Have a look at this question Calling a parent window function from an iframe. I am sure you will find you answer there. Make sure that your parent page and iframe use same domain if not - check this answer https://stackoverflow.com/a/14948796/2138959.

EDIT:
In the code example you posted updateButtons function is defined in the scope of anonymous function and is not available in global scope. If you want to make it available you should change it to something like:

```<code>(function($, global, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  global.updateButtons = function(event, from, to) {

  ...

  };

  ...

})(jQuery, window);
</code>```

Body:
I have an aspx page where I have a parent page xyz.aspx page where one js file(abc.js) mentioned in the  tag. I need to call a method written in abc.js in child aspx page on load based on some condition. I would like to know how to call this function in child aspx page under document.ready()/window.onload.

I tried using parent.methodname() under script tag but it didnt work.
Here is the code how it looks like:

If I write only Parent in my console i get the parent page(xyz.aspx) where the js file is mentioned under  tag.

PS: I have to call updateButtons method from deck.navigation.js file from my child.aspx page

(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  var updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);

Please let me know if there is any other way. Thanks for the help in advance.

Body:
Have a look at this question Calling a parent window function from an iframe. I am sure you will find you answer there. Make sure that your parent page and iframe use same domain if not - check this answer https://stackoverflow.com/a/14948796/2138959.

EDIT:
In the code example you posted updateButtons function is defined in the scope of anonymous function and is not available in global scope. If you want to make it available you should change it to something like:

(function($, global, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  global.updateButtons = function(event, from, to) {

  ...

  };

  ...

})(jQuery, window);


问:
URLSessionTask runs always into an error
In my ExtensionDelegate I'm starting a URLSessionTask with following code:

```<code>func scheduleNextURLSessionTask() {
    let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: "myIdentifier")

    let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
    let retrieveTask = backgroundSession.dataTask(with: URL(string: "https://api.wedtec.net/cryptocoins/index.php?bitcoin&simple")!)
    retrieveTask.resume()
}
</code>```

My ExtensionDelegate implements URLSessionDataDelegate, of course.
This runs always into an error. Means

```<code>func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
</code>```

Will be triggered will following error message:

URLSessionTask didCompleteWithError  Optional(Error Domain=NSURLErrorDomain Code=-997 "Lost connection to background transfer service" UserInfo={NSErrorFailingURLKey=https://api.wedtec.net/cryptocoins/index.php?bitcoin&simple, NSErrorFailingURLStringKey=https://api.wedtec.net/cryptocoins/index.php?bitcoin&simple, NSLocalizedDescription=Lost connection to background transfer service})

Any Idea what could be wrong here? scheduleNextURLSessionTask is called from a background process (WKApplicationRefreshBackgroundTask).

答:
According to Apple documentation, only download and upload tasks can be scheduled for executing as background tasks:

"Only upload and download tasks are supported (no data tasks)."

Check here, under "Background transfer considerations"-

Body:
In my ExtensionDelegate I'm starting a URLSessionTask with following code:

func scheduleNextURLSessionTask() {
    let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: "myIdentifier")

    let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
    let retrieveTask = backgroundSession.dataTask(with: URL(string: "https://api.wedtec.net/cryptocoins/index.php?bitcoin&simple")!)
    retrieveTask.resume()
}

My ExtensionDelegate implements URLSessionDataDelegate, of course.
This runs always into an error. Means

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)

Will be triggered will following error message:

URLSessionTask didCompleteWithError  Optional(Error Domain=NSURLErrorDomain Code=-997 "Lost connection to background transfer service" UserInfo={NSErrorFailingURLKey=https://api.wedtec.net/cryptocoins/index.php?bitcoin&simple, NSErrorFailingURLStringKey=https://api.wedtec.net/cryptocoins/index.php?bitcoin&simple, NSLocalizedDescription=Lost connection to background transfer service})

Any Idea what could be wrong here? scheduleNextURLSessionTask is called from a background process (WKApplicationRefreshBackgroundTask).


问:
C Pointers about the different data type
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.

Like

```<code>int a=3,*p=&a;
char c=r,*cha=&r;
</code>```

why can't we do like

```<code>int *c;
char r=a;
c=&r;
</code>```

答:
```<code>int *c;
char r=a;
c=&a;
</code>```

In your declaration a is just a character not a variable.
A pointer when defined can only store  the address of a specific type of variable. If you declare c as int *c, the pointer can only point on variables of type integer.

Body:
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.

Like

int a=3,*p=&a;
char c=r,*cha=&r;

why can't we do like

int *c;
char r=a;
c=&r;

Body:
int *c;
char r=a;
c=&a;

In your declaration a is just a character not a variable.
A pointer when defined can only store  the address of a specific type of variable. If you declare c as int *c, the pointer can only point on variables of type integer.


问:
Excel to DATATABLE using isn't working after hosting
```<code>var pck = new OfficeOpenXml.ExcelPackage();

pck.Load(File.OpenRead("~\\EXCELS\\Book2.xlsx"));
</code>```

How to map excel after hosting ...

I tried this code it is not working for me.

I tried system path it works but after hosting doesn't work
it shows

Could not find a part of the path
  'C:\Windows\SysWOW64\inetsrv\~\EXCELS\Book2.xlsx'.

Can anyone help me please..

答: Remove the ~ to get it to work, and change the path a little.</p>

Body:
var pck = new OfficeOpenXml.ExcelPackage();

pck.Load(File.OpenRead("~\\EXCELS\\Book2.xlsx"));

How to map excel after hosting ...

I tried this code it is not working for me.

I tried system path it works but after hosting doesn't work
it shows

Could not find a part of the path
  'C:\Windows\SysWOW64\inetsrv\~\EXCELS\Book2.xlsx'.

Can anyone help me please..


问:
Loading custom UIView in UIViewController's main view
I have subclassed UIView and created a NIB that controls the main logic for my application.

Hoping the view will scale nicely, I want to use it for both the iPhone and iPad versions of the app.

On the iPhone the view will cover the full screen. On the iPad the view will cover only part of the screen.

I have read that you shouldn't use UIViewControllers to control only part of the screen. So,  I am trying to embed the custom UIView in the main UIViewController's view using IB.

How can this be done?

答:
After a lot of trial and error I found a solution based on an approach explained in the following question, answered by Brian Webster.

The solution was originally suggested for a Cocoa environment. I hope it is valid in an iOS environment as well.

Create the main view controller with a NIB-file. In the NIB, the File's Owner should correspond to the class of your main view controller.

Create a custom view controller with a NIB-file. In this NIB, the File's Owner should correspond to the class of your custom view controller.

Create a custom view controller property in your main view controller class.

Create an UIView property in the main view controller class. It will hold your custom view controller's view. Define it as an IBOutlet, so it can be linked in the NIB.

Drop a UIView in your main view controller's NIB. Link it to the main view controller's view IBOutlet. It will be used as a placeholder for the custom view.

In the main view controller's viewDidLoad method, load the custom view controllers NIB, determine the custom view's frame size and copy the view in the main view controller's view.

Here is some code:

MainViewController.h
```<code>@interface MainViewController : UIViewController {
  CustomViewController *customViewController;
  UIView *customView;
}
@property (nonatomic, retain) CustomViewController *customViewController;
@property (nonatomic, retain) IBOutlet UIView *customView;
@end```

MainViewController.m
```<code>- (void)viewDidLoad {
  CustomViewController *controller = [[CustomViewController alloc] initWithNibName:@"CustomViewController" bundle:nil];
  self.customViewController = controller;
  [controller release];
  customViewController.view.frame = customView.frame;
  customViewController.view.autoresizingMask = customView.autoresizingMask;
  [customView removeFromSuperview];
  [self.view addSubview:customViewController.view];
  self.customView = customViewController.view;
  [super viewDidLoad];
}
```

Body:
After a lot of trial and error I found a solution based on an approach explained in the following question, answered by Brian Webster.

The solution was originally suggested for a Cocoa environment. I hope it is valid in an iOS environment as well.

Create the main view controller with a NIB-file. In the NIB, the File's Owner should correspond to the class of your main view controller.

Create a custom view controller with a NIB-file. In this NIB, the File's Owner should correspond to the class of your custom view controller.

Create a custom view controller property in your main view controller class.

Create an UIView property in the main view controller class. It will hold your custom view controller's view. Define it as an IBOutlet, so it can be linked in the NIB.

Drop a UIView in your main view controller's NIB. Link it to the main view controller's view IBOutlet. It will be used as a placeholder for the custom view.

In the main view controller's viewDidLoad method, load the custom view controllers NIB, determine the custom view's frame size and copy the view in the main view controller's view.

Here is some code:

MainViewController.h

@interface MainViewController : UIViewController {
  CustomViewController *customViewController;
  UIView *customView;
}
@property (nonatomic, retain) CustomViewController *customViewController;
@property (nonatomic, retain) IBOutlet UIView *customView;
@end

MainViewController.m

- (void)viewDidLoad {
  CustomViewController *controller = [[CustomViewController alloc] initWithNibName:@"CustomViewController" bundle:nil];
  self.customViewController = controller;
  [controller release];
  customViewController.view.frame = customView.frame;
  customViewController.view.autoresizingMask = customView.autoresizingMask;
  [customView removeFromSuperview];
  [self.view addSubview:customViewController.view];
  self.customView = customViewController.view;
  [super viewDidLoad];
}