问:
installing varnish in ubuntu 16.04
Tried with 2 different approaches to setup varnish on ubuntu 16.04 in azure but not sure whether the approach of installation is correct.

Referred with different websites all seems to be same set of commands.

Approach 1

```<code>sudo apt-get update
sudo apt-get upgrade
sudo apt-get install varnish

.........
.........
Setting up libvarnishapi1 (4.1.1-1ubuntu0.2) ...
Setting up manpages-dev (4.04-2) ...
Setting up libjemalloc1 (3.6.0-9ubuntu1) ...
Setting up varnish (4.1.1-1ubuntu0.2) ...
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(group) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
Processing triggers for libc-bin (2.23-0ubuntu9) ...
Processing triggers for systemd (229-4ubuntu21) ...
Processing triggers for ureadahead (0.100.0-19) ...
</code>```

Is the above installation is correct since it gives sent invalidate.

Approach 2

```<code>sudo curl http://repo.varnish-cache.org/debian/GPG-key.txt | sudo apt-key add -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   580  100   580    0     0   1172      0 --:--:-- --:--:-- --:--:--  1171
gpg: no valid OpenPGP data found.

sudo echo "deb http://repo.varnish-cache.org/ubuntu/ precise varnish-3.0" | sudo tee -a /etc/apt/sources.list

sudo apt-get update
</code>```

Doing a update will result in below error.

```<code>W: The repository 'http://repo.varnish-cache.org/ubuntu precise Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://repo.varnish-cache.org/ubuntu/dists/precise/varnish-3.0/binary-amd64/Packages  410  repo [IP: 176.58.90.154 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.
</code>```

Not sure both the approaches are correct as both are giving some errors.

答:
Is the above installation is correct since it gives sent invalidate.

It's a known issue about Ubuntu 16.04.

When we try to add user to Ubuntu 16.04, we will get this error message, like this:

```<code>root@ubuntu:~# adduser test
Adding user `test' ...
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
Adding new group `test' (1001) ...
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
Adding new user `test' (1001) with group `test' ...
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
Creating home directory `/home/test' ...
Copying files from `/etc/skel' ...
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for test
Enter the new value, or press ENTER for the default
    Full Name []:
    Room Number []:
</code>```

As far as I know, the error message will not effect it.

```<code>jason@ubuntu:~$ su - test
Password:
test@ubuntu:~$
</code>```

Here the link about this issue, please refer to it.

Title: installing varnish in ubuntu 16.04

Body:
Tried with 2 different approaches to setup varnish on ubuntu 16.04 in azure but not sure whether the approach of installation is correct.

Referred with different websites all seems to be same set of commands.

Approach 1

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install varnish

.........
.........
Setting up libvarnishapi1 (4.1.1-1ubuntu0.2) ...
Setting up manpages-dev (4.04-2) ...
Setting up libjemalloc1 (3.6.0-9ubuntu1) ...
Setting up varnish (4.1.1-1ubuntu0.2) ...
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(group) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
Processing triggers for libc-bin (2.23-0ubuntu9) ...
Processing triggers for systemd (229-4ubuntu21) ...
Processing triggers for ureadahead (0.100.0-19) ...

Is the above installation is correct since it gives sent invalidate.

Approach 2

sudo curl http://repo.varnish-cache.org/debian/GPG-key.txt | sudo apt-key add -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   580  100   580    0     0   1172      0 --:--:-- --:--:-- --:--:--  1171
gpg: no valid OpenPGP data found.

sudo echo "deb http://repo.varnish-cache.org/ubuntu/ precise varnish-3.0" | sudo tee -a /etc/apt/sources.list

sudo apt-get update

Doing a update will result in below error.

W: The repository 'http://repo.varnish-cache.org/ubuntu precise Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://repo.varnish-cache.org/ubuntu/dists/precise/varnish-3.0/binary-amd64/Packages  410  repo [IP: 176.58.90.154 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.

Not sure both the approaches are correct as both are giving some errors.

Body:
Is the above installation is correct since it gives sent invalidate.

It's a known issue about Ubuntu 16.04.

When we try to add user to Ubuntu 16.04, we will get this error message, like this:

root@ubuntu:~# adduser test
Adding user `test' ...
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
Adding new group `test' (1001) ...
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
Adding new user `test' (1001) with group `test' ...
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
Creating home directory `/home/test' ...
Copying files from `/etc/skel' ...
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for test
Enter the new value, or press ENTER for the default
    Full Name []:
    Room Number []:

As far as I know, the error message will not effect it.

jason@ubuntu:~$ su - test
Password:
test@ubuntu:~$

Here the link about this issue, please refer to it.


来源: stackexchange

问:
How to call two tags at same time on active: to make changes in css
I'm having a little problem. As, I'm currently working on a left side menu, and am trying to call the two tags li and a at the same time on :active in css. I searched a lot but couldn't get anything working for me. What I want is to change the color of the whole row of li and a on :active (when the user clicks on the button).

Here is my code:

.sub-menu li,
a:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-list">
  <ul id="menu-content" class="menu-content collapse out">
    <li data-toggle="collapse" class="collapsed">
      <a><i class="<?=$MainObj['Icon'];?>" style="color:#9f9e9e !important"></i><?=$MainObj['GroupMenuName'];?> <span class="arrow" style="color:#9f9e9e !important">
    </span></a>
      <ul class="sub-menu collapse" id="a">
        <li>check1</li>
        <li>check2</li>
        <li>check3</li>
        <li>check4</li>
      </ul>
    </li>

    <li>

        <i class="fa fa-user fa-lg" style="color:#9f9e9e !important"></i> Profile

    </li>

    <li>

        <i class="fa fa-users fa-lg" style="color:#9f9e9e !important"></i> Users

    </li>
  </ul>
  <span class="collapse-expand" data-ember-action="" data-ember-action-1815="1815"></span>

</div></code>```

答:
Is this giving you the result you're looking for? I changed some CSS code.

HTML:

```<code><div class="menu-list">
 <ul id="menu-content" class="menu-content collapse out">
 <li data-toggle="collapse"  class="collapsed">
 <a><i class="<?=$MainObj['Icon'];?>" style="color:#9f9e9e !important"></i><?=$MainObj['GroupMenuName'];?> <span class="arrow" style="color:#9f9e9e !important">
</span></a>
 <ul class="sub-menu collapse" id="a">
 <li><a href="#">check1</a></li>
 <li><a href="#">check2</a></li>
 <li><a href="#">check3</a></li>
 <li><a href="#">check4</a></li>
 </ul>
 </li>

             <li>
              <a href="#">
              <i class="fa fa-user fa-lg" style="color:#9f9e9e !important"></i> Profile
              </a>
              </li>

             <li>
              <a href="#">
              <i class="fa fa-users fa-lg" style="color:#9f9e9e !important"></i> Users
              </a>
            </li>
        </ul>
        <span class="collapse-expand" data-ember-action="" data-ember-action-1815="1815"></span>

 </div>
</code>```

CSS:

```<code>.sub-menu a {
  display: block;
}

a:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm having a little problem. As, I'm currently working on a left side menu, and am trying to call the two tags li and a at the same time on :active in css. I searched a lot but couldn't get anything working for me. What I want is to change the color of the whole row of li and a on :active (when the user clicks on the button).

Here is my code:

.sub-menu li,
a:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}

      <i class="<?=$MainObj['Icon'];?>" style="color:#9f9e9e !important"><?=$MainObj['GroupMenuName'];?>

check1

check2

check3

check4

         Profile

         Users

Body:
Is this giving you the result you're looking for? I changed some CSS code.

