问:
ASP.net MVC - Get currently logged user role in view
I know that there are a lot of topics about this issue but I already tried several solutions and cannot make it work.

So, I am trying to verify the currently logged user role in my view. As referred in the major part of topics about this in StackOverflow, I just have to do:

```<code>@User.IsInRole("Admin")
</code>```

Unfortunately this always returns false even with the "Role" column, in the AspNetUsers table, of the current logged user is populated with "Admin".

I also tried below approach but it says that "UserManager does not exist in current context".

```<code><p>@UserManager.GetRoles(userId)</p>
</code>```

One of my suspects is that I am not correctly setting the role for the user upon registration. My AspNetRoles table is correctly populated but AspNetUserRoles table is empty.

How can I troubleshoot this to find what is wrong with my application so I can use @User.IsInRole(...) instruction?

Thanks in advance for any help.

答:
Have you tried adding below at the top of the view page:

```<code>@using Microsoft.AspNet.Identity
</code>```

Alternatively:

```<code>@if(Roles.IsUserInRole(User.Identity.GetUserName(), "Admin"))
</code>```

Body:
I know that there are a lot of topics about this issue but I already tried several solutions and cannot make it work.

So, I am trying to verify the currently logged user role in my view. As referred in the major part of topics about this in StackOverflow, I just have to do:

@User.IsInRole("Admin")

Unfortunately this always returns false even with the "Role" column, in the AspNetUsers table, of the current logged user is populated with "Admin".

I also tried below approach but it says that "UserManager does not exist in current context".

@UserManager.GetRoles(userId)

One of my suspects is that I am not correctly setting the role for the user upon registration. My AspNetRoles table is correctly populated but AspNetUserRoles table is empty.

How can I troubleshoot this to find what is wrong with my application so I can use @User.IsInRole(...) instruction?

Thanks in advance for any help.

Body:
Have you tried adding below at the top of the view page:

@using Microsoft.AspNet.Identity

Alternatively:

@if(Roles.IsUserInRole(User.Identity.GetUserName(), "Admin"))


来源: stackexchange

问:
PHP include in JavaScript is not working
I've JavaScript and I want to run a include script in the JavaScript . I tried the following statement:

```<code>outputEl.innerHTML = '<?php include "./change/ud1.php";?>';
</code>```

When I run the script I get no response.

Does someone know why I didn't get any response and how I can fix it?

I tried to replace the PHP include with an html iframe. That worked but that is not the best solution for me.

答:
Simply Use

```<code><script type="text/javascript" src="filename.php"></script>
</code>```

Also pass this header("Content-type: text/javascript"); on top of the php file.

ContentLicense: CC BY-SA 3.0

Body:
I've JavaScript and I want to run a include script in the JavaScript . I tried the following statement:

outputEl.innerHTML = '<?php include "./change/ud1.php";?>';

When I run the script I get no response.

Does someone know why I didn't get any response and how I can fix it?

I tried to replace the PHP include with an html iframe. That worked but that is not the best solution for me.

Body:
Simply Use

<script type="text/javascript" src="filename.php"></script>

Also pass this header("Content-type: text/javascript"); on top of the php file.


问:
How to get the .config from a Linux kernel image?
I have a Linux kernel image in elf format and I want to find out what .config file was used to build this kernel. When I do an objdump of the image, I see a section called kernel_config_data that contains text but does not look like the config file. Is there a way to retrieve this information?

答:
You can zcat /proc/config.gz, for example:

```<code>zcat /proc/config.gz | grep 'CONFIG_PRINTK_TIME'
</code>```

To dump this into the .config used in the kernel build process:

```<code>zcat /proc/config.gz > .config
</code>```

Body:
You can zcat /proc/config.gz, for example:

zcat /proc/config.gz | grep 'CONFIG_PRINTK_TIME'

To dump this into the .config used in the kernel build process:

zcat /proc/config.gz > .config

ContentLicense: CC BY-SA 4.0


问:
NetworkStream Pooling
I have a multi-threaded application which communicates with a server over a TCP connection. The application would be deployed as a windows service.

The way it has been implemeted is, there is Controller which creates Communicator objects, assigns the port number, message count etc. properties to the Communicator and invokes its StartClient method to commence the dialog with the server.

Within the StartClient method, each Communicator object creates a connection to the server, using the port number and url specified by the Controller. After establishing the connection, it internally creates a thread and calls the ReadMessages method which keeps reading from the server till the message count is met and then gets closed down.

Based on the runtime conditions, there might be a need to reuse the Communicator object to talk with the server again and hence, the ReadMessages method woudl be called again.

Initially, we had been calling Dispose() method for the NetworkStream, StreamReader and StreamWriter objects when the ReadMessages method completed, but with the reconnecting scenario, it used to throw "Cannot access a disposed object" error. So, we commented out the Dispose method call for testing.

As of now, it works fine, but I am concerned that, this isnt the best way to achieve this functionlity as I am not disposing the objects ever.

I was thinking in terms of object pooling, If it is possible to have a pool of Stream objects which could be reused by different threads?

One way to tackle this can be to create a new instance of Stream objects each time the Communicator connects with the server, but I think that would be an expensive operation.

Can you please help me identify a better approach to handle the situation here so that I can reuse the Communicator object without a performance hit?

答: The approach will be based on how frequently you need to read messages - if its occasional the n, I would recommend that you re-factor your communicator object to make "ReadMessages" operation atomic - i.e. it would connect to the server, create network stream, read messages and then dispose every thing.</p>

ContentLicense: CC BY-SA 2.5

Title: NetworkStream Pooling


问:
add incremental value in xslt tag
```<code> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" />
  <soapenv:Body>
    <swiftResponseResponse xmlns="http://webservice.sbi.com">
      <swiftResponseReturn>15617TS006140|DC768736|13321.49|04-05-2017 15:13:03|SWIFTINR|NA|FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturn>
    </swiftResponseResponse>
  </soapenv:Body>
</soapenv:Envelope>
</code>```

and my xsl input is

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://webservice.sbi.com" exclude-result-prefixes="soapenv xsl  xsd xsi xs ">
  <!--<xsl:output method="xml" indent="yes"/>-->
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <!--<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>-->

  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:choose>
        <xsl:when test="not(contains($text, $separator))">
            <swiftResponseReturnValue>
                <xsl:value-of select="$text"/>
            </swiftResponseReturnValue>
        </xsl:when>
        <xsl:otherwise>
            <swiftResponseReturnValue>
                <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
            </swiftResponseReturnValue>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                <xsl:with-param name="separator" select="$separator"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
  <!--<xsl:template match="soapenv:Envelope/soapenv:Body/xs:swiftResponseResponse/xs:swiftResponseReturn">-->
   <xsl:template match="xs:swiftResponseReturn">
  <swiftResponseReturn>
     <xsl:call-template name="tokenize">
         <xsl:with-param name="text" select="."/>
         <xsl:with-param name="separator" select="'|'"/>
     </xsl:call-template>
  </swiftResponseReturn>
</xsl:template>
</xsl:stylesheet>
</code>```

my output is

```<code>     <swiftResponseReturn>
   <swiftResponseReturnValue>15617TS006140</swiftResponseReturnValue>
   <swiftResponseReturnValue>DC768736</swiftResponseReturnValue>
   <swiftResponseReturnValue>13321.49</swiftResponseReturnValue>
   <swiftResponseReturnValue>04-05-2017 15:13:03</swiftResponseReturnValue>
   <swiftResponseReturnValue>SWIFTINR</swiftResponseReturnValue>
   <swiftResponseReturnValue>NA</swiftResponseReturnValue>
   <swiftResponseReturnValue>FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue>
</swiftResponseReturn>
</code>```

i want my expected output should be like this

```<code>    <swiftResponseReturn>
   <swiftResponseReturnValue1>15617TS006140</swiftResponseReturnValue1>
   <swiftResponseReturnValue2>DC768736</swiftResponseReturnValue2>
   <swiftResponseReturnValue3>13321.49</swiftResponseReturnValue3>
   <swiftResponseReturnValue4>04-05-2017 15:13:03</swiftResponseReturnValue4>
   <swiftResponseReturnValue5>SWIFTINR</swiftResponseReturnValue5>
   <swiftResponseReturnValue6>NA</swiftResponseReturnValue6>
   <swiftResponseReturnValue7>FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue7>
