问:
Spring Boot - How to log all requests and responses with exceptions in single place?
I'm working on REST API with spring boot. I need to log all requests with input params (with methods, eg. GET, POST, etc.), request path, query string, corresponding class method of this request, also response of this action, both success and errors. For example:

Successful request:

```<code>http://example.com/api/users/1
</code>```

Log should look something like this:

{
   HttpStatus: 200,
   path: "api/users/1",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 1
   },
   response: {
      user: {
        id: 1,
        username: "user123",
        email: "user123@example.com"
      }
   },
   exceptions: []
}
```
<p>Or <strong>request with error:</strong></p>
```http://example.com/api/users/9999
```
<p>Log should be something like this:</p>
<pre class="lang-json prettyprint-override"><code>{
   HttpStatus: 404,
   errorCode: 101,
   path: "api/users/9999",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 9999
   },
   returns: {
   },
   exceptions: [
     {
       exception: "UserNotFoundException",
       message: "User with id 9999 not found",
       exceptionId: "adhaskldjaso98d7324kjh989",
       stacktrace: ...................
   ]
}
</code>```

I want Request/Response to be a single entity, with custom information related to this entity, both in successful and error cases.

What is best practice in spring to achieve this, may be with filters? if yes, can you provide concrete example?

I've played with @ControllerAdvice and @ExceptionHandler, but as I mentioned, I need to handle all success and error requests in single place (and single log).

答:
After adding Actuators to the spring boot bassed application you have /trace endpoint available with latest requests informations. This endpoint is working based on TraceRepository and default implementation is InMemoryTraceRepository that saves last 100 calls. You can change this by implementing this interface by yourself and make it available as a Spring bean. For example to log all requests to log (and still use default implementation as a basic storage for serving info on /trace endpoint) I'm using this kind of implementation:

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.trace.InMemoryTraceRepository;
import org.springframework.boot.actuate.trace.Trace;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class LoggingTraceRepository implements TraceRepository {

  private static final Logger LOG = LoggerFactory.getLogger(LoggingTraceRepository.class);
  private final TraceRepository delegate = new InMemoryTraceRepository();

  @Override
  public List<Trace> findAll() {
    return delegate.findAll();
  }

  @Override
  public void add(Map<String, Object> traceInfo) {
    LOG.info(traceInfo.toString());
    this.delegate.add(traceInfo);
  }
}
</code>```

This traceInfo map contains basic informations about request and response in this kind of form:
{method=GET, path=/api/hello/John, headers={request={host=localhost:8080, user-agent=curl/7.51.0, accept=*/*}, response={X-Application-Context=application, Content-Type=text/plain;charset=UTF-8, Content-Length=10, Date=Wed, 29 Mar 2017 20:41:21 GMT, status=200}}}. There is NO response content here.

EDIT! Logging POST data

You can access POST data by overriding WebRequestTraceFilter, but don't think it is a good idea (e.g. all uploaded file content will go to logs)
Here is sample code, but don't use it:

```<code>package info.fingo.nuntius.acuate.trace;

