问:
AWS Lambda: Unable to import module
please forgive me, I am totally new at Lambda and Node.

I am trying to replicate this git to order a pizza using an AWS IoT button.

My current code is:

var pizzapi = require('dominos');

var myStore = new pizzapi.Store(
    {
        ID: 'Example'
    }
);

var myAddress = new pizzapi.Address(
        {
            Street: 'Example',
            City: 'Example',
            Region: 'Example',
            PostalCode: 'Example'
        }
    );

var myCustomer = new pizzapi.Customer(
    {
        firstName: 'Example',
        lastName: 'Example',
        address: myAddress,
        phone: 'Example',
        email: 'Example@gmail.com'
    }
);

var order = new pizzapi.Order(
    {
        customer: myCustomer,
        storeID: myStore.ID
    }
);

var cardNumber='Example';
var cardInfo = new order.PaymentObject();
cardInfo.Amount = order.Amounts.Customer;
cardInfo.Number = cardNumber;
cardInfo.CardType = order.validateCC(cardNumber);
cardInfo.Expiration = 'Example';
cardInfo.SecurityCode = 'Example';
cardInfo.PostalCode = 'Example';

order.Payments.push(cardInfo);

function orderDominos(event, context) {
  var clickType = event.clickType;
  switch(clickType.toLowerCase()) {
    case "single": {
      order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
    case "double": {
        order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
    case "long": {
        order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
  }
  order.validate(
      function(result) {
          console.log("Order is Validated");
      }
  );
  order.price(
      function(result) {
            console.log("Order is Priced");
      }
  );
  order.place(
      function(result) {
          console.log("Price is", result.result.Order.Amounts, "\nEstimated Wait Time",result.result.Order.EstimatedWaitMinutes, "minutes");
          console.log("Order placed!");
          context.succeed(event);
      }
  );
}

exports.handler = orderDominos;```
</div>
</div>
</p>

<p>The file structure is:</p>

<ul>
<li>orderDominos.js</li>
<li>node_modules/dominos</li>
</ul>

<p>I zipped the files, uploaded to Lambda, and pointed the header to "index.handler"</p>

<p>What am I doing wrong?</p>

<p>Edit: The error</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Unable to import module 'orderDominos': Error
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/task/node_modules/dominos/src/http-json.js:1:74)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)</code>```

答: Ran into this problem as well. What solved it for me was realizing that the file path was too long on a Windows machine. After zipping, I realized that the contents of node_modules was empty. I copied the files for zipping to a higher level path e.g. C:\User\ and zipped the specified files. Hope this helps!</p>

Title: AWS Lambda: Unable to import module

Body:
please forgive me, I am totally new at Lambda and Node.

I am trying to replicate this git to order a pizza using an AWS IoT button.

My current code is:

var pizzapi = require('dominos');

var myStore = new pizzapi.Store(
    {
        ID: 'Example'
    }
);

var myAddress = new pizzapi.Address(
        {
            Street: 'Example',
            City: 'Example',
            Region: 'Example',
            PostalCode: 'Example'
        }
    );

var myCustomer = new pizzapi.Customer(
    {
        firstName: 'Example',
        lastName: 'Example',
        address: myAddress,
        phone: 'Example',
        email: 'Example@gmail.com'
    }
);

var order = new pizzapi.Order(
    {
        customer: myCustomer,
        storeID: myStore.ID
    }
);

var cardNumber='Example';
var cardInfo = new order.PaymentObject();
cardInfo.Amount = order.Amounts.Customer;
cardInfo.Number = cardNumber;
cardInfo.CardType = order.validateCC(cardNumber);
cardInfo.Expiration = 'Example';
cardInfo.SecurityCode = 'Example';
cardInfo.PostalCode = 'Example';

order.Payments.push(cardInfo);

function orderDominos(event, context) {
  var clickType = event.clickType;
  switch(clickType.toLowerCase()) {
    case "single": {
      order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
    case "double": {
        order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
    case "long": {
        order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
  }
  order.validate(
      function(result) {
          console.log("Order is Validated");
      }
  );
  order.price(
      function(result) {
            console.log("Order is Priced");
      }
  );
  order.place(
      function(result) {
          console.log("Price is", result.result.Order.Amounts, "\nEstimated Wait Time",result.result.Order.EstimatedWaitMinutes, "minutes");
          console.log("Order placed!");
          context.succeed(event);
      }
  );
}

exports.handler = orderDominos;

The file structure is:

orderDominos.js

node_modules/dominos

I zipped the files, uploaded to Lambda, and pointed the header to "index.handler"

What am I doing wrong?

Edit: The error

Unable to import module 'orderDominos': Error
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/task/node_modules/dominos/src/http-json.js:1:74)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)


来源: stackexchange

问:
How to get each specific value in an array?
I'm looking to be able to extract each 'hire_address' value from the following array and add it to a separate array.

```<code>var addr =
{
   "status":"success",
   "data":[
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Glasgow",
         "offer_oucu":"ac1",
         "offer_address":"Glasgow"
      },
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Poole",
         "offer_oucu":"ac1",
         "offer_address":"Poole"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Hastings",
         "offer_oucu":"ac1",
         "offer_address":"Hastings"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"London",
         "offer_oucu":"ac1",
         "offer_address":"London"
      }
   ]
};
</code>```

I currently have

```<code>var addresses = [];
$.each(addr.data.hire_address, function (index, value) {
addresses.push(value);
</code>```

But not having any luck. Any suggestions?

Thank you for the replies.

I now have

```<code>var addresses = [];
$.each(addr, function (index, value) {
    if (value == "data"){
        addresses.push(value.hire_address);
    }
}
);
</code>```

But can't seem to get it to work. Do I need the if statement? I added this because the first item is 'status' and was running into errors if I tried to add a 'hire_address' property of this because it doesn't exists.

答:
$.each takes two parameters, the first being an array. You should pass in the array you want to loop through.

the second parameter is the function that gets call per item in array. It is stored in the value parameter. If you are looping through the array, you can access the correct property like so:

```<code>value.hire_address
</code>```

http://api.jquery.com/jquery.each/

ContentLicense: CC BY-SA 3.0

Body:
I'm looking to be able to extract each 'hire_address' value from the following array and add it to a separate array.

var addr =
{
   "status":"success",
   "data":[
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Glasgow",
         "offer_oucu":"ac1",
         "offer_address":"Glasgow"
      },
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Poole",
         "offer_oucu":"ac1",
         "offer_address":"Poole"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Hastings",
         "offer_oucu":"ac1",
         "offer_address":"Hastings"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"London",
         "offer_oucu":"ac1",
         "offer_address":"London"
      }
   ]
};

I currently have

var addresses = [];
$.each(addr.data.hire_address, function (index, value) {
addresses.push(value);

But not having any luck. Any suggestions?

Thank you for the replies.

I now have

var addresses = [];
$.each(addr, function (index, value) {
    if (value == "data"){
        addresses.push(value.hire_address);
    }
}
);

But can't seem to get it to work. Do I need the if statement? I added this because the first item is 'status' and was running into errors if I tried to add a 'hire_address' property of this because it doesn't exists.

Body:
$.each takes two parameters, the first being an array. You should pass in the array you want to loop through.

the second parameter is the function that gets call per item in array. It is stored in the value parameter. If you are looping through the array, you can access the correct property like so:

value.hire_address

http://api.jquery.com/jquery.each/


问:
Boostrap datepicker, disabled dates dynamically each month
I can disable dates with:

```<code>$('#datepicker').datepicker({
    todayHighlight: true,
    datesDisabled: ['03/06/2017', '03/21/2017','04/14/2017']
});
</code>```

but with my use case, since you can go over the year by the calendar, I can have 300 disable days out of 365 in 2017 and 200 disabled days out of 365 in 2016.

I want to optimize, imagine after 5 years, he could have 2500 disabled days to load.
Someone know how to do it dynamically, I mean, each time a change the  current month.

Or another way to do this?

答:
You can dynamically update disabled dates using setDatesDisabled and you can listen to view changes adding handler for changeMonth, changeYear, changeDecade and changeCentury events.

EDIT: As Dave Herman stated here, there was a bug with version 1.6.4 fixed with 1.7.1 and you have to add updateViewDate: false option.

Here my attempt (unsing getDisabledDates function to simulate dynamc disabled dates):

function getDisabledDates(month){
  if( month<0 || month>12){
    return [];
  }
  var disabled = [
    ['01/01/2017', '01/02/2017', '01/03/2017'],
    ['02/04/2017', '02/05/2017', '02/06/2017'],
    ['03/08/2017', '03/09/2017', '03/10/2017'],
    ['04/05/2017', '04/06/2017', '04/07/2017'],
    ['05/15/2017', '05/16/2017', '05/17/2017'],
    ['06/11/2017', '06/12/2017', '06/13/2017'],
    ['07/15/2017', '07/16/2017', '07/17/2017'],
    ['08/07/2017', '08/08/2017', '08/09/2017'],
    ['09/05/2017', '09/06/2017', '09/07/2017'],
    ['10/11/2017', '10/12/2017', '10/13/2017'],
    ['11/06/2017', '11/07/2017', '11/08/2017'],
    ['12/13/2017', '12/14/2017', '12/15/2017'],
  ];
  return disabled[month];
}

$('#datepicker').datepicker({
  todayHighlight: true,
  updateViewDate: false,
  //datesDisabled: ['03/06/2017', '03/21/2017','04/14/2017']
}).on('changeMonth', function(e){
  var month = e.date.getMonth();
  var disabled = getDisabledDates(month);
  $('#datepicker').datepicker('setDatesDisabled', disabled);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker3.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.js"></script>

<input type="text" class="form-control" id="datepicker"></code>```

Body:
I can disable dates with:

$('#datepicker').datepicker({
    todayHighlight: true,
    datesDisabled: ['03/06/2017', '03/21/2017','04/14/2017']
});

but with my use case, since you can go over the year by the calendar, I can have 300 disable days out of 365 in 2017 and 200 disabled days out of 365 in 2016.

I want to optimize, imagine after 5 years, he could have 2500 disabled days to load.
Someone know how to do it dynamically, I mean, each time a change the  current month.

Or another way to do this?

Body:
You can dynamically update disabled dates using setDatesDisabled and you can listen to view changes adding handler for changeMonth, changeYear, changeDecade and changeCentury events.

EDIT: As Dave Herman stated here, there was a bug with version 1.6.4 fixed with 1.7.1 and you have to add updateViewDate: false option.

Here my attempt (unsing getDisabledDates function to simulate dynamc disabled dates):

function getDisabledDates(month){
  if( month<0 || month>12){
    return [];
  }
  var disabled = [
    ['01/01/2017', '01/02/2017', '01/03/2017'],
    ['02/04/2017', '02/05/2017', '02/06/2017'],
    ['03/08/2017', '03/09/2017', '03/10/2017'],
    ['04/05/2017', '04/06/2017', '04/07/2017'],
    ['05/15/2017', '05/16/2017', '05/17/2017'],
    ['06/11/2017', '06/12/2017', '06/13/2017'],
    ['07/15/2017', '07/16/2017', '07/17/2017'],
    ['08/07/2017', '08/08/2017', '08/09/2017'],
    ['09/05/2017', '09/06/2017', '09/07/2017'],
    ['10/11/2017', '10/12/2017', '10/13/2017'],
    ['11/06/2017', '11/07/2017', '11/08/2017'],
    ['12/13/2017', '12/14/2017', '12/15/2017'],
  ];
  return disabled[month];
}

$('#datepicker').datepicker({
  todayHighlight: true,
  updateViewDate: false,
  //datesDisabled: ['03/06/2017', '03/21/2017','04/14/2017']
}).on('changeMonth', function(e){
  var month = e.date.getMonth();
  var disabled = getDisabledDates(month);
  $('#datepicker').datepicker('setDatesDisabled', disabled);
});

<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker3.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.js"></script>

<input type="text" class="form-control" id="datepicker">


问:
Usage of NSException in iPhone Apps
One of my friends asked me not to use NSException in iPhone Apps. The reason he gave was "performance bottleneck". But I am not convinced of it.

Can someone confirm me that we should restrain from using NSException in iPhone App? If you have best practices for using NSException, please provide that too.

UPDATE:

This link requests us to use Exception handling at the app level. Have someone ever done it? Please give the advantages of it and any other performance hitches it could create.

答: Generally ask yourself if you're trying to signal an error, or do you actually have an exceptional condition? If the former, then it's a very bad idea regardless of any performance issue, real or perceived. If the latter, it's most definitely the right thing to do.</p>

ContentLicense: CC BY-SA 2.5

Title: Usage of NSException in iPhone Apps


问:
Mirror half of a N x N adjacency matrix in Javascript
I have half of an N x N matrix in a javascript array of arrays, and i need to get this half and "mirror" it on the other side of the main diagonal.

Here is an image that explains better:

The main diagonal is the red line, and i have the upper half of the matrix that needs to be "placed" below the red line too, forming a full matrix.

The data structure is something like this:

```<code>var map = [ ["0","1","2","3"], ["0", "1", "2"], ["0","1"], ["0"] ];
</code>```

Lines with columns inside.

I often insert things i already tried in my questions, but in this time i couldn't even find out how to start. So, my apologize if i am not providing some more info.

答:
One way to do it is something like this

```<code>var i = 0;
var j = 0;
var map = [ ["0","1","2","3"], ["0", "1", "2"], ["0","1"], ["0"] ];
var n = map.length;
var res = new Array(n);

for (i = 0; i < n; i++) {
  res[i] = new Array(n);
  for (j = 0; j < n - i; j++) {
    res[i][i+j] = map[i][j];
  }
}

for (i = 0; i < n; i++) {
  for (j = i + 1; j < n; j++) {
    res[j][i] = res[i][j];
  }
}
</code>```

res will contain the mirrored array

Body:
I have half of an N x N matrix in a javascript array of arrays, and i need to get this half and "mirror" it on the other side of the main diagonal.

Here is an image that explains better:

The main diagonal is the red line, and i have the upper half of the matrix that needs to be "placed" below the red line too, forming a full matrix.

The data structure is something like this:

var map = [ ["0","1","2","3"], ["0", "1", "2"], ["0","1"], ["0"] ];

Lines with columns inside.

I often insert things i already tried in my questions, but in this time i couldn't even find out how to start. So, my apologize if i am not providing some more info.

Body:
One way to do it is something like this

var i = 0;
var j = 0;
var map = [ ["0","1","2","3"], ["0", "1", "2"], ["0","1"], ["0"] ];
var n = map.length;
var res = new Array(n);

for (i = 0; i < n; i++) {
  res[i] = new Array(n);
  for (j = 0; j < n - i; j++) {
    res[i][i+j] = map[i][j];
  }
}

for (i = 0; i < n; i++) {
  for (j = i + 1; j < n; j++) {
    res[j][i] = res[i][j];
  }
}

res will contain the mirrored array


问:
can't insert into database (webservice)
I am creating a web service which will be called from an android app. Actually I am trying to do an insert into my database but i can't figure out why it is not working. Here is my code, with some tests I have made in order to find the bug :

```<code><?php
    $con = mysqli_connect("localhost", "xxx", "xxx", "xxx");

    /* here is the original code that I commented in order to do my tests
    $mail = $_POST["mail"];
    $mdp = $_POST["mdp"];
    $nom = $_POST["nom"];
    $prenom = $_POST["prenom"];
    $dateNaissance = $_POST["dateNaissance"];
    */
    $mail = "test@mail.fr";
    $mdp = "test";
    $nom = "test";
    $prenom = "test";
    $dateNaissance = "2000/01/01";

    $statement = mysqli_prepare($con, "INSERT INTO utilisateur (mail, mdp, nom, prenom, dateNaissance) VALUES (?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "sssss", $mail, $mdp, $nom, $prenom, $dateNaissance);
    mysqli_stmt_execute($statement);

    $query = "SELECT * FROM utilisateur";
    $result2 = mysqli_query($con, $query);
    $final = mysqli_fetch_row($result2);

    print_r($final);
?>
</code>```

The SELECT request returns me the row I have in my utilisateur table so I suppose it's not a problem of connection.

Moreover, mysqli_stmt_execute($statement) returns 1... So if i'm not wrong it's supposed to mean that my request worked ? Anyway, nothing is inserted.

I'm hosting my database with 000webhost, don't know if this will help... I'm starting developing so everything is not crystal clear.

Hope that I was understandable and that you'll enlighten me!

答:
The query causes this error

```<code>Error: Field 'idUser' doesn't have a default value.
</code>```

You will need to fix your table. Make it an InnoDB table.

```<code>CREATE TABLE `utilisateur` (
  `idUser` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `mail` VARCHAR(40) COLLATE utf8_bin NOT NULL,
  `mdp` VARCHAR(40) COLLATE utf8_bin DEFAULT NULL,
  `nom` VARCHAR(40) COLLATE utf8_bin DEFAULT NULL,
  `prenom` VARCHAR(30) COLLATE utf8_bin DEFAULT NULL,
  `dateNaissance` DATE DEFAULT NULL,
  PRIMARY KEY (`idUser`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
</code>```

Title: can't insert into database (webservice)

Body:
I am creating a web service which will be called from an android app. Actually I am trying to do an insert into my database but i can't figure out why it is not working. Here is my code, with some tests I have made in order to find the bug :

<?php
    $con = mysqli_connect("localhost", "xxx", "xxx", "xxx");

    /* here is the original code that I commented in order to do my tests
    $mail = $_POST["mail"];
    $mdp = $_POST["mdp"];
    $nom = $_POST["nom"];
    $prenom = $_POST["prenom"];
    $dateNaissance = $_POST["dateNaissance"];
    */
    $mail = "test@mail.fr";
    $mdp = "test";
    $nom = "test";
    $prenom = "test";
    $dateNaissance = "2000/01/01";

    $statement = mysqli_prepare($con, "INSERT INTO utilisateur (mail, mdp, nom, prenom, dateNaissance) VALUES (?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "sssss", $mail, $mdp, $nom, $prenom, $dateNaissance);
    mysqli_stmt_execute($statement);

    $query = "SELECT * FROM utilisateur";
    $result2 = mysqli_query($con, $query);
    $final = mysqli_fetch_row($result2);

    print_r($final);
?>

The SELECT request returns me the row I have in my utilisateur table so I suppose it's not a problem of connection.

Moreover, mysqli_stmt_execute($statement) returns 1... So if i'm not wrong it's supposed to mean that my request worked ? Anyway, nothing is inserted.

I'm hosting my database with 000webhost, don't know if this will help... I'm starting developing so everything is not crystal clear.

Hope that I was understandable and that you'll enlighten me!

Body:
The query causes this error

Error: Field 'idUser' doesn't have a default value.

You will need to fix your table. Make it an InnoDB table.

CREATE TABLE `utilisateur` (
  `idUser` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `mail` VARCHAR(40) COLLATE utf8_bin NOT NULL,
  `mdp` VARCHAR(40) COLLATE utf8_bin DEFAULT NULL,
  `nom` VARCHAR(40) COLLATE utf8_bin DEFAULT NULL,
  `prenom` VARCHAR(30) COLLATE utf8_bin DEFAULT NULL,
  `dateNaissance` DATE DEFAULT NULL,
  PRIMARY KEY (`idUser`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;


问:
Error when add more table column to jhi_user
I have a jhipter app and I want to add a salt column to jhi_user table. I have added a salt column to jhi_user table and I added salt property to User domain and UserDTO. When run mvnw -Pprod,swagger,no-liquibase package I got an error:

```<code>iveEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPro
pertiesSet(AbstractEntityManagerFactoryBean.java:362)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getOb
ject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
y.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBe
an(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:197)
        at org.springframework.context.support.AbstractApplicationContext.getBea
n(AbstractApplicationContext.java:1081)
        at org.springframework.context.support.AbstractApplicationContext.finish
BeanFactoryInitialization(AbstractApplicationContext.java:856)
        at org.springframework.context.support.AbstractApplicationContext.refres
h(AbstractApplicationContext.java:542)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.
java:737)
        at org.springframework.boot.SpringApplication.refreshContext(SpringAppli
cation.java:370)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java
:314)
        at org.springframework.boot.test.context.SpringBootContextLoader.loadCon
text(SpringBootContextLoader.java:120)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoader
Delegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoader
Delegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
        at org.springframework.test.context.support.DefaultTestContext.getApplic
ationContext(DefaultTestContext.java:83)
        at org.springframework.test.context.web.ServletTestExecutionListener.set
UpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
        at org.springframework.test.context.web.ServletTestExecutionListener.pre
pareTestInstance(ServletTestExecutionListener.java:131)
        at org.springframework.test.context.TestContextManager.prepareTestInstan
ce(TestContextManager.java:230)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.creat
eTest(SpringJUnit4ClassRunner.java:228)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.run
ReflectiveCall(SpringJUnit4ClassRunner.java:287)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCal
lable.java:12)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.metho
dBlock(SpringJUnit4ClassRunner.java:289)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runCh
ild(SpringJUnit4ClassRunner.java:247)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runCh
ild(SpringJUnit4ClassRunner.java:94)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClass
Callbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassC
allbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(S
pringJUnit4ClassRunner.java:191)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provide
r.java:283)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUni
t4Provider.java:173)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4
Provider.java:153)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider
.java:128)
        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameCla
ssLoader(ForkedBooter.java:203)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(Fork
edBooter.java:155)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:
103)
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-valid
ation: missing column [salt] in table [jhi_user]
        at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateTa
ble(AbstractSchemaValidator.java:136)
        at org.hibernate.tool.schema.internal.GroupedSchemaValidatorImpl.validat
eTables(GroupedSchemaValidatorImpl.java:42)
        at org.hibernate.tool.schema.internal.AbstractSchemaValidator.performVal
idation(AbstractSchemaValidator.java:89)
        at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidati
on(AbstractSchemaValidator.java:68)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.perform
DatabaseAction(SchemaManagementToolCoordinator.java:191)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process
(SchemaManagementToolCoordinator.java:72)
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.j
ava:309)
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFa
ctoryBuilderImpl.java:445)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build
(EntityManagerFactoryBuilderImpl.java:889)
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvi
der.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.ja
va:60)
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.cr
eateNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNat
iveEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPro
pertiesSet(AbstractEntityManagerFactoryBean.java:362)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getOb
ject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
y.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBe
an(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:197)
        at org.springframework.context.support.AbstractApplicationContext.getBea