HTML:

<div class="menu-list">
 <ul id="menu-content" class="menu-content collapse out">
 <li data-toggle="collapse"  class="collapsed">
 <a><i class="<?=$MainObj['Icon'];?>" style="color:#9f9e9e !important"></i><?=$MainObj['GroupMenuName'];?> <span class="arrow" style="color:#9f9e9e !important">
</span></a>
 <ul class="sub-menu collapse" id="a">
 <li><a href="#">check1</a></li>
 <li><a href="#">check2</a></li>
 <li><a href="#">check3</a></li>
 <li><a href="#">check4</a></li>
 </ul>
 </li>

             <li>
              <a href="#">
              <i class="fa fa-user fa-lg" style="color:#9f9e9e !important"></i> Profile
              </a>
              </li>

             <li>
              <a href="#">
              <i class="fa fa-users fa-lg" style="color:#9f9e9e !important"></i> Users
              </a>
            </li>
        </ul>
        <span class="collapse-expand" data-ember-action="" data-ember-action-1815="1815"></span>

 </div>

CSS:

.sub-menu a {
  display: block;
}

a:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}


问:
Imperavi redactor.js table plugin with bullets
I would like to add an unordered list in the table of the Redactor WYSIWYG-editor but I cannot get it work. Other formatted text like bold, links etc. work. It just does not seem to work in the table plugin. Did anyone manage to do so?</p>

答:
Yes, I got the same issue and my plugin version is 2.11. In this plugin I have to modify some code to make it work.

Go to line number 6913 where you will find the code

```<code>list: function() {
</code>```

in toggle function comment out the following block of code:

```<code>if (this.utils.inBlocks(['table', 'td', 'th', 'tr']))
{
    return;
}
</code>```

Then later you need to comment 1 more line at line number 6996:

```<code>$listParent.replaceWith($listParent.contents());
</code>```

After commenting out the above code you will be able to put ordered/unordered lists in table.

Body:
Yes, I got the same issue and my plugin version is 2.11. In this plugin I have to modify some code to make it work.

Go to line number 6913 where you will find the code

list: function() {

in toggle function comment out the following block of code:

if (this.utils.inBlocks(['table', 'td', 'th', 'tr']))
{
    return;
}

Then later you need to comment 1 more line at line number 6996:

$listParent.replaceWith($listParent.contents());

After commenting out the above code you will be able to put ordered/unordered lists in table.


问:
'ul li' hover color with hyperlink inside
Consider:

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
  color: #555;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li a:hover {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='titlewrap'>
  <ul>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
  </ul>
</div></code>```

Hovering, li a color is changed to white, but when I move the pointer outside of a and still inside of li- color is again #555.

答:
ul li a is more specific than ul li:hover.

Rather have the nested anchor tag inherit its color from its containing list item tag.

```<code>ul li a {
    color: inherit;
}
</code>```

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
    color: inherit;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li a:hover {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='titlewrap'>
  <ul>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
  </ul>
</div></code>```

Body:
Consider:

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
  color: #555;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li a:hover {
  color: white;
}

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

Hovering, li a color is changed to white, but when I move the pointer outside of a and still inside of li- color is again #555.

Body:
ul li a is more specific than ul li:hover.

Rather have the nested anchor tag inherit its color from its containing list item tag.

ul li a {
    color: inherit;
}

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
    color: inherit;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li a:hover {
  color: white;
}

<div class='titlewrap'>
  <ul>
    <li class='title'><a href='view.php?id=1' target='_blank'>lorem ipsum</a></li>
    <li class='title'><a href='view.php?id=2' target='_blank'>lorem ipsum</a></li>
    <li class='title'><a href='view.php?id=3' target='_blank'>lorem ipsum</a></li>
    <li class='title'><a href='view.php?id=4' target='_blank'>lorem ipsum</a></li>
  </ul>
</div>


问:
Ruby on Rails Test Database Not Committing New Records
Is there a way to use Factory Girl to commit new changes to the test database in Ruby on Rails?

I have the following factory:

```<code>Factory.define :shipping_info do |si|
    si.name "Foo Bar"
    si.street "12 Candy Lane"
    si.country "US"
    si.zip "12345"
    si.state "IL"
end
</code>```

And I have the the following test:

```<code>require File.dirname(__FILE__) + '/../../spec_helper'

describe CgCart::ShippingInfo do

   before(:each) do
      @order = Factory(:order)
      @order.order_line_item = Factory(:order_line_item)
      @shipping_info = Factory(:shipping_info)
   end

    it "order should not be nil" do
        @shipping_info.should_not be_nil
    end
end
</code>```

When I run this test it passes. However, no new records are created in my test database. I need data in there for a Dameon to work with.

Any suggestions?

答:
Using Factory.create(:order) should write that object to your database.
If you have transactional fixture set to true, all data that gets written to database gets rolled back after the tests finish.

You cant tail -f log/test.log before running your tests and you will see a lot of activity there.

I hope that clears your situation.

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to use Factory Girl to commit new changes to the test database in Ruby on Rails?

I have the following factory:

Factory.define :shipping_info do |si|
    si.name "Foo Bar"
    si.street "12 Candy Lane"
    si.country "US"
    si.zip "12345"
    si.state "IL"
end

And I have the the following test:

require File.dirname(__FILE__) + '/../../spec_helper'

describe CgCart::ShippingInfo do

   before(:each) do
      @order = Factory(:order)
      @order.order_line_item = Factory(:order_line_item)
      @shipping_info = Factory(:shipping_info)
   end

    it "order should not be nil" do
        @shipping_info.should_not be_nil
    end
end

When I run this test it passes. However, no new records are created in my test database. I need data in there for a Dameon to work with.

Any suggestions?


问:
How to access the search bar in a Firefox 57+ ("Quantum") web extension
I try to write my very first webextension, following this tutorial. I wrote a manifest.json and added a background script as I want to provide global functionality: I want to clear the search bar once the search was performed - basically it's this, but for Firefox 57+.

My question: How can I access the search bar at all?

I found a list of available APIs, including the tabs, the menus, and so on, but no search bar...

答: Currently it is not possible. You might want to file a bug for it: https://bugzilla.mozilla.org/</p>


问:
Is there a way to remove attribute after calling `AddAttribute`
Is there any way to remove attribute after the attribute was added by AddAttribute (msdn)?

Example:

```<code>public static void GenerateFieldInput(HtmlTextWriter writer)
{
    writer.RenderBeginTag(HtmlTextWriterTag.Input);
    writer.AddAttribute("placeholder", "some value");

    // some code logic

    writer.RemoveAttribute("placeholder"); // there isn't such method in HtmlTextWriter
}
</code>```

答:
HtmlTextWriter, like many other TextWriters, only writes stuff into a stream. There isn't an official way to delete stuff from it.

And why do you want to remove the attribute in the first place? Did you find that later on in the code, that the attribute is not needed anymore? If that's the case, try determining whether the tag is actually needed before you write it.

If you can't do that, you can put all the attributes you want to add in a List<T>, which allows you to add and delete elements. After you are absolutely sure that that is what you are going to write, do a foreach loop and write each attribute.

Body:
Is there any way to remove attribute after the attribute was added by AddAttribute (msdn)?

Example:

public static void GenerateFieldInput(HtmlTextWriter writer)
{
    writer.RenderBeginTag(HtmlTextWriterTag.Input);
    writer.AddAttribute("placeholder", "some value");

    // some code logic

    writer.RemoveAttribute("placeholder"); // there isn't such method in HtmlTextWriter
}


问:
could not get input field value in jquery
I am creating an input field using foreach loop like this