import org.apache.commons.io.IOUtils;
import org.springframework.boot.actuate.trace.TraceProperties;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.boot.actuate.trace.WebRequestTraceFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class CustomWebTraceFilter extends WebRequestTraceFilter {

  public CustomWebTraceFilter(TraceRepository repository, TraceProperties properties) {
    super(repository, properties);
}

  @Override
  protected Map<String, Object> getTrace(HttpServletRequest request) {
    Map<String, Object> trace = super.getTrace(request);
    String multipartHeader = request.getHeader("content-type");
    if (multipartHeader != null && multipartHeader.startsWith("multipart/form-data")) {
        Map<String, Object> parts = new LinkedHashMap<>();
        try {
            request.getParts().forEach(
                    part -> {
                        try {
                            parts.put(part.getName(), IOUtils.toString(part.getInputStream(), Charset.forName("UTF-8")));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
            );
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }
        if (!parts.isEmpty()) {
            trace.put("multipart-content-map", parts);
        }
    }
    return trace;
  }
}
</code>```

Body:
I'm working on REST API with spring boot. I need to log all requests with input params (with methods, eg. GET, POST, etc.), request path, query string, corresponding class method of this request, also response of this action, both success and errors. For example:

Successful request:

http://example.com/api/users/1

Log should look something like this:

{
   HttpStatus: 200,
   path: "api/users/1",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 1
   },
   response: {
      user: {
        id: 1,
        username: "user123",
        email: "user123@example.com"
      }
   },
   exceptions: []
}

Or request with error:

http://example.com/api/users/9999

Log should be something like this:

{
   HttpStatus: 404,
   errorCode: 101,
   path: "api/users/9999",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 9999
   },
   returns: {
   },
   exceptions: [
     {
       exception: "UserNotFoundException",
       message: "User with id 9999 not found",
       exceptionId: "adhaskldjaso98d7324kjh989",
       stacktrace: ...................
   ]
}

I want Request/Response to be a single entity, with custom information related to this entity, both in successful and error cases.

What is best practice in spring to achieve this, may be with filters? if yes, can you provide concrete example?

I've played with @ControllerAdvice and @ExceptionHandler, but as I mentioned, I need to handle all success and error requests in single place (and single log).

Body:
After adding Actuators to the spring boot bassed application you have /trace endpoint available with latest requests informations. This endpoint is working based on TraceRepository and default implementation is InMemoryTraceRepository that saves last 100 calls. You can change this by implementing this interface by yourself and make it available as a Spring bean. For example to log all requests to log (and still use default implementation as a basic storage for serving info on /trace endpoint) I'm using this kind of implementation:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.trace.InMemoryTraceRepository;
import org.springframework.boot.actuate.trace.Trace;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class LoggingTraceRepository implements TraceRepository {

  private static final Logger LOG = LoggerFactory.getLogger(LoggingTraceRepository.class);
  private final TraceRepository delegate = new InMemoryTraceRepository();

  @Override
  public List<Trace> findAll() {
    return delegate.findAll();
  }

  @Override
  public void add(Map<String, Object> traceInfo) {
    LOG.info(traceInfo.toString());
    this.delegate.add(traceInfo);
  }
}

This traceInfo map contains basic informations about request and response in this kind of form:
{method=GET, path=/api/hello/John, headers={request={host=localhost:8080, user-agent=curl/7.51.0, accept=*/*}, response={X-Application-Context=application, Content-Type=text/plain;charset=UTF-8, Content-Length=10, Date=Wed, 29 Mar 2017 20:41:21 GMT, status=200}}}. There is NO response content here.

EDIT! Logging POST data

You can access POST data by overriding WebRequestTraceFilter, but don't think it is a good idea (e.g. all uploaded file content will go to logs)
Here is sample code, but don't use it:

package info.fingo.nuntius.acuate.trace;

import org.apache.commons.io.IOUtils;
import org.springframework.boot.actuate.trace.TraceProperties;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.boot.actuate.trace.WebRequestTraceFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class CustomWebTraceFilter extends WebRequestTraceFilter {

  public CustomWebTraceFilter(TraceRepository repository, TraceProperties properties) {
    super(repository, properties);
}

  @Override
  protected Map<String, Object> getTrace(HttpServletRequest request) {
    Map<String, Object> trace = super.getTrace(request);
    String multipartHeader = request.getHeader("content-type");
    if (multipartHeader != null && multipartHeader.startsWith("multipart/form-data")) {
        Map<String, Object> parts = new LinkedHashMap<>();
        try {
            request.getParts().forEach(
                    part -> {
                        try {
                            parts.put(part.getName(), IOUtils.toString(part.getInputStream(), Charset.forName("UTF-8")));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
            );
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }
        if (!parts.isEmpty()) {
            trace.put("multipart-content-map", parts);
        }
    }
    return trace;
  }
}


来源: stackexchange

问:
Path name can't find in java

Project File

config Folder

specificfiles.props

This is where my properties located but still it can't find the path..

I tried this

```<code>input = MainClass.class.getResourceAsStream("/config/specificfiles.props");
        if(input==null){
                System.out.println("Sorry, unable to find ");
            return;
        }
</code>```

and also this

```<code>String filename = "specificfiles.props";
        input = MainClass.class.getClassLoader().getResourceAsStream(filename);
        if(input==null){
                System.out.println("Sorry, unable to find " + filename);
            return;
        }
</code>```

I also tried these things no work.

specificfiles.props

/specificfiles.props

config/specificfiles.props

ProjectName/config/specificfiles.props

I try to search on other questions here but nothing solves my problem..
Please help!

答:
you could try this :

```<code>input = MainClass.class.getClassLoader().getResourceAsStream("config/specificfiles.props");
</code>```

In my project, I use above and it works.

ContentLicense: CC BY-SA 3.0

Title: Path name can't find in java

Body:
Project File

config Folder

specificfiles.props

This is where my properties located but still it can't find the path..

I tried this

input = MainClass.class.getResourceAsStream("/config/specificfiles.props");
        if(input==null){
                System.out.println("Sorry, unable to find ");
            return;
        }

and also this

String filename = "specificfiles.props";
        input = MainClass.class.getClassLoader().getResourceAsStream(filename);
        if(input==null){
                System.out.println("Sorry, unable to find " + filename);
            return;
        }

I also tried these things no work.

specificfiles.props

/specificfiles.props

config/specificfiles.props

ProjectName/config/specificfiles.props

I try to search on other questions here but nothing solves my problem..
Please help!

Body:
you could try this :

input = MainClass.class.getClassLoader().getResourceAsStream("config/specificfiles.props");

In my project, I use above and it works.


问:
Matlab - Can you combine 2 circular antenna arrays in one plot
I'm trying to do this using both Antenna Toolbox and Phased Array toolbox. But it's not allowing me to have multiple circular arrays. </p>

<p>Is there any way to combine 2 circular Antenna arrays and plot the summation of their phase patterns? </p>

答:
It's easy to plot more than 1 plot on the same axis in MATLAB:

```<code>hFigure = figure();
hAxes = axes();
set(hAxes, 'NextPlot', add); %<! New plot will be added instead of replacing
...
Plotting Code #001
...
Plotting Code #002
...
</code>```

If you have a function which plots in a new figure and you want to merge 2 figures you should use the abilities to extract data from a figure.

IF the data is a Line based you can extract data using the XData, YData and ZData (See Chart Line Properties).

Start with the Axes handler to get its children handlers and extract the data.

Then just add it to the other figure as explained above.

Body:
I'm trying to do this using both Antenna Toolbox and Phased Array toolbox. But it's not allowing me to have multiple circular arrays.

Is there any way to combine 2 circular Antenna arrays and plot the summation of their phase patterns?

Body:
It's easy to plot more than 1 plot on the same axis in MATLAB:

hFigure = figure();
hAxes = axes();
set(hAxes, 'NextPlot', add); %<! New plot will be added instead of replacing
...
Plotting Code #001
...
Plotting Code #002
...

If you have a function which plots in a new figure and you want to merge 2 figures you should use the abilities to extract data from a figure.

IF the data is a Line based you can extract data using the XData, YData and ZData (See Chart Line Properties).

Start with the Axes handler to get its children handlers and extract the data.

Then just add it to the other figure as explained above.


问:
how to change .do in struts 1 to .html for 1 action
Ex：when I click button submit, I will　go to

../showMemberList.do

Now I want to go action ShowMemberListAction but url change to

../showMemberList.html

Plz help me!

答:
Struts Framework by default appends .do extension.

You need to modify the action value as action="actionsomthing.html" for your expected result.


问:
How to insert text on the end of sql statement result?
For example, my sql command returns this

```<code> 01234567
</code>```

So how would I be able to insert text so it would return this at the end of the statement. So if I return multiple values, then TEXT would only appear at the end.

```<code> 01234567TEXT
</code>```

I cant seem to find too much online for assistance but I know this is possible. My current sql command is as follows:

```<code> SqlCommand command = new SqlCommand("SELECT PID = RIGHT(REPLICATE('0',8) + CAST(PID AS VARCHAR(8)),8) FROM dbo.MDRMASTER WHERE PARENTPID = @PARENTPID",con);
</code>```

Any help or a point to the right direction would be awesome. Thank you so much

UPDATE I misworded the question in the beginning. I ment to say at the end of the last statement. Thanks Siva for clearing that up. I did thumbs up everyone though. Thanks everyone for your help.

答:
If you want to input a text, for example "text"
then just do this:

select 'text'

You can then add it above or below the result of your actual query with UNION

Body:
For example, my sql command returns this

 01234567

So how would I be able to insert text so it would return this at the end of the statement. So if I return multiple values, then TEXT would only appear at the end.

 01234567TEXT

I cant seem to find too much online for assistance but I know this is possible. My current sql command is as follows:

 SqlCommand command = new SqlCommand("SELECT PID = RIGHT(REPLICATE('0',8) + CAST(PID AS VARCHAR(8)),8) FROM dbo.MDRMASTER WHERE PARENTPID = @PARENTPID",con);

Any help or a point to the right direction would be awesome. Thank you so much

UPDATE I misworded the question in the beginning. I ment to say at the end of the last statement. Thanks Siva for clearing that up. I did thumbs up everyone though. Thanks everyone for your help.


问:
Vertically connected images with line - CSS HTML
can anyone please suggest a method for creating a div portion like in the image. The height should depend on the outer div. I need to use this as a separator between two divs with text on its left and right. Each circled image should come next to the related heading

答:
HTML

```<code><div class="circle_small">0</div>
<div class="circle">Step 1</div>
<div class="circle">Step 2</div>
<div class="circle">Step 3</div>
<div class="circle_small_last">0</div>
</code>```

CSS

```<code>* {
    font-family: 'Segoe UI';
    font-size: 10pt;
}
.circle_small{
    position: relative;
    border: 2px solid #999;
    border-radius: 100%;
    width: 20px;
    line-height: 20px;
    text-align: center;
    margin-top: 50px;
    background-color: #fff;
    z-index: 2;
    left:15px;
  }
.circle_small_last{
  position: relative;
    border: 2px solid #999;
    border-radius: 100%;
    width: 20px;
    line-height: 20px;
    text-align: center;
    margin-top: 50px;
    background-color: #fff;
    z-index: 2;
    left:15px;
}
.circle {
    position: relative;
    border: 2px solid #999;
    border-radius: 100%;
    width: 50px;
    line-height: 50px;
    text-align: center;
    margin-top: 50px;
    background-color: #fff;
    z-index: 2;
}
.circle:first-child {
    margin-top: 0;
}
.circle:before {
    position: absolute;
    border: 1px solid #999;
    width: 0;
    height: 50px;
    display: block;
    content: '';
    left: 50%;
    z-index: 1;
    top: -54px;
    margin-left: -1px;
}
.circle:first-child:before {
    display: none;
}

.circle_small_last:before {
    position: absolute;
    border: 1px solid #999;
    width: 0;
    height: 50px;
    display: block;
    content: '';
    left: 50%;
    z-index: 1;
    top: -54px;
    margin-left: -1px;
}
.circle_small_last:last-child:before {
    display: none;
}
</code>```

Body:
HTML

<div class="circle_small">0</div>
<div class="circle">Step 1</div>
<div class="circle">Step 2</div>
<div class="circle">Step 3</div>
<div class="circle_small_last">0</div>

CSS

* {
    font-family: 'Segoe UI';
    font-size: 10pt;
}
.circle_small{
    position: relative;
    border: 2px solid #999;
    border-radius: 100%;
    width: 20px;
    line-height: 20px;
    text-align: center;
    margin-top: 50px;
    background-color: #fff;
    z-index: 2;
    left:15px;
  }
.circle_small_last{
  position: relative;
    border: 2px solid #999;
    border-radius: 100%;
    width: 20px;
    line-height: 20px;
    text-align: center;
    margin-top: 50px;
    background-color: #fff;
    z-index: 2;
    left:15px;
}
.circle {
    position: relative;
    border: 2px solid #999;
    border-radius: 100%;
    width: 50px;
    line-height: 50px;
    text-align: center;
    margin-top: 50px;
    background-color: #fff;
    z-index: 2;
}
.circle:first-child {
    margin-top: 0;
}
.circle:before {
    position: absolute;
    border: 1px solid #999;
    width: 0;
    height: 50px;
    display: block;
    content: '';
    left: 50%;
    z-index: 1;
    top: -54px;
    margin-left: -1px;
}
.circle:first-child:before {
    display: none;
}

.circle_small_last:before {
    position: absolute;
    border: 1px solid #999;
    width: 0;
    height: 50px;
    display: block;
    content: '';
    left: 50%;
    z-index: 1;
    top: -54px;
    margin-left: -1px;
}
.circle_small_last:last-child:before {
    display: none;
}


问:
Merge default options containing object with JSON Object
I need to merge these two objects to get below output using JS. Thanks in advance and its ok to use jquery library if needed

var defaultOptions = {
        count:3
    };

    var JSON = {
      one:{
        title:"something",
        count:15
      },
      two:{
        title:"another"
      }
    }

    // expecting

    var JSON = {
      one:{
        title:"something",
        count:15
      },
      two:{
        title:"another",
        count:3
      }
    }```

答:
It's like this:

function mergeObjs(){
  var a = [].slice.call(arguments), o = a.shift();
  for(var i=0,l=a.length; i<l; i++){
    for(var p in a[i]){
      o[p] = a[i][p];
    }
  }
  return o;
}
console.log(mergeObjs({neat:'totally'}, {cool:'works', someAry:[1,7,5,'test']}, {what:'now', really:7}));```


问:
Problem installing mysql gem on Snow Leopard: uninitialized constant MysqlCompat::MysqlRes
I've got a problem trying to install the Ruby mysql gem driver.

I recently upgraded to Snow Leopard and did the Hivelogic manual install of MySQL. This all seems to work fine as I can access mysql from the command line and make changes to the database.

My problem is that if I now use

```<code>rake db:migrate
</code>```

I get:

```<code>rake aborted!
uninitialized constant MysqlCompat::MysqlRes

(See full trace by running task with --trace)
</code>```

Now it appears that my mysql gem isn't working correctly as I can access MySQL fine from Python using the Python driver (which I compiled to). I therefore tried to rebuild the gem using the following command from this site: http://techliberty.blogspot.com/, (incidentally I am using a recent Intel MacBook Pro):

```<code>  sudo env ARCHFLAGS="-arch x86_64" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
</code>```

This compiles although I get No definition for the documentation:

```<code>  Building native extensions.  This could take a while...
  Successfully installed mysql-2.8.1
  1 gem installed
  Installing ri documentation for mysql-2.8.1...

  No definition for next_result

  No definition for field_name
  ...
</code>```

I'm a little stumped as my mysql_config is located in the correct place:

```<code> /usr/local/mysql/bin/mysql_config
</code>```

And I have removed all other instances of the mysql gem, from my system.

Any suggestions would be greatly appreciated. Many thanks.

PS I saw this previous post uninitialized constant MysqlCompat::MysqlRes (using mms2r gem) but it doesn't seem applicable for my version.

答:
I had this, or at least a similar, issue (Hivelogic was not involved and it was not an upgrade, but rather a new system).  I agree that it is probably a 64 bit issue.  I have a link for you, that after all the other head and butt scratching I did, finally saved my ass (and brain).

[http://forums.mysql.com/read.php?116,359591,359591]

Best of luck getting past this configuration BS and on to some coding.

ContentLicense: CC BY-SA 2.5

Body:
I've got a problem trying to install the Ruby mysql gem driver.

I recently upgraded to Snow Leopard and did the Hivelogic manual install of MySQL. This all seems to work fine as I can access mysql from the command line and make changes to the database.

My problem is that if I now use

rake db:migrate

I get:

rake aborted!
uninitialized constant MysqlCompat::MysqlRes

(See full trace by running task with --trace)

Now it appears that my mysql gem isn't working correctly as I can access MySQL fine from Python using the Python driver (which I compiled to). I therefore tried to rebuild the gem using the following command from this site: http://techliberty.blogspot.com/, (incidentally I am using a recent Intel MacBook Pro):

  sudo env ARCHFLAGS="-arch x86_64" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config

This compiles although I get No definition for the documentation:

  Building native extensions.  This could take a while...
  Successfully installed mysql-2.8.1
  1 gem installed
  Installing ri documentation for mysql-2.8.1...

  No definition for next_result

  No definition for field_name
  ...

I'm a little stumped as my mysql_config is located in the correct place:

 /usr/local/mysql/bin/mysql_config

And I have removed all other instances of the mysql gem, from my system.

Any suggestions would be greatly appreciated. Many thanks.

PS I saw this previous post uninitialized constant MysqlCompat::MysqlRes (using mms2r gem) but it doesn't seem applicable for my version.


问:
Env var returning null in path
I have set up to ENV Vars (Ubuntu 14.04)

```<code>CERT_PATH=/home/ubuntu/certs/developer.cert.co.uk.pem
CA_PATH=/home/ubuntu/certs/ca.pem
</code>```

I am then grabbing those values in a JS script

```<code>var certPath = process.env.CERT_PATH;
var caPath = process.env.CA_PATH;
</code>```

But I am stumped as to why one of the vars return null in the path:

```<code>-- console log here
CERT Path: null/certs/developer.cert.co.uk.pem
CA Path: /home/ubuntu/certs/ca.pem
</code>```

What I don't understand is the same setup on OSX does not have this issue.

答:
In the pipeline groovy script simply use
env.CERT_PATH = /home/ubuntu/certs/developer.cert.co.uk.pem</p>

ContentLicense: CC BY-SA 4.0

Title: Env var returning null in path

Body:
I have set up to ENV Vars (Ubuntu 14.04)

CERT_PATH=/home/ubuntu/certs/developer.cert.co.uk.pem
CA_PATH=/home/ubuntu/certs/ca.pem

I am then grabbing those values in a JS script

var certPath = process.env.CERT_PATH;
var caPath = process.env.CA_PATH;

But I am stumped as to why one of the vars return null in the path:

-- console log here
CERT Path: null/certs/developer.cert.co.uk.pem
CA Path: /home/ubuntu/certs/ca.pem

What I don't understand is the same setup on OSX does not have this issue.


问:
Not able to install VS-2013 with update 3
When I install visual studio I get below error. I tried multiple times but it's failing all the time. Knidly help me here.

Log file: Log file with error

答:
I found two error messages in your log file as below:

Applied non-vital package: trintrir_71, encountered error: 0x80070643, the error code ‘0x80070643’ is a general, since you used the ISO file to install, you can verify the integrity of it. Using the FCIV.exe tool to check the SHA1 value of the ISO, the expected value comes from VS 2013 SHA-1 Value, any discrepancy means the ISO is corrupted. After that, you can manually install the Visual Studio 2010 Tools for Office Runtime to solve this issue.

Applied non-vital package: vsupdate_kb2829760, encountered error: 0x80044000, for the error code, we can have a look at this: Error in installation log for Visual Studio 2013 Update 2 RC can be misleading, you can try to re-run the VS installer to repair it. Or go to Tools-Extensions and updates-Updates, now the latest updates for VS 2013 is VS 2013 update 5, you can find it under Updates tab, click it to install.

Meanwhile, there has some installation tips you can have a look: windows update is up-to-date, temporarily disable any antivirus software, clean up %temp% folder and re-run the VS installer as administrator.


问:
Linker "Duplicate Symbol" error due to circular reference
I have two header of a class and it's extension(generated by Xcode for NSManaged object). But I'm getting a linker error and I figured out it was due to a circular reference.

Conversation+CoreDataClass.h

```<code>NS_ASSUME_NONNULL_BEGIN

@interface Conversation : NSManagedObject

@end

NS_ASSUME_NONNULL_END

#import "Conversation+CoreDataProperties.h"
</code>```

Conversation+CoreDataProperties.h

```<code>#import "Conversation+CoreDataClass.h"

NS_ASSUME_NONNULL_BEGIN

@interface Conversation (CoreDataProperties)

+ (NSFetchRequest<Conversation *> *)fetchRequest;

@end

NS_ASSUME_NONNULL_END
</code>```

You can clearly see the circular reference here. I found this question where the problem was to add a @class declaration and remove the header. So I commented out the import statement in the Conversation+CoreDataProperties.h and added @class Conversation;. Now two errors pop up saying it's an undefined class. Have attached the screenshot of the error below. I don't quite understand why this is happening and what I need to do to fix it. Any help is much appreciated. Thanks!

Linker error

duplicate symbol _OBJC_CLASS_$_Conversation in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/Conversation+CoreDataClass.o
  duplicate symbol _OBJC_METACLASS_$_Conversation in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/Conversation+CoreDataClass.o
  duplicate symbol _OBJC_CLASS_$_ConversationDate in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/ConversationDate+CoreDataClass.o
  duplicate symbol _OBJC_METACLASS_$_ConversationDate in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/ConversationDate+CoreDataClass.o
  ld: 4 duplicate symbols for architecture arm64 clang: error: linker
  command failed with exit code 1 (use -v to see invocation)

答: Found the solution to my problem in this answer. I just had to remove the .m files from the Compile Sources.</p>

Body:
I have two header of a class and it's extension(generated by Xcode for NSManaged object). But I'm getting a linker error and I figured out it was due to a circular reference.

Conversation+CoreDataClass.h

NS_ASSUME_NONNULL_BEGIN

@interface Conversation : NSManagedObject

@end

NS_ASSUME_NONNULL_END

#import "Conversation+CoreDataProperties.h"

Conversation+CoreDataProperties.h

#import "Conversation+CoreDataClass.h"

NS_ASSUME_NONNULL_BEGIN

@interface Conversation (CoreDataProperties)

+ (NSFetchRequest<Conversation *> *)fetchRequest;

@end

NS_ASSUME_NONNULL_END

You can clearly see the circular reference here. I found this question where the problem was to add a @class declaration and remove the header. So I commented out the import statement in the Conversation+CoreDataProperties.h and added @class Conversation;. Now two errors pop up saying it's an undefined class. Have attached the screenshot of the error below. I don't quite understand why this is happening and what I need to do to fix it. Any help is much appreciated. Thanks!

Linker error

duplicate symbol _OBJC_CLASS_$_Conversation in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/Conversation+CoreDataClass.o
  duplicate symbol _OBJC_METACLASS_$_Conversation in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/Conversation+CoreDataClass.o
  duplicate symbol _OBJC_CLASS_$_ConversationDate in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/ConversationDate+CoreDataClass.o
  duplicate symbol _OBJC_METACLASS_$_ConversationDate in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/ConversationDate+CoreDataClass.o
  ld: 4 duplicate symbols for architecture arm64 clang: error: linker
  command failed with exit code 1 (use -v to see invocation)


问:
Understanding ReactElement proptype
I am playing around with material-uito learn about React. And I am wondering why I get the following error message :

Invalid prop 'rightIconButton' of type 'function' supplied to 'ListItem', expected a single ReactElement.

When I use a stateless component it work just fine but what if I need to have a stateful component or I need to access the props object.

How should it be done correctly?

```<code>class ParticipantList extends Component {
  render() {

    return (
        <List>
            {this.props.participants.map(function(participant){
                return (
                    <ListItem key={participant._id}
                    primaryText={participant.fullname()}
                    rightIconButton={participant.needHelp ? rightIconMenu : null}
                    />);
            })}
      </List>
    );
  }
}

class rightIconMenu extends Component {
  render(){
    return (
        <IconMenu iconButtonElement={menuIconButton}>
        <MenuItem>Action</MenuItem>
      </IconMenu>
    );
  }
};

const menuIconButton = (
      <IconButton
        touch={true}
        tooltip="more"
        tooltipPosition="bottom-left"
      >
        <ActionGrade color={pinkA200} />
      </IconButton>
);
</code>```

答:
The object rightIconMenu is a class. In JavaScript land, a class is essentially a JavaScript function, and at times, it is literally a JavaScript function (that is, if you are compiling ES6/ES2015/ES.next down to ES5).

Hence why the error message is saying 'rightIconButton' of type 'function' supplied to 'ListItem'. The identifier, rightIconButton, represents an uninitialized class, which, if you recall, is essentially a function. Based on ListItem's definition, rightIconButton must to be a React element, and not anything else, be it a string, number or a function.

In React, a way to suppress this error is to actually initialize said class (that semantically represents a component) using the following syntax:

```<code><rightIconButton />
{/* Just be sure to supply any necessary props */}
</code>```

And also, depending on the PropType defined in the ListItem component, double check with the library to confirm whether or not rightIconButton is optional. If it is not optional, then null may equally raise an error. Fortunately, a workaround may simply involve supplying an empty span, like so:

```<code>rightIconButton={participant.needHelp ? <rightIconMenu /> : <span />}
</code>```

Title: Understanding ReactElement proptype

Body:
I am playing around with material-uito learn about React. And I am wondering why I get the following error message :

Invalid prop 'rightIconButton' of type 'function' supplied to 'ListItem', expected a single ReactElement.

When I use a stateless component it work just fine but what if I need to have a stateful component or I need to access the props object.

How should it be done correctly?

class ParticipantList extends Component {
  render() {

    return (
        <List>
            {this.props.participants.map(function(participant){
                return (
                    <ListItem key={participant._id}
                    primaryText={participant.fullname()}
                    rightIconButton={participant.needHelp ? rightIconMenu : null}
                    />);
            })}
      </List>
    );
  }
}

class rightIconMenu extends Component {
  render(){
    return (
        <IconMenu iconButtonElement={menuIconButton}>
        <MenuItem>Action</MenuItem>
      </IconMenu>
    );
  }
};

const menuIconButton = (
      <IconButton
        touch={true}
        tooltip="more"
        tooltipPosition="bottom-left"
      >
        <ActionGrade color={pinkA200} />
      </IconButton>
);

Body:
The object rightIconMenu is a class. In JavaScript land, a class is essentially a JavaScript function, and at times, it is literally a JavaScript function (that is, if you are compiling ES6/ES2015/ES.next down to ES5).

Hence why the error message is saying 'rightIconButton' of type 'function' supplied to 'ListItem'. The identifier, rightIconButton, represents an uninitialized class, which, if you recall, is essentially a function. Based on ListItem's definition, rightIconButton must to be a React element, and not anything else, be it a string, number or a function.

In React, a way to suppress this error is to actually initialize said class (that semantically represents a component) using the following syntax:

<rightIconButton />
{/* Just be sure to supply any necessary props */}

And also, depending on the PropType defined in the ListItem component, double check with the library to confirm whether or not rightIconButton is optional. If it is not optional, then null may equally raise an error. Fortunately, a workaround may simply involve supplying an empty span, like so:

rightIconButton={participant.needHelp ? <rightIconMenu /> : <span />}


问:
How can I create a list of new objects in C#?
I'd like to create a list of objects for a list. I understand it possible to do this below but this isn't what I am after.

```<code>view.BindingContext =
                new ViewModel
            {
                List = new List<Section> {
                    new Section
                    {
                        Title = "Chapter 1",
                        List = new List<Reading> {
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                        }
                    },
                }
            };
</code>```

Instead of the code above I'd like to create new objects from another list of objects. so something like this;

```<code>view.BindingContext =
            new ViewModel
            {
                List = new List<Section>
                {
                 foreach(Chapter chapter in ChapterList)
                    {
                    new Section { Title = chapter.Title, List = chapter.ReadingList },
                    }
                }
            };
</code>```

答:
You could make a whole new list of the new object type you need to have list of.
And for each item in chapterlist, you could create a new list element and add it to the newly made list. So you could serialize or create an object for the each list element.</p>

```<code>new ViewModel
        {
            Newlist List<differentlist> = new List<differentlist>();

            List = new List<Section> {
                new Section
                {
                    var ChapterList = new List<ChapterList>();
                    foreach(var Chapter in ChapterList ){
                        differentlist new = {Title = String.Empty, List = String.Empty};
                        new.Title = Chapter.Title;
                        new.List = Chapter.list;
                        Newlist.Add(new);
                    };
              }
         }
</code>```

Body:
I'd like to create a list of objects for a list. I understand it possible to do this below but this isn't what I am after.

view.BindingContext =
                new ViewModel
            {
                List = new List
 {
                    new Section
                    {
                        Title = "Chapter 1",
                        List = new List<Reading> {
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                            new Reading { Title = "Title" Text = "abc" },
                        }
                    },
                }
            };

Instead of the code above I'd like to create new objects from another list of objects. so something like this;

view.BindingContext =
            new ViewModel
            {
                List = new List

                {
                 foreach(Chapter chapter in ChapterList)
                    {
                    new Section { Title = chapter.Title, List = chapter.ReadingList },
                    }
                }
            };

Body:
You could make a whole new list of the new object type you need to have list of.
And for each item in chapterlist, you could create a new list element and add it to the newly made list. So you could serialize or create an object for the each list element.

new ViewModel
        {
            Newlist List<differentlist> = new List<differentlist>();

            List = new List<Section> {
                new Section
                {
                    var ChapterList = new List<ChapterList>();
                    foreach(var Chapter in ChapterList ){
                        differentlist new = {Title = String.Empty, List = String.Empty};
                        new.Title = Chapter.Title;
                        new.List = Chapter.list;
                        Newlist.Add(new);
                    };
              }
         }


问:
How to edit user password in Rails with custom Devise controller? :require_no_authentication rendered or redirected
I tried to let the user from http://localhost:3000/account/password edit their passwords.

But I get this in the Rails log:

Started GET "/users/password/edit" for ::1 at 2017-03-30 10:10:32 +0800

Processing by Users::PasswordsController#edit as HTML

User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]

Redirected to http://localhost:3000/

Filter chain halted as :require_no_authentication rendered or redirected

Here is something that I tried.

rails g devise:controllers users

rails g devise:views users

Routes

```<code>devise_for :users, controllers: {
  registrations: 'users/registrations',
  sessions: 'users/sessions',
  passwords: 'users/passwords',
  confirmations: 'users/confirmations'
}

devise_scope :user do
  get 'sign_up', to: 'users/registrations#new'
  get 'sign_in', to: 'users/sessions#new'
  delete 'sign_out', to: 'users/sessions#destroy'
  get 'account/users', to: 'users/registrations#edit'
  get 'account/password', to: 'users/passwords#edit'
end
</code>```

Controller

app/controllers/users/passwords_controller.rb

```<code>class Users::PasswordsController < Devise::PasswordsController

  def edit
    # super
    @user = current_user
  end

def update
# super
@user = User.find(current_user.id)

if @user.update_with_password(user_params)
  bypass_sign_in(@user)
  redirect_to account_users_path, notice: "恭喜，密码更改成功。"
else
  render :edit
end

end

protected

def user_params
  params.require(:user).permit(:password, :password_confirmation)
end

end
</code>```

Views

app/views/users/passwords/edit.html.erb

```<code><%= link_to "Edit Password", account_password_path %>
</code>```

Any help will be welcome.

答:
Add this in your contoller

```<code>prepend_before_filter :require_no_authentication, :only => [ :edit, :update]
</code>```

if you are using latest version of rails the use:

```<code>prepend_before_action :require_no_authentication, only: [ :edit, :update]
</code>```

Body:
I tried to let the user from http://localhost:3000/account/password edit their passwords.

But I get this in the Rails log:

Started GET "/users/password/edit" for ::1 at 2017-03-30 10:10:32 +0800

Processing by Users::PasswordsController#edit as HTML

User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]

Redirected to http://localhost:3000/

Filter chain halted as :require_no_authentication rendered or redirected

Here is something that I tried.

rails g devise:controllers users

rails g devise:views users

Routes

devise_for :users, controllers: {
  registrations: 'users/registrations',
  sessions: 'users/sessions',
  passwords: 'users/passwords',
  confirmations: 'users/confirmations'
}

devise_scope :user do
  get 'sign_up', to: 'users/registrations#new'
  get 'sign_in', to: 'users/sessions#new'
  delete 'sign_out', to: 'users/sessions#destroy'
  get 'account/users', to: 'users/registrations#edit'
  get 'account/password', to: 'users/passwords#edit'
end

Controller

app/controllers/users/passwords_controller.rb

class Users::PasswordsController < Devise::PasswordsController

  def edit
    # super
    @user = current_user
  end

def update
# super
@user = User.find(current_user.id)

if @user.update_with_password(user_params)
  bypass_sign_in(@user)
  redirect_to account_users_path, notice: "恭喜，密码更改成功。"
else
  render :edit
end

end

protected

def user_params
  params.require(:user).permit(:password, :password_confirmation)
end

end

Views

app/views/users/passwords/edit.html.erb

<%= link_to "Edit Password", account_password_path %>

Any help will be welcome.

Body:
Add this in your contoller

prepend_before_filter :require_no_authentication, :only => [ :edit, :update]

if you are using latest version of rails the use:

prepend_before_action :require_no_authentication, only: [ :edit, :update]


问:
Fast calculation of cosine similarity of one vector with many
I'm keen to hear ideas for optimising code to compute the cosine similarity of a vector x (with length l) with n other vectors (stored in any structure such as a matrix m with n rows and l columns).

Values for n will typically be much larger than values for l.

I'm currently using this custom Rcpp function to compute the similarity of a vector x to each row of a matrix m:

```<code>library(Rcpp)
cppFunction('NumericVector cosine_x_to_m(NumericVector x, NumericMatrix m) {
  int nrows = m.nrow();
  NumericVector out(nrows);
  for (int i = 0; i < nrows; i++) {
    NumericVector y = m(i, _);
    out[i] = sum(x * y) / sqrt(sum(pow(x, 2.0)) * sum(pow(y, 2.0)));
  }
  return out;
}')
</code>```

Varying n and l, I'm getting the following sorts of timings:

Reproducible code below.

```<code># Function to simulate data
sim_data <- function(l, n) {
  # Feature vector to be used for computing similarity
  x <- runif(l)

  # Matrix of feature vectors (1 per row) to compare against x
  m <- matrix(runif(n * l), nrow = n)

  list(x = x, m = m)
}

# Rcpp function to compute similarity of x to each row of m
library(Rcpp)
cppFunction('NumericVector cosine_x_to_m(NumericVector x, NumericMatrix m) {
  int nrows = m.nrow();
  NumericVector out(nrows);
  for (int i = 0; i < nrows; i++) {
    NumericVector y = m(i, _);
    out[i] = sum(x * y) / sqrt(sum(pow(x, 2.0)) * sum(pow(y, 2.0)));
  }
  return out;
}')

# Timer function
library(microbenchmark)
timer <- function(l, n) {
  dat <- sim_data(l, n)
  microbenchmark(cosine_x_to_m(dat$x, dat$m))
}

# Results for grid of l and n
library(tidyverse)
results <- cross_d(list(l = seq(200, 1000, by = 200), n = seq(500, 4000, by = 500))) %>%
  mutate(timings = map2(l, n, timer))

# Plot results
results_plot <- results %>%
  unnest(timings) %>%
  mutate(time = time / 1000000) %>%  # Convert time to seconds
  group_by(l, n) %>%
  summarise(mean = mean(time), ci = 1.96 * sd(time) / sqrt(n()))

pd <- position_dodge(width = 20)

results_plot %>%
  ggplot(aes(n, mean, group= l)) +
  geom_line(aes(color = factor(l)), position = pd, size = 2) +
  geom_errorbar(aes(ymin = mean - ci, ymax = mean + ci), position = pd, width = 100) +
  geom_point(position = pd, size = 2) +
  scale_color_brewer(palette = "Blues") +
  theme_minimal() +
  labs(x = "n", y = "Seconds", color = "l") +
  ggtitle("Algorithm Runtime",
          subtitle = "Error bars represent 95% confidence intervals")
</code>```

答:
I'm using Microsoft R (with Intel MKL) which makes matrix multiplications faster, but for fair comparison I set it to be single threaded.

```<code>setMKLthreads(1)
</code>```

In my tests this pure R version cosine_x_to_m is twice faster than yours.

```<code>cosine_x_to_m2 = function(x,m){
  x = x / sqrt(crossprod(x));
  return(  as.vector((m %*% x) / sqrt(rowSums(m^2))) );
}
</code>```

Rewriting rowSums(m^2) in C/C++ makes it even faster, about four times faster than the original.

```<code>library(ramwas)
cosine_x_to_m2 = function(x,m){
  x = x / sqrt(crossprod(x));
  return(  as.vector((m %*% x) / sqrt(rowSumsSq(m))) );
}
</code>```

Initial performance:

Final version performance:

Body:
I'm keen to hear ideas for optimising code to compute the cosine similarity of a vector x (with length l) with n other vectors (stored in any structure such as a matrix m with n rows and l columns).

Values for n will typically be much larger than values for l.

I'm currently using this custom Rcpp function to compute the similarity of a vector x to each row of a matrix m:

library(Rcpp)
cppFunction('NumericVector cosine_x_to_m(NumericVector x, NumericMatrix m) {
  int nrows = m.nrow();
  NumericVector out(nrows);
  for (int i = 0; i < nrows; i++) {
    NumericVector y = m(i, _);
    out[i] = sum(x * y) / sqrt(sum(pow(x, 2.0)) * sum(pow(y, 2.0)));
  }
  return out;
}')

Varying n and l, I'm getting the following sorts of timings:

Reproducible code below.

# Function to simulate data
sim_data <- function(l, n) {
  # Feature vector to be used for computing similarity
  x <- runif(l)

  # Matrix of feature vectors (1 per row) to compare against x
  m <- matrix(runif(n * l), nrow = n)

  list(x = x, m = m)
}

# Rcpp function to compute similarity of x to each row of m
library(Rcpp)
cppFunction('NumericVector cosine_x_to_m(NumericVector x, NumericMatrix m) {
  int nrows = m.nrow();
  NumericVector out(nrows);
  for (int i = 0; i < nrows; i++) {
    NumericVector y = m(i, _);
    out[i] = sum(x * y) / sqrt(sum(pow(x, 2.0)) * sum(pow(y, 2.0)));
  }
  return out;
}')

# Timer function
library(microbenchmark)
timer <- function(l, n) {
  dat <- sim_data(l, n)
  microbenchmark(cosine_x_to_m(dat$x, dat$m))
}

# Results for grid of l and n
library(tidyverse)
results <- cross_d(list(l = seq(200, 1000, by = 200), n = seq(500, 4000, by = 500))) %>%
  mutate(timings = map2(l, n, timer))

# Plot results
results_plot <- results %>%
  unnest(timings) %>%
  mutate(time = time / 1000000) %>%  # Convert time to seconds
  group_by(l, n) %>%
  summarise(mean = mean(time), ci = 1.96 * sd(time) / sqrt(n()))

pd <- position_dodge(width = 20)

results_plot %>%
  ggplot(aes(n, mean, group= l)) +
  geom_line(aes(color = factor(l)), position = pd, size = 2) +
  geom_errorbar(aes(ymin = mean - ci, ymax = mean + ci), position = pd, width = 100) +
  geom_point(position = pd, size = 2) +
  scale_color_brewer(palette = "Blues") +
  theme_minimal() +
  labs(x = "n", y = "Seconds", color = "l") +
  ggtitle("Algorithm Runtime",
          subtitle = "Error bars represent 95% confidence intervals")

Body:
I'm using Microsoft R (with Intel MKL) which makes matrix multiplications faster, but for fair comparison I set it to be single threaded.

setMKLthreads(1)

In my tests this pure R version cosine_x_to_m is twice faster than yours.

cosine_x_to_m2 = function(x,m){
  x = x / sqrt(crossprod(x));
  return(  as.vector((m %*% x) / sqrt(rowSums(m^2))) );
}

Rewriting rowSums(m^2) in C/C++ makes it even faster, about four times faster than the original.

library(ramwas)
cosine_x_to_m2 = function(x,m){
  x = x / sqrt(crossprod(x));
  return(  as.vector((m %*% x) / sqrt(rowSumsSq(m))) );
}

Initial performance:

Final version performance:


问:
Rails set(wait: 2.minutes) method for active job does not works
Creating an background job with the resque_scheduler gem on Redis server.

```<code> class Estamps::OrderAssignment < ActiveRecord::Base

  after_save :enqueue_check_status

   def enqueue_check_status
       AutoRejectionJob.set(wait: 2.minutes).perform_later(self.id)
   end
 end

 class AutoRejectionJob < ActiveJob::Base
   queue_as :default

   def perform(*args)
    order_assignment_id = args[0]
    order_assignment = Estamps::OrderAssignment.find(order_assignment_id)
    if order_assignment.status_id == 1 || order_assignment.status_id == nil
      order_assignment.status_id = 3
      order_assignment.save!
    end
  end
 end
</code>```

On creation of OrderAssignment record or when updated after 2 minutes it should run AutoRejection Job. Here the prob is the set(wait: 2.minutes) does not seem to run, i.e.

```<code>   AutoRejectionJob.perform_later(self.id)
</code>```

works perfectly fine, but

```<code>  AutoRejectionJob.set(wait: 2.minutes).perform_later(self.id)
</code>```

does nothing. Haven't been able to rectify the issue. Newbie to Rails so please help.

答:
I see no problem with your code.
I checked : .set(wait: 2.minutes) works as expected in rails 5.0.2 on top of ruby 2.4.0

So does your call of the job.
The way I see it, you're trying to set a status used elsewhere.
Probably,  the error is due to the OrderAssignment being manipulated in an outside treatment (destroyed ?)

Since you said you're new to rails (I suppose that's what "newbie" means) I'm going to make some suggestions. Disregard them if you're past that ...

There also are some great debugging tools out there to help you find what's going on : byebug, better_errors, pry and of course, the rails console.
Do yourself a favor : try them.

When I can't find my way around some behavior that goes beyond my grasp, I use some "puts", and some  "try / catch errors" structures (begin rescue ensure in ruby)...  :

```<code>def perform(*args)
  puts "@@@@@@@ JOB TRIGGERED @@@@@@"
  begin
    order_assignment_id = args[0]
    order_assignment = Estamps::OrderAssignment.find(order_assignment_id)
    puts "#{order_assignment.inspect}"
    if order_assignment.status_id == 1 || order_assignment.status_id == nil
      order_assignment.status_id = 3
      order_assignment.save!
    end
    puts "@@@@@@@ JOB DONE @@@@@@"
  rescue StandardError => e
    # ... display e.message ...
  ensure
    #...
  end
end
</code>```

Body:
Creating an background job with the resque_scheduler gem on Redis server.

 class Estamps::OrderAssignment < ActiveRecord::Base

  after_save :enqueue_check_status

   def enqueue_check_status
       AutoRejectionJob.set(wait: 2.minutes).perform_later(self.id)
   end
 end

 class AutoRejectionJob < ActiveJob::Base
   queue_as :default

   def perform(*args)
    order_assignment_id = args[0]
    order_assignment = Estamps::OrderAssignment.find(order_assignment_id)
    if order_assignment.status_id == 1 || order_assignment.status_id == nil
      order_assignment.status_id = 3
      order_assignment.save!
    end
  end
 end

On creation of OrderAssignment record or when updated after 2 minutes it should run AutoRejection Job. Here the prob is the set(wait: 2.minutes) does not seem to run, i.e.

   AutoRejectionJob.perform_later(self.id)

works perfectly fine, but

  AutoRejectionJob.set(wait: 2.minutes).perform_later(self.id)

does nothing. Haven't been able to rectify the issue. Newbie to Rails so please help.

Body:
I see no problem with your code.
I checked : .set(wait: 2.minutes) works as expected in rails 5.0.2 on top of ruby 2.4.0

So does your call of the job.
The way I see it, you're trying to set a status used elsewhere.
Probably,  the error is due to the OrderAssignment being manipulated in an outside treatment (destroyed ?)

Since you said you're new to rails (I suppose that's what "newbie" means) I'm going to make some suggestions. Disregard them if you're past that ...

There also are some great debugging tools out there to help you find what's going on : byebug, better_errors, pry and of course, the rails console.
Do yourself a favor : try them.

When I can't find my way around some behavior that goes beyond my grasp, I use some "puts", and some  "try / catch errors" structures (begin rescue ensure in ruby)...  :

def perform(*args)
  puts "@@@@@@@ JOB TRIGGERED @@@@@@"
  begin
    order_assignment_id = args[0]
    order_assignment = Estamps::OrderAssignment.find(order_assignment_id)
    puts "#{order_assignment.inspect}"
    if order_assignment.status_id == 1 || order_assignment.status_id == nil
      order_assignment.status_id = 3
      order_assignment.save!
    end
    puts "@@@@@@@ JOB DONE @@@@@@"
  rescue StandardError => e
    # ... display e.message ...
  ensure
    #...
  end
end


问:
Update Column of a Hive Table without using Sub query
This is a question regarding updating a new column in a Hive table.  Since I think Hive does not allow to update a column of an existing table using subqueries, I wanted to ask what will be the best way to achieve the following update operation.

I have the following two example tables:

Table A:

KeyId ValId Val

   W1    V1    10

   W2    V2    20

Table B:

KeyId ValId Val

   W1    V1    10

   W1    V1    30

   W1    V3    40

   W1    V4    50

   W2    V2    0

   W2    V2    50

   W2    V2    70

   W2    V4    80

I want to create another column in Table A, lets say avgVal that takes the KeyId and ValId in each row in Table A and takes the average of Val for those corresponding KeyId and ValId in Table B.  Thus, my final output table should look like:

Updated Table A:

KeyId ValId Val   avgVal

   W1    V1    10     20

   W2    V2    20     40

Please let me know if the question is not clear.

答:
You can use below query to get avg of data in Table_B corresponding to row in table_A :-

```<code>    select t1.keyid, t1.valid , t1.val , avgval from table_A t1 left join
(select keyid as k , valid as v, avg(val) as avgval from Table_B group by keyid,valid )temp
 on k=t1.keyid and t1.valid=v;
</code>```

You have to check the table_A is updatable to change the schema else you can make other table to load the data.

Body:
You can use below query to get avg of data in Table_B corresponding to row in table_A :-

    select t1.keyid, t1.valid , t1.val , avgval from table_A t1 left join
(select keyid as k , valid as v, avg(val) as avgval from Table_B group by keyid,valid )temp
 on k=t1.keyid and t1.valid=v;

You have to check the table_A is updatable to change the schema else you can make other table to load the data.


问:
Automatically passing focus betwen EditText
Since my question asking about separating characters that are typed in an EditText into groups or blocks didn't receive much attention, I've come here with another question on an alternative way to accomplish what I need.

So, my idea is to have four EditText that have 4 char length. Now what I want is to change the focus as the user type, from an EdutText to another when the limit is reached.
Example: Let's say we have EditText A, B, C, D; the first to gain focus is EditText A, then when the chars length at A reach 4, the focus passes to EditText B and so on and stops At D.

I'm trying something like the code bellow, but the focus is not requested when the length reaches 4 chars.

```<code>inputFieldA.requestFocus();

    inputFieldA.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldB.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldB.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldC.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldC.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldD.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldD.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                //send all to Main EditText (A + B + C + D)
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
</code>```

So I'm here asking if there is a way to do that.

答:
Write your conditions in afterTextChanged method and make changes as follows :</p>

```<code>inputFieldA.requestFocus();

    inputFieldA.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(inputFieldA.getText().toString().trim().length() == 4){
                inputFieldB.requestFocus();
            }
        }
    });
    inputFieldB.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(inputFieldB.getText().toString().trim().length() == 4){
                inputFieldC.requestFocus();
            }
        }
    });
    inputFieldC.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(inputFieldC.getText().toString().trim().length() == 4){
                inputFieldD.requestFocus();
            }
        }
    });
    inputFieldD.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(inputFieldD.getText().toString().trim().length() == 4){
                //send all to Main EditText (A + B + C + D)
            }
        }
    });