</swiftResponseReturn>
</code>```

can help me to add ids in my tag or any other value that can uniquely identify my columns.please help been stuck here for while.

答:
Firstly, why would you want to do that? it makes processing the result more difficult. You should be using elementnames that describe what their content means.

That being said, you could add a third optional parameter to the tokenize template, fill it with 1 by default and add 1 to it on the recursive calls to tokenize. Then use that parameter to construct the tagname. something like:

<xsl:element name="'swiftResponseReturnValue'+$myThirdParameter">

```<code><xsl:template name="tokenize">
  <xsl:param name="text"/>
  <xsl:param name="separator" />
  <xsl:param name="index" select="1"/>
  <xsl:choose>
      <xsl:when test="not(contains($text, $separator))">
          <xsl:element name="'swiftResponseReturnValue'+$index">
              <xsl:value-of select="$text"/>
          <xsl:element>
      </xsl:when>
      <xsl:otherwise>
          <swiftResponseReturnValue pos="{$index}">
              <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
          </swiftResponseReturnValue>
          <xsl:call-template name="tokenize">
              <xsl:with-param name="text" select="substring-after($text, $separator)"/>
              <xsl:with-param name="separator" select="$separator"/>
              <xsl:with-param name="index" select="$index + 1"/>
          </xsl:call-template>
      </xsl:otherwise>
  </xsl:choose>
</xsl:template>
</code>```

Title: add incremental value in xslt tag

Body:
 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" />
  <soapenv:Body>
    <swiftResponseResponse xmlns="http://webservice.sbi.com">
      <swiftResponseReturn>15617TS006140|DC768736|13321.49|04-05-2017 15:13:03|SWIFTINR|NA|FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturn>
    </swiftResponseResponse>
  </soapenv:Body>
</soapenv:Envelope>

and my xsl input is

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://webservice.sbi.com" exclude-result-prefixes="soapenv xsl  xsd xsi xs ">

  <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:choose>
        <xsl:when test="not(contains($text, $separator))">
            <swiftResponseReturnValue>
                <xsl:value-of select="$text"/>
            </swiftResponseReturnValue>
        </xsl:when>
        <xsl:otherwise>
            <swiftResponseReturnValue>
                <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
            </swiftResponseReturnValue>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                <xsl:with-param name="separator" select="$separator"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

   <xsl:template match="xs:swiftResponseReturn">
  <swiftResponseReturn>
     <xsl:call-template name="tokenize">
         <xsl:with-param name="text" select="."/>
         <xsl:with-param name="separator" select="'|'"/>
     </xsl:call-template>
  </swiftResponseReturn>
</xsl:template>
</xsl:stylesheet>

my output is

     <swiftResponseReturn>
   <swiftResponseReturnValue>15617TS006140</swiftResponseReturnValue>
   <swiftResponseReturnValue>DC768736</swiftResponseReturnValue>
   <swiftResponseReturnValue>13321.49</swiftResponseReturnValue>
   <swiftResponseReturnValue>04-05-2017 15:13:03</swiftResponseReturnValue>
   <swiftResponseReturnValue>SWIFTINR</swiftResponseReturnValue>
   <swiftResponseReturnValue>NA</swiftResponseReturnValue>
   <swiftResponseReturnValue>FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue>
</swiftResponseReturn>

i want my expected output should be like this

    <swiftResponseReturn>
   <swiftResponseReturnValue1>15617TS006140</swiftResponseReturnValue1>
   <swiftResponseReturnValue2>DC768736</swiftResponseReturnValue2>
   <swiftResponseReturnValue3>13321.49</swiftResponseReturnValue3>
   <swiftResponseReturnValue4>04-05-2017 15:13:03</swiftResponseReturnValue4>
   <swiftResponseReturnValue5>SWIFTINR</swiftResponseReturnValue5>
   <swiftResponseReturnValue6>NA</swiftResponseReturnValue6>
   <swiftResponseReturnValue7>FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue7>
</swiftResponseReturn>

can help me to add ids in my tag or any other value that can uniquely identify my columns.please help been stuck here for while.

Body:
Firstly, why would you want to do that? it makes processing the result more difficult. You should be using elementnames that describe what their content means.

That being said, you could add a third optional parameter to the tokenize template, fill it with 1 by default and add 1 to it on the recursive calls to tokenize. Then use that parameter to construct the tagname. something like:

<xsl:element name="'swiftResponseReturnValue'+$myThirdParameter">

<xsl:template name="tokenize">
  <xsl:param name="text"/>
  <xsl:param name="separator" />
  <xsl:param name="index" select="1"/>
  <xsl:choose>
      <xsl:when test="not(contains($text, $separator))">
          <xsl:element name="'swiftResponseReturnValue'+$index">
              <xsl:value-of select="$text"/>
          <xsl:element>
      </xsl:when>
      <xsl:otherwise>
          <swiftResponseReturnValue pos="{$index}">
              <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
          </swiftResponseReturnValue>
          <xsl:call-template name="tokenize">
              <xsl:with-param name="text" select="substring-after($text, $separator)"/>
              <xsl:with-param name="separator" select="$separator"/>
              <xsl:with-param name="index" select="$index + 1"/>
          </xsl:call-template>
      </xsl:otherwise>
  </xsl:choose>
</xsl:template>


问:
CSS underline animation - Reading direction
I found a code to animate the underline of a link but I would like to be on the other direction, as we read (left to right) which is actually the opposite. Here is a JSFiddle

.sliding-u-l-r-l-inverse {
  display: inline-block;
  position: relative;
  padding-bottom: 3px;
}

.sliding-u-l-r-l-inverse:before {
  content: '';
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  transition: width 0s ease;
}

.sliding-u-l-r-l-inverse:after {
  content: '';
  display: block;
  position: absolute;
  right: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:before {
  width: 0%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:after {
  width: 0%;
  background: transparent;
  transition: width 0s ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sliding-u-l-r-l-inverse">
  I want it to slide on the other direction.
</div></code>```

答:
Change the value declaration of left and right.

i.e. .sliding-u-l-r-l-inverse:before consist of left:0 change that to right:0 and same in other pseudo selector :after right:0 to left:0. This changes the direction and makes line to start from left to right.

.sliding-u-l-r-l-inverse {
  display: inline-block;
  position: relative;
  padding-bottom: 3px;
}

.sliding-u-l-r-l-inverse:before {
  content: '';
  display: block;
  position: absolute;
  right: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  transition: width 0s ease;
}