```<code><?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
</code>```

$data is Array

```<code>(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)
</code>```

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

```<code><script type="text/javascript">
 $(document).ready(function () {
           var typename = $('#typename').val();
           alert(typename);
});
</script>
</code>```

i have to disable this input field when value is 'Generator'

答:
The id attribute specifies a unique id for an HTML element it's not a good practice to use same ID more than once on a page, instead of ID attribute loop the class attribute in jquery.

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <?php $incr_var = 1; ?>
  <?php foreach($data as $key=>$val) { ?>
    <td class="table-td-1">
    <input readonly class="form-control common-class" name="model[]" id="typename<?php echo $incr_var ?>" type="text" value="<?php echo $val['asset']; ?>">
    </td>
    <?php } ?></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating an input field using foreach loop like this

<?php foreach($data as $key=>$val) { ?>

<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">

<?php } ?>

$data is Array

(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

i have to disable this input field when value is 'Generator'

Body:
The id attribute specifies a unique id for an HTML element it's not a good practice to use same ID more than once on a page, instead of ID attribute loop the class attribute in jquery.

 <script type="text/javascript">
     $(document).ready(function () {
     $('.common-class').each(function() {
      alert($(this).val());
     });

    });
 </script>

  <?php $incr_var = 1; ?>
  <?php foreach($data as $key=>$val) { ?>
    <td class="table-td-1">
    <input readonly class="form-control common-class" name="model[]" id="typename<?php echo $incr_var ?>" type="text" value="<?php echo $val['asset']; ?>">
    </td>
    <?php } ?>


问:
Which thread async operations take place
Afte reading the asio's documentation, it's clear to me that the completion handlers are called by one of the threads that called the io_service's  io.run() method. However, something that's is not clear to me is which thread the read/write async methods take place. Is it the thread that I call the methods or is it in one of the threads that called the io.run() method? Or, in last case, does the library create another thread behind the scenes and performs the operation?

答:
The I/O operation will be attempted within the initiating async_* function.  If either the operation's completion condition is satisfied or an error occurs, then the operation is complete and the completion handler will be posted into the io_service.  Otherwise, the operation is not complete, and it will be enqueued into the io_service, where an application thread running the io_service's function poll(), poll_one(), run(), or run_one() performs the underlying I/O operation.  In both cases, the completion handler is invoked by a thread processing the io_service.

The async_write() documentation notes that the asynchronous operation may be completed immediately:

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

This behavior is also noted in the Requirements on Asynchronous Operations documentation:

When an asynchronous operation is complete, the handler for the operation will be invoked as if by:

Constructing a bound completion handler bch for the handler ...

Calling ios.post(bch) to schedule the handler for deferred invocation ...

This implies that the handler must not be called directly from within the initiating function, even if the asynchronous operation completes immediately.

Here is a complete example demonstrating this behavior.  In it, socket1 and socket2 are connected.  Initially, socket2 has no data available.  However, after invoking async_write(socket1, ...), socket2 has data even though the io_service has not been ran:

```<code>#include <boost/asio.hpp>

constexpr auto noop = [](auto&& ...){};

int main()
{
  using boost::asio::ip::tcp;
  boost::asio::io_service io_service;

  // Create all I/O objects.
  tcp::acceptor acceptor{io_service, {{}, 0}};
  tcp::socket socket1{io_service};
  tcp::socket socket2{io_service};

  // Connect sockets.
  acceptor.async_accept(socket1, noop);
  socket2.async_connect(acceptor.local_endpoint(), noop);
  io_service.run();
  io_service.reset();

  // Verify socket2 has no data.
  assert(0 == socket2.available());

  // Initiate an asynchronous write.  However, do not run
  // the `io_service`.
  std::string data{"example"};
  async_write(socket1, boost::asio::buffer(data), noop);

  // Verify socket2 has data.
  assert(0 < socket2.available());
}
</code>```

Body:
The I/O operation will be attempted within the initiating async_* function.  If either the operation's completion condition is satisfied or an error occurs, then the operation is complete and the completion handler will be posted into the io_service.  Otherwise, the operation is not complete, and it will be enqueued into the io_service, where an application thread running the io_service's function poll(), poll_one(), run(), or run_one() performs the underlying I/O operation.  In both cases, the completion handler is invoked by a thread processing the io_service.

The async_write() documentation notes that the asynchronous operation may be completed immediately:

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

This behavior is also noted in the Requirements on Asynchronous Operations documentation:

When an asynchronous operation is complete, the handler for the operation will be invoked as if by:

Constructing a bound completion handler bch for the handler ...

Calling ios.post(bch) to schedule the handler for deferred invocation ...

This implies that the handler must not be called directly from within the initiating function, even if the asynchronous operation completes immediately.

Here is a complete example demonstrating this behavior.  In it, socket1 and socket2 are connected.  Initially, socket2 has no data available.  However, after invoking async_write(socket1, ...), socket2 has data even though the io_service has not been ran:

#include <boost/asio.hpp>

constexpr auto noop = [](auto&& ...){};

int main()
{
  using boost::asio::ip::tcp;
  boost::asio::io_service io_service;

  // Create all I/O objects.
  tcp::acceptor acceptor{io_service, {{}, 0}};
  tcp::socket socket1{io_service};
  tcp::socket socket2{io_service};

  // Connect sockets.
  acceptor.async_accept(socket1, noop);
  socket2.async_connect(acceptor.local_endpoint(), noop);
  io_service.run();
  io_service.reset();

  // Verify socket2 has no data.
  assert(0 == socket2.available());

  // Initiate an asynchronous write.  However, do not run
  // the `io_service`.
  std::string data{"example"};
  async_write(socket1, boost::asio::buffer(data), noop);

  // Verify socket2 has data.
  assert(0 < socket2.available());
}


答:
pure js approach;

replace id with class;

```<code><?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control typename" name="model[]" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
</code>```

js

```<code>window.onload = alertTypeNames();

function alertTypeNames() {
    document.getElementsByClassName('typename').map((inputTag) => {
        alert(inputTag.value);
         return true;
    });
}
</code>```

Title: could not get input field value in jquery

Body:
pure js approach;

replace id with class;

<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control typename" name="model[]" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>

js

window.onload = alertTypeNames();

function alertTypeNames() {
    document.getElementsByClassName('typename').map((inputTag) => {
        alert(inputTag.value);
         return true;
    });
}


问:
sftp outbound-gateway with get command throws exception when file with the same name already exists
I am attempting to use an sftp outbound gateway to download a file from a remote sftp server. Here is the gateway configuration:

```<code><int-sftp:outbound-gateway id="downloadGateway"
                command="get"
                command-options="-P"
                expression="payload.remoteDirectory + payload.filename"
                session-factory="cachingSessionFactory"
                local-directory="downloads"
                auto-create-directory="true"
                use-temporary-file-name="true"
                mode="REPLACE"
                local-filename-generator-expression="#remoteFileName + '.' + @currentDate.getDateStr()"
                />
</code>```

In cases when a local file with the same name already exists, I'd like to replace it with the newly downloaded file. This is why I set the mode to "REPLACE". Instead, I get an exception:

```<code>Caused by: org.springframework.messaging.MessagingException: Local file downloads\myFile.xml.2015-04-14 already exists
at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.get(AbstractRemoteFileOutboundGateway.java:700)
at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway$2.doInSession(AbstractRemoteFileOutboundGateway.java:436)
at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway$2.doInSession(AbstractRemoteFileOutboundGateway.java:432)
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:334)
at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.doGet(AbstractRemoteFileOutboundGateway.java:432)
at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.handleRequestMessage(AbstractRemoteFileOutboundGateway.java:394)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:99)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:123)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:95)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:248)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:171)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:119)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:105)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:123)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:95)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:248)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:171)
at org.springframework.integration.splitter.AbstractMessageSplitter.produceOutput(AbstractMessageSplitter.java:129)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:119)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:105)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:123)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:95)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:248)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:171)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:119)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:105)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.handler.MessageHandlerChain.handleMessageInternal(MessageHandlerChain.java:104)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
... 7 more
</code>```

Am I correct t assume that mode attribute is meant for remote files when the gateway is used with put commands? Is there any way for me to achieve the behavior I am looking for with sftp outbound gateway?

答:
Its an old thread but in case you are looking for your valid values for mode, here they are(Ref: org.springframework.integration.file.support.FileExistsMode):

```<code>   /**
     * Append data to any pre-existing files; close after each append.
     */
    APPEND,

    /**
     * Append data to any pre-existing files; do not flush/close after
     * appending.
     * @since 4.3
     */
    APPEND_NO_FLUSH,

    /**
     * Raise an exception in case the file to be written already exists.
     */
    FAIL,

    /**
     * If the file already exists, do nothing.
     */
    IGNORE,

    /**
     * If the file already exists, replace it.
     */
    REPLACE;
</code>```

Body:
I am attempting to use an sftp outbound gateway to download a file from a remote sftp server. Here is the gateway configuration:

<int-sftp:outbound-gateway id="downloadGateway"
                command="get"
                command-options="-P"
                expression="payload.remoteDirectory + payload.filename"
                session-factory="cachingSessionFactory"
                local-directory="downloads"
                auto-create-directory="true"
                use-temporary-file-name="true"
                mode="REPLACE"
                local-filename-generator-expression="#remoteFileName + '.' + @currentDate.getDateStr()"
                />

In cases when a local file with the same name already exists, I'd like to replace it with the newly downloaded file. This is why I set the mode to "REPLACE". Instead, I get an exception:

Caused by: org.springframework.messaging.MessagingException: Local file downloads\myFile.xml.2015-04-14 already exists
at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.get(AbstractRemoteFileOutboundGateway.java:700)
at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway$2.doInSession(AbstractRemoteFileOutboundGateway.java:436)
at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway$2.doInSession(AbstractRemoteFileOutboundGateway.java:432)
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:334)
at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.doGet(AbstractRemoteFileOutboundGateway.java:432)
at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.handleRequestMessage(AbstractRemoteFileOutboundGateway.java:394)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:99)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:123)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:95)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:248)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:171)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:119)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:105)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:123)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:95)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:248)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:171)
at org.springframework.integration.splitter.AbstractMessageSplitter.produceOutput(AbstractMessageSplitter.java:129)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:119)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:105)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:123)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:95)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:248)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:171)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:119)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:105)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.handler.MessageHandlerChain.handleMessageInternal(MessageHandlerChain.java:104)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
... 7 more