</code>```

Body:
Since my question asking about separating characters that are typed in an EditText into groups or blocks didn't receive much attention, I've come here with another question on an alternative way to accomplish what I need.

So, my idea is to have four EditText that have 4 char length. Now what I want is to change the focus as the user type, from an EdutText to another when the limit is reached.
Example: Let's say we have EditText A, B, C, D; the first to gain focus is EditText A, then when the chars length at A reach 4, the focus passes to EditText B and so on and stops At D.

I'm trying something like the code bellow, but the focus is not requested when the length reaches 4 chars.

inputFieldA.requestFocus();

    inputFieldA.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldB.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldB.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldC.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldC.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldD.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldD.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                //send all to Main EditText (A + B + C + D)
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

So I'm here asking if there is a way to do that.

Body:
Write your conditions in afterTextChanged method and make changes as follows :

inputFieldA.requestFocus();

    inputFieldA.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(inputFieldA.getText().toString().trim().length() == 4){
                inputFieldB.requestFocus();
            }
        }
    });
    inputFieldB.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(inputFieldB.getText().toString().trim().length() == 4){
                inputFieldC.requestFocus();
            }
        }
    });
    inputFieldC.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(inputFieldC.getText().toString().trim().length() == 4){
                inputFieldD.requestFocus();
            }
        }
    });
    inputFieldD.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(inputFieldD.getText().toString().trim().length() == 4){
                //send all to Main EditText (A + B + C + D)
            }
        }
    });


问:
Git Revert Remote Branch
I am stuck with this problem: there have been a few commits, including some merged commits which have corrupted the remote development branch.

I have the commit where everything was fine. I want to revert all changes post this commit. Effectively, I want the commit where everything was fine to be the active branch locally and remotely.

答:
Assume the local branch is X, the remote is origin and the branch there is also X. There are 2 scenarios. The first is if someone has modified origin/X (i.e. the X branch on the remote server) after your push and you care about those modifications. The second is if no one has modified it or you don't care about the modifications.

In the first scenario, origin/X looks something like this

```<code>1 - 2 - 3 - 4 - 5 - 6
</code>```

X currently points to 6, your "good commit" is at 2 and your bad commits are 3 and 4, 5 and 6 are pushed by someone else and are necessary for the project. In this case you can do the following on your own branch

```<code>git pull # This will fetch `5` and `6`
git revert `3` `4` # Will apply reverse patches "removing" `3` and `4`
</code>```

Your tree will be like so now

```<code>1 - 2 - 3 - 4 - 5 - 6 - 7 - 8
</code>```

where 7 is the opposite of 3 and 8 is the opposite of 4. This will change your code to look like it has 1, 2, 5 and 6. Then you just git push origin X your local repo.

In the second scenario, you don't care about 5 and 6 (or they don't exist). This allows you to reset your branch. Simply do

```<code> git reset --hard `2`
 git push --force origin X