.sliding-u-l-r-l-inverse:after {
  content: '';
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:before {
  width: 0%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:after {
  width: 0%;
  background: transparent;
  transition: width 0s ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sliding-u-l-r-l-inverse">
  I want it to slide on the other direction.
</div></code>```

Body:
I found a code to animate the underline of a link but I would like to be on the other direction, as we read (left to right) which is actually the opposite. Here is a JSFiddle

.sliding-u-l-r-l-inverse {
  display: inline-block;
  position: relative;
  padding-bottom: 3px;
}

.sliding-u-l-r-l-inverse:before {
  content: '';
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  transition: width 0s ease;
}

.sliding-u-l-r-l-inverse:after {
  content: '';
  display: block;
  position: absolute;
  right: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:before {
  width: 0%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:after {
  width: 0%;
  background: transparent;
  transition: width 0s ease;
}

  I want it to slide on the other direction.

Body:
Change the value declaration of left and right.

i.e. .sliding-u-l-r-l-inverse:before consist of left:0 change that to right:0 and same in other pseudo selector :after right:0 to left:0. This changes the direction and makes line to start from left to right.

.sliding-u-l-r-l-inverse {
  display: inline-block;
  position: relative;
  padding-bottom: 3px;
}

.sliding-u-l-r-l-inverse:before {
  content: '';
  display: block;
  position: absolute;
  right: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  transition: width 0s ease;
}

.sliding-u-l-r-l-inverse:after {
  content: '';
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:before {
  width: 0%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:after {
  width: 0%;
  background: transparent;
  transition: width 0s ease;
}

<div class="sliding-u-l-r-l-inverse">
  I want it to slide on the other direction.
</div>


问:
Error with $http.get in angularJS -- Success not a Function
Getting this error:

angular.min.js:122 TypeError: $http.get(...).success is not a function
      at getUserInfo (app.js:7)
      at new  (app.js:12)
      at Object.invoke (angular.min.js:43)
      at Q.instance (angular.min.js:93)
      at p (angular.min.js:68)
      at g (angular.min.js:60)
      at g (angular.min.js:61)
      at g (angular.min.js:61)
      at angular.min.js:60
      at angular.min.js:21

Here is my code:

```<code>var gitHub = angular.module('gitHub', []);

gitHub.controller('mainController', ['$scope', '$http', function($scope, $http) {

    var $scope.user = '';
    function getUserInfo($scope, $http){
        $http.get('https://api.github.com/users')
            .success(function (result) {
                $scope.user = result;
                console.log(result);
            });
    };
    getUserInfo($scope, $http);
}]);
</code>```

and here is the html

```<code><!DOCTYPE html>
<html ng-app="gitHub">
<head>
    <title>Github Users Directory</title>
    <script src="angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body>
    <div ng-controller="mainController">
        <div>
            <h1>GitHub Users</h1>
            Who do you want to search for?<input type="text" name="FindHim" ng-model="queryName" />
            <button ng-click="getUserInfo()">Search</button>
        </div>
        <div>
            {{ user }}
        </div>

    </div>
</body>
</html>
</code>```

答:
```<code>$http({
    method: 'GET',
    url: '....',
    headers: {
        'Authorization': 'Bearer ' + localStorage["token"]
    }
})
.then(function (data, status, headers, config) {
     alert(JSON.stringify(data) + "Status" + status);
})
.error(function (data, status, headers, config) {
     alert(JSON.stringify(data) + "Status" + status);
});
</code>```

Body:
Getting this error:

angular.min.js:122 TypeError: $http.get(...).success is not a function
      at getUserInfo (app.js:7)
      at new  (app.js:12)
      at Object.invoke (angular.min.js:43)
      at Q.instance (angular.min.js:93)
      at p (angular.min.js:68)
      at g (angular.min.js:60)
      at g (angular.min.js:61)
      at g (angular.min.js:61)
      at angular.min.js:60
      at angular.min.js:21

Here is my code:

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

gitHub.controller('mainController', ['$scope', '$http', function($scope, $http) {

    var $scope.user = '';
    function getUserInfo($scope, $http){
        $http.get('https://api.github.com/users')
            .success(function (result) {
                $scope.user = result;
                console.log(result);
            });
    };
    getUserInfo($scope, $http);
}]);

and here is the html

<!DOCTYPE html>

    <title>Github Users Directory</title>

GitHub Users

            Who do you want to search for?<input type="text" name="FindHim" ng-model="queryName" />
            <button ng-click="getUserInfo()">Search</button>

            {{ user }}


问:
std::atomic bool or Normal global bool is good in single thread?
I have global vaiable in a below thread (bool allow) which  restrict client to wait (by assign allow=false) till it is completed. After completed allow =true

```<code>bool allow =true;
static void * mythread(void *arg)
{

/* here is  Lock mutex code */

 allow =false;(**non atomic**)

 system(command);

  allow =true;

/* here is Unlock Mutex code */

}

if(allow)
{

// validate thread output

}

else
{
// wait
}
</code>```

My concern is should i use std::atomic for the global varibale or its good as bove

```<code>std::atomic<bool>allow(true);

static void * mythread(void *arg)
{

 /* here is  Lock mutex code */

allow.store(false, std::memory_order_seq_cst);

 system(command);

allow.store(true, std::memory_order_seq_cst);

/* here is Unlock Mutex code */

}

if(allow)
{

// validate thread output

}

else
{
// wait
}
</code>```

答:
If all access to the boolean is protected by a mutex, then it does not matter either way (in terms of correctness).  Use the atomic<> or don't.  The correctness of your code will not suffer.

But the performance might suffer, other than the fact that you are locking access to something that already has a mutex protecting it, std::atomic<> has the potential to use a mutex under the hood itself.    std::atomic_flag however, is guaranteed to be lock-free.  See the cppreference documentation for more.

If you have a single thread accessing that boolean, then no point having any synchronization at all.

Body:
I have global vaiable in a below thread (bool allow) which  restrict client to wait (by assign allow=false) till it is completed. After completed allow =true

bool allow =true;
static void * mythread(void *arg)
{

/* here is  Lock mutex code */

 allow =false;(**non atomic**)

 system(command);

  allow =true;

/* here is Unlock Mutex code */

}

if(allow)
{

// validate thread output

}

else
{
// wait
}

My concern is should i use std::atomic for the global varibale or its good as bove

std::atomic<bool>allow(true);

static void * mythread(void *arg)
{

 /* here is  Lock mutex code */

allow.store(false, std::memory_order_seq_cst);

 system(command);

allow.store(true, std::memory_order_seq_cst);

/* here is Unlock Mutex code */

}

if(allow)
{

// validate thread output

}

else
{
// wait
}


问:
Why Chrome shows the listeners count is smaller than actual it has?
I have code like this:

```<code>function ManyNodes() {
  const nums = new Array(1e5).fill(0).map(_ => Math.floor(Math.random()*1e8));
  return (
  <ul>{nums.map(n => <li key={n} onClick={e=>console.log(n)}>{n}</li>)}</ul>
  )
}

render(<ManyNodes />, document.querySelector('#app'))
</code>```

Then it should 1e5 li in the document and every li has its own click listeners. So there should be more than 1e5 listeners on the page.

But I use Chrome Web Developer Tool, and in its Performance tab, you can see just hundreds of listeners. That's strange.

How react handle this?

答:
TL;DR Event Delegation and Event Pooling

Event Delegation

Attaching event listeners to DOM nodes is painfully slow and
  memory-consuming. Instead, React implements a popular technique called
  "event delegation".

What is Event Delegation?

A single event listener is attached to the root of the document. When
  an event is fired, the browser gives us the target DOM node [...]

For you information, Vjeux is a Facebook Software Engineer in the Front-end team working on React Native.

http://blog.vjeux.com/2013/javascript/react-performance.html (check Event Delegation section)

Event pooling

The SyntheticEvent is pooled. This means that the SyntheticEvent
  object will be reused and all properties will be nullified after the
  event callback has been invoked. This is for performance reasons. As
  such, you cannot access the event in an asynchronous way.

https://facebook.github.io/react/docs/events.html

Body:
I have code like this:

function ManyNodes() {
  const nums = new Array(1e5).fill(0).map(_ => Math.floor(Math.random()*1e8));
  return (

{nums.map(n =>
console.log(n)}>{n}
)}

  )
}

render(<ManyNodes />, document.querySelector('#app'))

Then it should 1e5 li in the document and every li has its own click listeners. So there should be more than 1e5 listeners on the page.

But I use Chrome Web Developer Tool, and in its Performance tab, you can see just hundreds of listeners. That's strange.

How react handle this?


问:
how to render
 to a new line in django template?
I am trying to render a message in a template using django.
I used this code:

```<code>message = "hello <br /> how are you? "
t = loader.get_template(template_html)
context = {"message":message}
return t.render(context)
</code>```

The problem is that:

```<code> I get hello <br /> how are you?
</code>```

in the template instead of a new line,
how can I fix this?

答:
You can either apply the safe filter in the template or mark message as safe in the view:

```<code># template
{{ message|safe }}
</code>```

or

```<code># view
from django.utils.safestring import mark_safe
context = {"message": mark_safe(message)}
</code>```

This will then render your message as html.

Title: how to render <br /> to a new line in django template?

Body:
I am trying to render a message in a template using django.
I used this code:

message = "hello
 how are you? "
t = loader.get_template(template_html)
context = {"message":message}
return t.render(context)

The problem is that:

 I get hello
 how are you?

in the template instead of a new line,
how can I fix this?

Body:
You can either apply the safe filter in the template or mark message as safe in the view:

# template
{{ message|safe }}

or

# view
from django.utils.safestring import mark_safe
context = {"message": mark_safe(message)}

This will then render your message as html.


问:
Equivalent of Index options (using index) in Oracle to SQL Server 2014
I need to move the data from Oracle database to MS SQL Server 2014.
But I got the problem with this "USING INDEX" statement which help me in oracle to add some constraint. I would like to know if someone could provide me and equivalence of "USING INDEX" in Sql Server.</p>

```<code>CONSTRAINT "MESSAGE_LOG_RECORD_PK" PRIMARY KEY ("RECORD_NO")
**USING INDEX** PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1   BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)   TABLESPACE "DATA"  ENABLE,
</code>```

答:
To add a Primary Key constraint backed by a BTree index to a Heap, and store its backing index on a particular filegroup, something like:

```<code>CREATE TABLE MESSAGE_LOG
(
  RECORD_NO INT NOT NULL,
  OTHER_COLUMN INT NOT NULL,
  --. . .
  CONSTRAINT MESSAGE_LOG_RECORD_PK PRIMARY KEY NONCLUSTERED (RECORD_NO) ON DATA
)
</code>```

Although in SQL Server we typically use Clustered Index tables instead of heaps, just leave of NONCLUSTERED, as CLUSTERED is the default for Primary Key constraints.  Also each database has its own filegroups, so you don't often place tables or indexes directly on non-default filegroups.  So typically in SQL Server you would just have:

```<code>CREATE TABLE MESSAGE_LOG
(
  RECORD_NO INT NOT NULL,
  OTHER_COLUMN INT NOT NULL,
  --. . .
  CONSTRAINT MESSAGE_LOG_RECORD_PK PRIMARY KEY (RECORD_NO)
)
</code>```

Body:
I need to move the data from Oracle database to MS SQL Server 2014.
But I got the problem with this "USING INDEX" statement which help me in oracle to add some constraint. I would like to know if someone could provide me and equivalence of "USING INDEX" in Sql Server.

CONSTRAINT "MESSAGE_LOG_RECORD_PK" PRIMARY KEY ("RECORD_NO")
**USING INDEX** PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1   BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)   TABLESPACE "DATA"  ENABLE,

Body:
To add a Primary Key constraint backed by a BTree index to a Heap, and store its backing index on a particular filegroup, something like:

CREATE TABLE MESSAGE_LOG
(
  RECORD_NO INT NOT NULL,
  OTHER_COLUMN INT NOT NULL,
  --. . .
  CONSTRAINT MESSAGE_LOG_RECORD_PK PRIMARY KEY NONCLUSTERED (RECORD_NO) ON DATA
)

Although in SQL Server we typically use Clustered Index tables instead of heaps, just leave of NONCLUSTERED, as CLUSTERED is the default for Primary Key constraints.  Also each database has its own filegroups, so you don't often place tables or indexes directly on non-default filegroups.  So typically in SQL Server you would just have:

CREATE TABLE MESSAGE_LOG
(
  RECORD_NO INT NOT NULL,
  OTHER_COLUMN INT NOT NULL,
  --. . .
  CONSTRAINT MESSAGE_LOG_RECORD_PK PRIMARY KEY (RECORD_NO)
)


问:
How to display particular records first in a for reach loop in xsl
I have requirement to display particular string records first , for example here i want to display all Rehman records first then all others in no particular order.

XML

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
  <cd>
    <title>Roja</title>
    <artist>Rehman</artist>
    <country>USA</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
  <cd>
    <title>Still got the blues</title>
    <artist>Gary Moore</artist>
    <country>UK</country>
    <company>Virgin records</company>
    <price>10.20</price>
    <year>1990</year>
  </cd>
  <cd>
    <title>Eros</title>
    <artist>Zack</artist>
    <country>EU</country>
    <company>BMG</company>
    <price>9.90</price>
    <year>1997</year>
  </cd>
  <cd>
    <title>Rockstar</title>
    <artist>Rehman</artist>
    <country>UK</country>
    <company>Polydor</company>
    <price>10.90</price>
    <year>1998</year>
  </cd>
  <cd>
    <title>Sylvias Mother</title>
    <artist>Dr.Hook</artist>
    <country>UK</country>
    <company>CBS</company>
    <price>8.10</price>
    <year>1973</year>
  </cd>

</catalog>
</code>```

XSL

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for-each select="catalog/cd">
      <xsl:sort select="artist" order ="descending"/>
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="artist"/></td>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>
</code>```

Result

My CD Collection

Title Artist

```<code>Empire Burlesque    Bob Dylan
Hide your heart Bonnie Tyler
Sylvias Mother  Dr.Hook
Still got the blues Gary Moore
Roja    Rehman
Rockstar    Rehman
Eros    Zack
</code>```

答:
You can use this

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">
        <html>
            <body>
                <h2>My CD Collection</h2>
                <table border="1">
                    <tr bgcolor="#9acd32">
                        <th>Title</th>
                        <th>Artist</th>
                    </tr>
                    <xsl:for-each select="catalog/cd[artist='Rehman']">
                        <xsl:sort select="artist" order ="descending"/>
                        <tr>
                            <td><xsl:value-of select="title"/></td>
                            <td><xsl:value-of select="artist"/></td>
                        </tr>
                    </xsl:for-each>
                    <xsl:for-each select="catalog/cd[artist!='Rehman']">
                       <!-- You can use this for sorting of rest -->
                       <!-- <xsl:sort select="artist" order ="descending"/> -->
                        <tr>
                            <td><xsl:value-of select="title"/></td>
                            <td><xsl:value-of select="artist"/></td>
                        </tr>
                    </xsl:for-each>

                </table>
            </body>
        </html>
    </xsl:template>

</xsl:stylesheet>
</code>```

Body:
I have requirement to display particular string records first , for example here i want to display all Rehman records first then all others in no particular order.

XML

    <?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
  <cd>
    <title>Roja</title>
    <artist>Rehman</artist>
    <country>USA</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
  <cd>
    <title>Still got the blues</title>
    <artist>Gary Moore</artist>
    <country>UK</country>
    <company>Virgin records</company>
    <price>10.20</price>
    <year>1990</year>
  </cd>
  <cd>
    <title>Eros</title>
    <artist>Zack</artist>
    <country>EU</country>
    <company>BMG</company>
    <price>9.90</price>
    <year>1997</year>
  </cd>
  <cd>
    <title>Rockstar</title>
    <artist>Rehman</artist>
    <country>UK</country>
    <company>Polydor</company>
    <price>10.90</price>
    <year>1998</year>
  </cd>
  <cd>
    <title>Sylvias Mother</title>
    <artist>Dr.Hook</artist>
    <country>UK</country>
    <company>CBS</company>
    <price>8.10</price>
    <year>1973</year>
  </cd>

</catalog>

XSL

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

My CD Collection

        Title
        Artist

      <xsl:for-each select="catalog/cd">
      <xsl:sort select="artist" order ="descending"/>

        <xsl:value-of select="title"/>
        <xsl:value-of select="artist"/>

      </xsl:for-each>

</xsl:template>

</xsl:stylesheet>

Result

My CD Collection

Title Artist

Empire Burlesque    Bob Dylan
Hide your heart Bonnie Tyler
Sylvias Mother  Dr.Hook
Still got the blues Gary Moore
Roja    Rehman
Rockstar    Rehman
Eros    Zack

Body:
You can use this

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">
        <html>
            <body>
                <h2>My CD Collection</h2>
                <table border="1">
                    <tr bgcolor="#9acd32">
                        <th>Title</th>
                        <th>Artist</th>
                    </tr>
                    <xsl:for-each select="catalog/cd[artist='Rehman']">
                        <xsl:sort select="artist" order ="descending"/>
                        <tr>
                            <td><xsl:value-of select="title"/></td>
                            <td><xsl:value-of select="artist"/></td>
                        </tr>
                    </xsl:for-each>
                    <xsl:for-each select="catalog/cd[artist!='Rehman']">
                       <!-- You can use this for sorting of rest -->
                       <!-- <xsl:sort select="artist" order ="descending"/> -->
                        <tr>
                            <td><xsl:value-of select="title"/></td>
                            <td><xsl:value-of select="artist"/></td>
                        </tr>
                    </xsl:for-each>

                </table>
            </body>
        </html>
    </xsl:template>

</xsl:stylesheet>


问:
Change Password Validation Rules in Aspnet Boilerplate
I want to set my own Password Validation in ASP.NET Boilerplate for the UserManager. I write a custom PasswordValidator class which derived from IPasswordValidator<User> interface and registered that within the Startup.cs: services.AddPasswordValidator<PasswordValidator>()

Now the problem is, that my own Password Validation is active and the default validation of Boilerplate. How can I disable the default password validation?

答:
Create your own PasswordValidator and set it to PasswordValidator property of UserManager in it's constructor. If you create your own PasswordValidator, you can derive from Microsoft.AspNet.Identity.PasswordValidator which already makes many checks. Override ValidateAsync method and add your own logic.

See the issue on github

See aspnet identity custom password policy


问:
How to recursively change the owner and group on a directory with Chef?
the resource_directory has only 2 actions available: create and delete

I need to update the owner and group of a directory recursively.

How do I do that?

using a simple resource_execute?

```<code>execute "chown-data-www" do
  command "chown -R www-data:www-data /var/www/myfoler"
  user "root"
  action :run
end
</code>```

答:
I would use plain resource directory with action :create.
Per documentation:

```<code>:create
Default. Create a directory. If a directory already exists (but does not match), update that directory to match
</code>```

https://docs.chef.io/resource_directory.html

Body:
the resource_directory has only 2 actions available: create and delete

I need to update the owner and group of a directory recursively.

How do I do that?

using a simple resource_execute?

execute "chown-data-www" do
  command "chown -R www-data:www-data /var/www/myfoler"
  user "root"
  action :run
end

Body:
I would use plain resource directory with action :create.
Per documentation:

:create
Default. Create a directory. If a directory already exists (but does not match), update that directory to match

https://docs.chef.io/resource_directory.html


问:
What data structure should I use to store a collection of items in C#?
I have following string : [Value:"Car" - Name:"Manufactor" [Value:"Audi" - Name:"A6"][Value:"BMW" - Name:"M4"]]]

I need to split the string and save data into suitable data structure. Starting bracket "[" indicates the beginning of the collection, and
matching ending bracket "]" indicates the end of the collection. The "-" character seperates key and values. So I was wondering what is most
logical datastructure to use here? Is using a tree good solution? I have splitted the string up in parts, I only need help to choose a logical datastructure.

Thanks!

答: It looks like a sort of tree, or possibly nested dictionaries if there are other types than Car. Or a simple dictionary, like; Dictionary<Manufacturer, List<CarModels>>


问:
Fastest way to initialize a value for ConcurrentHashMap
ConcurrentHashMap is often used in concurrent environments for aggregation of some events under a key - like counting hits for some string values. In case we don't know the keys in advance we need to have a good way to initialize key on need, it should to be fast and safe in terms of concurrency.
What is the best pattern (in terms of efficiency) for this problem?

I will use a model map with <String, AtomicInteger> declared like:

```<code>ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<>();
</code>```

But it could be a map with any key-value pair, where we need to initialize a key-value pair if the key does not already exists in the map and mutate the state of value to record event.

There are two popular approaches:
The first one uses ConcurrentHashMap.putIfAbsent:

```<code>AtomicInteger count = map.get(s);
if (count == null) {
    count = new AtomicInteger(0);
    AtomicInteger prevCount = map.putIfAbsent(s, count);
    if (prevCount != null) {
        count = prevCount;
    }
}
count.incrementAndGet();
</code>```

The second one uses ConcurrentHashMap.computeIfAbsent:

```<code>AtomicInteger count = map.computeIfAbsent(s, (k) -> new AtomicInteger(0));
count.incrementAndGet();
</code>```

Which one is better suited for this task? Are there other approaches?

答:
Unfortunatelly up to jdk1.8.0_131, the computeIfAbsent always go into the synchronized block, regardles if the key is already there or not, which makes it way slower than the putIfAbsent.

This benchmark confirms this, it appears that depending on contention level putIfAbsent is from 2 to 50 times faster than computeIfAbsent.

```<code>import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class ConcurrentHashMapTest {
    private final static int numberOfRuns = 1000000;
    private final static int numberOfThreads = Runtime.getRuntime().availableProcessors();
    private final static int keysSize = 10;
    private final static String[] strings = new String[keysSize];
    static {
        for (int n = 0; n < keysSize; n++) {
            strings[n] = "" + (char) ('A' + n);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int n = 0; n < 20; n++) {
            testPutIfAbsent();
            testComputeIfAbsentLambda();
        }
    }

    private static void testPutIfAbsent() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
        final Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);

        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        String s = strings[random.nextInt(strings.length)];
                        start = System.nanoTime();

                        AtomicInteger count = map.get(s);
                        if (count == null) {
                            count = new AtomicInteger(0);
                            AtomicInteger prevCount = map.putIfAbsent(s, count);
                            if (prevCount != null) {
                                count = prevCount;
                            }
                        }
                        count.incrementAndGet();
                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

    private static void testComputeIfAbsentLambda() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
        final Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        String s = strings[random.nextInt(strings.length)];
                        start = System.nanoTime();

                        AtomicInteger count = map.computeIfAbsent(s, (k) -> new AtomicInteger(0));
                        count.incrementAndGet();

                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

}
</code>```

the output:

```<code>Test testPutIfAbsent average time per run: 115.756501 ns
Test testComputeIfAbsentLambda average time per run: 276.9667055 ns
Test testPutIfAbsent average time per run: 134.2332435 ns
Test testComputeIfAbsentLambda average time per run: 223.222063625 ns
Test testPutIfAbsent average time per run: 119.968893625 ns
Test testComputeIfAbsentLambda average time per run: 216.707419875 ns
Test testPutIfAbsent average time per run: 116.173902375 ns
Test testComputeIfAbsentLambda average time per run: 215.632467375 ns
Test testPutIfAbsent average time per run: 112.21422775 ns
Test testComputeIfAbsentLambda average time per run: 210.29563725 ns
Test testPutIfAbsent average time per run: 120.50643475 ns
Test testComputeIfAbsentLambda average time per run: 200.79536475 ns
</code>```

We can use the putIfAbsent approach to create faster computeIfAbsent.
The only difference would be that this new computeIfAbsent could call the initialization function more than once in case of concurrent initialization of the same key. The benchmark results are identical as with the 'putIfAbsent', since it is the same code, it is not a big surprise, but in case anyone would like to test this, here is the benchmark:

```<code>import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;

public class CocnurrentHashMap2Benchmark {
    private final static int numberOfRuns = 1000000;
    private final static int numberOfThreads = Runtime.getRuntime().availableProcessors();
    private final static int keysSize = 10;
    private final static String[] strings = new String[keysSize];
    static {
        for (int n = 0; n < keysSize; n++) {
            strings[n] = "" + (char) ('A' + n);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int n = 0; n < 20; n++) {
            testPutIfAbsent();
            testComputeIfAbsent2Lambda();
        }
    }

    private static void testPutIfAbsent() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
        final Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);

        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        String s = strings[random.nextInt(strings.length)];
                        start = System.nanoTime();

                        AtomicInteger count = map.get(s);
                        if (count == null) {
                            count = new AtomicInteger(0);
                            AtomicInteger prevCount = map.putIfAbsent(s, count);
                            if (prevCount != null) {
                                count = prevCount;
                            }
                        }
                        count.incrementAndGet();
                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

     private static void testComputeIfAbsent2Lambda() throws InterruptedException {
            final AtomicLong totalTime = new AtomicLong();
            final ConcurrentHashMap2<String, AtomicInteger> map = new ConcurrentHashMap2<String, AtomicInteger>();
            final Random random = new Random();
            ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
            for (int i = 0; i < numberOfThreads; i++) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        long start, end;
                        for (int n = 0; n < numberOfRuns; n++) {
                            String s = strings[random.nextInt(strings.length)];
                            start = System.nanoTime();

                            AtomicInteger count = map.computeIfAbsent2(s, (k) -> new AtomicInteger(0));
                            count.incrementAndGet();

                            end = System.nanoTime();
                            totalTime.addAndGet(end - start);
                        }
                    }
                });
            }
            executorService.shutdown();
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
            System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                    + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
        }

        public static class ConcurrentHashMap2<K,V> extends ConcurrentHashMap<K,V> {

            /**
             * If there is no mapping for the key then computes and puts the mapping,
             * otherwise it simply return the value for that key.
             * In case of concurrent initialization of the same key the mappingFunction can be called more than once.
             * @param key - the key to be initialized or retrieved
             * @param mappingFunction - the function to be called for computation of initial value.
             * @return computed value if the key wasn't already in the map otherwise return the actual value for provided key.
             */
            public V computeIfAbsent2(K key, Function<K,V> mappingFunction) {
                V value = get(key);
                if (value == null) {
                    value = mappingFunction.apply(key);
                    V prevValue = putIfAbsent(key, value);
                    if (prevValue != null) {
                        value = prevValue;
                    }
                }
                return value;
            }
        }
}
</code>```

the results:

```<code>Test testComputeIfAbsent2Lambda average time per run: 138.1053415 ns
Test testPutIfAbsent average time per run: 129.45236425 ns
Test testComputeIfAbsent2Lambda average time per run: 128.48006825 ns
Test testPutIfAbsent average time per run: 118.733798375 ns
Test testComputeIfAbsent2Lambda average time per run: 134.038046625 ns
Test testPutIfAbsent average time per run: 119.7947695 ns
Test testComputeIfAbsent2Lambda average time per run: 134.183876375 ns
Test testPutIfAbsent average time per run: 137.969932625 ns
Test testComputeIfAbsent2Lambda average time per run: 137.97531275 ns
Test testPutIfAbsent average time per run: 136.904379125 ns
Test testComputeIfAbsent2Lambda average time per run: 148.899750125 ns
Test testPutIfAbsent average time per run: 129.788293125 ns
Test testComputeIfAbsent2Lambda average time per run: 141.50586625 ns
Test testPutIfAbsent average time per run: 129.081558875 ns
Test testComputeIfAbsent2Lambda average time per run: 122.36628625 ns
Test testPutIfAbsent average time per run: 127.1215535 ns
Test testComputeIfAbsent2Lambda average time per run: 108.129917625 ns
Test testPutIfAbsent average time per run: 133.630786875 ns
Test testComputeIfAbsent2Lambda average time per run: 134.978805625 ns
Test testPutIfAbsent average time per run: 132.7747585 ns
Test testComputeIfAbsent2Lambda average time per run: 132.4352885 ns
Test testPutIfAbsent average time per run: 133.753792875 ns
Test testComputeIfAbsent2Lambda average time per run: 134.09569175 ns
Test testPutIfAbsent average time per run: 145.610141125 ns
Test testComputeIfAbsent2Lambda average time per run: 139.437622125 ns
</code>```

If we compare the speed of putting mapping into the map when the key doesn't already exists it appears that the new 'computeIfAbsent2' is also much faster. The benchmark:

```<code>import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;

public class CocnurrentHashMap2PutBenchmark {
    private final static int numberOfRuns = 1000000;
    private final static int numberOfThreads = Runtime.getRuntime().availableProcessors();

    public static void main(String[] args) throws InterruptedException {
        for (int n = 0; n < 20; n++) {
            testComputeIfAbsent2();
            testComputeIfAbsent();
        }
    }

    private static void testComputeIfAbsent2() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap2<Integer, String> map = new ConcurrentHashMap2<Integer, String>();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        Integer key = Integer.valueOf(n);
                        start = System.nanoTime();

                        String value = map.computeIfAbsent2(key, (k) -> "value");

                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

    private static void testComputeIfAbsent() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<Integer, String>();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        Integer key = Integer.valueOf(n);
                        start = System.nanoTime();

                        String value = map.computeIfAbsent(key, (k) -> "value");

                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

    public static class ConcurrentHashMap2<K, V> extends ConcurrentHashMap<K, V> {

        /**
         * If there is no mapping for the key then computes and puts the
         * mapping, otherwise it simply return the value for that key. In case
         * of concurrent initialization of the same key the mappingFunction can
         * be called more than once.
         *
         * @param key
         *            - the key to be initialized or retrieved
         * @param mappingFunction
         *            - the function to be called for computation of initial
         *            value.
         * @return computed value if the key wasn't already in the map otherwise
         *         return the actual value for provided key.
         */
        public V computeIfAbsent2(K key, Function<K, V> mappingFunction) {
            V value = get(key);
            if (value == null) {
                value = mappingFunction.apply(key);
                V prevValue = putIfAbsent(key, value);
                if (prevValue != null) {
                    value = prevValue;
                }
            }
            return value;
        }
    }
}
</code>```

the results:

```<code>Test testComputeIfAbsent2 average time per run: 445.077932375 ns
Test testComputeIfAbsent average time per run: 784.786391 ns
Test testComputeIfAbsent2 average time per run: 294.10136375 ns
Test testComputeIfAbsent average time per run: 314.8724765 ns
Test testComputeIfAbsent2 average time per run: 236.56533275 ns
Test testComputeIfAbsent average time per run: 350.863664625 ns
Test testComputeIfAbsent2 average time per run: 346.19498275 ns
Test testComputeIfAbsent average time per run: 641.995172625 ns
Test testComputeIfAbsent2 average time per run: 255.441646125 ns
Test testComputeIfAbsent average time per run: 326.399150125 ns
Test testComputeIfAbsent2 average time per run: 275.626666125 ns
Test testComputeIfAbsent average time per run: 201.207314125 ns
Test testComputeIfAbsent2 average time per run: 289.19059725 ns
Test testComputeIfAbsent average time per run: 318.448059 ns
Test testComputeIfAbsent2 average time per run: 225.19701825 ns
Test testComputeIfAbsent average time per run: 306.461814125 ns
Test testComputeIfAbsent2 average time per run: 213.460366 ns
Test testComputeIfAbsent average time per run: 334.325044625 ns
Test testComputeIfAbsent2 average time per run: 256.4048955 ns
Test testComputeIfAbsent average time per run: 256.366700625 ns
Test testComputeIfAbsent2 average time per run: 231.88875575 ns
Test testComputeIfAbsent average time per run: 246.076624 ns
Test testComputeIfAbsent2 average time per run: 222.4649485 ns
Test testComputeIfAbsent average time per run: 266.505719625 ns
Test testComputeIfAbsent2 average time per run: 228.708391375 ns
Test testComputeIfAbsent average time per run: 261.866442625 ns
Test testComputeIfAbsent2 average time per run: 198.614718875 ns
Test testComputeIfAbsent average time per run: 225.43031925 ns
Test testComputeIfAbsent2 average time per run: 300.478359 ns
Test testComputeIfAbsent average time per run: 306.03640225 ns
Test testComputeIfAbsent2 average time per run: 195.0444215 ns
Test testComputeIfAbsent average time per run: 271.461982625 ns
Test testComputeIfAbsent2 average time per run: 224.306529875 ns
Test testComputeIfAbsent average time per run: 334.52790425 ns
Test testComputeIfAbsent2 average time per run: 212.217131625 ns
Test testComputeIfAbsent average time per run: 184.541579125 ns
Test testComputeIfAbsent2 average time per run: 265.417909625 ns
Test testComputeIfAbsent average time per run: 213.9811425 ns
Test testComputeIfAbsent2 average time per run: 298.76602575 ns
Test testComputeIfAbsent average time per run: 347.883728125 ns
</code>```

Body:
ConcurrentHashMap is often used in concurrent environments for aggregation of some events under a key - like counting hits for some string values. In case we don't know the keys in advance we need to have a good way to initialize key on need, it should to be fast and safe in terms of concurrency.
What is the best pattern (in terms of efficiency) for this problem?

I will use a model map with <String, AtomicInteger> declared like:

ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<>();

But it could be a map with any key-value pair, where we need to initialize a key-value pair if the key does not already exists in the map and mutate the state of value to record event.

There are two popular approaches:
The first one uses ConcurrentHashMap.putIfAbsent:

AtomicInteger count = map.get(s);
if (count == null) {
    count = new AtomicInteger(0);
    AtomicInteger prevCount = map.putIfAbsent(s, count);
    if (prevCount != null) {
        count = prevCount;
    }
}
count.incrementAndGet();

The second one uses ConcurrentHashMap.computeIfAbsent:

AtomicInteger count = map.computeIfAbsent(s, (k) -> new AtomicInteger(0));
count.incrementAndGet();

Which one is better suited for this task? Are there other approaches?

Body:
Unfortunatelly up to jdk1.8.0_131, the computeIfAbsent always go into the synchronized block, regardles if the key is already there or not, which makes it way slower than the putIfAbsent.

This benchmark confirms this, it appears that depending on contention level putIfAbsent is from 2 to 50 times faster than computeIfAbsent.

import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class ConcurrentHashMapTest {
    private final static int numberOfRuns = 1000000;
    private final static int numberOfThreads = Runtime.getRuntime().availableProcessors();
    private final static int keysSize = 10;
    private final static String[] strings = new String[keysSize];
    static {
        for (int n = 0; n < keysSize; n++) {
            strings[n] = "" + (char) ('A' + n);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int n = 0; n < 20; n++) {
            testPutIfAbsent();
            testComputeIfAbsentLambda();
        }
    }

    private static void testPutIfAbsent() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
        final Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);

        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        String s = strings[random.nextInt(strings.length)];
                        start = System.nanoTime();

                        AtomicInteger count = map.get(s);
                        if (count == null) {
                            count = new AtomicInteger(0);
                            AtomicInteger prevCount = map.putIfAbsent(s, count);
                            if (prevCount != null) {
                                count = prevCount;
                            }
                        }
                        count.incrementAndGet();
                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

    private static void testComputeIfAbsentLambda() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
        final Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        String s = strings[random.nextInt(strings.length)];
                        start = System.nanoTime();

                        AtomicInteger count = map.computeIfAbsent(s, (k) -> new AtomicInteger(0));
                        count.incrementAndGet();

                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

}