n(AbstractApplicationContext.java:1081)
        at org.springframework.context.support.AbstractApplicationContext.finish
BeanFactoryInitialization(AbstractApplicationContext.java:856)
        at org.springframework.context.support.AbstractApplicationContext.refres
h(AbstractApplicationContext.java:542)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.
java:737)
        at org.springframework.boot.SpringApplication.refreshContext(SpringAppli
cation.java:370)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java
:314)
        at org.springframework.boot.test.context.SpringBootContextLoader.loadCon
text(SpringBootContextLoader.java:120)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoader
Delegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoader
Delegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
        at org.springframework.test.context.support.DefaultTestContext.getApplic
ationContext(DefaultTestContext.java:83)
        at org.springframework.test.context.web.ServletTestExecutionListener.set
UpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
        at org.springframework.test.context.web.ServletTestExecutionListener.pre
pareTestInstance(ServletTestExecutionListener.java:131)
        at org.springframework.test.context.TestContextManager.prepareTestInstan
ce(TestContextManager.java:230)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.creat
eTest(SpringJUnit4ClassRunner.java:228)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.run
ReflectiveCall(SpringJUnit4ClassRunner.java:287)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCal
lable.java:12)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.metho
dBlock(SpringJUnit4ClassRunner.java:289)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runCh
ild(SpringJUnit4ClassRunner.java:247)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runCh
ild(SpringJUnit4ClassRunner.java:94)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClass
Callbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassC
allbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(S
pringJUnit4ClassRunner.java:191)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provide
r.java:283)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUni
t4Provider.java:173)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4
Provider.java:153)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider
.java:128)
        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameCla
ssLoader(ForkedBooter.java:203)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(Fork
edBooter.java:155)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:
103)

Results :

Tests in error:
  UserServiceIntTest.assertThatAnonymousUserIsNotGet » IllegalState Failed to lo
...
  UserServiceIntTest.assertThatOnlyActivatedUserCanRequestPasswordReset » Illega
lState
  UserServiceIntTest.assertThatResetKeyMustBeValid » IllegalState Failed to load
...
  UserServiceIntTest.assertThatResetKeyMustNotBeOlderThan24Hours » IllegalState
...
  UserServiceIntTest.assertThatUserCanResetPassword » IllegalState Failed to loa
...
  UserServiceIntTest.assertThatUserMustExistToResetPassword » IllegalState Faile
...
  UserServiceIntTest.testFindNotActivatedUsersByCreationDateBefore » IllegalStat
e
  AccountResourceIntTest.testAuthenticatedUser » IllegalState Failed to load App
...
  AccountResourceIntTest.testGetExistingAccount » IllegalState Failed to load Ap
...
  AccountResourceIntTest.testGetUnknownAccount » IllegalState Failed to load App
...
  AccountResourceIntTest.testNonAuthenticatedUser » IllegalState Failed to load
...
  AccountResourceIntTest.testRegisterAdminIsIgnored » IllegalState Failed to loa
...
  AccountResourceIntTest.testRegisterDuplicateEmail » IllegalState Failed to loa
...
  AccountResourceIntTest.testRegisterDuplicateLogin » IllegalState Failed to loa
...
  AccountResourceIntTest.testRegisterInvalidEmail » IllegalState Failed to load
...
  AccountResourceIntTest.testRegisterInvalidLogin » IllegalState Failed to load
...
  AccountResourceIntTest.testRegisterInvalidPassword » IllegalState Failed to lo
...
  AccountResourceIntTest.testRegisterValid » IllegalState Failed to load Applica
...
  AccountResourceIntTest.testSaveInvalidLogin » IllegalState Failed to load Appl
...
  AuditResourceIntTest.getAllAudits » IllegalState Failed to load ApplicationCon
...
  AuditResourceIntTest.getAudit » IllegalState Failed to load ApplicationContext

  AuditResourceIntTest.getAuditsByDate » IllegalState Failed to load Application
...
  AuditResourceIntTest.getNonExistingAudit » IllegalState Failed to load Applica
...
  AuditResourceIntTest.getNonExistingAuditsByDate » IllegalState Failed to load
...
  AuthorResourceIntTest.checkNameIsRequired » IllegalState Failed to load Applic
...
  AuthorResourceIntTest.createAuthor » IllegalState Failed to load ApplicationCo
...
  AuthorResourceIntTest.createAuthorWithExistingId » IllegalState Failed to load
...
  AuthorResourceIntTest.deleteAuthor » IllegalState Failed to load ApplicationCo
...
  AuthorResourceIntTest.equalsVerifier » IllegalState Failed to load Application
...
  AuthorResourceIntTest.getAllAuthors » IllegalState Failed to load ApplicationC
...
  AuthorResourceIntTest.getAuthor » IllegalState Failed to load ApplicationConte