</code>```

And you'll be done. The extra commits after 2 will be completely destroyed.

Title: Git Revert Remote Branch

Body:
Assume the local branch is X, the remote is origin and the branch there is also X. There are 2 scenarios. The first is if someone has modified origin/X (i.e. the X branch on the remote server) after your push and you care about those modifications. The second is if no one has modified it or you don't care about the modifications.

In the first scenario, origin/X looks something like this

1 - 2 - 3 - 4 - 5 - 6

X currently points to 6, your "good commit" is at 2 and your bad commits are 3 and 4, 5 and 6 are pushed by someone else and are necessary for the project. In this case you can do the following on your own branch

git pull # This will fetch `5` and `6`
git revert `3` `4` # Will apply reverse patches "removing" `3` and `4`

Your tree will be like so now

1 - 2 - 3 - 4 - 5 - 6 - 7 - 8

where 7 is the opposite of 3 and 8 is the opposite of 4. This will change your code to look like it has 1, 2, 5 and 6. Then you just git push origin X your local repo.

In the second scenario, you don't care about 5 and 6 (or they don't exist). This allows you to reset your branch. Simply do

 git reset --hard `2`
 git push --force origin X

And you'll be done. The extra commits after 2 will be completely destroyed.


问:
Retrieving the value of textarea in a v-for array
Considering this scenario

At .vue template

```<code><div v-for="(tweet, index) in tweets">
  <div class="each_tweet">
    <textarea v-on:keyup="typing(index)"
              placeholder="What's happening now">{{ tweet.content }}</textarea>
  </div>