the output:

Test testPutIfAbsent average time per run: 115.756501 ns
Test testComputeIfAbsentLambda average time per run: 276.9667055 ns
Test testPutIfAbsent average time per run: 134.2332435 ns
Test testComputeIfAbsentLambda average time per run: 223.222063625 ns
Test testPutIfAbsent average time per run: 119.968893625 ns
Test testComputeIfAbsentLambda average time per run: 216.707419875 ns
Test testPutIfAbsent average time per run: 116.173902375 ns
Test testComputeIfAbsentLambda average time per run: 215.632467375 ns
Test testPutIfAbsent average time per run: 112.21422775 ns
Test testComputeIfAbsentLambda average time per run: 210.29563725 ns
Test testPutIfAbsent average time per run: 120.50643475 ns
Test testComputeIfAbsentLambda average time per run: 200.79536475 ns

We can use the putIfAbsent approach to create faster computeIfAbsent.
The only difference would be that this new computeIfAbsent could call the initialization function more than once in case of concurrent initialization of the same key. The benchmark results are identical as with the 'putIfAbsent', since it is the same code, it is not a big surprise, but in case anyone would like to test this, here is the benchmark:

import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;

public class CocnurrentHashMap2Benchmark {
    private final static int numberOfRuns = 1000000;
    private final static int numberOfThreads = Runtime.getRuntime().availableProcessors();
    private final static int keysSize = 10;
    private final static String[] strings = new String[keysSize];
    static {
        for (int n = 0; n < keysSize; n++) {
            strings[n] = "" + (char) ('A' + n);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int n = 0; n < 20; n++) {
            testPutIfAbsent();
            testComputeIfAbsent2Lambda();
        }
    }