...
  AuthorResourceIntTest.getNonExistingAuthor » IllegalState Failed to load Appli
...
  AuthorResourceIntTest.searchAuthor » IllegalState Failed to load ApplicationCo
...
  AuthorResourceIntTest.updateAuthor » IllegalState Failed to load ApplicationCo
...
  AuthorResourceIntTest.updateNonExistingAuthor » IllegalState Failed to load Ap
...
  UserResourceIntTest.equalsVerifier » IllegalState Failed to load ApplicationCo
...
  UserResourceIntTest.testGetExistingUser » IllegalState Failed to load Applicat
...
  UserResourceIntTest.testGetUnknownUser » IllegalState Failed to load Applicati
...

Tests run: 41, Failures: 0, Errors: 38, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:53 min
[INFO] Finished at: 2017-03-18T10:12:54+07:00
[INFO] Final Memory: 54M/456M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.
18.1:test (default-test) on project nsw-web: There are test failures.
[ERROR]
[ERROR] Please refer to G:\Learning\NSWWeb\target\surefire-reports for the indiv
idual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
ch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureExc
eption
</code>```

答:
You can't add attributes in User or columns in JHI_USER. It's necessary to use another approach.

Follow this article on jhipster official site.

Body:
I have a jhipter app and I want to add a salt column to jhi_user table. I have added a salt column to jhi_user table and I added salt property to User domain and UserDTO. When run mvnw -Pprod,swagger,no-liquibase package I got an error:

iveEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPro
pertiesSet(AbstractEntityManagerFactoryBean.java:362)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getOb
ject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
y.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBe
an(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:197)
        at org.springframework.context.support.AbstractApplicationContext.getBea
n(AbstractApplicationContext.java:1081)
        at org.springframework.context.support.AbstractApplicationContext.finish
BeanFactoryInitialization(AbstractApplicationContext.java:856)
        at org.springframework.context.support.AbstractApplicationContext.refres
h(AbstractApplicationContext.java:542)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.
java:737)
        at org.springframework.boot.SpringApplication.refreshContext(SpringAppli
cation.java:370)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java
:314)
        at org.springframework.boot.test.context.SpringBootContextLoader.loadCon
text(SpringBootContextLoader.java:120)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoader
Delegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoader
Delegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
        at org.springframework.test.context.support.DefaultTestContext.getApplic
ationContext(DefaultTestContext.java:83)
        at org.springframework.test.context.web.ServletTestExecutionListener.set
UpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
        at org.springframework.test.context.web.ServletTestExecutionListener.pre
pareTestInstance(ServletTestExecutionListener.java:131)
        at org.springframework.test.context.TestContextManager.prepareTestInstan
ce(TestContextManager.java:230)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.creat
eTest(SpringJUnit4ClassRunner.java:228)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.run
ReflectiveCall(SpringJUnit4ClassRunner.java:287)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCal
lable.java:12)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.metho
dBlock(SpringJUnit4ClassRunner.java:289)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runCh
ild(SpringJUnit4ClassRunner.java:247)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runCh
ild(SpringJUnit4ClassRunner.java:94)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClass
Callbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassC
allbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(S
pringJUnit4ClassRunner.java:191)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provide
r.java:283)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUni
t4Provider.java:173)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4
Provider.java:153)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider
.java:128)
        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameCla
ssLoader(ForkedBooter.java:203)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(Fork
edBooter.java:155)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:
103)
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-valid
ation: missing column [salt] in table [jhi_user]
        at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateTa
ble(AbstractSchemaValidator.java:136)
        at org.hibernate.tool.schema.internal.GroupedSchemaValidatorImpl.validat
eTables(GroupedSchemaValidatorImpl.java:42)
        at org.hibernate.tool.schema.internal.AbstractSchemaValidator.performVal
idation(AbstractSchemaValidator.java:89)
        at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidati
on(AbstractSchemaValidator.java:68)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.perform
DatabaseAction(SchemaManagementToolCoordinator.java:191)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process
(SchemaManagementToolCoordinator.java:72)
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.j
ava:309)
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFa
ctoryBuilderImpl.java:445)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build
(EntityManagerFactoryBuilderImpl.java:889)
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvi
der.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.ja
va:60)
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.cr
eateNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNat
iveEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPro
pertiesSet(AbstractEntityManagerFactoryBean.java:362)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getOb
ject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
y.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBe
an(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:197)
        at org.springframework.context.support.AbstractApplicationContext.getBea
n(AbstractApplicationContext.java:1081)
        at org.springframework.context.support.AbstractApplicationContext.finish
BeanFactoryInitialization(AbstractApplicationContext.java:856)
        at org.springframework.context.support.AbstractApplicationContext.refres
h(AbstractApplicationContext.java:542)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.
java:737)
        at org.springframework.boot.SpringApplication.refreshContext(SpringAppli
cation.java:370)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java
:314)
        at org.springframework.boot.test.context.SpringBootContextLoader.loadCon
text(SpringBootContextLoader.java:120)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoader
Delegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoader
Delegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
        at org.springframework.test.context.support.DefaultTestContext.getApplic
ationContext(DefaultTestContext.java:83)
        at org.springframework.test.context.web.ServletTestExecutionListener.set
UpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
        at org.springframework.test.context.web.ServletTestExecutionListener.pre
pareTestInstance(ServletTestExecutionListener.java:131)
        at org.springframework.test.context.TestContextManager.prepareTestInstan
ce(TestContextManager.java:230)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.creat
eTest(SpringJUnit4ClassRunner.java:228)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.run
ReflectiveCall(SpringJUnit4ClassRunner.java:287)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCal
lable.java:12)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.metho
dBlock(SpringJUnit4ClassRunner.java:289)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runCh
ild(SpringJUnit4ClassRunner.java:247)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runCh
ild(SpringJUnit4ClassRunner.java:94)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClass
Callbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassC
allbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(S
pringJUnit4ClassRunner.java:191)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provide
r.java:283)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUni
t4Provider.java:173)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4
Provider.java:153)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider
.java:128)
        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameCla
ssLoader(ForkedBooter.java:203)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(Fork
edBooter.java:155)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:
103)

Results :

Tests in error:
  UserServiceIntTest.assertThatAnonymousUserIsNotGet » IllegalState Failed to lo
...
  UserServiceIntTest.assertThatOnlyActivatedUserCanRequestPasswordReset » Illega
lState
  UserServiceIntTest.assertThatResetKeyMustBeValid » IllegalState Failed to load
...
  UserServiceIntTest.assertThatResetKeyMustNotBeOlderThan24Hours » IllegalState
...
  UserServiceIntTest.assertThatUserCanResetPassword » IllegalState Failed to loa
...
  UserServiceIntTest.assertThatUserMustExistToResetPassword » IllegalState Faile
...
  UserServiceIntTest.testFindNotActivatedUsersByCreationDateBefore » IllegalStat
e
  AccountResourceIntTest.testAuthenticatedUser » IllegalState Failed to load App
...
  AccountResourceIntTest.testGetExistingAccount » IllegalState Failed to load Ap
...
  AccountResourceIntTest.testGetUnknownAccount » IllegalState Failed to load App
...
  AccountResourceIntTest.testNonAuthenticatedUser » IllegalState Failed to load
...
  AccountResourceIntTest.testRegisterAdminIsIgnored » IllegalState Failed to loa
...
  AccountResourceIntTest.testRegisterDuplicateEmail » IllegalState Failed to loa
...
  AccountResourceIntTest.testRegisterDuplicateLogin » IllegalState Failed to loa
...
  AccountResourceIntTest.testRegisterInvalidEmail » IllegalState Failed to load
...
  AccountResourceIntTest.testRegisterInvalidLogin » IllegalState Failed to load
...
  AccountResourceIntTest.testRegisterInvalidPassword » IllegalState Failed to lo
...
  AccountResourceIntTest.testRegisterValid » IllegalState Failed to load Applica
...
  AccountResourceIntTest.testSaveInvalidLogin » IllegalState Failed to load Appl
...
  AuditResourceIntTest.getAllAudits » IllegalState Failed to load ApplicationCon
...
  AuditResourceIntTest.getAudit » IllegalState Failed to load ApplicationContext

  AuditResourceIntTest.getAuditsByDate » IllegalState Failed to load Application
...
  AuditResourceIntTest.getNonExistingAudit » IllegalState Failed to load Applica
...
  AuditResourceIntTest.getNonExistingAuditsByDate » IllegalState Failed to load
...
  AuthorResourceIntTest.checkNameIsRequired » IllegalState Failed to load Applic
...
  AuthorResourceIntTest.createAuthor » IllegalState Failed to load ApplicationCo
...
  AuthorResourceIntTest.createAuthorWithExistingId » IllegalState Failed to load
...
  AuthorResourceIntTest.deleteAuthor » IllegalState Failed to load ApplicationCo
...
  AuthorResourceIntTest.equalsVerifier » IllegalState Failed to load Application
...
  AuthorResourceIntTest.getAllAuthors » IllegalState Failed to load ApplicationC
...
  AuthorResourceIntTest.getAuthor » IllegalState Failed to load ApplicationConte
...
  AuthorResourceIntTest.getNonExistingAuthor » IllegalState Failed to load Appli
...
  AuthorResourceIntTest.searchAuthor » IllegalState Failed to load ApplicationCo
...
  AuthorResourceIntTest.updateAuthor » IllegalState Failed to load ApplicationCo
...
  AuthorResourceIntTest.updateNonExistingAuthor » IllegalState Failed to load Ap
...
  UserResourceIntTest.equalsVerifier » IllegalState Failed to load ApplicationCo
...
  UserResourceIntTest.testGetExistingUser » IllegalState Failed to load Applicat
...
  UserResourceIntTest.testGetUnknownUser » IllegalState Failed to load Applicati
...

Tests run: 41, Failures: 0, Errors: 38, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:53 min
[INFO] Finished at: 2017-03-18T10:12:54+07:00
[INFO] Final Memory: 54M/456M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.
18.1:test (default-test) on project nsw-web: There are test failures.
[ERROR]
[ERROR] Please refer to G:\Learning\NSWWeb\target\surefire-reports for the indiv
idual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
ch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureExc
eption


问:
Lua/Luajit: pause current Lua thread
I am currently using Luajit along side Lua 5.1 and currently trying to register a function called "Wait" within the Lua C APIs. The main purpose of the function is to pause the current thread.

Example usage:

```<code>print("Working");
Wait()
print("A");
</code>```

However the function does not work as expected. Here is my C++ code.

```<code>#include <iostream>
#include <Windows.h>