Am I correct t assume that mode attribute is meant for remote files when the gateway is used with put commands? Is there any way for me to achieve the behavior I am looking for with sftp outbound gateway?

Body:
Its an old thread but in case you are looking for your valid values for mode, here they are(Ref: org.springframework.integration.file.support.FileExistsMode):

   /**
     * Append data to any pre-existing files; close after each append.
     */
    APPEND,

    /**
     * Append data to any pre-existing files; do not flush/close after
     * appending.
     * @since 4.3
     */
    APPEND_NO_FLUSH,

    /**
     * Raise an exception in case the file to be written already exists.
     */
    FAIL,

    /**
     * If the file already exists, do nothing.
     */
    IGNORE,

    /**
     * If the file already exists, replace it.
     */
    REPLACE;


问:
How to access file in parent directory using python?
I am trying to access a text file in the parent directory,

Eg : python script is in codeSrc & the text file is in mainFolder.

script path:

```<code>G:\mainFolder\codeSrc\fun.py
</code>```

desired file path:

```<code>G:\mainFolder\foo.txt
</code>```

I am currently using this syntax with python 2.7x,

```<code>import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"
</code>```

Although this works fine, is there a better (prettier :P) way to do this?

答:
You can try this </p>

```<code>import environ
environ.Path() - 1 + 'foo.txt'
</code>```

Body:
I am trying to access a text file in the parent directory,

Eg : python script is in codeSrc & the text file is in mainFolder.

script path:

G:\mainFolder\codeSrc\fun.py

desired file path:

G:\mainFolder\foo.txt

I am currently using this syntax with python 2.7x,

import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"

Although this works fine, is there a better (prettier :P) way to do this?

Body:
You can try this

import environ
environ.Path() - 1 + 'foo.txt'


问:
Regular expression string search in Java
I know this can be done in many ways but im curious as to what the regex would be to pick out all strings not containing a particular substring, say GDA from
strings like GADSA, GDSARTCC, , THGDAERY. </p>

答:
If your input is one long string then you have to decide how you define a substring. If it's separated by spaces then:</p>

```<code>String[] split = mylongstr.split(" ");
for (String s : split) {
  if (!s.contains("GDA")) {
    // do whatever
  }
}
</code>```

Body:
If your input is one long string then you have to decide how you define a substring. If it's separated by spaces then:

String[] split = mylongstr.split(" ");
for (String s : split) {
  if (!s.contains("GDA")) {
    // do whatever
  }
}


问:
Using apache mod_rewrite to redirect to php file
I'd like to redirect the following url:

```<code>http://www.example.com/food/?p=11&q=22&r=33
</code>```

to

```<code>http://www.example.com/food/api.php/DBNAME/?p=11&q=22&r=33
</code>```

As you may have noticed, DBNAME is the name of a database.
With the API I'm using it is necessary to include it in the URL.

Here's a brief folder structure of my program:

```<code>food/
   ->include/
   ->models/
   ->.htaccess
   ->api.php
   ->config.php
   ->test.php
</code>```

I tried writing the rules on the .htaccess file but I get an Internal server error.

My .htaccess file looks like this:

```<code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(.*)$ api.php/DBNAME/$1 [L]
</IfModule>
</code>```

I can get my head around achieving the redirection.
I also tried

```<code>RewriteRule ^food/(.*)$ api.php/DBNAME/$1 [L]
</code>```

but this rule just lists the files in the directory food.

Any ideas?
Thanks!

PS: The query string is not just p=11&q=22&r=33 it may use any letter or word such as type, quantity and so on. p=11&q=22&r=33 is just an example.

Edit
From the link that @sanj provided I changed my .htaccess ffile to this

```<code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/food/?$
RewriteRule ^(.*)$ api.php/DBNAME/$1
</IfModule>
</code>```

It works partially. Why partially?

I have two servers, one for testing and one for production. It works well on the testing server but not on the production server. I get an Authorization Required error. I believe it's due to the configuration in my .htaccess because if I remove the mod_rewrite module and access the url directly it works. Any ideas?

Found my mistake. The folder was protected by Basic Authentication. I needed to include login parameters in my code. I can't believe I overlooked that.

答:
I think this will work:</p>

```<code><IfModule mod_rewrite.c>
    RewriteBase /food
    RewriteEngine on
    RewriteCond %{QUERY_STRING} /DBNAME/
    RewriteCond %{QUERY_STRING} (.*)
    RewriteRule ^$                index.php/DBNAME/?%1 [L]
</IfModule>
</code>```

Body:
I'd like to redirect the following url:

http://www.example.com/food/?p=11&q=22&r=33

to