    private static void testPutIfAbsent() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
        final Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);

        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        String s = strings[random.nextInt(strings.length)];
                        start = System.nanoTime();

                        AtomicInteger count = map.get(s);
                        if (count == null) {
                            count = new AtomicInteger(0);
                            AtomicInteger prevCount = map.putIfAbsent(s, count);
                            if (prevCount != null) {
                                count = prevCount;
                            }
                        }
                        count.incrementAndGet();
                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

     private static void testComputeIfAbsent2Lambda() throws InterruptedException {
            final AtomicLong totalTime = new AtomicLong();
            final ConcurrentHashMap2<String, AtomicInteger> map = new ConcurrentHashMap2<String, AtomicInteger>();
            final Random random = new Random();
            ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
            for (int i = 0; i < numberOfThreads; i++) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        long start, end;
                        for (int n = 0; n < numberOfRuns; n++) {
                            String s = strings[random.nextInt(strings.length)];
                            start = System.nanoTime();

                            AtomicInteger count = map.computeIfAbsent2(s, (k) -> new AtomicInteger(0));
                            count.incrementAndGet();

                            end = System.nanoTime();
                            totalTime.addAndGet(end - start);
                        }
                    }
                });
            }
            executorService.shutdown();
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
            System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                    + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
        }

        public static class ConcurrentHashMap2<K,V> extends ConcurrentHashMap<K,V> {

            /**
             * If there is no mapping for the key then computes and puts the mapping,
             * otherwise it simply return the value for that key.
             * In case of concurrent initialization of the same key the mappingFunction can be called more than once.
             * @param key - the key to be initialized or retrieved
             * @param mappingFunction - the function to be called for computation of initial value.
             * @return computed value if the key wasn't already in the map otherwise return the actual value for provided key.
             */
            public V computeIfAbsent2(K key, Function<K,V> mappingFunction) {
                V value = get(key);
                if (value == null) {
                    value = mappingFunction.apply(key);
                    V prevValue = putIfAbsent(key, value);
                    if (prevValue != null) {
                        value = prevValue;
                    }
                }
                return value;
            }
        }
}