extern "C" {
    #include "Luajit/luajit.h"
    #include <Luajit/lua.h>
    #include <Luajit/lualib.h>
    #include <Luajit/lauxlib.h>
}

static int wait(lua_State* lua) {
    return lua_yield(lua, 0);
}

int main() {
    lua_State* lua = luaL_newstate();

    if (!lua) {
        std::cout << "Failed to create Lua state" << std::endl;
        system("PAUSE");
        return -1;
    }

luaL_openlibs(lua);
lua_register(lua, "Wait", wait);

lua_State* thread = lua_newthread(lua);

if (!thread) {
    std::cout << "Failed to create Lua thread" << std::endl;
    system("PAUSE");
    return -1;
}

int status = luaL_loadfile(thread, "Z:/Projects/Visual Studio/Examples/Lua/Debug/Main.lua");

if (status == LUA_ERRFILE) {
    std::cout << "Failed to load file" << std::endl;
    system("PAUSE");
    return -1;
}

int error = lua_pcall(thread, 0, 0, 0);

if (error) {
    std::cout << "Error: " << lua_tostring(thread, 1) << std::endl;
}

system("PAUSE");
return 0;
}
</code>```

When I load up the Lua script I posted above I get the following output:

```<code>Working
Error: attempt to yield across C-call boundary
Press any key to continue . . .
</code>```

I been programming in Lua for more than 4 years now. I just recently started using the C APIs and I never seen the C-call boundary error before. I did some Googling and ask friends and no one seems to be able to help me. Any idea what is wrong with my code?

The error occur when I call the lua_yield(lua, 0) function in C++.

I tried the answers of the following question and nothing seems to work.

```<code>http://stackoverflow.com/questions/8459459/lua-coroutine-error-tempt-to-yield-across-metamethod-c-call-boundary
</code>```

答: lua_pcall does not start a yieldable coroutine. The proper function to start a coroutine is lua_resume.

Title: Lua/Luajit: pause current Lua thread

Body:
I am currently using Luajit along side Lua 5.1 and currently trying to register a function called "Wait" within the Lua C APIs. The main purpose of the function is to pause the current thread.

Example usage:

print("Working");
Wait()
print("A");

However the function does not work as expected. Here is my C++ code.

#include <iostream>
#include <Windows.h>

extern "C" {
    #include "Luajit/luajit.h"
    #include <Luajit/lua.h>
    #include <Luajit/lualib.h>
    #include <Luajit/lauxlib.h>
}

static int wait(lua_State* lua) {
    return lua_yield(lua, 0);
}

int main() {
    lua_State* lua = luaL_newstate();

    if (!lua) {
        std::cout << "Failed to create Lua state" << std::endl;
        system("PAUSE");
        return -1;
    }

luaL_openlibs(lua);
lua_register(lua, "Wait", wait);

lua_State* thread = lua_newthread(lua);

if (!thread) {
    std::cout << "Failed to create Lua thread" << std::endl;
    system("PAUSE");
    return -1;
}

int status = luaL_loadfile(thread, "Z:/Projects/Visual Studio/Examples/Lua/Debug/Main.lua");

if (status == LUA_ERRFILE) {
    std::cout << "Failed to load file" << std::endl;
    system("PAUSE");
    return -1;
}

int error = lua_pcall(thread, 0, 0, 0);

if (error) {
    std::cout << "Error: " << lua_tostring(thread, 1) << std::endl;
}

system("PAUSE");
return 0;
}

When I load up the Lua script I posted above I get the following output:

Working
Error: attempt to yield across C-call boundary
Press any key to continue . . .

I been programming in Lua for more than 4 years now. I just recently started using the C APIs and I never seen the C-call boundary error before. I did some Googling and ask friends and no one seems to be able to help me. Any idea what is wrong with my code?

The error occur when I call the lua_yield(lua, 0) function in C++.

I tried the answers of the following question and nothing seems to work.

http://stackoverflow.com/questions/8459459/lua-coroutine-error-tempt-to-yield-across-metamethod-c-call-boundary


问:
Angular JS - How to apply / bind ng-model late (lazy)
I have a simple scenario in a large piece of code:

Angular APP & Controller (all working well)

one ng-model element is dynamically created later (or lets say it comes from an ajax call). How to bind this into that controller?

For example:

```<code>var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope)
{
  .
  .
  .
  .
  $scope.xyz='1';
}
.
.
.
//element created dynamically on click:
<input type="text" ng-model="xyz" />
.
</code>```

This is just an example, but it will solve the actual and larger problem if I know the solution.

Thanks a lot.

答: You need to use $compile. See AngularJS - Dynamically creating elements that specify directives</p>

Body:
I have a simple scenario in a large piece of code:

Angular APP & Controller (all working well)

one ng-model element is dynamically created later (or lets say it comes from an ajax call). How to bind this into that controller?

For example:

var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope)
{
  .
  .
  .
  .
  $scope.xyz='1';
}
.
.
.
//element created dynamically on click:
<input type="text" ng-model="xyz" />
.

This is just an example, but it will solve the actual and larger problem if I know the solution.

Thanks a lot.


问:
Bitbucket daily personal log
I've been using Bitbucket for a week now. It seems like a capable platform. Personally in my development activities, I keep a daily "journal" of whatever I need to keep track of separately from any commits to the Git repo. It gives me a place to keep all my "thoughts and ideas" in one place.

Before I end a day's work, or I jot down what I last worked on and any thoughts I think I'll need on the following day. And before I begin each day's work, I just flip to the last page of my journal and it quickly brings me back up to speed of where I was at yesterday, no matter how little sleep I got.  :-)

I see Bitbucket has "Comments", "Work Log", "History" and "Activity", but they seem to be tied only to user stories, todos and the like.

Does anyone know of a way where I can have something like a "Work Log" tied directly to my user account? I'm thinking I could use it for my personal "Journal".

Note: I'm using a locally installed Bitbucket server.

答:
If you are using JIRA and Bitbucket already, maybe consider Confluence? Confluence has some convenient and easy to manage TODO functionality and it lets you expand on those thoughts with all the power of a wiki when you are done.

I keep a "TODO" page and additionally put the checkbox on any tasks in other pages. They are all aggregated together in a tasks view.

See:
https://confluence.atlassian.com/conf54/confluence-user-s-guide/managing-changes-and-notifications-and-tasks/managing-tasks-in-confluence

Title: Bitbucket daily personal log


问:
Passing member function to function pointer
I have to pass in a function pointer of a member function to another class. I couldn't get it to compile and I get the "undefined reference to classB::classB(classA::*)(std::shared_ptr) " error. Can someone help me with this?

Thanks.

```<code>classA{
  string functionA(share_ptr<int>);
  void functionB(){
     classB* ptr = new classB(&classA::functionA);
  }
}

//in other .h file
classA; //forward declaration

classB{
  classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}
</code>```

答:
Just for giggles, going to answer this even though you said it compiled for you ...

```<code>// In a.hpp
#include "b.hpp" // you need to include this because you will not
                 // be able to call B's constructor in your functionB() method

class A
{
public:
  string functionA ( shared_ptr<int> ); // IIRC, needs to be public to call it
                                        // from B's constructor.

  // can be public/protected/private depending on where it's called ...
  void functionB () {
    B * ptrB = new B ( &A::functionA );
  }
};
</code>```

and

```<code>// In b.hpp

// Forward declare class A
class A;
// To make the constructor of B cleaner, use a typedef.
typedef string (A::*IntPtrToStrFn) ( shared_ptr<int> );