http://www.example.com/food/api.php/DBNAME/?p=11&q=22&r=33

As you may have noticed, DBNAME is the name of a database.
With the API I'm using it is necessary to include it in the URL.

Here's a brief folder structure of my program:

food/
   ->include/
   ->models/
   ->.htaccess
   ->api.php
   ->config.php
   ->test.php

I tried writing the rules on the .htaccess file but I get an Internal server error.

My .htaccess file looks like this:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(.*)$ api.php/DBNAME/$1 [L]
</IfModule>

I can get my head around achieving the redirection.
I also tried

RewriteRule ^food/(.*)$ api.php/DBNAME/$1 [L]

but this rule just lists the files in the directory food.

Any ideas?
Thanks!

PS: The query string is not just p=11&q=22&r=33 it may use any letter or word such as type, quantity and so on. p=11&q=22&r=33 is just an example.

Edit
From the link that @sanj provided I changed my .htaccess ffile to this

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/food/?$
RewriteRule ^(.*)$ api.php/DBNAME/$1
</IfModule>

It works partially. Why partially?

I have two servers, one for testing and one for production. It works well on the testing server but not on the production server. I get an Authorization Required error. I believe it's due to the configuration in my .htaccess because if I remove the mod_rewrite module and access the url directly it works. Any ideas?

Found my mistake. The folder was protected by Basic Authentication. I needed to include login parameters in my code. I can't believe I overlooked that.

Body:
I think this will work:

<IfModule mod_rewrite.c>
    RewriteBase /food
    RewriteEngine on
    RewriteCond %{QUERY_STRING} /DBNAME/
    RewriteCond %{QUERY_STRING} (.*)
    RewriteRule ^$                index.php/DBNAME/?%1 [L]
</IfModule>


问:
Why aren't std::count and std::find optimised to use memchr?
I was reading sehe's answer to this question and was surprised to see sehe found using a hand written loop using std::memchr to be over 3 times faster than using std::count (see comments). The code using std::count can be seen in edit 2, but it basically boils down to:

```<code>const auto num_lines = std::count(f, l, '\n');
</code>```

vs

```<code>uintmax_t num_lines = 0;
while (f && f != l)
    if ((f = static_cast<const char*>(memchr(f, '\n', l - f))))
        num_lines++, f++;
</code>```

I would have expected the std::count version to be at least as fast as the std::memchr one - for a similar reason to why using std::copy should be at least as fast as std::memcpy.

I checked my standard library's (libc++) implementation of std::count, and there is no attempt to optimise for char input types (ditto for std::find).

Why is this? Could the implementations not dispatch to std::memchr if provided with char* iterators, and a char value?

答:
Using an actual function call to memchr is only a win if the average distance between matches is not small.

Especially for count, calling memchr could be a lot slower if you were counting t characters when they appear on average every 2 or maybe every 4.  (e.g. with DNA base-pairs using an alphabet of ACGT).

I'd be skeptical of using a memchr loop as the default implementation for std::count over char arrays.  There are more likely other ways to tweak the source so it compiles to better asm.

For find it would make more sense, even though it does potentially increase the overhead significantly vs. a simple byte-at-a-time loop if there's a hit in the first couple bytes.

You could also look at this as a compiler missed-optimization.  If compilers made better code for the loops in std::count and std::find, there'd be less to gain from calling hand-written asm library functions.

gcc and clang never auto-vectorize loops when the trip-count isn't known before entering the loop.  (i.e. they don't do search loops, which is a major missed optimization for element sizes as small as bytes).  ICC doesn't have this limitation, and can vectorize search loops.  I haven't looked at how it does with libc++'s std::count or find, though.

std::count has to check every element, so it should auto-vectorize.  But if gcc or clang don't even with -O3, then that's unfortunate.  It should vectorize very well on x86 with pcmpeqb (packed compare bytes), and then paddb the 0/-1 compare results.  (every 255 iterations at least, psadbw against zero to horizontally sum the byte elements).

Library function call overhead is at least an indirect call with a function pointer from memory (which can cache miss).  On Linux with dynamic linking there's usually an extra jmp through the PLT as well (unless you compiled with -fno-plt).  memchr is easier to optimize with low startup overhead than strchr, because you can quickly check whether a 16B vector load can go past the end (vs. aligning the pointer for strchr or strlen to avoid crossing a page or cache-line boundary)

If calling memchr is the best way to implement something in asm, then in theory that's what the compiler should emit.  gcc/clang already optimize large copy loops to calls to libc memcpy, depending on target options (-march=).  e.g. when the copy is large enough that the libc version may decide to use NT stores on x86.

Body:
I was reading sehe's answer to this question and was surprised to see sehe found using a hand written loop using std::memchr to be over 3 times faster than using std::count (see comments). The code using std::count can be seen in edit 2, but it basically boils down to:

const auto num_lines = std::count(f, l, '\n');

vs

uintmax_t num_lines = 0;
while (f && f != l)
    if ((f = static_cast<const char*>(memchr(f, '\n', l - f))))
        num_lines++, f++;

I would have expected the std::count version to be at least as fast as the std::memchr one - for a similar reason to why using std::copy should be at least as fast as std::memcpy.

I checked my standard library's (libc++) implementation of std::count, and there is no attempt to optimise for char input types (ditto for std::find).

Why is this? Could the implementations not dispatch to std::memchr if provided with char* iterators, and a char value?


问:
How to set rightmost 8 bit of a 64bit int to a char var?
For example, I have a 64 bit var a, and a 8 bit char b

```<code>unsigned long long a = 0x1234567890123456;
unsigned char b = 0x78;
</code>```

I want a to become 0x1234567890123478

I want rightmost 8 bit of a to set to b, and remain left 56 bits untouched, how can i do this?

```<code>a = a & (0xFFffFFffFFffFFff | b); //is this correct?
</code>```

??

答:
There's a useful macro defined in limits.h that can help make it portable. It's CHAR_BIT.

```<code>a = ((a >> CHAR_BIT) << CHAR_BIT) | b;
</code>```

And that's it. The piece in parentheses clears the least significant CHAR_BITs of a, and then that can be bitwise-ored with b.

Body:
For example, I have a 64 bit var a, and a 8 bit char b

unsigned long long a = 0x1234567890123456;
unsigned char b = 0x78;

I want a to become 0x1234567890123478

I want rightmost 8 bit of a to set to b, and remain left 56 bits untouched, how can i do this?

a = a & (0xFFffFFffFFffFFff | b); //is this correct?

??

Body:
There's a useful macro defined in limits.h that can help make it portable. It's CHAR_BIT.

a = ((a >> CHAR_BIT) << CHAR_BIT) | b;

And that's it. The piece in parentheses clears the least significant CHAR_BITs of a, and then that can be bitwise-ored with b.


问:
What is the difference between no access specifier and public in java 9 module?
From java 9, public access is limited to it's own module. Does it mean public acts like a package protected ( no access specifier )? Can someone clarify this?

答:
One of the primary goals of the Module system is to provide :

Strong encapsulation, to allow a component to declare which of its public types are accessible to other components, and which are
  not.

To add to the #accessibility aspect of it -

The Java compiler and virtual machine consider the public types in a
  package in one module to be accessible by code in some other module
  only when the first module is readable by the second module, in the
  sense defined above, and the first module exports that package

So, in order to access the public types of a package as well from another module, the accessed module needs to export that package to make it readable.

But then this wouldn't necessarily be true for all types of modules ( e.g. automatic modules) in the module system.

Does it mean public acts like a package protected ( no access
  specifier )?