</div>
</code>```

At .vue

答:
You can use v-model:

You can use the v-model directive to create two-way data bindings on
form input and textarea elements.

For example:

```<code><div v-for="(tweet, index) in tweets">
  <div class="each_tweet">
    <textarea v-on:keyup="typing(index)"
              v-model="tweet.content"
              placeholder="What's happening now"></textarea>
  </div>
</div>
</code>```

Body:
Considering this scenario

At .vue template

    <textarea v-on:keyup="typing(index)"
              placeholder="What's happening now">{{ tweet.content }}</textarea>

At .vue

Body:
You can use v-model:

You can use the v-model directive to create two-way data bindings on
form input and textarea elements.

For example:

<div v-for="(tweet, index) in tweets">
  <div class="each_tweet">
    <textarea v-on:keyup="typing(index)"
              v-model="tweet.content"
              placeholder="What's happening now"></textarea>
  </div>
</div>


问:
Why WebApi marks empty string as error in model state?
I have strange behaviour of Web API, .Net 4.5.2. If optional string parameter is null, ModelState has no error. If it is not null and not empty, no errors again. But if it is just an empty string I have model state error.

Why do I get it and how to disable it?

Assuming app served on localhost:82 I have those results:

```<code>Url: http://localhost:82/
Response: "null"