class B
{
public:
  B ( IntPtrToStrFn fnptr );
};
</code>```

As far as style and code readability goes, this is horrible - ties the two classes together and reaks of code smell. Need to look at some kind of adapter class or other design pattern to get the two classes to work together.

Body:
I have to pass in a function pointer of a member function to another class. I couldn't get it to compile and I get the "undefined reference to classB::classB(classA::*)(std::shared_ptr) " error. Can someone help me with this?

Thanks.

classA{
  string functionA(share_ptr<int>);
  void functionB(){
     classB* ptr = new classB(&classA::functionA);
  }
}

//in other .h file
classA; //forward declaration

classB{
  classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}

Body:
Just for giggles, going to answer this even though you said it compiled for you ...

// In a.hpp
#include "b.hpp" // you need to include this because you will not
                 // be able to call B's constructor in your functionB() method

class A
{
public:
  string functionA ( shared_ptr<int> ); // IIRC, needs to be public to call it
                                        // from B's constructor.

  // can be public/protected/private depending on where it's called ...
  void functionB () {
    B * ptrB = new B ( &A::functionA );
  }
};

and

// In b.hpp

// Forward declare class A
class A;
// To make the constructor of B cleaner, use a typedef.
typedef string (A::*IntPtrToStrFn) ( shared_ptr<int> );

class B
{
public:
  B ( IntPtrToStrFn fnptr );
};

As far as style and code readability goes, this is horrible - ties the two classes together and reaks of code smell. Need to look at some kind of adapter class or other design pattern to get the two classes to work together.


问:
How to use single quotes in the MySQL query in Python
So I am trying to create a script with a MySQL Query "show databases like 'login';"

I am able to use string substitution and use "login" but i am unable to get the single quotes around it.

Below is how I am trying to do it but i cant get the single quotes even if I escape it using "\".

```<code>  db = "'"+val+"'"
  print "DB...", db
  run.cmd("echo 'res = cur.execute(\"SHOW DATABASES like  %s;\")\n' >> /run.py" % (db))
</code>```

答: SHOW DATABASES like '\'%s\'';\" -> this is what worked. </p>

Body:
So I am trying to create a script with a MySQL Query "show databases like 'login';"

I am able to use string substitution and use "login" but i am unable to get the single quotes around it.

Below is how I am trying to do it but i cant get the single quotes even if I escape it using "\".

  db = "'"+val+"'"
  print "DB...", db
  run.cmd("echo 'res = cur.execute(\"SHOW DATABASES like  %s;\")\n' >> /run.py" % (db))


问:
Converting an IP Address into CIDR
I want to design a code where I can search an inputted IP address, and using it, it gives the output of the IP address' CIDR. I need the output being a variable as I need that CIDR for another step in the code. </p>

```<code> static void Main(string[] args)
 {
            IPAddress addr = IPAddress.Parse("8.8.8.8");
            IPHostEntry entry = Dns.GetHostEntry(addr);
            Console.WriteLine("IP Address: " + addr);
            Console.WriteLine("Host Name: " + entry.HostName);
</code>```

答:
I assume by CIDR you want to get the classful netmask length of the given IP address.
Using this wiki as a reference, you could convert the address to an array of bits, and then check the first leading bits.

This useful extension class converts your IP address to bits (booleans, really):

```<code>/// <summary>
/// Converts an array of bytes to a BitArray instance,
/// respecting the endian form of the operating system
/// </summary>
public static class BitArrayExtensions
{
    public static BitArray ToBitArray(this byte[] bytes)
    {
        bool[] allbits = new bool[bytes.Length * 8];
        for (int b = 0; b < bytes.Length; b++)
        {
            bool[] bits = new bool[8];
            new BitArray(new byte[] { bytes[b] }).CopyTo(bits, 0);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bits);

            bits.CopyTo(allbits, b * 8);
        }
        return new BitArray(allbits);
    }
}
</code>```

With this class at your disposal, it's quite easy to write a method that finds the classful mask length of the IP address: /8, /16 or /24

```<code>    /// <summary>
    /// Gets the length of the classful subnet mask of a given IPv4 address
    /// </summary>
    public int GetClassfulMaskbits(IPAddress address)
    {
        BitArray addressInBits = address.GetAddressBytes().ToBitArray();
        if (!addressInBits[0])  //leading bit = 0 => class A
            return 8; //default mask of class A = 255.0.0.0
        if(!addressInBits[1]) //leading bits = 10 => class B
            return 16; //default mask of class B = 255.255.0.0
        if (!addressInBits[2]) //leading bits = 110 => class C
            return 24; //default mask of class C = 255.255.255.0

        return 0; //class D or E has no classful subnet mask
    }