No, the public types shall be accessible to different packages within the same modules as well as when(if) exported, the package exposes the access to the public types by other packages of other modules as well.


问:
Magento category view next and previous page toolbar
Whomever worked on the site previous me has somehow turned off the toolbar on the category view page. They had wanted to get rid of the filter by, and other options.

Now we have too many products to display them all on one page, so I went ahead and limited it to show 12 products, which it does. But now navigation shows up. I assume this is because of how they turned off the toolbar. Where do I find the code (using a theme) to control this toolbar? I am hoping they just commented out the code.

Magento 1.9.3.3

答:
over ride the below given files  into your theme

app/design/frontend/base/default/template/catalog/product/list.phtml

and you can see the code that call child html of tool bar
in line numbers 42 and 125 for bottom side

<?php echo $this->getToolbarHtml() ?>

so if you commented this line then corresponding tool bars not shows

or if you want to customize the tool bar part then you can edit in the file.

app/design/frontend/base/default/template/catalog/product/list/toolbar.phtml

this file is render for toolbar


问:
How to disable VirtualStore for C++ programs?
I'd like my program to throw an error when it tries to create files in protected locations like the root of the C:\ drive (eg: FILE* FileHandle = fopen("\\file.txt", a)).  Instead the file gets created in the Virtual Store under %APPDATA%.

How can I disable that Virtual Store?

Thanks

EDIT: Just to be clear, I'm not asking how to circumvent the security and create my file in a protected location.  I want the file creation to FAIL so that I can tell the user he was an idiot.

答:
You add an application manifest. Choose asInvoker, highestAvailable, or requireAdministrator. It sounds like you want asInvoker.

From http://msdn.microsoft.com/en-us/library/bb756929.aspx:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="IsUserAdmin"
     type="win32"/>
  <description>Description of your application</description>
  <!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="asInvoker"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>
</code>```

Body:
You add an application manifest. Choose asInvoker, highestAvailable, or requireAdministrator. It sounds like you want asInvoker.

From http://msdn.microsoft.com/en-us/library/bb756929.aspx:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="IsUserAdmin"
     type="win32"/>
  <description>Description of your application</description>
  <!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="asInvoker"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>


问:
SQL Update on Duplicate key
In SQL Server, I have a table with just one primary key but I need to Insert or Update if a set of columns (non primary) exists.

I know about the composed keys - multiple keys on a table but I can not alter the table.

Is there a way to do it on a single query, maybe a variable of the on duplicate key functionality? or should be resolve on several queries?

For example:

Table_Name: Contacts

Columns:

```<code>id (int) PK
Name (vc30)
usrName (vc20)
Email (vc30)
Pass (vc15)
otherUsrData (...)
</code>```

The constraint should be (usrName,Email)

You can have the same usrName with different emails each or different usrName with the same email (I know that sounds illogic but it's just an example)

```<code>1 - usr1 - email_A@example.com - textA
2 - usr1 - email_B@example.com - textA
3 - usr2 - email_A@example.com - textA
4 - usr2 - email_B@example.com - textA
</code>```

So a new record is generated with usr2 and email email_C, I insert it on the table, because the combination (user2,email_C) doesn't exist.

But if it's usr2 with email_B, then I will update textA to textB because there exists a record with a combination (user2,email_B)

答:
You can create an unique index on the key column(s) with the IGNORE_DUP_KEY option set to on. This will result in the duplicate rows being ignored during the INSERT operation for instance. You will have to however update the rows by inserting into another table and then performing update

Use a worktable approach where you insert all the rows into the worktable and then use insert/update as into the main table.

Title: SQL Update on Duplicate key

Body:
In SQL Server, I have a table with just one primary key but I need to Insert or Update if a set of columns (non primary) exists.

I know about the composed keys - multiple keys on a table but I can not alter the table.

Is there a way to do it on a single query, maybe a variable of the on duplicate key functionality? or should be resolve on several queries?

For example:

Table_Name: Contacts

Columns:

id (int) PK
Name (vc30)
usrName (vc20)
Email (vc30)
Pass (vc15)
otherUsrData (...)

The constraint should be (usrName,Email)

You can have the same usrName with different emails each or different usrName with the same email (I know that sounds illogic but it's just an example)

1 - usr1 - email_A@example.com - textA
2 - usr1 - email_B@example.com - textA
3 - usr2 - email_A@example.com - textA
4 - usr2 - email_B@example.com - textA

So a new record is generated with usr2 and email email_C, I insert it on the table, because the combination (user2,email_C) doesn't exist.

But if it's usr2 with email_B, then I will update textA to textB because there exists a record with a combination (user2,email_B)


问:
Android 7 buttons are not showing in XML
I have a App with Login Layout So I have added 2 Buttons Save,Cancel

this is my XML Layout

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#303F9F"
        android:layout_alignParentTop="true"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="My App Login"
            android:id="@+id/ota"
            android:textColor="#FFF"
            android:textStyle="bold"
            android:layout_gravity="center_horizontal"/>
    </RelativeLayout>

    <ScrollView
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/footer"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_below="@id/header">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt5"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="@string/ui"
                android:textSize="14sp"
                android:layout_below="@+id/et3"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et4"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter User Name"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt5"
                android:inputType="text"/>

            <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt6"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="@string/pw"
                android:textSize="14sp"
                android:layout_below="@+id/et4"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et5"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter Password"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt6"
                android:inputType="textPassword"/>

            <Button android:id="@+id/save"
                android:layout_width="fill_parent"
                android:layout_height="0.0dip"
                android:layout_marginBottom="5.0dip"
                android:text="@string/save"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="@drawable/selector_btn"
                android:drawableLeft="@android:drawable/ic_menu_save"
                android:layout_weight="0.1"
                android:layout_marginTop="50dp"
                android:textColor="@color/text_white"/>

            <Button android:id="@+id/cancel"
                android:layout_width="fill_parent"
                android:layout_height="0.0dip"
                android:text="@string/cancel"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="@drawable/c_selector_btn"
                android:drawableLeft="@android:drawable/ic_menu_close_clear_cancel"
                android:layout_weight="0.1"
                android:textColor="@color/text_white"/>

        </LinearLayout>

    </ScrollView>

</RelativeLayout>
</code>```

Here its working fine for android 5,6 but in android 7 buttons are not showing in emulator,xml,Real Device

But its not working in android 7

its showing like this

can any one suggest me what I am missing for android 7 in android XML.. I am using same in android 5,6 its worked but its not showing in 7

答:
```<code><Button android:id="@+id/save"
                android:layout_width="match_parenr"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5.0dip"
                android:text="@string/save"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="@drawable/selector_btn"
                android:drawableLeft="@android:drawable/ic_menu_save"
                 android:layout_marginTop="50dp"
                android:textColor="@color/text_white"/>
</code>```

<p>You should give height of button to wrap_content </p>

Body:
I have a App with Login Layout So I have added 2 Buttons Save,Cancel