the results:

Test testComputeIfAbsent2Lambda average time per run: 138.1053415 ns
Test testPutIfAbsent average time per run: 129.45236425 ns
Test testComputeIfAbsent2Lambda average time per run: 128.48006825 ns
Test testPutIfAbsent average time per run: 118.733798375 ns
Test testComputeIfAbsent2Lambda average time per run: 134.038046625 ns
Test testPutIfAbsent average time per run: 119.7947695 ns
Test testComputeIfAbsent2Lambda average time per run: 134.183876375 ns
Test testPutIfAbsent average time per run: 137.969932625 ns
Test testComputeIfAbsent2Lambda average time per run: 137.97531275 ns
Test testPutIfAbsent average time per run: 136.904379125 ns
Test testComputeIfAbsent2Lambda average time per run: 148.899750125 ns
Test testPutIfAbsent average time per run: 129.788293125 ns
Test testComputeIfAbsent2Lambda average time per run: 141.50586625 ns
Test testPutIfAbsent average time per run: 129.081558875 ns
Test testComputeIfAbsent2Lambda average time per run: 122.36628625 ns
Test testPutIfAbsent average time per run: 127.1215535 ns
Test testComputeIfAbsent2Lambda average time per run: 108.129917625 ns
Test testPutIfAbsent average time per run: 133.630786875 ns
Test testComputeIfAbsent2Lambda average time per run: 134.978805625 ns
Test testPutIfAbsent average time per run: 132.7747585 ns
Test testComputeIfAbsent2Lambda average time per run: 132.4352885 ns
Test testPutIfAbsent average time per run: 133.753792875 ns
Test testComputeIfAbsent2Lambda average time per run: 134.09569175 ns
Test testPutIfAbsent average time per run: 145.610141125 ns
Test testComputeIfAbsent2Lambda average time per run: 139.437622125 ns