</code>```

The BitArray extension class could be useful for other IP calculations as well.

Title: Converting an IP Address into CIDR

Body:
I want to design a code where I can search an inputted IP address, and using it, it gives the output of the IP address' CIDR. I need the output being a variable as I need that CIDR for another step in the code.

 static void Main(string[] args)
 {
            IPAddress addr = IPAddress.Parse("8.8.8.8");
            IPHostEntry entry = Dns.GetHostEntry(addr);
            Console.WriteLine("IP Address: " + addr);
            Console.WriteLine("Host Name: " + entry.HostName);

Body:
I assume by CIDR you want to get the classful netmask length of the given IP address.
Using this wiki as a reference, you could convert the address to an array of bits, and then check the first leading bits.

This useful extension class converts your IP address to bits (booleans, really):

/// <summary>
/// Converts an array of bytes to a BitArray instance,
/// respecting the endian form of the operating system
/// </summary>
public static class BitArrayExtensions
{
    public static BitArray ToBitArray(this byte[] bytes)
    {
        bool[] allbits = new bool[bytes.Length * 8];
        for (int b = 0; b < bytes.Length; b++)
        {
            bool[] bits = new bool[8];
            new BitArray(new byte[] { bytes[b] }).CopyTo(bits, 0);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bits);

            bits.CopyTo(allbits, b * 8);
        }
        return new BitArray(allbits);
    }
}

With this class at your disposal, it's quite easy to write a method that finds the classful mask length of the IP address: /8, /16 or /24

    /// <summary>
    /// Gets the length of the classful subnet mask of a given IPv4 address
    /// </summary>
    public int GetClassfulMaskbits(IPAddress address)
    {
        BitArray addressInBits = address.GetAddressBytes().ToBitArray();
        if (!addressInBits[0])  //leading bit = 0 => class A
            return 8; //default mask of class A = 255.0.0.0
        if(!addressInBits[1]) //leading bits = 10 => class B
            return 16; //default mask of class B = 255.255.0.0
        if (!addressInBits[2]) //leading bits = 110 => class C
            return 24; //default mask of class C = 255.255.255.0

        return 0; //class D or E has no classful subnet mask
    }

The BitArray extension class could be useful for other IP calculations as well.


问:
ReactJS ES6 adding logic to the component
I have a chat feature and I'm trying to display an array of messages into my JSX code with a conditionally rendered className depending on a value in an object.

I'm really new to ES6 and React and I cannot figure how to go about this logic inside the JSX. I am using redux to map my state into props. For brevity, I've cut the code into its simplest form.

```<code>class ChatWidget extends Component {

  render() {
    return (
      <div className={chat.body}>
        {/* if from_id == 1 */}
        <div className={chat.float-right}>
            <p>  {/* message of from_id==1 */} </p>
        </div>
        {/* else */}
        <div className={chat.float-left}>
            <p> {/* else message here */} </p>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    messages: state.messages
  };
}
</code>```

Here is my sample JSON array.

```<code>[
        {
            msg_id: 1,
            to_id: 1,
            from_id: 2,
            message_id: "Marzipan jelly-o croissanty"
        },
        {
            msg_id: 2,
            to_id: 2,
            from_id: 1,
            message_id: "Jelly sw"
        }
]
</code>```

答:
You can use your messages array to create an array of JSX elements which can be used in another JSX expression for rendering.

Since you want the message with from_id == 1 to appear first you can use Array#sort to order the messages array
(to avoid mutating messages a shallow copy of the array is made using Array#slice).

You then then call Array#map on the newly returned array to iterate through the sorted messages creating new JSX on each iteration.

The code could look something like this:

```<code>class ChatWidget extends Component {

  render() {
    // deconstruct messages from props
    const {messages} = this.props;

    // Mutating data should be avoided and Array#sort mutates
    // the array so we use Array#slice to create a
    // shallow copy before we sort it
    const msgCopy = messages.slice();

    // sort messages so message where from_id === 1 is first
    const sorted = msgCopy.sort((a,b) => {
      return a.from_id - b.from_id;
    });

    // iterate through sorted array to create
    // an array JSX elements
    sorted.map(message => {
      const {from_id, message_id} = message;

      // Change class if from_id is 1
      const classToAdd = (from_id === 1) ? ('chat.convo + ' ' + chat.them'):('chat.convo');

      return (
        <div className={classToAdd}>
          <div className={chat.text}>
            <p>  { message_id } </p>
          </div>
        </div>
      );
    });

    // use sorted array as follows to create a div containing
    // a child div for each message
    return
    (
      <div className={chat.body}>
        {sorted}
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    messages: state.messages
  };
}
</code>```

Body:
I have a chat feature and I'm trying to display an array of messages into my JSX code with a conditionally rendered className depending on a value in an object.

I'm really new to ES6 and React and I cannot figure how to go about this logic inside the JSX. I am using redux to map my state into props. For brevity, I've cut the code into its simplest form.

class ChatWidget extends Component {

  render() {
    return (

        {/* if from_id == 1 */}

  {/* message of from_id==1 */}

        {/* else */}

 {/* else message here */}

    );
  }
}

function mapStateToProps(state) {
  return {
    messages: state.messages
  };
}

Here is my sample JSON array.

[
        {
            msg_id: 1,
            to_id: 1,
            from_id: 2,
            message_id: "Marzipan jelly-o croissanty"
        },
        {
            msg_id: 2,
            to_id: 2,
            from_id: 1,
            message_id: "Jelly sw"
        }
]

Body:
You can use your messages array to create an array of JSX elements which can be used in another JSX expression for rendering.

Since you want the message with from_id == 1 to appear first you can use Array#sort to order the messages array
(to avoid mutating messages a shallow copy of the array is made using Array#slice).

You then then call Array#map on the newly returned array to iterate through the sorted messages creating new JSX on each iteration.

The code could look something like this:

class ChatWidget extends Component {

  render() {
    // deconstruct messages from props
    const {messages} = this.props;

    // Mutating data should be avoided and Array#sort mutates
    // the array so we use Array#slice to create a
    // shallow copy before we sort it
    const msgCopy = messages.slice();

    // sort messages so message where from_id === 1 is first
    const sorted = msgCopy.sort((a,b) => {
      return a.from_id - b.from_id;
    });

    // iterate through sorted array to create
    // an array JSX elements
    sorted.map(message => {
      const {from_id, message_id} = message;

      // Change class if from_id is 1
      const classToAdd = (from_id === 1) ? ('chat.convo + ' ' + chat.them'):('chat.convo');

      return (
        <div className={classToAdd}>
          <div className={chat.text}>
            <p>  { message_id } </p>
          </div>
        </div>
      );
    });

    // use sorted array as follows to create a div containing
    // a child div for each message
    return
    (
      <div className={chat.body}>
        {sorted}
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    messages: state.messages
  };
}


问:
Creating an async webservice method
I've tried to read up on async methods and am now trying to create my own async method. The method is a webservice call that returns a list of error logs. I'm not sure that I've understood correctly so I thought I'd share my code to see if I should do anything different.

All I want the code to do is return a list of errorlogs by calling a method GetAllErrorLogs(), that is a synchronized method. Since it can take a second to fetch all the error logs I want to have the opportunity to do other stuff once I called the GetAllErrorLogs() method. Here is the code.

```<code>[WebMethod]
public async Task<List<ErrorLog>> GetAllErrorLogs()
{
    List<ErrorLog> errorLogs = new List<ErrorLog>();

    await System.Threading.Tasks.Task.Run(() => {
        errorLogs = ErrorLogRepository.GetAllErrorLogs();
    });

    if (errorLogs == null)
        return new List<ErrorLog>();

    return errorLogs;
}
</code>```

Thanks!

答:
Handling Async exceptions is also VERY VERY important.. although this is for a windows console app, the same principles should apply.

source: https://blogs.msdn.microsoft.com/ptorr/2014/12/10/async-exceptions-in-c/

```<code>  using System;
  using System.Runtime.CompilerServices;
  using System.Threading;
  using System.Threading.Tasks;

  namespace AsyncAndExceptions
  {
class Program
{
  static void Main(string[] args)
  {
    AppDomain.CurrentDomain.UnhandledException += (s, e) => Log("*** Crash! ***", "UnhandledException");
    TaskScheduler.UnobservedTaskException += (s, e) => Log("*** Crash! ***", "UnobservedTaskException");

    RunTests();

    // Let async tasks complete...
    Thread.Sleep(500);
    GC.Collect(3, GCCollectionMode.Forced, true);
  }

  private static async Task RunTests()
  {
    try
    {
      // crash
      // _1_VoidNoWait();

      // crash
      // _2_AsyncVoidAwait();

      // OK
      // _3_AsyncVoidAwaitWithTry();

      // crash - no await
      // _4_TaskNoWait();

      // crash - no await
      // _5_TaskAwait();

      // OK
      // await _4_TaskNoWait();

      // OK
      // await _5_TaskAwait();
    }
    catch (Exception ex) { Log("Exception handled OK"); }

    // crash - no try
    // await _4_TaskNoWait();

    // crash - no try
    // await _5_TaskAwait();
  }

  // Unsafe
  static void _1_VoidNoWait()
  {
    ThrowAsync();
  }

  // Unsafe
  static async void _2_AsyncVoidAwait()
  {
    await ThrowAsync();
  }

  // Safe
  static async void _3_AsyncVoidAwaitWithTry()
  {
    try { await ThrowAsync(); }
    catch (Exception ex) { Log("Exception handled OK"); }
  }

  // Safe only if caller uses await (or Result) inside a try
  static Task _4_TaskNoWait()
  {
    return ThrowAsync();
  }

  // Safe only if caller uses await (or Result) inside a try
  static async Task _5_TaskAwait()
  {
    await ThrowAsync();
  }

  // Helper that sets an exception asnychronously
  static Task ThrowAsync()
  {
    TaskCompletionSource tcs = new TaskCompletionSource();
    ThreadPool.QueueUserWorkItem(_ => tcs.SetException(new Exception("ThrowAsync")));
    return tcs.Task;
  }
  internal static void Log(string message, [CallerMemberName] string caller = "")
  {
    Console.WriteLine("{0}: {1}", caller, message);
  }
}
</code>```

}

Title: Creating an async webservice method

Body:
I've tried to read up on async methods and am now trying to create my own async method. The method is a webservice call that returns a list of error logs. I'm not sure that I've understood correctly so I thought I'd share my code to see if I should do anything different.

All I want the code to do is return a list of errorlogs by calling a method GetAllErrorLogs(), that is a synchronized method. Since it can take a second to fetch all the error logs I want to have the opportunity to do other stuff once I called the GetAllErrorLogs() method. Here is the code.

[WebMethod]
public async Task<List<ErrorLog>> GetAllErrorLogs()
{
    List<ErrorLog> errorLogs = new List<ErrorLog>();

    await System.Threading.Tasks.Task.Run(() => {
        errorLogs = ErrorLogRepository.GetAllErrorLogs();
    });

    if (errorLogs == null)
        return new List<ErrorLog>();

    return errorLogs;
}

Thanks!

Body:
Handling Async exceptions is also VERY VERY important.. although this is for a windows console app, the same principles should apply.

source: https://blogs.msdn.microsoft.com/ptorr/2014/12/10/async-exceptions-in-c/

  using System;
  using System.Runtime.CompilerServices;
  using System.Threading;
  using System.Threading.Tasks;

  namespace AsyncAndExceptions
  {
class Program
{
  static void Main(string[] args)
  {
    AppDomain.CurrentDomain.UnhandledException += (s, e) => Log("*** Crash! ***", "UnhandledException");
    TaskScheduler.UnobservedTaskException += (s, e) => Log("*** Crash! ***", "UnobservedTaskException");

    RunTests();

    // Let async tasks complete...
    Thread.Sleep(500);
    GC.Collect(3, GCCollectionMode.Forced, true);
  }

  private static async Task RunTests()
  {
    try
    {
      // crash
      // _1_VoidNoWait();

      // crash
      // _2_AsyncVoidAwait();

      // OK
      // _3_AsyncVoidAwaitWithTry();

      // crash - no await
      // _4_TaskNoWait();

      // crash - no await
      // _5_TaskAwait();

      // OK
      // await _4_TaskNoWait();

      // OK
      // await _5_TaskAwait();
    }
    catch (Exception ex) { Log("Exception handled OK"); }

    // crash - no try
    // await _4_TaskNoWait();

    // crash - no try
    // await _5_TaskAwait();
  }

  // Unsafe
  static void _1_VoidNoWait()
  {
    ThrowAsync();
  }

  // Unsafe
  static async void _2_AsyncVoidAwait()
  {
    await ThrowAsync();
  }

  // Safe
  static async void _3_AsyncVoidAwaitWithTry()
  {
    try { await ThrowAsync(); }
    catch (Exception ex) { Log("Exception handled OK"); }
  }

  // Safe only if caller uses await (or Result) inside a try
  static Task _4_TaskNoWait()
  {
    return ThrowAsync();
  }

  // Safe only if caller uses await (or Result) inside a try
  static async Task _5_TaskAwait()
  {
    await ThrowAsync();
  }

  // Helper that sets an exception asnychronously
  static Task ThrowAsync()
  {
    TaskCompletionSource tcs = new TaskCompletionSource();
    ThreadPool.QueueUserWorkItem(_ => tcs.SetException(new Exception("ThrowAsync")));
    return tcs.Task;
  }
  internal static void Log(string message, [CallerMemberName] string caller = "")
  {
    Console.WriteLine("{0}: {1}", caller, message);
  }
}

}


问:
C# Reflection: Getting the fields of a DataRow from a Typed DataSet
I am currently building a method that takes an object that is of type DataRow from a typed DataSet, and then returning a string in JSON format of the fields in the DataRow (for use in a Web Service).

By using System.Reflection, I am doing something like this :

```<code>public string getJson(DataRow r)
    {
        Type controlType = r.GetType();
        PropertyInfo[] props = controlType.GetProperties();
        foreach (PropertyInfo controlProperty in props)
        {

        }
        return "";
    }
</code>```

And then in the foreach statement, I would iterate every field and get the field name and value, and format it into JSON.

The problem is that when iterating over the props (of type PropertyInfo[]), I am getting properties that I do not want to be iterated over:

alt text http://img88.imageshack.us/img88/2001/datarowreflectionht0.gif

As you can see from the above image, I only need the fields that range from 0 - 11 in the props array, because those are the 'real fields' of this particular typed row.

So my question is, How can I get the fields of the Typed DataRow only, and not the other 'metadata' ?

[UPDATE with Solution]

As Mehrdad Afshari suggested, instead of using Reflection, I am using the Table.Columns array.

Here is the completed function:

```<code>public string GetJson(DataRow r)
{
    int index = 0;
    StringBuilder json = new StringBuilder();
    foreach (DataColumn item in r.Table.Columns)
    {
        json.Append(String.Format("\"{0}\" : \"{1}\"", item.ColumnName, r[item.ColumnName].ToString()));
        if (index < r.Table.Columns.Count - 1)
        {
            json.Append(", ");
        }
        index++;
    }
    return "{" + json.ToString() + "}";
}
</code>```

答: Why don't you use row.Table.Columns property instead of reflection?

OwnerDisplayName: Dreas Grech

Body:
I am currently building a method that takes an object that is of type DataRow from a typed DataSet, and then returning a string in JSON format of the fields in the DataRow (for use in a Web Service).

By using System.Reflection, I am doing something like this :

public string getJson(DataRow r)
    {
        Type controlType = r.GetType();
        PropertyInfo[] props = controlType.GetProperties();
        foreach (PropertyInfo controlProperty in props)
        {

        }
        return "";
    }

And then in the foreach statement, I would iterate every field and get the field name and value, and format it into JSON.

The problem is that when iterating over the props (of type PropertyInfo[]), I am getting properties that I do not want to be iterated over:

alt text http://img88.imageshack.us/img88/2001/datarowreflectionht0.gif

As you can see from the above image, I only need the fields that range from 0 - 11 in the props array, because those are the 'real fields' of this particular typed row.

So my question is, How can I get the fields of the Typed DataRow only, and not the other 'metadata' ?

[UPDATE with Solution]

As Mehrdad Afshari suggested, instead of using Reflection, I am using the Table.Columns array.

Here is the completed function:

public string GetJson(DataRow r)
{
    int index = 0;
    StringBuilder json = new StringBuilder();
    foreach (DataColumn item in r.Table.Columns)
    {
        json.Append(String.Format("\"{0}\" : \"{1}\"", item.ColumnName, r[item.ColumnName].ToString()));
        if (index < r.Table.Columns.Count - 1)
        {
            json.Append(", ");
        }
        index++;
    }
    return "{" + json.ToString() + "}";
}

LastEditorDisplayName: Dreas Grech

OwnerDisplayName: Mehrdad Afshari


问:
AWS Cognito - getSessionInBackground fails when ID token needs refreshing
My ID token is valid for an hour. When I call getSessionInBackground on the CognitoUser object in my service call after an hour, my call fails. Isn't this supposed to return a new ID token if the previous one has expired? Doesn't help that this behavior is not consistently reproducible - it only happens on some screens. Also, it only seems to be happening in Android, not iOS.</p>

答:
This happen cuz in the sdk is not completely thread safe, this bug happens in aws-sdk-version <2.3, cuz one thread reads the correct value and if the token is expired, it clears the cachedToken which leaves nothing for the second thread to read, and the second thread assumes that no tokens exist(while the first thread is refreshing the token) and hence throws a user not authorized exception.

If you are using aws-sdk2.2 this is prominent bug, and you can use the following code snippet to fix it:

```<code>new Thread(new Runnable() {

        @Override
        public void run() {

            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            CognitoUser user = userPool.getCurrentUser();

            user.getSessionInBackground(new AuthenticationHandler() {
                @Override
                public void onSuccess(final CognitoUserSession userSession) {
                    Log.d("Authenticator.java", userSession.getIdToken().getJWTToken().toString());
                    semaphore.release();
                    callback.onSuccess(userSession);
                }

                @Override
                public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String UserId) {

                    semaphore.release();
                    callback.onNeedsPassword();
                }

                @Override
                public void getMFACode(MultiFactorAuthenticationContinuation continuation) {

                    semaphore.release();
                    callback.onNeedsPassword();
                }

                @Override
                public void onFailure(final Exception exception) {

                    semaphore.release();
                    callback.onFailure(exception);
                }
            });
        }
    }).start();
</code>```

There is also a bug in the current aws-sdk-2.4 version, related to this which increases your network traffic if you make multiple calls to aws to get a new ID token.(its an edge case, but still)
https://github.com/aws/aws-sdk-android/pull/272

Body:
This happen cuz in the sdk is not completely thread safe, this bug happens in aws-sdk-version <2.3, cuz one thread reads the correct value and if the token is expired, it clears the cachedToken which leaves nothing for the second thread to read, and the second thread assumes that no tokens exist(while the first thread is refreshing the token) and hence throws a user not authorized exception.

If you are using aws-sdk2.2 this is prominent bug, and you can use the following code snippet to fix it:

new Thread(new Runnable() {

        @Override
        public void run() {

            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            CognitoUser user = userPool.getCurrentUser();

            user.getSessionInBackground(new AuthenticationHandler() {
                @Override
                public void onSuccess(final CognitoUserSession userSession) {
                    Log.d("Authenticator.java", userSession.getIdToken().getJWTToken().toString());
                    semaphore.release();
                    callback.onSuccess(userSession);
                }

                @Override
                public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String UserId) {

                    semaphore.release();
                    callback.onNeedsPassword();
                }

                @Override
                public void getMFACode(MultiFactorAuthenticationContinuation continuation) {

                    semaphore.release();
                    callback.onNeedsPassword();
                }

                @Override
                public void onFailure(final Exception exception) {

                    semaphore.release();
                    callback.onFailure(exception);
                }
            });
        }
    }).start();

There is also a bug in the current aws-sdk-2.4 version, related to this which increases your network traffic if you make multiple calls to aws to get a new ID token.(its an edge case, but still)
https://github.com/aws/aws-sdk-android/pull/272


问:
Android update TextView in Thread and Runnable
I want to make a simple timer in Android that updates a TextView every second. It simply counts seconds like in Minesweeper.

The problem is when i ignore the tvTime.setText(...) (make it //tvTime.setText(...), in LogCat will be printed the following number every second.
But when i want to set this number to a TextView (created in another Thread), the program crashes.

Does anyone have an idea how to solve this easily?

Here's the code (method is called on startup):

```<code>private void startTimerThread() {
    Thread th = new Thread(new Runnable() {
        private long startTime = System.currentTimeMillis();
        public void run() {
            while (gameState == GameState.Playing) {
                System.out.println((System.currentTimeMillis() - this.startTime) / 1000);
                tvTime.setText("" + ((System.currentTimeMillis() - this.startTime) / 1000));
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    th.start();
}
</code>```

EDIT:

Finally, I got it.
Here is the solution, for those who are interested in.

```<code>private void startTimerThread() {
    Thread th = new Thread(new Runnable() {
        private long startTime = System.currentTimeMillis();
        public void run() {
            while (gameState == GameState.Playing) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTime.setText(""+((System.currentTimeMillis()-startTime)/1000));
                    }
                });
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    th.start();
}
</code>```

答:
As an option use runOnUiThread() to change de views properties in the main thread.</p>

```<code>  runOnUiThread(new Runnable() {
        @Override
        public void run() {
                textView.setText("Stackoverflow is cool!");
        }
    });
</code>```

Body:
I want to make a simple timer in Android that updates a TextView every second. It simply counts seconds like in Minesweeper.

The problem is when i ignore the tvTime.setText(...) (make it //tvTime.setText(...), in LogCat will be printed the following number every second.
But when i want to set this number to a TextView (created in another Thread), the program crashes.

Does anyone have an idea how to solve this easily?

Here's the code (method is called on startup):

private void startTimerThread() {
    Thread th = new Thread(new Runnable() {
        private long startTime = System.currentTimeMillis();
        public void run() {
            while (gameState == GameState.Playing) {
                System.out.println((System.currentTimeMillis() - this.startTime) / 1000);
                tvTime.setText("" + ((System.currentTimeMillis() - this.startTime) / 1000));
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    th.start();
}

EDIT:

Finally, I got it.
Here is the solution, for those who are interested in.

private void startTimerThread() {
    Thread th = new Thread(new Runnable() {
        private long startTime = System.currentTimeMillis();
        public void run() {
            while (gameState == GameState.Playing) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTime.setText(""+((System.currentTimeMillis()-startTime)/1000));
                    }
                });
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    th.start();
}

Body:
As an option use runOnUiThread() to change de views properties in the main thread.

  runOnUiThread(new Runnable() {
        @Override
        public void run() {
                textView.setText("Stackoverflow is cool!");
        }
    });