this is my XML Layout

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#303F9F"
        android:layout_alignParentTop="true"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="My App Login"
            android:id="@+id/ota"
            android:textColor="#FFF"
            android:textStyle="bold"
            android:layout_gravity="center_horizontal"/>
    </RelativeLayout>

    <ScrollView
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/footer"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_below="@id/header">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt5"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="@string/ui"
                android:textSize="14sp"
                android:layout_below="@+id/et3"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et4"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter User Name"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt5"
                android:inputType="text"/>

            <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt6"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="@string/pw"
                android:textSize="14sp"
                android:layout_below="@+id/et4"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et5"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter Password"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt6"
                android:inputType="textPassword"/>

            <Button android:id="@+id/save"
                android:layout_width="fill_parent"
                android:layout_height="0.0dip"
                android:layout_marginBottom="5.0dip"
                android:text="@string/save"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="@drawable/selector_btn"
                android:drawableLeft="@android:drawable/ic_menu_save"
                android:layout_weight="0.1"
                android:layout_marginTop="50dp"
                android:textColor="@color/text_white"/>

            <Button android:id="@+id/cancel"
                android:layout_width="fill_parent"
                android:layout_height="0.0dip"
                android:text="@string/cancel"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="@drawable/c_selector_btn"
                android:drawableLeft="@android:drawable/ic_menu_close_clear_cancel"
                android:layout_weight="0.1"
                android:textColor="@color/text_white"/>

        </LinearLayout>

    </ScrollView>

</RelativeLayout>

Here its working fine for android 5,6 but in android 7 buttons are not showing in emulator,xml,Real Device

But its not working in android 7

its showing like this

can any one suggest me what I am missing for android 7 in android XML.. I am using same in android 5,6 its worked but its not showing in 7

Body:
<Button android:id="@+id/save"
                android:layout_width="match_parenr"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5.0dip"
                android:text="@string/save"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="@drawable/selector_btn"
                android:drawableLeft="@android:drawable/ic_menu_save"
                 android:layout_marginTop="50dp"
                android:textColor="@color/text_white"/>

You should give height of button to wrap_content


问:
Make plot out of multiple plot.ly figures in Python
I've made 4 figures in plot.ly, for example:

```<code>import plotly.plotly as py
import plotly.graph_objs as go

trace1 = go.Scatter(
    x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    y=[8, 7, 6, 5, 4, 3, 2, 1, 0]
)
trace2 = go.Scatter(
    x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    y=[0, 1, 2, 3, 4, 5, 6, 7, 8]
)
data = [trace1, trace2]
fig1 = go.Figure(data=data, layout=layout)
fig2 = go.Figure(data=data, layout=layout)
fig3 = go.Figure(data=data, layout=layout)
fig4 = go.Figure(data=data, layout=layout)
</code>```

Now I want to make a subplot, and add each figure to a quadrant of it:

```<code>from plotly import tools
fig = tools.make_subplots(rows=2, cols=2)
</code>```

but I don't see any fig.append_fig() method, only an append_trace() method.  Is there no easy way to drop in a figure into a subplot in plot.ly?

答:
I think fig['data'] += data can help.

```<code>import plotly.plotly as py
import plotly.graph_objs as go

x1 = [0, 1, 2, 3, 4, 5, 6, 7, 8]
y1 = [8, 7, 6, 5, 4, 3, 2, 1, 0]
x2 = [0, 1, 2, 3, 4, 5, 6, 7, 8]
y2 = [0, 1, 2, 3, 4, 5, 6, 7, 8]

data1 = [go.Scatter(x=x1, y=y1), go.Scatter(x=x2, y=y2)]
data2 = [go.Scatter(x=x1, y=y1, xaxis='x2', yaxis='y2'), go.Scatter(x=x2, y=y2, xaxis='x2', yaxis='y2')]
data3 = [go.Scatter(x=x1, y=y1, xaxis='x3', yaxis='y3'), go.Scatter(x=x2, y=y2, xaxis='x3', yaxis='y3')]
data4 = [go.Scatter(x=x1, y=y1, xaxis='x4', yaxis='y4'), go.Scatter(x=x2, y=y2, xaxis='x4', yaxis='y4')]

from plotly import tools
fig = tools.make_subplots(rows=2, cols=2)
fig['data'] += data1
fig['data'] += data2
fig['data'] += data3
fig['data'] += data4
py.plot(fig, filename = 'basic-line')
</code>```

Body:
I've made 4 figures in plot.ly, for example:

import plotly.plotly as py
import plotly.graph_objs as go

trace1 = go.Scatter(
    x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    y=[8, 7, 6, 5, 4, 3, 2, 1, 0]
)
trace2 = go.Scatter(
    x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    y=[0, 1, 2, 3, 4, 5, 6, 7, 8]
)
data = [trace1, trace2]
fig1 = go.Figure(data=data, layout=layout)
fig2 = go.Figure(data=data, layout=layout)
fig3 = go.Figure(data=data, layout=layout)
fig4 = go.Figure(data=data, layout=layout)

Now I want to make a subplot, and add each figure to a quadrant of it:

from plotly import tools
fig = tools.make_subplots(rows=2, cols=2)

but I don't see any fig.append_fig() method, only an append_trace() method.  Is there no easy way to drop in a figure into a subplot in plot.ly?

Body:
I think fig['data'] += data can help.

import plotly.plotly as py
import plotly.graph_objs as go

x1 = [0, 1, 2, 3, 4, 5, 6, 7, 8]
y1 = [8, 7, 6, 5, 4, 3, 2, 1, 0]
x2 = [0, 1, 2, 3, 4, 5, 6, 7, 8]
y2 = [0, 1, 2, 3, 4, 5, 6, 7, 8]

data1 = [go.Scatter(x=x1, y=y1), go.Scatter(x=x2, y=y2)]
data2 = [go.Scatter(x=x1, y=y1, xaxis='x2', yaxis='y2'), go.Scatter(x=x2, y=y2, xaxis='x2', yaxis='y2')]
data3 = [go.Scatter(x=x1, y=y1, xaxis='x3', yaxis='y3'), go.Scatter(x=x2, y=y2, xaxis='x3', yaxis='y3')]
data4 = [go.Scatter(x=x1, y=y1, xaxis='x4', yaxis='y4'), go.Scatter(x=x2, y=y2, xaxis='x4', yaxis='y4')]

from plotly import tools
fig = tools.make_subplots(rows=2, cols=2)
fig['data'] += data1
fig['data'] += data2
fig['data'] += data3
fig['data'] += data4
py.plot(fig, filename = 'basic-line')


问:
How to call two tags at same time on active: to make changes in css
I'm having a little problem. As, I'm currently working on a left side menu, and am trying to call the two tags li and a at the same time on :active in css. I searched a lot but couldn't get anything working for me. What I want is to change the color of the whole row of li and a on :active (when the user clicks on the button).

Here is my code:

.sub-menu li,
a:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-list">
  <ul id="menu-content" class="menu-content collapse out">
    <li data-toggle="collapse" class="collapsed">
      <a><i class="<?=$MainObj['Icon'];?>" style="color:#9f9e9e !important"></i><?=$MainObj['GroupMenuName'];?> <span class="arrow" style="color:#9f9e9e !important">
    </span></a>
      <ul class="sub-menu collapse" id="a">
        <li>check1</li>
        <li>check2</li>
        <li>check3</li>
        <li>check4</li>
      </ul>
    </li>

    <li>

        <i class="fa fa-user fa-lg" style="color:#9f9e9e !important"></i> Profile

    </li>

    <li>

        <i class="fa fa-users fa-lg" style="color:#9f9e9e !important"></i> Users

    </li>
  </ul>
  <span class="collapse-expand" data-ember-action="" data-ember-action-1815="1815"></span>