If we compare the speed of putting mapping into the map when the key doesn't already exists it appears that the new 'computeIfAbsent2' is also much faster. The benchmark:

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;

public class CocnurrentHashMap2PutBenchmark {
    private final static int numberOfRuns = 1000000;
    private final static int numberOfThreads = Runtime.getRuntime().availableProcessors();

    public static void main(String[] args) throws InterruptedException {
        for (int n = 0; n < 20; n++) {
            testComputeIfAbsent2();
            testComputeIfAbsent();
        }
    }

    private static void testComputeIfAbsent2() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap2<Integer, String> map = new ConcurrentHashMap2<Integer, String>();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        Integer key = Integer.valueOf(n);
                        start = System.nanoTime();

                        String value = map.computeIfAbsent2(key, (k) -> "value");

                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

    private static void testComputeIfAbsent() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<Integer, String>();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        Integer key = Integer.valueOf(n);
                        start = System.nanoTime();

                        String value = map.computeIfAbsent(key, (k) -> "value");

                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

    public static class ConcurrentHashMap2<K, V> extends ConcurrentHashMap<K, V> {

        /**
         * If there is no mapping for the key then computes and puts the
         * mapping, otherwise it simply return the value for that key. In case
         * of concurrent initialization of the same key the mappingFunction can
         * be called more than once.
         *
         * @param key
         *            - the key to be initialized or retrieved
         * @param mappingFunction
         *            - the function to be called for computation of initial
         *            value.
         * @return computed value if the key wasn't already in the map otherwise
         *         return the actual value for provided key.
         */
        public V computeIfAbsent2(K key, Function<K, V> mappingFunction) {
            V value = get(key);
            if (value == null) {
                value = mappingFunction.apply(key);
                V prevValue = putIfAbsent(key, value);
                if (prevValue != null) {
                    value = prevValue;
                }
            }
            return value;
        }
    }
}

the results:

Test testComputeIfAbsent2 average time per run: 445.077932375 ns
Test testComputeIfAbsent average time per run: 784.786391 ns
Test testComputeIfAbsent2 average time per run: 294.10136375 ns
Test testComputeIfAbsent average time per run: 314.8724765 ns
Test testComputeIfAbsent2 average time per run: 236.56533275 ns
Test testComputeIfAbsent average time per run: 350.863664625 ns
Test testComputeIfAbsent2 average time per run: 346.19498275 ns
Test testComputeIfAbsent average time per run: 641.995172625 ns
Test testComputeIfAbsent2 average time per run: 255.441646125 ns
Test testComputeIfAbsent average time per run: 326.399150125 ns
Test testComputeIfAbsent2 average time per run: 275.626666125 ns
Test testComputeIfAbsent average time per run: 201.207314125 ns
Test testComputeIfAbsent2 average time per run: 289.19059725 ns
Test testComputeIfAbsent average time per run: 318.448059 ns
Test testComputeIfAbsent2 average time per run: 225.19701825 ns
Test testComputeIfAbsent average time per run: 306.461814125 ns
Test testComputeIfAbsent2 average time per run: 213.460366 ns
Test testComputeIfAbsent average time per run: 334.325044625 ns
Test testComputeIfAbsent2 average time per run: 256.4048955 ns
Test testComputeIfAbsent average time per run: 256.366700625 ns
Test testComputeIfAbsent2 average time per run: 231.88875575 ns
Test testComputeIfAbsent average time per run: 246.076624 ns
Test testComputeIfAbsent2 average time per run: 222.4649485 ns
Test testComputeIfAbsent average time per run: 266.505719625 ns
Test testComputeIfAbsent2 average time per run: 228.708391375 ns
Test testComputeIfAbsent average time per run: 261.866442625 ns
Test testComputeIfAbsent2 average time per run: 198.614718875 ns
Test testComputeIfAbsent average time per run: 225.43031925 ns
Test testComputeIfAbsent2 average time per run: 300.478359 ns
Test testComputeIfAbsent average time per run: 306.03640225 ns
Test testComputeIfAbsent2 average time per run: 195.0444215 ns
Test testComputeIfAbsent average time per run: 271.461982625 ns
Test testComputeIfAbsent2 average time per run: 224.306529875 ns
Test testComputeIfAbsent average time per run: 334.52790425 ns
Test testComputeIfAbsent2 average time per run: 212.217131625 ns
Test testComputeIfAbsent average time per run: 184.541579125 ns
Test testComputeIfAbsent2 average time per run: 265.417909625 ns
Test testComputeIfAbsent average time per run: 213.9811425 ns
Test testComputeIfAbsent2 average time per run: 298.76602575 ns
Test testComputeIfAbsent average time per run: 347.883728125 ns


问:
Axis 1.4 to 1.6.2
i was migrating project from axis2 1.4 to axis2 1.6.2 and my ant scripts are not working now, i'm not good at ant scripts so im asking you

```<code><taskdef name="osql"
        classname="OSqlTask"
        classpath="${build.ant.dir}"/>
    <taskdef name="finddbpatches"
        classname="FindDBPatchesTask"
        classpath="${build.ant.dir}"/>
    <taskdef resource="axis-tasks.properties"
        classpathref="ant.cp"/>
</code>```