Url: http://localhost:82/?q=1
Response: "1"

Url: http://localhost:82/?q=
Response: {
  "Message": "The request is invalid.",
  "ModelState": {
    "q.String": [
      "A value is required but was not present in the request."
    ]
  }
}
</code>```

Test controller and config is below. This is reduced to bare minimum default "Asp.net web application" with "WebApi" in VS2013.

```<code>namespace Web.Api.Test.Controllers
{
    using System.Web.Http;

    [Route]
    public class HomeController : ApiController
    {
        [Route]
        [HttpGet]
        public IHttpActionResult Search(string q = default(string))
        {
            return this.ModelState.IsValid
                ? this.Ok(q ?? "null")
                : (IHttpActionResult)this.BadRequest(this.ModelState);
        }
    }
}
</code>```

Startup.cs is:

```<code>using Microsoft.Owin;

using WebApplication1;

[assembly: OwinStartup(typeof(Startup))]

namespace WebApplication1
{
    using System.Web.Http;

    using Newtonsoft.Json;

    using Owin;

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            GlobalConfiguration.Configure(config =>
            {
                config.MapHttpAttributeRoutes();
                config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;

                config.Formatters.Remove(config.Formatters.XmlFormatter);
            });
        }
    }
}
</code>```

PS: This question has a workaround, but it does not answer the main question: why does this situation happen and what reasons are behind this design decision.

答:
That's why:

This is a MVC feature which binds empty strings to nulls.

We have found the same behavior in our application, and deep dive debugging with source code

```<code>git clone https://github.com/ASP-NET-MVC/aspnetwebstack
</code>```

makes sense to search in the right direction. Here the method which set whitespace strings to null, and here the error is added to model state:

```<code>if (parentNode == null && ModelMetadata.Model == null)
{
    string trueModelStateKey = ModelBindingHelper.CreatePropertyModelName(ModelStateKey, ModelMetadata.GetDisplayName());
    modelState.AddModelError(trueModelStateKey, SRResources.Validation_ValueNotFound);
    return;
}
</code>```

IMHO it is a bug. But who cares. We used this workaround

Body:
I have strange behaviour of Web API, .Net 4.5.2. If optional string parameter is null, ModelState has no error. If it is not null and not empty, no errors again. But if it is just an empty string I have model state error.

Why do I get it and how to disable it?

Assuming app served on localhost:82 I have those results:

Url: http://localhost:82/
Response: "null"

Url: http://localhost:82/?q=1
Response: "1"

Url: http://localhost:82/?q=
Response: {
  "Message": "The request is invalid.",
  "ModelState": {
    "q.String": [
      "A value is required but was not present in the request."
    ]
  }
}

Test controller and config is below. This is reduced to bare minimum default "Asp.net web application" with "WebApi" in VS2013.

namespace Web.Api.Test.Controllers
{
    using System.Web.Http;

    [Route]
    public class HomeController : ApiController
    {
        [Route]
        [HttpGet]
        public IHttpActionResult Search(string q = default(string))
        {
            return this.ModelState.IsValid
                ? this.Ok(q ?? "null")
                : (IHttpActionResult)this.BadRequest(this.ModelState);
        }
    }
}

Startup.cs is:

using Microsoft.Owin;

using WebApplication1;

[assembly: OwinStartup(typeof(Startup))]

namespace WebApplication1
{
    using System.Web.Http;

    using Newtonsoft.Json;

    using Owin;

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            GlobalConfiguration.Configure(config =>
            {
                config.MapHttpAttributeRoutes();
                config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;

                config.Formatters.Remove(config.Formatters.XmlFormatter);
            });
        }
    }
}

PS: This question has a workaround, but it does not answer the main question: why does this situation happen and what reasons are behind this design decision.

Body:
That's why:

This is a MVC feature which binds empty strings to nulls.

We have found the same behavior in our application, and deep dive debugging with source code

git clone https://github.com/ASP-NET-MVC/aspnetwebstack

makes sense to search in the right direction. Here the method which set whitespace strings to null, and here the error is added to model state:

if (parentNode == null && ModelMetadata.Model == null)
{
    string trueModelStateKey = ModelBindingHelper.CreatePropertyModelName(ModelStateKey, ModelMetadata.GetDisplayName());
    modelState.AddModelError(trueModelStateKey, SRResources.Validation_ValueNotFound);
    return;
}

IMHO it is a bug. But who cares. We used this workaround