</div></code>```

答:
hope this help.
**

a:hover #b

**
this make on hover #a, #b can change.
instead of hover use active as you want.
If this didn't work then try

a:hover + #b

or

a:hover ~ #b

this always work for me on latest version of chrome.

Body:
I'm having a little problem. As, I'm currently working on a left side menu, and am trying to call the two tags li and a at the same time on :active in css. I searched a lot but couldn't get anything working for me. What I want is to change the color of the whole row of li and a on :active (when the user clicks on the button).

Here is my code:

.sub-menu li,
a:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}

      <i class="<?=$MainObj['Icon'];?>" style="color:#9f9e9e !important"><?=$MainObj['GroupMenuName'];?>

check1

check2

check3

check4

         Profile

         Users


问:
Angular does not execute bindings, directive and ngOnInit when route change
In my application, I am facing problems with Angular not binding properties. It also does not call ngOnInit and ngAfterViewInit or execute directives.

Here is partial LoginComponent code:

```<code>@Component({
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit

//.....

    public test: string = 'some dummy test';

    constructor(
        private cd: ChangeDetectorRef,
        private fb: FormBuilder, private router: Router, private route: ActivatedRoute,
        private authService: AuthService,
        private usersService: UserService,
        private notificationsService: NotificationsService
    )
    {
        this.loginForm = fb.group({
            email: ["", Validators.required],
            password: ["", Validators.required]
        });
        console.info("constructor");
    }

    ngOnInit()
    {
        console.info("ngOnInit");
        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    ngAfterViewInit()
    {
        this.initGapi();
        console.info("afterviewinit");
    }
</code>```

Strange is that this works when I open page, or HMR refresh page, but not when I login and logout.

Here is the logout code:

```<code>logout(): boolean
{
    this.authService.logout();
}

//authservice.ts
logout()
{
    localStorage.removeItem("token");
    localStorage.removeItem("refresh_token");
    localStorage.removeItem("profile");

    if (gapi.auth2)
    {
        const instance = gapi.auth2.getAuthInstance();
        if (instance)
        {
            instance.signOut().then(() =>
            {
                this.router.navigate(["login"]);
            });
            return;
        }
    }
    this.router.navigate(["login"]);
}
</code>```

The differences when I logout and binding not occur are:

Button is not styled. This should do kendoButton directive <button class="center" kendoButton type="submit">

Binding to test (some dummy test) is missing

ngOnInit and ngAfterViewInit is not called.

There is no error in console. I also record screen (it starts with empty page). I have the latest Chrome and Firefox, and same problem is in both browsers.

Does anybody have any idea what is wrong or what else can I try?

答:
If gapi is running outside Angulars zone, then change detection doesn't get notified to run. You can run code explicitly inside Angulars zone like

```<code>constructor(private zone:NgZone) {}

...

  this.zone.run(() => {
    this.router.navigate(["login"])
  });
</code>```

Body:
In my application, I am facing problems with Angular not binding properties. It also does not call ngOnInit and ngAfterViewInit or execute directives.

Here is partial LoginComponent code:

@Component({
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit

//.....

    public test: string = 'some dummy test';

    constructor(
        private cd: ChangeDetectorRef,
        private fb: FormBuilder, private router: Router, private route: ActivatedRoute,
        private authService: AuthService,
        private usersService: UserService,
        private notificationsService: NotificationsService
    )
    {
        this.loginForm = fb.group({
            email: ["", Validators.required],
            password: ["", Validators.required]
        });
        console.info("constructor");
    }

    ngOnInit()
    {
        console.info("ngOnInit");
        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    ngAfterViewInit()
    {
        this.initGapi();
        console.info("afterviewinit");
    }

Strange is that this works when I open page, or HMR refresh page, but not when I login and logout.

Here is the logout code:

logout(): boolean
{
    this.authService.logout();
}

//authservice.ts
logout()
{
    localStorage.removeItem("token");
    localStorage.removeItem("refresh_token");
    localStorage.removeItem("profile");

    if (gapi.auth2)
    {
        const instance = gapi.auth2.getAuthInstance();
        if (instance)
        {
            instance.signOut().then(() =>
            {
                this.router.navigate(["login"]);
            });
            return;
        }
    }
    this.router.navigate(["login"]);
}

The differences when I logout and binding not occur are:

Button is not styled. This should do kendoButton directive <button class="center" kendoButton type="submit">

Binding to test (some dummy test) is missing

ngOnInit and ngAfterViewInit is not called.

There is no error in console. I also record screen (it starts with empty page). I have the latest Chrome and Firefox, and same problem is in both browsers.

Does anybody have any idea what is wrong or what else can I try?

Body:
If gapi is running outside Angulars zone, then change detection doesn't get notified to run. You can run code explicitly inside Angulars zone like

constructor(private zone:NgZone) {}

...

  this.zone.run(() => {
    this.router.navigate(["login"])
  });


问:
Alphabet and code ascii
I am trying to create a program in c language that gets a number and a string, for example the number is 3 and the string is "Zig".
The output should be alphabet's codes + the number. If the character's number goes more than "Z" (90) it should start from "A" again. Similarily, for lower case characters, when going beyond "z" start again from "a".
input  : "Zig"

number : 3

output : "Clj"

I have a problem with the part that it should start from A(for capitals) & a again.
this is my code now ! I have a problem with rotation part how to start from A or a again :)

```<code>char a[50];

int n,i;
printf("enter your number:\t");

scanf("%d",&n);
printf("enter your string:\t");

fflush(stdin);

gets(a);

while('A'<= a[i] <= 'Z'){
    if(a[i]+n > 'Z'){

    }
    else{
    a[i]=a[i]+n;
}
i++;
}
while('a' <= a[i] <= 'z'){
    if(a[i]+n > 'z'){

}
    else{
        a[i]=a[i]+n;
    }
    i++;
}
printf("string:\n");
puts(a);
</code>```

}

答:
Fixed Bug</p>

```<code>#include <stdio.h>
#include <strings.h>

int main(){
  char str [80];
  int number;

  printf ("Enter your string: ");
  scanf ("%79s",str);

  printf ("Enter your number: ");
  scanf ("%d",&number);

  for(int i= 0; i < strlen(str);i++){
    str[i]+=number;
    while(str[i]>'Z' && str[i] < 'a'){
        str[i] = 'A'+ str[i] - 'Z';
    }
    while(str[i]>'z'){
        str[i] = 'a'+ str[i] - 'z';
    }
  }

  printf("%s",str);

}
</code>```

Title: Alphabet and code ascii

Body:
I am trying to create a program in c language that gets a number and a string, for example the number is 3 and the string is "Zig".
The output should be alphabet's codes + the number. If the character's number goes more than "Z" (90) it should start from "A" again. Similarily, for lower case characters, when going beyond "z" start again from "a".
input  : "Zig"

number : 3

output : "Clj"

I have a problem with the part that it should start from A(for capitals) & a again.
this is my code now ! I have a problem with rotation part how to start from A or a again :)

char a[50];

int n,i;
printf("enter your number:\t");

scanf("%d",&n);
printf("enter your string:\t");

fflush(stdin);

gets(a);

while('A'<= a[i] <= 'Z'){
    if(a[i]+n > 'Z'){

    }
    else{
    a[i]=a[i]+n;
}
i++;
}
while('a' <= a[i] <= 'z'){
    if(a[i]+n > 'z'){

}
    else{
        a[i]=a[i]+n;
    }
    i++;
}
printf("string:\n");
puts(a);

}

Body:
Fixed Bug

#include <stdio.h>
#include <strings.h>

int main(){
  char str [80];
  int number;

  printf ("Enter your string: ");
  scanf ("%79s",str);

  printf ("Enter your number: ");
  scanf ("%d",&number);

  for(int i= 0; i < strlen(str);i++){
    str[i]+=number;
    while(str[i]>'Z' && str[i] < 'a'){
        str[i] = 'A'+ str[i] - 'Z';
    }
    while(str[i]>'z'){
        str[i] = 'a'+ str[i] - 'z';
    }
  }

  printf("%s",str);

}