this yells at me that it cannot find those tasks, but if i switch back old libraries axis-1.4.jar <-> axis-1.6.2.jar it works. I was unable to find proper way to change it. Can anyone help?

//edit

taskdef class OSqlTask cannot be found using the classloader AntClassLoader[]

taskdef class FindDBPatchesTask cannot be found using the classloader AntClassLoader[]

askdef A class needed by class org.apache.axis.tools.ant.wsdl.Wsdl2javaAntTask cannot be found: org/apache/
 axis/utils/DefaultAuthenticator using the classloader AntClassLoader[]

答: I found out that 'axis-tasks.properties' cannot be used with axis2-1.6.2.jar as it's no longer supported by that version, api has changed and i needed to write my own task defnitions to generate code from  WSDL.</p>

Title: Axis 1.4 to 1.6.2

Body:
i was migrating project from axis2 1.4 to axis2 1.6.2 and my ant scripts are not working now, i'm not good at ant scripts so im asking you

<taskdef name="osql"
        classname="OSqlTask"
        classpath="${build.ant.dir}"/>
    <taskdef name="finddbpatches"
        classname="FindDBPatchesTask"
        classpath="${build.ant.dir}"/>
    <taskdef resource="axis-tasks.properties"
        classpathref="ant.cp"/>

this yells at me that it cannot find those tasks, but if i switch back old libraries axis-1.4.jar <-> axis-1.6.2.jar it works. I was unable to find proper way to change it. Can anyone help?

//edit

taskdef class OSqlTask cannot be found using the classloader AntClassLoader[]

taskdef class FindDBPatchesTask cannot be found using the classloader AntClassLoader[]

askdef A class needed by class org.apache.axis.tools.ant.wsdl.Wsdl2javaAntTask cannot be found: org/apache/
 axis/utils/DefaultAuthenticator using the classloader AntClassLoader[]


问:
How can I fill / populate DropDown with my IEnumerable<Model> value ASP.NET MVC
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

```<code>@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}
<div class="">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                    <h2><i class="fa fa-filter"></i> </h2>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">
                    <br />
                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <div class="col-md-12 col-sm-12">
                            <div class="col-md-12 col-sm-12">
                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })
                            </div>
                        </div>

                    }

                }
            }
        }
    }
}
</code>```

Controller action:

```<code>public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}
</code>```

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

答:
model

```<code>   public class LanguageViewModel
    {
        public int LanguageId { get; set; }
        public IEnumerable<Language> ActiveLanguages{get; set;}
    }

    public class Language
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
</code>```

Controller

```<code>   [HttpGet]
   public ActionResult Language()
    {
       var languageViewModel = new LanguageViewModel
        {
          ActiveLanguages = LanguageController.GetAll();
        }
         return View(languageViewModel);
     }
</code>```

View

```<code>@model LanguageViewModel
@using Web.Helpers
@{
    ViewBag.Title = "";
}
<div class="">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                    <h2><i class="fa fa-filter"></i> </h2>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">
                    <br />
                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <div class="col-md-12 col-sm-12">
                            <div class="col-md-12 col-sm-12">
                                @Html.DropDownListFor(model => model.LanguageId, new SelectList(Model.ActiveLanguages, "Id", "Name"), new { @class = "form-control" })
                            </div>
                        </div>

                    }

                }
            }
        }
    }
}
</code>```

Body:
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}

                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })

                    }

                }
            }
        }
    }
}

Controller action:

public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

Body:
model

   public class LanguageViewModel
    {
        public int LanguageId { get; set; }
        public IEnumerable<Language> ActiveLanguages{get; set;}
    }

    public class Language
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Controller

   [HttpGet]
   public ActionResult Language()
    {
       var languageViewModel = new LanguageViewModel
        {
          ActiveLanguages = LanguageController.GetAll();
        }
         return View(languageViewModel);
     }

View

@model LanguageViewModel
@using Web.Helpers
@{
    ViewBag.Title = "";
}
<div class="">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                    <h2><i class="fa fa-filter"></i> </h2>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">
                    <br />
                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <div class="col-md-12 col-sm-12">
                            <div class="col-md-12 col-sm-12">
                                @Html.DropDownListFor(model => model.LanguageId, new SelectList(Model.ActiveLanguages, "Id", "Name"), new { @class = "form-control" })
                            </div>
                        </div>

                    }

                }
            }
        }
    }
}


答:
Having an index in element names is usually not considered a good XML design but if you are sure you want that you could add a parameter to your template and use it, either in the element name or perhaps better in an attribute:

```<code>  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:param name="index" select="1"/>
    <xsl:choose>
        <xsl:when test="not(contains($text, $separator))">
            <swiftResponseReturnValue pos="{$index}">
                <xsl:value-of select="$text"/>
            </swiftResponseReturnValue>
        </xsl:when>
        <xsl:otherwise>
            <swiftResponseReturnValue pos="{$index}">
                <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
            </swiftResponseReturnValue>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                <xsl:with-param name="separator" select="$separator"/>
                <xsl:with-param name="index" select="$index + 1"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</code>```

If you want to construct the element name with an index then use <xsl:element name="swiftResponseReturnValue{$index}">...</xsl:element> instead of <swiftResponseReturnValue pos="{$index}">.

Title: add incremental value in xslt tag

Body:
 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" />
  <soapenv:Body>
    <swiftResponseResponse xmlns="http://webservice.sbi.com">
      <swiftResponseReturn>15617TS006140|DC768736|13321.49|04-05-2017 15:13:03|SWIFTINR|NA|FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturn>
    </swiftResponseResponse>
  </soapenv:Body>
</soapenv:Envelope>

and my xsl input is

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://webservice.sbi.com" exclude-result-prefixes="soapenv xsl  xsd xsi xs ">

  <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:choose>
        <xsl:when test="not(contains($text, $separator))">
            <swiftResponseReturnValue>
                <xsl:value-of select="$text"/>
            </swiftResponseReturnValue>
        </xsl:when>
        <xsl:otherwise>
            <swiftResponseReturnValue>
                <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
            </swiftResponseReturnValue>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                <xsl:with-param name="separator" select="$separator"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

   <xsl:template match="xs:swiftResponseReturn">
  <swiftResponseReturn>
     <xsl:call-template name="tokenize">
         <xsl:with-param name="text" select="."/>
         <xsl:with-param name="separator" select="'|'"/>
     </xsl:call-template>
  </swiftResponseReturn>
</xsl:template>
</xsl:stylesheet>

my output is

     <swiftResponseReturn>
   <swiftResponseReturnValue>15617TS006140</swiftResponseReturnValue>
   <swiftResponseReturnValue>DC768736</swiftResponseReturnValue>
   <swiftResponseReturnValue>13321.49</swiftResponseReturnValue>
   <swiftResponseReturnValue>04-05-2017 15:13:03</swiftResponseReturnValue>
   <swiftResponseReturnValue>SWIFTINR</swiftResponseReturnValue>
   <swiftResponseReturnValue>NA</swiftResponseReturnValue>
   <swiftResponseReturnValue>FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue>
</swiftResponseReturn>

i want my expected output should be like this

    <swiftResponseReturn>
   <swiftResponseReturnValue1>15617TS006140</swiftResponseReturnValue1>
   <swiftResponseReturnValue2>DC768736</swiftResponseReturnValue2>
   <swiftResponseReturnValue3>13321.49</swiftResponseReturnValue3>
   <swiftResponseReturnValue4>04-05-2017 15:13:03</swiftResponseReturnValue4>
   <swiftResponseReturnValue5>SWIFTINR</swiftResponseReturnValue5>
   <swiftResponseReturnValue6>NA</swiftResponseReturnValue6>
   <swiftResponseReturnValue7>FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue7>
</swiftResponseReturn>

can help me to add ids in my tag or any other value that can uniquely identify my columns.please help been stuck here for while.

Body:
Having an index in element names is usually not considered a good XML design but if you are sure you want that you could add a parameter to your template and use it, either in the element name or perhaps better in an attribute:

  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:param name="index" select="1"/>
    <xsl:choose>
        <xsl:when test="not(contains($text, $separator))">
            <swiftResponseReturnValue pos="{$index}">
                <xsl:value-of select="$text"/>
            </swiftResponseReturnValue>
        </xsl:when>
        <xsl:otherwise>
            <swiftResponseReturnValue pos="{$index}">
                <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
            </swiftResponseReturnValue>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                <xsl:with-param name="separator" select="$separator"/>
                <xsl:with-param name="index" select="$index + 1"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

If you want to construct the element name with an index then use <xsl:element name="swiftResponseReturnValue{$index}">...</xsl:element> instead of <swiftResponseReturnValue pos="{$index}">.