答:
I suspect in this instance it would be faster simply to use str_replace as follows:</p>

```<code>$cleanedData = str_replace(array('www.example.com/en/', 'www.example.com/fr/'), '', $sourceData);
</code>```

Title: replace url using preg_replace php

Body:
I suspect in this instance it would be faster simply to use str_replace as follows:

$cleanedData = str_replace(array('www.example.com/en/', 'www.example.com/fr/'), '', $sourceData);


来源: stackexchange

问:
Expected BEGIN_ARRAY but was BEGIN_OBJECT retrofit2
I have some problem about retrofit2

How to fix Expected BEGIN_ARRAY but was BEGIN_OBJECT in retrofit2

I don't know to fix it

What's my wrong ?

my json is

```<code>{
    "result": true,
    "message": "success",
    "data": [
        {
            "id": "10",
            "type_name": "pppppp"
        },
        {
            "id_mt": "11",
            "type_name": "aaaaaa"
        }
    ]
}
</code>```

and my model class is

```<code>public class MessageFastModel {
    private boolean result;
    private String message;

    private List<DataBean> data;

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        private String id;
        private String type_name;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getType_name() {
            return type_name;
        }

        public void setType_name(String type_name) {
            this.type_name = type_name;
        }
    }
}
</code>```

My code is

```<code> @FormUrlEncoded
 @POST("api/message_type")
 Call<MessageFastModel> listMessageFast(@Field("token") String token);
</code>```

and

```<code>Call<MessageFastModel> dddddCall = ooooo.listMessageFast(Preferences.getToken());
                        dddddCall.enqueue(new Callback<MessageFastModel>() {
                            @Override
                            public void onResponse(Call<MessageFastModel> call, Response<MessageFastModel> response) {
                                if (response.isSuccessful()) {
                                    Log.d("ddd", "onResponse: " + response.body().getData().size());
                                }
                            }

                            @Override
                            public void onFailure(Call<MessageFastModel> call, Throwable t) {
                                Log.e("ddd", "onFailure: " + t.getMessage());
                            }
                        });
</code>```

but My error is

E/ddd: onFailure: java.lang.IllegalStateException: Expected
  BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 44 path $.data

what's problem ? thanks!

答:
```<code>  @GET("photos")
Call<Model> savePhoto();
</code>```

And Call your retrofit method like this >>>

```<code> Call<Model> call = apiService.savePhoto();

        call.enqueue(new retrofit2.Callback<Model>() {
            @Override
            public void onResponse(Call<Model> call, retrofit2.Response<Model> response) {
                int statusCode = response.code();
                try {
                    Model model;
                   // Log.w("resedatasync", new Gson().toJson(response));
                    model= response.body();
</code>```

And Create Your Model Class like this

```<code>public class Model{

@SerializedName("ArrayName")
 public List<DataBean > arraylist= new ArrayList<>();

@SerializedName("message")
private String message;

public class DataBean {

    @SerializedName("id")
     private String id;

    @SerializedName("typename")
     private String typename;

    @SerializedName("typename")
    public void settypename(String typename) {
        this.typename= typename;
    }

}
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
I have some problem about retrofit2

How to fix Expected BEGIN_ARRAY but was BEGIN_OBJECT in retrofit2

I don't know to fix it

What's my wrong ?

my json is

{
    "result": true,
    "message": "success",
    "data": [
        {
            "id": "10",
            "type_name": "pppppp"
        },
        {
            "id_mt": "11",
            "type_name": "aaaaaa"
        }
    ]
}

and my model class is

public class MessageFastModel {
    private boolean result;
    private String message;

    private List<DataBean> data;

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        private String id;
        private String type_name;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getType_name() {
            return type_name;
        }

        public void setType_name(String type_name) {
            this.type_name = type_name;
        }
    }
}

My code is

 @FormUrlEncoded
 @POST("api/message_type")
 Call<MessageFastModel> listMessageFast(@Field("token") String token);

and

Call<MessageFastModel> dddddCall = ooooo.listMessageFast(Preferences.getToken());
                        dddddCall.enqueue(new Callback<MessageFastModel>() {
                            @Override
                            public void onResponse(Call<MessageFastModel> call, Response<MessageFastModel> response) {
                                if (response.isSuccessful()) {
                                    Log.d("ddd", "onResponse: " + response.body().getData().size());
                                }
                            }

                            @Override
                            public void onFailure(Call<MessageFastModel> call, Throwable t) {
                                Log.e("ddd", "onFailure: " + t.getMessage());
                            }
                        });

but My error is

E/ddd: onFailure: java.lang.IllegalStateException: Expected
  BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 44 path $.data

what's problem ? thanks!

Body:
  @GET("photos")
Call<Model> savePhoto();

And Call your retrofit method like this >>>

 Call<Model> call = apiService.savePhoto();

        call.enqueue(new retrofit2.Callback<Model>() {
            @Override
            public void onResponse(Call<Model> call, retrofit2.Response<Model> response) {
                int statusCode = response.code();
                try {
                    Model model;
                   // Log.w("resedatasync", new Gson().toJson(response));
                    model= response.body();

And Create Your Model Class like this

public class Model{

@SerializedName("ArrayName")
 public List<DataBean > arraylist= new ArrayList<>();

@SerializedName("message")
private String message;

public class DataBean {

    @SerializedName("id")
     private String id;

    @SerializedName("typename")
     private String typename;

    @SerializedName("typename")
    public void settypename(String typename) {
        this.typename= typename;
    }

}

}


问:
ZAP Jenkins configuration for windows
I am a beginner in Jenkins and I am trying to use Jenkins with the ZAP plugin.

I managed to follow the step-by-step guideline provided by Jenkins but I have some questions regarding what actually ZAP for Jenkins can manage.

If I just use ZAP without Jenkins I can write the path of the server I would like to test, and the process will start.

However,ZAP for Jenkins requires the source code of the website. Is there an option to just import the url of the site I would like to test and then proceed?

It might be a silly question but It really bothers me.

答: Probably best to ask on the ZAP Jenkins group: https://groups.google.com/forum/#%21forum/zaproxy-jenkins. I know that the project lead doesnt monitor stackoverflow.</p>

Title: ZAP Jenkins configuration for windows


问:
TestNG Assert showing error in selenium project
Assert is showing error even though testng is imported. error is "Assert cannot be resolved" and in the import of Assert the error is "The import org.testng.Assert cannot be resolved" .. Please help me to resolve this issue..

答: Might be you did not imported the correct testNG jar in your project. Just for reference , download it from here .</p>


问:
Dynamic pivot with time datatype in SQL Server
```<code>SELECT
    PARTNO, BATCHNO, ' +   @IdleHoursColumns + '
INTO
    TEMPTABLE_IH
FROM
    [dbo].[PRODUCTION_IH]
PIVOT
    (SUM(IDLETIME))
          FOR REASON IN (' + @IdleHoursColumns + ')) AS P'

--printed query
SELECT
    PARTNO, BATCHNO, [POWERCUT]
INTO
    TEMPTABLE_IH
FROM
    [dbo].[PRODUCTION_IH]
PIVOT
    (SUM(IDLETIME)
          FOR REASON IN ([POWERCUT])) AS P
</code>```

How to use dynamic pivot with time datatype in SQL Server? I tried to move my data into a temp table and display the row values to as columns dynamically. The query works perfectly for integer datatype columns. But I got an error

Operand data type time is invalid for sum operator

I tried with cast function and Datediff but it is also throwing errors.

答:
If your datatype is not numeric then you should use  MAX or MIN instead of SUM

```<code>SELECT PARTNO,BATCHNO, ' +   @IdleHoursColumns + '
INTO TEMPTABLE_IH
FROM [dbo].[PRODUCTION_IH]
PIVOT( MAX(IDLETIME))
      FOR REASON IN (' + @IdleHoursColumns + ')) AS P'
</code>```

Body:
SELECT
    PARTNO, BATCHNO, ' +   @IdleHoursColumns + '
INTO
    TEMPTABLE_IH
FROM
    [dbo].[PRODUCTION_IH]
PIVOT
    (SUM(IDLETIME))
          FOR REASON IN (' + @IdleHoursColumns + ')) AS P'

--printed query
SELECT
    PARTNO, BATCHNO, [POWERCUT]
INTO
    TEMPTABLE_IH
FROM
    [dbo].[PRODUCTION_IH]
PIVOT
    (SUM(IDLETIME)
          FOR REASON IN ([POWERCUT])) AS P

How to use dynamic pivot with time datatype in SQL Server? I tried to move my data into a temp table and display the row values to as columns dynamically. The query works perfectly for integer datatype columns. But I got an error

Operand data type time is invalid for sum operator

I tried with cast function and Datediff but it is also throwing errors.

Body:
If your datatype is not numeric then you should use  MAX or MIN instead of SUM

SELECT PARTNO,BATCHNO, ' +   @IdleHoursColumns + '
INTO TEMPTABLE_IH
FROM [dbo].[PRODUCTION_IH]
PIVOT( MAX(IDLETIME))
      FOR REASON IN (' + @IdleHoursColumns + ')) AS P'


问:
Change Graphql json response Rails
This is simple query:

```<code>query {
   comment(id: 1) {
      id,
      title
   }
}
</code>```

And it result look like this:

```<code>{
   "data": {
      "comment": {
         "id": 1,
         "title": "Hello world"
      }
   }
}
</code>```

Now, i want change json result to:

```<code>{
   "id": 1,
   "title": "Hello world"
}
</code>```

I'm using rails and gem graphql-ruby. Somebody can help me!!!!

答:
If I understood you right</p>

```<code>irb(main):007:0> hash = {"data": {"comment": {"id": 1, "title": "Hello World"}}}
=> {:data=>{:comment=>{:id=>1, :title=>"Hello World"}}}
irb(main):008:0> result = hash[:data][:comment]
=> {:id=>1, :title=>"Hello World"}
</code>```

Title: Change Graphql json response Rails

Body:
This is simple query:

query {
   comment(id: 1) {
      id,
      title
   }
}

And it result look like this:

{
   "data": {
      "comment": {
         "id": 1,
         "title": "Hello world"
      }
   }
}

Now, i want change json result to:

{
   "id": 1,
   "title": "Hello world"
}

I'm using rails and gem graphql-ruby. Somebody can help me!!!!

Body:
If I understood you right

irb(main):007:0> hash = {"data": {"comment": {"id": 1, "title": "Hello World"}}}
=> {:data=>{:comment=>{:id=>1, :title=>"Hello World"}}}
irb(main):008:0> result = hash[:data][:comment]
=> {:id=>1, :title=>"Hello World"}


问:
Query to produce data only within the asked hour range
Oracle SQL:

I been trying to get this some snippet of query working. When you run it, it prompts you for an hour, and displays no records. I don’t want the query to have a static hour as it will need to be run 4 times a day.
So from the ‘&date’ input, I want it to show data for the past 24 hours. Is that possible?

```<code>dt_time = timestamp(6) field

select distinct to_char(dt_ time,'dd/mm/yyyy hh24'), fault_description
from order
where to_char(dt_time,'hh24') <= '&date' -24
order by to_char(dt_ time,'dd/mm/yyyy hh24');
</code>```

Example, if you enter 10 (when query executed) it will show the data from 10(:00) through to 10(:00)next day

[Hope there is enough info for someone to answer, please]

答:
Use a combination of between and interval:

```<code>where dt_time between
to_date(&date, 'ddmmyyyy hh24') and
to_date(&date, 'ddmmyyyy hh24') + interval  '24' hour
</code>```

You'll need to pass/parse the input date as a full date and not only the hour part, in order to prevent unexpected results.

Body:
Oracle SQL:

I been trying to get this some snippet of query working. When you run it, it prompts you for an hour, and displays no records. I don’t want the query to have a static hour as it will need to be run 4 times a day.
So from the ‘&date’ input, I want it to show data for the past 24 hours. Is that possible?

dt_time = timestamp(6) field

select distinct to_char(dt_ time,'dd/mm/yyyy hh24'), fault_description
from order
where to_char(dt_time,'hh24') <= '&date' -24
order by to_char(dt_ time,'dd/mm/yyyy hh24');

Example, if you enter 10 (when query executed) it will show the data from 10(:00) through to 10(:00)next day

[Hope there is enough info for someone to answer, please]

Body:
Use a combination of between and interval:

where dt_time between
to_date(&date, 'ddmmyyyy hh24') and
to_date(&date, 'ddmmyyyy hh24') + interval  '24' hour

You'll need to pass/parse the input date as a full date and not only the hour part, in order to prevent unexpected results.


问:
What does it mean to recycle the dynamic memory?
I learned about ‘free’ which is used after malloc not to make garbage memory in C. What’s recycle? I looked up for it but could not find any code. All I got is the explanation about free.. Are they the same?

To add, in my book about data structure (general linear lists) says that “Recycle is a pseudocode command to return a node’s space to dynamic memory.

Thanks a lot.

I will discard the picture if there is any problem with the license.

答:
Recycling means freeing unused memory so that they can be used later.

If you keep on malloc-ing without free-ing, after some time of running, your program may be taking GBs of RAMs, mostly unused. Direct consequences may be the operating system's denying your program's further malloc request, or even burden down the whole system.

Recycling is not pseudo-code. It's real code telling the OS that "This block of memory is no longer used. You can allocate it to any program." After that the system can manage this specific block of memory again instead of leaving it wasted. The real code is free(), while recycling is just a term used in computer science.

It's always a good practice to free unused memory in terms of efficiency.


问:
Tensorflow import error: Naive Pip Windows 10
having problems while

screenshot given below. I want the solution badly.

import tensorflow as tf

https://i.stack.imgur.com/jgghK.png

答:
You're using tensorflow-gpu but do not have CUDA / cuDNN installed on your computer.

Shor answer: run pip unintall tensorflow-gpu and pip install tensorflow.

Long answer: Install CUDA / cuDNN


问:
How to display output on different screen in c?
I want to display output on different screen, but how?
For example:
I want to display " hello world " on the first black screen, and when I press enter button, the old screen will disappear and another new black screen will display "thank you" .
Just how to do that in c?</p>

答:
Depending on what you want but just clear the screen after getting an enter.

puts("\033[2J"); will work on most terminal using VT100 escape codes.

clrscr() is a nonstandard function defined in <conio.h> that some older compilers use.

system("cls"); works with Windows and system("clear"); with Linux and is in <stdlib.h>.

These options would cover most environments that you would encounter when using C.


问:
InfiniBand explained
Can anybody explain what is InfiniBand? What is the key differences in comparison with Ethernet, how these differences allow for it to be faster than Ethernet?

In the official description from mellanox it is written that

Introduce InfiniBand, a switch-based serial I/O interconnect architecture operating at...

What does it mean that Infiniband is a switch-based interconnect? I found this description, but it does not explain what happens if several inputs want to write to a single output, how is the collision resolved?

It is also said that Infiniband has end-to-end flow control. Does it mean that there is no (need) for any other (in-between) flow control? Why?

答:
To learn basics of InfiniBand I suggest you to visit Mellanox Academy Web-Site and after registration take
InfiniBand Essentials or InfiniBand Fundamentals course (in a section Technologies).

In my opinion "switch-based architecture" means that switches are part of fabric (see picture below, where I have shown switch by blue shape).

End-to-end flow control, aka message level flow control, is a feature (capability) for reliable connections. This can be used by a responder to optimize the use of its receive resources. Essentially, a requester cannot send a request message unless it has appropriate credits to do so. Please, refer to InfiniBand specification for details.

Title: InfiniBand explained


问:
Logstash Docker with pipelines.yml
I've been trying to get a Logstash Docker container (docker.elastic.co/logstash/logstash-oss:6.0.0) to run with multiples pipelines using pipelines.yml, but I can't get it running. Here follows my Dockerfile:

```<code>FROM docker.elastic.co/logstash/logstash-oss:6.0.0
RUN rm -f /usr/share/logstash/pipeline/logstash.conf
RUN rm -f /usr/share/logstash/config/pipelines.yml
ADD pipeline/ /usr/share/logstash/pipeline/
COPY pipelines.yml /usr/share/logstash/config/pipelines.yml
</code>```

If I add logstash.conf inside pipeline/ it will run, but will ignore pipelines.yml.

Any ideas?

答:
How are you running logstash? If you want to use the pipelines.yml file to drive pipeline configuration, you must start logstash like bin/logstash with neither -f (--config.path) nor -e (--config.string).

More information here: https://www.elastic.co/guide/en/logstash/master/multiple-pipelines.html#multiple-pipelines

Title: Logstash Docker with pipelines.yml

Body:
I've been trying to get a Logstash Docker container (docker.elastic.co/logstash/logstash-oss:6.0.0) to run with multiples pipelines using pipelines.yml, but I can't get it running. Here follows my Dockerfile:

FROM docker.elastic.co/logstash/logstash-oss:6.0.0
RUN rm -f /usr/share/logstash/pipeline/logstash.conf
RUN rm -f /usr/share/logstash/config/pipelines.yml
ADD pipeline/ /usr/share/logstash/pipeline/
COPY pipelines.yml /usr/share/logstash/config/pipelines.yml

If I add logstash.conf inside pipeline/ it will run, but will ignore pipelines.yml.

Any ideas?


问:
How to express a regular expression?
How to express a regular expression over the alphabet {a, b, c} that doesn't contain the contiguous sub-string baa?

答:
If your regex flavor supports negative lookaheads, then it's relatively simple. E.g. in php it looks like this:

```<code>^^(?:(?!baa)[abc])*$
</code>```

Demo here.

Explanation:

^...$ makes sure we match the entire line

[abc] is a character class that defines the alphabet

(?!baa) is the negative lookahead. It checks for every position if it is followed by baa. If it is, then it's not a match

finally, we group these two with a non-capturing group: (?:...) and repeat them as many times as fits into the line: (?:...)*

Update

Updated the demo and the regex according to ClasG -s comment. Indeed, to make sure it fails for a simple baa, the lookahead must come first, then the character class.

Title: How to express a regular expression?

Body:
If your regex flavor supports negative lookaheads, then it's relatively simple. E.g. in php it looks like this:

^^(?:(?!baa)[abc])*$

Demo here.

Explanation:

^...$ makes sure we match the entire line

[abc] is a character class that defines the alphabet

(?!baa) is the negative lookahead. It checks for every position if it is followed by baa. If it is, then it's not a match

finally, we group these two with a non-capturing group: (?:...) and repeat them as many times as fits into the line: (?:...)*

Update

Updated the demo and the regex according to ClasG -s comment. Indeed, to make sure it fails for a simple baa, the lookahead must come first, then the character class.


问:
Lync error in Silverlight: Client not trusted
When I try to load my Lync Controls in a Silverlight application I get the error: Client is not trusted. This error doesn't appear when I debug the Silverlight application without the corresponding web project.

This is the code that generates the error:

```<code>LyncClient l = LyncClient.GetClient();
</code>```

This is the error:

```<code>AutomationServerException was unhandled by user code
Client is not trusted
</code>```

What must I do?

答: The probabble cause may be because of the security.Right click the dll and goto properties and set unblock.</p>

ContentLicense: CC BY-SA 2.5

Body:
When I try to load my Lync Controls in a Silverlight application I get the error: Client is not trusted. This error doesn't appear when I debug the Silverlight application without the corresponding web project.

This is the code that generates the error:

LyncClient l = LyncClient.GetClient();

This is the error:

AutomationServerException was unhandled by user code
Client is not trusted

What must I do?


问:
Removing rules attribute from asp.net gridview
i have a gridview i wish to style without borders but whenever i use the control asp.net adds in the attribute rules="all" i've tried overriding in on the control like so:

<asp:GridView ID="GridView1" runat="server" rules="none">

but this doesn't work either

答:
It can be achieved by applying inline style to Gridview.</p>

```<code><asp:GridView ID="GridView1" style="border-width:0;" runat="server">
</code>```

Body:
It can be achieved by applying inline style to Gridview.

<asp:GridView ID="GridView1" style="border-width:0;" runat="server">


问:
How to use Enzyme Shallow with Jest snapshots
I'm trying to use shallow from enzyme and also use snapshots from jest together.

The problem I'm facing is that I need to change something from the state using setState() from enzyme and then match the result with the snapshot.

See the code of my component:

```<code>....

getPrevProduct = () => {
  const key = this.state.indexCurrent > 0 &&
   this.productsKeys[this.state.indexCurrent - 1];

  let product = null;

  if (key) {
    product = this.props.products[key];
  }

  return product;
}

renderPrev = () => this.getPrevProduct() && <PrevButton />;

render() {
  return (
    <div>
      ...
      {this.renderPrev()}
      ...
    <div>
  )
}
</code>```

The previous code checks if the product, passed from props in the currentIndex, exists.

That's why I need Enzyme to change the state. Then, if it matches, <PrevButton /> has to be rendered.

This test is when I want to match the component with the snapshot:

```<code>const nextProps = {
  products: {
    test: 'test'
  }
};

const tree = create(<Component nextProps={nextProps} />).toJSON();

expect(tree).toMatchSnapshot();
</code>```

But I need to change the state. How I can do that? This doesn't work:

```<code>it('should render component with prev button', () => {
  const nextProps = {
    products: {
      test: 'test'
    }
  };
  const instance = shallow(<Component nextProps={nextProps} />).instance()

  instance.setState({
    indexCurrent: 1
  });

  const tree = create(<Component nextProps={nextProps} />).toJSON();

  expect(tree).toMatchSnapshot();
});
</code>```

I also tried to save the declaration of the component into a variable like the next uncompleted code and use it in shallow and create:

```<code>const component = <Component nextProps={nextProps} />;

 shallow(component).instance()).instance()
 create(component).toJSON()`
</code>```

I also tried with no luck enzyme-to-json.

What would you do?

答:
Probably, its not the way enzyme-to-json is supposed to be used. Try this way :

```<code>import { shallowToJson  } from 'enzyme-to-json';
import { shallow } from 'enzyme';
</code>```

and then in your test :

```<code>const wrapper = shallow(<Component />);
expect(shallowToJson(wrapper)).toMatchSnapshot();
</code>```

Body:
I'm trying to use shallow from enzyme and also use snapshots from jest together.

The problem I'm facing is that I need to change something from the state using setState() from enzyme and then match the result with the snapshot.

See the code of my component:

....

getPrevProduct = () => {
  const key = this.state.indexCurrent > 0 &&
   this.productsKeys[this.state.indexCurrent - 1];

  let product = null;

  if (key) {
    product = this.props.products[key];
  }

  return product;
}

renderPrev = () => this.getPrevProduct() && <PrevButton />;

render() {
  return (

      ...
      {this.renderPrev()}
      ...

  )
}

The previous code checks if the product, passed from props in the currentIndex, exists.

That's why I need Enzyme to change the state. Then, if it matches, <PrevButton /> has to be rendered.

This test is when I want to match the component with the snapshot:

const nextProps = {
  products: {
    test: 'test'
  }
};

const tree = create(<Component nextProps={nextProps} />).toJSON();

expect(tree).toMatchSnapshot();

But I need to change the state. How I can do that? This doesn't work:

it('should render component with prev button', () => {
  const nextProps = {
    products: {
      test: 'test'
    }
  };
  const instance = shallow(<Component nextProps={nextProps} />).instance()

  instance.setState({
    indexCurrent: 1
  });

  const tree = create(<Component nextProps={nextProps} />).toJSON();

  expect(tree).toMatchSnapshot();
});

I also tried to save the declaration of the component into a variable like the next uncompleted code and use it in shallow and create:

const component = <Component nextProps={nextProps} />;

 shallow(component).instance()).instance()
 create(component).toJSON()`

I also tried with no luck enzyme-to-json.

What would you do?

Body:
Probably, its not the way enzyme-to-json is supposed to be used. Try this way :

import { shallowToJson  } from 'enzyme-to-json';
import { shallow } from 'enzyme';

and then in your test :

const wrapper = shallow(<Component />);
expect(shallowToJson(wrapper)).toMatchSnapshot();


问:
torch.nn.LSTM runtime error
I'm trying to implement the structure from "Livelinet: A multimodal Deep Recurrent Neural Network to Predict Liveliness in Educational Videos".

For a brief explanation, I split 10-second audio clip into ten 1-second audio clip and get a spectrogram (a picture) from that 1-second audio clip. Then I use CNN to get a representation vector from the picture, finally getting 10 vectors of each 1-second video clips.

Next, I feed those 10 vectors to LSTM, and I got some errors there.
My code and the error traceback are as follows:

```<code>class AudioCNN(nn.Module):

def __init__(self):
    super(AudioCNN,self).__init__()
    self.features = alexnet.features
    self.features2 = nn.Sequential(*classifier)
    self.lstm = nn.LSTM(512, 256,2)
    self.classifier = nn.Linear(2*256,2)

def forward(self, x):
    x = self.features(x)
    print x.size()
    x = x.view(x.size(0),256*6*6)
    x = self.features2(x)
    x = x.view(10,1,512)
    h_0,c_0 = self.init_hidden()
    _, (_, _) = self.lstm(x,(h_0,c_0)) # x dim : 2 x 1 x 256
    assert False
    x = x.view(1,1,2*256)
    x = self.classifier(x)

    return x

def init_hidden(self):
    h_0 = torch.randn(2,1,256) #layer * batch * input_dim
    c_0 = torch.randn(2,1,256)
    return h_0, c_0

audiocnn = AudioCNN()
input = torch.randn(10,3,223,223)
input = Variable(input)
audiocnn(input)
</code>```

Error:

```<code>RuntimeErrorTraceback (most recent call last)
<ipython-input-64-2913316dbb34> in <module>()
----> 1 audiocnn(input)

/home//local/lib/python2.7/site-packages/torch/nn/modules/module.pyc in __call__(self, *input, **kwargs)
    222         for hook in self._forward_pre_hooks.values():
    223             hook(self, input)
--> 224         result = self.forward(*input, **kwargs)
    225         for hook in self._forward_hooks.values():
    226             hook_result = hook(self, input, result)

<ipython-input-60-31881982cca9> in forward(self, x)
     15         x = x.view(10,1,512)
     16         h_0,c_0 = self.init_hidden()
---> 17         _, (_, _) = self.lstm(x,(h_0,c_0)) # x dim : 2 x 1 x 256
     18         assert False
     19         x = x.view(1,1,2*256)

/home/local/lib/python2.7/site-packages/torch/nn/modules/module.pyc in __call__(self, *input, **kwargs)
    222         for hook in self._forward_pre_hooks.values():
    223             hook(self, input)
--> 224         result = self.forward(*input, **kwargs)
    225         for hook in self._forward_hooks.values():
    226             hook_result = hook(self, input, result)

/home//local/lib/python2.7/site-packages/torch/nn/modules/rnn.pyc in forward(self, input, hx)
    160             flat_weight=flat_weight
    161         )
--> 162         output, hidden = func(input, self.all_weights, hx)
    163         if is_packed:
    164             output = PackedSequence(output, batch_sizes)

/home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, *fargs, **fkwargs)
    349         else:
    350             func = AutogradRNN(*args, **kwargs)
--> 351         return func(input, *fargs, **fkwargs)
    352
    353     return forward

/home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, weight, hidden)
    242             input = input.transpose(0, 1)
    243
--> 244         nexth, output = func(input, hidden, weight)
    245
    246         if batch_first and batch_sizes is None:

/home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, hidden, weight)
     82                 l = i * num_directions + j
     83
---> 84                 hy, output = inner(input, hidden[l], weight[l])
     85                 next_hidden.append(hy)
     86                 all_output.append(output)

/home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, hidden, weight)
    111         steps = range(input.size(0) - 1, -1, -1) if reverse else range(input.size(0))
    112         for i in steps:
--> 113             hidden = inner(input[i], hidden, *weight)
    114             # hack to handle LSTM
    115             output.append(hidden[0] if isinstance(hidden, tuple) else hidden)

/home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in LSTMCell(input, hidden, w_ih, w_hh, b_ih, b_hh)
     29
     30     hx, cx = hidden
---> 31     gates = F.linear(input, w_ih, b_ih) + F.linear(hx, w_hh, b_hh)
     32
     33     ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)

/home//local/lib/python2.7/site-packages/torch/nn/functional.pyc in linear(input, weight, bias)
    551     if input.dim() == 2 and bias is not None:
    552         # fused op is marginally faster
--> 553         return torch.addmm(bias, input, weight.t())
    554
    555     output = input.matmul(weight.t())

/home//local/lib/python2.7/site-packages/torch/autograd/variable.pyc in addmm(cls, *args)
    922         @classmethod
    923         def addmm(cls, *args):
--> 924             return cls._blas(Addmm, args, False)
    925
    926         @classmethod

/home//local/lib/python2.7/site-packages/torch/autograd/variable.pyc in _blas(cls, args, inplace)
    918             else:
    919                 tensors = args
--> 920             return cls.apply(*(tensors + (alpha, beta, inplace)))
    921
    922         @classmethod

RuntimeError: save_for_backward can only save input or output tensors, but argument 0 doesn't satisfy this condition
</code>```

答:
The error message

RuntimeError: save_for_backward can only save input or output tensors, but argument 0 doesn't satisfy this condition

generally indicates that you are passing a tensor or something else that cannot store history as an input into a module. In your case, your problem is that you return tensors in init_hidden() instead of Variable instances. Therefore, when the LSTM runs it cannot compute the gradient for the hidden layer as its initial input is not a part of the backprop graph.

Solution:

```<code>def init_hidden(self):
    h_0 = torch.randn(2,1,256) #layer * batch * input_dim
    c_0 = torch.randn(2,1,256)
    return Variable(h_0), Variable(c_0)
</code>```

It is also likely that a mean of 0 and a variance of 1 is not helpful as initial values for the LSTM hidden state. Ideally, you would make the initial state trainable as well, e.g.:

```<code>h_0 = torch.zeros(2,1,256) # layer * batch * input_dim
c_0 = torch.zeros(2,1,256)
h_0_param = torch.nn.Parameter(h_0)
c_0_param = torch.nn.Parameter(c_0)

def init_hidden(self):
    return h_0_param, c_0_param
</code>```

In this case the network can learn what initial state suits best. Note that in this case there is no need to wrap h_0_param in a Variable as a Parameter is essentially a Variable with require_grad=True.

Title: torch.nn.LSTM runtime error

Body:
I'm trying to implement the structure from "Livelinet: A multimodal Deep Recurrent Neural Network to Predict Liveliness in Educational Videos".

For a brief explanation, I split 10-second audio clip into ten 1-second audio clip and get a spectrogram (a picture) from that 1-second audio clip. Then I use CNN to get a representation vector from the picture, finally getting 10 vectors of each 1-second video clips.

Next, I feed those 10 vectors to LSTM, and I got some errors there.
My code and the error traceback are as follows:

class AudioCNN(nn.Module):

def __init__(self):
    super(AudioCNN,self).__init__()
    self.features = alexnet.features
    self.features2 = nn.Sequential(*classifier)
    self.lstm = nn.LSTM(512, 256,2)
    self.classifier = nn.Linear(2*256,2)

def forward(self, x):
    x = self.features(x)
    print x.size()
    x = x.view(x.size(0),256*6*6)
    x = self.features2(x)
    x = x.view(10,1,512)
    h_0,c_0 = self.init_hidden()
    _, (_, _) = self.lstm(x,(h_0,c_0)) # x dim : 2 x 1 x 256
    assert False
    x = x.view(1,1,2*256)
    x = self.classifier(x)

    return x

def init_hidden(self):
    h_0 = torch.randn(2,1,256) #layer * batch * input_dim
    c_0 = torch.randn(2,1,256)
    return h_0, c_0

audiocnn = AudioCNN()
input = torch.randn(10,3,223,223)
input = Variable(input)
audiocnn(input)

Error:

RuntimeErrorTraceback (most recent call last)
<ipython-input-64-2913316dbb34> in <module>()
----> 1 audiocnn(input)

/home//local/lib/python2.7/site-packages/torch/nn/modules/module.pyc in __call__(self, *input, **kwargs)
    222         for hook in self._forward_pre_hooks.values():
    223             hook(self, input)
--> 224         result = self.forward(*input, **kwargs)
    225         for hook in self._forward_hooks.values():
    226             hook_result = hook(self, input, result)

<ipython-input-60-31881982cca9> in forward(self, x)
     15         x = x.view(10,1,512)
     16         h_0,c_0 = self.init_hidden()
---> 17         _, (_, _) = self.lstm(x,(h_0,c_0)) # x dim : 2 x 1 x 256
     18         assert False
     19         x = x.view(1,1,2*256)

/home/local/lib/python2.7/site-packages/torch/nn/modules/module.pyc in __call__(self, *input, **kwargs)
    222         for hook in self._forward_pre_hooks.values():
    223             hook(self, input)
--> 224         result = self.forward(*input, **kwargs)
    225         for hook in self._forward_hooks.values():
    226             hook_result = hook(self, input, result)

/home//local/lib/python2.7/site-packages/torch/nn/modules/rnn.pyc in forward(self, input, hx)
    160             flat_weight=flat_weight
    161         )
--> 162         output, hidden = func(input, self.all_weights, hx)
    163         if is_packed:
    164             output = PackedSequence(output, batch_sizes)

/home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, *fargs, **fkwargs)
    349         else:
    350             func = AutogradRNN(*args, **kwargs)
--> 351         return func(input, *fargs, **fkwargs)
    352
    353     return forward

/home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, weight, hidden)
    242             input = input.transpose(0, 1)
    243
--> 244         nexth, output = func(input, hidden, weight)
    245
    246         if batch_first and batch_sizes is None:

/home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, hidden, weight)
     82                 l = i * num_directions + j
     83
---> 84                 hy, output = inner(input, hidden[l], weight[l])
     85                 next_hidden.append(hy)
     86                 all_output.append(output)

/home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, hidden, weight)
    111         steps = range(input.size(0) - 1, -1, -1) if reverse else range(input.size(0))
    112         for i in steps:
--> 113             hidden = inner(input[i], hidden, *weight)
    114             # hack to handle LSTM
    115             output.append(hidden[0] if isinstance(hidden, tuple) else hidden)

/home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in LSTMCell(input, hidden, w_ih, w_hh, b_ih, b_hh)
     29
     30     hx, cx = hidden
---> 31     gates = F.linear(input, w_ih, b_ih) + F.linear(hx, w_hh, b_hh)
     32
     33     ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)

/home//local/lib/python2.7/site-packages/torch/nn/functional.pyc in linear(input, weight, bias)
    551     if input.dim() == 2 and bias is not None:
    552         # fused op is marginally faster
--> 553         return torch.addmm(bias, input, weight.t())
    554
    555     output = input.matmul(weight.t())

/home//local/lib/python2.7/site-packages/torch/autograd/variable.pyc in addmm(cls, *args)
    922         @classmethod
    923         def addmm(cls, *args):
--> 924             return cls._blas(Addmm, args, False)
    925
    926         @classmethod

/home//local/lib/python2.7/site-packages/torch/autograd/variable.pyc in _blas(cls, args, inplace)
    918             else:
    919                 tensors = args
--> 920             return cls.apply(*(tensors + (alpha, beta, inplace)))
    921
    922         @classmethod

RuntimeError: save_for_backward can only save input or output tensors, but argument 0 doesn't satisfy this condition

Body:
The error message

RuntimeError: save_for_backward can only save input or output tensors, but argument 0 doesn't satisfy this condition

generally indicates that you are passing a tensor or something else that cannot store history as an input into a module. In your case, your problem is that you return tensors in init_hidden() instead of Variable instances. Therefore, when the LSTM runs it cannot compute the gradient for the hidden layer as its initial input is not a part of the backprop graph.

Solution:

def init_hidden(self):
    h_0 = torch.randn(2,1,256) #layer * batch * input_dim
    c_0 = torch.randn(2,1,256)
    return Variable(h_0), Variable(c_0)

It is also likely that a mean of 0 and a variance of 1 is not helpful as initial values for the LSTM hidden state. Ideally, you would make the initial state trainable as well, e.g.:

h_0 = torch.zeros(2,1,256) # layer * batch * input_dim
c_0 = torch.zeros(2,1,256)
h_0_param = torch.nn.Parameter(h_0)
c_0_param = torch.nn.Parameter(c_0)

def init_hidden(self):
    return h_0_param, c_0_param

In this case the network can learn what initial state suits best. Note that in this case there is no need to wrap h_0_param in a Variable as a Parameter is essentially a Variable with require_grad=True.


问:
How to access a local image resource from Cocoa webview?
How to access a local image resource from the path in Cocoa webview?

```<code>NSURLRequest *requst = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://10.1.24.23:8080"]];
    [_webView.mainFrame loadRequest:requst];

<img src="file:///Users/xxx/xxx">
</code>```

The above code returns

Not allowed to load local resource

in the Safari inspector.
Is it even possible to load a local resource in Safari？

答:
If I understand your question correctly, you're trying to reference local resource from a web page, located on a web server. That will not work because of security limitations. Those limitations are totally sane, it's the main thing why evil hackers can't easily access any files on your mac just by opening a web page in your browser.

You have 2 options to resolve this issue. Either move the local file to the same server, where the web page is located. Or do vice versa - open a local web page. For example, you can download html and related resources, store them locally and open downloaded file in a web view. You can also consider running HTTP server locally for your application, f.e. GCDWebServer.

In case if I've misunderstood your question, and no html page is involved, my recommendations still should remain valid.

Body:
How to access a local image resource from the path in Cocoa webview?

NSURLRequest *requst = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://10.1.24.23:8080"]];
    [_webView.mainFrame loadRequest:requst];

The above code returns

Not allowed to load local resource

in the Safari inspector.
Is it even possible to load a local resource in Safari？


问:
can we have foreign keys on a column having json datat type in mysql?
I have two tables and I want to set the data type of one of the field of a table as JSON and make it as a foreign key to another table.is it possible in MySQL now as of version 5.7.8.</p>

答:
I found this :

Note that JSON columns cannot have a default value, be used as a primary key, be referenced as a foreign key or have an index. You can create secondary indexes on generated virtual columns, but it’s possibly easier to retain an indexed value in a separate field.

(https://www.sitepoint.com/use-json-data-fields-mysql-databases/)

So no you can't and by the way it's strongly recommanded to use simple field as key like 'int' for example.


问:
React TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery___default(...)(...).draggable is not a function
I'm using React-Redux for my project. When I want to use draggable I got this error on browser. I added Jquery and Jquery-ui. But I still got this error. I searched this topic but they didn't use react. I tried many things and finally I solve the problem. Maybe you need it as well so I want to share it.

First of all you should add this modules like this:

```<code>import $ from 'jquery';
import  draggable from '../../../node_modules/jquery-ui/ui/widgets/draggable';
</code>```

And then;

```<code> $(document).ready(function() {
            $('#external-events div.external-event').each(function(index,element) {

                // store data so the calendar knows to render an event upon drop
                $(element).data('event', {
                    title: $.trim($(element).text()), // use the element's text as the event title
                    stick: true // maintain when user navigates (see docs on the renderEvent method)
                });

                // make the event draggable using jQuery UI
                $(element).draggable({
                    zIndex: 1111999,
                    revert: true,      // will cause the event to go back to its
                    revertDuration: 0  //  original position after the drag
                });

            });

        });
</code>```

But be attention please we are not use $(this) for element.
I found example like below but it did not work because of $(this).

```<code>$('#external-events div.external-event').each(function() {

            // store data so the calendar knows to render an event upon drop
            $(this).data('event', {
                title: $.trim($(this).text()), // use the element's text as the event title
                stick: true // maintain when user navigates (see docs on the renderEvent method)
            });

            // make the event draggable using jQuery UI
            $(this).draggable({
                zIndex: 1111999,
                revert: true,      // will cause the event to go back to its
                revertDuration: 0  //  original position after the drag
            });

        });
</code>```

I hope it helps :)

Here is my full code.

```<code>import React, {Component} from 'react';
import $ from 'jquery';
import  draggable from '../../../node_modules/jquery-ui/ui/widgets/draggable';
import fullCalendar from 'fullcalendar';

class Activity extends Component {

    componentDidMount() {

        $(document).ready(function() {
            $('#external-events div.external-event').each(function(index,element) {

                // store data so the calendar knows to render an event upon drop
                $(element).data('event', {
                    title: $.trim($(element).text()), // use the element's text as the event title
                    stick: true // maintain when user navigates (see docs on the renderEvent method)
                });

                // make the event draggable using jQuery UI
                $(element).draggable({
                    zIndex: 1111999,
                    revert: true,      // will cause the event to go back to its
                    revertDuration: 0  //  original position after the drag
                });

            });

        });

        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();

        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            editable: true,
            droppable: true, // this allows things to be dropped onto the calendar
            drop: function() {
                // is the "remove after drop" checkbox checked?
                if ($('#drop-remove').is(':checked')) {
                    // if so, remove the element from the "Draggable Events" list
                    $(this).remove();
                }
            },
            events: [
                {
                    title: 'All Day Event',
                    start: new Date(y, m, 1)
                },
                {
                    title: 'Long Event',
                    start: new Date(y, m, d-5),
                    end: new Date(y, m, d-2)
                },
                {
                    id: 999,
                    title: 'Repeating Event',
                    start: new Date(y, m, d-3, 16, 0),
                    allDay: false
                },
                {
                    id: 999,
                    title: 'Repeating Event',
                    start: new Date(y, m, d+4, 16, 0),
                    allDay: false
                },
                {
                    title: 'Meeting',
                    start: new Date(y, m, d, 10, 30),
                    allDay: false
                },
                {
                    title: 'Lunch',
                    start: new Date(y, m, d, 12, 0),
                    end: new Date(y, m, d, 14, 0),
                    allDay: false
                },
                {
                    title: 'Birthday Party',
                    start: new Date(y, m, d+1, 19, 0),
                    end: new Date(y, m, d+1, 22, 30),
                    allDay: false
                },
                {
                    title: 'Click for Google',
                    start: new Date(y, m, 28),
                    end: new Date(y, m, 29),
                    url: 'http://google.com/'
                }
            ]
        });
    }

    render() {
        return (
            <div className="wrapper wrapper-content">
                <div className="row animated fadeInDown">
                    <div className="col-lg-3">
                        <div className="ibox float-e-margins">
                            <div className="ibox-title">
                                <h5>Draggable Events</h5>
                                <div className="ibox-tools">
                                    <a className="collapse-link">
                                        <i className="fa fa-chevron-up"></i>
                                    </a>
                                    <a className="dropdown-toggle" data-toggle="dropdown" href="#">
                                        <i className="fa fa-wrench"></i>
                                    </a>
                                    <ul className="dropdown-menu dropdown-user">
                                        <li><a href="#">Config option 1</a>
                                        </li>
                                        <li><a href="#">Config option 2</a>
                                        </li>
                                    </ul>
                                    <a className="close-link">
                                        <i className="fa fa-times"></i>
                                    </a>
                                </div>
                            </div>
                            <div className="ibox-content">
                                <div id='external-events'>
                                    <p>Drag a event and drop into callendar.</p>
                                    <div className="external-event navy-bg">Go to shop and buy some products.</div>
                                    <div className="external-event navy-bg">Check the new CI from Corporation.</div>
                                    <div className="external-event navy-bg">Send documents to John.</div>
                                    <div className="external-event navy-bg">Phone to Sandra.</div>
                                    <div className="external-event navy-bg">Chat with Michael.</div>
                                    <p className="m-t">
                                        <input type='checkbox' id='drop-remove' className="i-checks" checked/> <label>remove after drop</label>
                                    </p>
                                </div>
                            </div>
                        </div>
                        <div className="ibox float-e-margins">
                            <div className="ibox-content">
                                <h2>FullCalendar</h2> is a jQuery plugin that provides a full-sized, drag & drop
                                calendar like the one below. It uses AJAX to fetch events on-the-fly for each month and
                                is
                                easily configured to use your own feed format (an extension is provided for Google
                                Calendar).
                                <p>
                                    <a href="http://arshaw.com/fullcalendar/" target="_blank">FullCalendar
                                        documentation</a>
                                </p>
                            </div>
                        </div>
                    </div>
                    <div className="col-lg-9">
                        <div className="ibox float-e-margins">
                            <div className="ibox-title">
                                <h5>Striped Table </h5>
                                <div className="ibox-tools">
                                    <a className="collapse-link">
                                        <i className="fa fa-chevron-up"></i>
                                    </a>
                                    <a className="dropdown-toggle" data-toggle="dropdown" href="#">
                                        <i className="fa fa-wrench"></i>
                                    </a>
                                    <ul className="dropdown-menu dropdown-user">
                                        <li><a href="#">Config option 1</a>
                                        </li>
                                        <li><a href="#">Config option 2</a>
                                        </li>
                                    </ul>
                                    <a className="close-link">
                                        <i className="fa fa-times"></i>
                                    </a>
                                </div>
                            </div>
                            <div className="ibox-content">
                                <div id="calendar"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default Activity;
</code>```

答:
Error you have in here is very clear:

```<code>import  draggable from
     '../../../node_modules/jquery-ui/ui/widgets/draggable';
</code>```

Read more about es 6 import

Can you tell me about your app, combine redux and jQuery is so weird....

Body:
I'm using React-Redux for my project. When I want to use draggable I got this error on browser. I added Jquery and Jquery-ui. But I still got this error. I searched this topic but they didn't use react. I tried many things and finally I solve the problem. Maybe you need it as well so I want to share it.

First of all you should add this modules like this:

import $ from 'jquery';
import  draggable from '../../../node_modules/jquery-ui/ui/widgets/draggable';

And then;

 $(document).ready(function() {
            $('#external-events div.external-event').each(function(index,element) {

                // store data so the calendar knows to render an event upon drop
                $(element).data('event', {
                    title: $.trim($(element).text()), // use the element's text as the event title
                    stick: true // maintain when user navigates (see docs on the renderEvent method)
                });

                // make the event draggable using jQuery UI
                $(element).draggable({
                    zIndex: 1111999,
                    revert: true,      // will cause the event to go back to its
                    revertDuration: 0  //  original position after the drag
                });

            });

        });

But be attention please we are not use $(this) for element.
I found example like below but it did not work because of $(this).

$('#external-events div.external-event').each(function() {

            // store data so the calendar knows to render an event upon drop
            $(this).data('event', {
                title: $.trim($(this).text()), // use the element's text as the event title
                stick: true // maintain when user navigates (see docs on the renderEvent method)
            });

            // make the event draggable using jQuery UI
            $(this).draggable({
                zIndex: 1111999,
                revert: true,      // will cause the event to go back to its
                revertDuration: 0  //  original position after the drag
            });

        });

I hope it helps :)

Here is my full code.

import React, {Component} from 'react';
import $ from 'jquery';
import  draggable from '../../../node_modules/jquery-ui/ui/widgets/draggable';
import fullCalendar from 'fullcalendar';

class Activity extends Component {

    componentDidMount() {

        $(document).ready(function() {
            $('#external-events div.external-event').each(function(index,element) {

                // store data so the calendar knows to render an event upon drop
                $(element).data('event', {
                    title: $.trim($(element).text()), // use the element's text as the event title
                    stick: true // maintain when user navigates (see docs on the renderEvent method)
                });

                // make the event draggable using jQuery UI
                $(element).draggable({
                    zIndex: 1111999,
                    revert: true,      // will cause the event to go back to its
                    revertDuration: 0  //  original position after the drag
                });

            });

        });

        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();

        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            editable: true,
            droppable: true, // this allows things to be dropped onto the calendar
            drop: function() {
                // is the "remove after drop" checkbox checked?
                if ($('#drop-remove').is(':checked')) {
                    // if so, remove the element from the "Draggable Events" list
                    $(this).remove();
                }
            },
            events: [
                {
                    title: 'All Day Event',
                    start: new Date(y, m, 1)
                },
                {
                    title: 'Long Event',
                    start: new Date(y, m, d-5),
                    end: new Date(y, m, d-2)
                },
                {
                    id: 999,
                    title: 'Repeating Event',
                    start: new Date(y, m, d-3, 16, 0),
                    allDay: false
                },
                {
                    id: 999,
                    title: 'Repeating Event',
                    start: new Date(y, m, d+4, 16, 0),
                    allDay: false
                },
                {
                    title: 'Meeting',
                    start: new Date(y, m, d, 10, 30),
                    allDay: false
                },
                {
                    title: 'Lunch',
                    start: new Date(y, m, d, 12, 0),
                    end: new Date(y, m, d, 14, 0),
                    allDay: false
                },
                {
                    title: 'Birthday Party',
                    start: new Date(y, m, d+1, 19, 0),
                    end: new Date(y, m, d+1, 22, 30),
                    allDay: false
                },
                {
                    title: 'Click for Google',
                    start: new Date(y, m, 28),
                    end: new Date(y, m, 29),
                    url: 'http://google.com/'
                }
            ]
        });
    }

    render() {
        return (

Draggable Events

Config option 1

Config option 2

Drag a event and drop into callendar.

Go to shop and buy some products.

Check the new CI from Corporation.

Send documents to John.

Phone to Sandra.

Chat with Michael.

                                        <input type='checkbox' id='drop-remove' className="i-checks" checked/> remove after drop

FullCalendar
 is a jQuery plugin that provides a full-sized, drag & drop
                                calendar like the one below. It uses AJAX to fetch events on-the-fly for each month and
                                is
                                easily configured to use your own feed format (an extension is provided for Google
                                Calendar).

                                    FullCalendar
                                        documentation

Striped Table

Config option 1

Config option 2

        );
    }
}

export default Activity;

Body:
Error you have in here is very clear:

import  draggable from
     '../../../node_modules/jquery-ui/ui/widgets/draggable';

Read more about es 6 import

Can you tell me about your app, combine redux and jQuery is so weird....


问:
Make buttons appear after a couple of seconds
I'm making a "landing page" for my website where I put all of my exercises.
I would like to make my buttons "fade in" after a couple a seconds. How do I do this?

This is my button class: .fadeButton

I got this far with jquery to make it animate after couple of seconds: $( ".fadeButton" ).delay( 6000 );

But I don't know how to let the buttons fade in instead of showing it directly

答: The easiest way to do this would probably be using animate.css (https://daneden.github.io/animate.css/). Then it's as simple as adding a class with 'animated' and 'fadeIn' to any element you want to fade in.</p>


问:
Does Clear Data on App Settings clears all Android KeyStore stored for that certain app?
Just want to know if Clear Data in App's Setting clears all Android Keystore stored in that certain app? Or it leaves certain bits of data?

Android Keystore I'm referring to is similar to this KeyStore. See Tutorials below.

From Android Developer

From Medium Tutorial

From Android Authority Tutorial

答:
clears all Android Keystore stored in that certain app? Or it leaves
  certain bits of data?

Yes, It will reset all data of that application.

Clearing the data, however, will remove any user data, databases, etc -- this includes things like account settings, persistent preferences, etc.

Clearing the data should revert the application back to it's state as it was when you first installed it.

As an example, assume we have a Twitter application.
Clearing the data would remove any information at all, including your login information, who you're following, whether or not you want to be notified of new tweets, and things like that.

In short, it delete all applications data.

Check description for more details


问:
Android Facebook Integration Invalid Key hash error on Android device but working fine on Emulator
When I run my Android app in my android device it was working fine when I clicked first time on Continues with Facebook button.When i try to login again after logged out it is showing an error "Invalid Key has" The key has does not match any stored key hash. I have already  regenerated key hash and replaced new key on facebook. bUt still did not get result.

First time I had easily logged-in, But after logged out again I'm trying to Continues with Facebook but it is showing an error message "Invalid Key has":

But the same application is running perfectly fine on Emulator. why it is not working on my devices?

答:
Here is what you need to do -

Download openSSl from Code Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.

detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step.

detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-

```<code>$ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64
</code>```

it will ask for password, put android that's all. u will get a key-hash

Body:
Here is what you need to do -

Download openSSl from Code Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.

detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step.

detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-

$ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64

it will ask for password, put android that's all. u will get a key-hash


问:
react native TextInput onBlur get unedfined at android
My react-native version is 0.38.0

```<code><TextInput onBlur={ (event) =>
   this.handleBlurCheck(event.nativeEvent.text,params) } />
</code>```

In function handleBlurCheck, I get the value at iOS, but I get undefined at Android.

How to get value when TextInput is blurred on android platform?

The nativeEvent object on iOS:

```<code>nativeEvent:{
    eventCount: 5,
    target: 1046,
    text: '56'
}
</code>```

The nativeEvent on Android:

```<code>nativeEvent:{
    target: 1046,
}
</code>```

答:
I just use onChange to get the value.

```<code>  onChange={(event) => this.setState({
                         value: event.nativeEvent.text
                       })}
</code>```

and trigger the functions on blur

Body:
My react-native version is 0.38.0

<TextInput onBlur={ (event) =>
   this.handleBlurCheck(event.nativeEvent.text,params) } />

In function handleBlurCheck, I get the value at iOS, but I get undefined at Android.

How to get value when TextInput is blurred on android platform?

The nativeEvent object on iOS:

nativeEvent:{
    eventCount: 5,
    target: 1046,
    text: '56'
}

The nativeEvent on Android:

nativeEvent:{
    target: 1046,
}

Body:
I just use onChange to get the value.

  onChange={(event) => this.setState({
                         value: event.nativeEvent.text
                       })}

and trigger the functions on blur


问:
Need to display 2 input text after selecting a specific value in drop down in angular 4
I have a specific requirement. I need to display 2 input text fields after selecting a specific value from a drop down which is 'Add New...'
My code snippet is below -

```<code>    <td>
    <div *ngIf="item.showOperationField">
        <p-checkbox
            value ="inflationaryImpactCheck"
            label="Save for Inflationary Impact"
            name = "calculationSaveInflation"
            [(ngModel)]="item.inflationaryImpact"
            pTooltip="Check the Inflationary Impact box to map this calculation to an index for Inflationary Pressure calculation."
            binary="true">
        </p-checkbox>
    </div>
    </td>
    <td>
    <div *ngIf="item.inflationaryImpact">
        <p-dropdown
            [style]="{'width':'200px'}"
            [options]="inflation"
            name = "calculationInflation"
            [(ngModel)]="item.selectedInflation">
        </p-dropdown>
    </div>
    </td>
<td>
<div *ngIf="item.selectedInflation=='Add New...'">
   <input
    [style]="{'width':'200px'}"
    type="text"
    name="catValue"
    pInputText
    [(ngModel)]="item.catValue"
    />
</div>
</td>
</code>```

Now I need to display 2 input boxes while selecting a specific value from the drop down "inflation" which is 'Add New...'. I have tried with the above  code snippet but nothing happened.
Please help me.

答:
You should use a FormGroup or FormArray(better way but for your code maybe FormGroup is better) in the component class and when 'Add new' is selected trigger a funtion that add a new FormControl to the FormGroup or FormArray, then use *ngFor in the html template.

```<code><div *ngIf="item.selectedInflation==='Add New...'">
<div [formGroupName]="FormGroup" *ngFor="let entry of FormGroup.controls; let i=index" >
   <input
    [style]="{'width':'200px'}"
    type="text"
    name="catValue"
    pInputText
    [(ngModel)]="item.catValue"
    />
</div>
</div>
</td>
</code>```

This work for adding a new input everythime 'Add new' is selected, but if you want to show only one input then the *ngIf should work, if not check [(ngModel)] maybe the problem is there or maybe the string in item.selectedInflation is not equal to 'Add New...'. Anyway post more code for a better answer.

```<code> <div *ngIf="item.selectedInflation==='Add New...'">
</code>```

Body:
I have a specific requirement. I need to display 2 input text fields after selecting a specific value from a drop down which is 'Add New...'
My code snippet is below -

   <input
    [style]="{'width':'200px'}"
    type="text"
    name="catValue"
    pInputText
    [(ngModel)]="item.catValue"
    />

Now I need to display 2 input boxes while selecting a specific value from the drop down "inflation" which is 'Add New...'. I have tried with the above  code snippet but nothing happened.
Please help me.

Body:
You should use a FormGroup or FormArray(better way but for your code maybe FormGroup is better) in the component class and when 'Add new' is selected trigger a funtion that add a new FormControl to the FormGroup or FormArray, then use *ngFor in the html template.

<div *ngIf="item.selectedInflation==='Add New...'">
<div [formGroupName]="FormGroup" *ngFor="let entry of FormGroup.controls; let i=index" >
   <input
    [style]="{'width':'200px'}"
    type="text"
    name="catValue"
    pInputText
    [(ngModel)]="item.catValue"
    />
</div>
</div>
</td>

This work for adding a new input everythime 'Add new' is selected, but if you want to show only one input then the *ngIf should work, if not check [(ngModel)] maybe the problem is there or maybe the string in item.selectedInflation is not equal to 'Add New...'. Anyway post more code for a better answer.

 <div *ngIf="item.selectedInflation==='Add New...'">


问:
Do a count and group by weeks or months
I have an object array like this:

```<code>[ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ]
</code>```

Using the momentJS library and pure javascript only (no lodash _groupBy etc), how can I group the results and add together the 'count' to be like this:

Week Grouping: (Monday is start of week)

```<code>[ { date: '2017-11-13', count: 104 }, { date: '2017-11-06', count: 22 }, { date: '2017-10-02', count: 66 } ]
</code>```

Month Grouping: (1st of month is start of month)

```<code>[ { date: '2017-11-01', count: 26 }, { date: '2017-10-01', count: 66 } ]
</code>```

Thank You.

答:
You can use array#reduce to group your data array into groups of month and week using a object lookup.

const data = [ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ];

var sortedByMonth = data.reduce((res, {date, count}) => {
  let [year, month, day] = date.split('-');
  res[month] ? res[month].count += count : res[month] = { date : year+'-'+month+'-'+'01', count};
  return res;
},{});

console.log(Object.values(sortedByMonth));

var sortedByWeek = data.reduce((res, {date, count}) => {
  var startOfWeek = moment(date, 'YYYY-MM-DD').startOf('week').add(1,'days');
  res[startOfWeek] ? res[startOfWeek].count += count : res[startOfWeek] = {date: moment(startOfWeek).format('YYYY-MM-DD'), count};
  return res;
},{});
console.log(Object.values(sortedByWeek));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```

Title: Do a count and group by weeks or months

Body:
I have an object array like this:

[ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ]

Using the momentJS library and pure javascript only (no lodash _groupBy etc), how can I group the results and add together the 'count' to be like this:

Week Grouping: (Monday is start of week)

[ { date: '2017-11-13', count: 104 }, { date: '2017-11-06', count: 22 }, { date: '2017-10-02', count: 66 } ]

Month Grouping: (1st of month is start of month)

[ { date: '2017-11-01', count: 26 }, { date: '2017-10-01', count: 66 } ]

Thank You.

Body:
You can use array#reduce to group your data array into groups of month and week using a object lookup.

const data = [ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ];

var sortedByMonth = data.reduce((res, {date, count}) => {
  let [year, month, day] = date.split('-');
  res[month] ? res[month].count += count : res[month] = { date : year+'-'+month+'-'+'01', count};
  return res;
},{});

console.log(Object.values(sortedByMonth));

var sortedByWeek = data.reduce((res, {date, count}) => {
  var startOfWeek = moment(date, 'YYYY-MM-DD').startOf('week').add(1,'days');
  res[startOfWeek] ? res[startOfWeek].count += count : res[startOfWeek] = {date: moment(startOfWeek).format('YYYY-MM-DD'), count};
  return res;
},{});
console.log(Object.values(sortedByWeek));

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>


问:
Simple string as JSON return value in spring rest controller
Let's take a look at the following simple test controller (Used with Spring 4.0.3):

@RestController
public class TestController
{
    @RequestMapping("/getList")
    public List<String> getList()
    {
        final List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        return list;
    }

    @RequestMapping("/getString")
    public String getString()
    {
        return "Hello World";
    }
}
```

<p>In theory both controller methods should return valid JSON. Calling the first controller method indeed does return the following JSON array:</p>

```$ curl -i -H "Accept: application/json" http://localhost:8080/getList
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8

["1","2"]
```

<p>But the second controller method returns the string without quotes which is not a valid JSON string:</p>

```$ curl -i -H "Accept: application/json" http://localhost:8080/getString
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8

Hello World
```

Why is that so? Can it be configured? Is it a bug? Or a feature I don't understand?

答:
If you want to return a String object, Spring MVC interprets that as the content to put in the response body and doesn't modify it further. If you're wanting an actual string to be the JSON response, you'll need to either quote it yourself or run it through Jackson explicitly.</p>

```<code>@RestController
public class TestController
{
   @RequestMapping("/getString")
   public String getString()
  {
    return JSONObject.quote("Hello World");
  }
}
</code>```

Body:
Let's take a look at the following simple test controller (Used with Spring 4.0.3):

@RestController
public class TestController
{
    @RequestMapping("/getList")
    public List<String> getList()
    {
        final List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        return list;
    }

    @RequestMapping("/getString")
    public String getString()
    {
        return "Hello World";
    }
}

In theory both controller methods should return valid JSON. Calling the first controller method indeed does return the following JSON array:

$ curl -i -H "Accept: application/json" http://localhost:8080/getList
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8

["1","2"]

But the second controller method returns the string without quotes which is not a valid JSON string:

$ curl -i -H "Accept: application/json" http://localhost:8080/getString
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8

Hello World

Why is that so? Can it be configured? Is it a bug? Or a feature I don't understand?

Body:
If you want to return a String object, Spring MVC interprets that as the content to put in the response body and doesn't modify it further. If you're wanting an actual string to be the JSON response, you'll need to either quote it yourself or run it through Jackson explicitly.

@RestController
public class TestController
{
   @RequestMapping("/getString")
   public String getString()
  {
    return JSONObject.quote("Hello World");
  }
}


问:
Java Hibernate H2-sql database
I have a java program that is annotated to create tables in a test database. Right now I get 3 tables created with my annotations and I have a SQL statement that works that JOINS all the 3 tables into one and displays the information way better than to have to check all 3 tables individually.

Iam wondering if there is a way to incorporate my SQL statement into that database so that when i start the program i dont have to write the statement every time to join the 3 tables. Is it possible to apply a SQL statement in application.properties file that creates a VIEW TABLE automatically that joins the 3 tables? Or is there a simpler way? maybe write a sql query in the java code that does that?

答:
You can use JDBCTemplate and execute native SQL query adding mapping to convert query results to Java POJO class - DTO. (See the example)

Or you can use H2 CREATE VIEW to have a view for the query and add a read only hibernate entity to map to the view.

Title: Java Hibernate H2-sql database


问:
Java: Mixin implementation classes
I've seen in several code libraries classes named Mixin with comments like:

```<code>//Mixin style implementation
public class DetachableMixin implements Detachable {}
</code>```

Which is the concept under this style of implementations?

答:
The other answer is spot on, but it might be worth pointing out that other JVM languages go even further.

Scala for examples has traits - basically "interfaces" with method implementations. In scala, you can mix one class together with multiple traits, thereby allowing to inherit behavior from several different "places.

Basically the same concept that Java picked up with Java 8, where you know can add default method behavior to interfaces. And for the record: if I recall it correctly, Java8 interfaces and default methods are not meant to introduce a full "mixin" concept in the Java language. The idea is not that you should use this feature to achieve multiple inheritance through the back door. See this lengthy answer from Stuart Mark, one of the people driving the Java language evolution. They state:

The purpose of default methods ... is to enable interfaces to be evolved in a compatible manner after their initial publication.

Title: Java: Mixin implementation classes

Body:
I've seen in several code libraries classes named Mixin with comments like:

//Mixin style implementation
public class DetachableMixin implements Detachable {}

Which is the concept under this style of implementations?


问:
Create products Google play and in-app billing
I'm doing an app that have a RecyclerView with many items (some of them are fixed and are by default for everyone), but I'd like to make some of them "not free", means that you have to pay (if possible using Google Play) to unlock those items, can you guide to me how do I figure out this scenario? How do I know that the user has items that has paid for them, and when I know that he paid for them.

I do not want to use a Database because I only need two tables I guess, for example;

TABLE USER

Where I'll will store an id (I guess it will be the email if I finally create a Login GMAIL,FACEBOOK)

TABLE BOX

Where I'll put the BOX that are free and not free and as a Foreign Key I'll put the user.id to get references what BOX's he/she owns.

Right?

But, If I have to choose this way, because if the user pays for a box on my APP and then he want to use it in other device, it won't have the box unless he logs in on the new device, correct? So, If I had had to choose a Database and Hosting to do it, what will be your recommendation? (From start, I won't have too much data, so I don't need the best one, I only want to communicate with my Android app).

I hope it's clear now, otherwise, put a comment and I'll try to explain it better.

EDIT

Reading the answers I see that I can use Firebase, as @Haris Qureshi said, well what I'm confused is :

How do I store the product? I mean, I've read and watched videos on YouTube and I have to do it in Console of Google Play but do I need to send the .apk and then add the products?

If I do not need to create a Database, and I have to end up using Firebase, using the Storage stuff from Firebase will store my products? But I can assign it as a PURCHASED, PAID, AVAILABLE? Also I'll need to integrate the Authentication, right? Because he said that once you buy a product, it stores the gmail that has paid for it and you know who paid and not paid, so if he uses another device it will have the same products boughts (if he still with the same gmail).

The products can be dynamics? I mean, you can create for example an "event" and put that product only for x days, as I'll need an Image to show the product, I mean the product will have also an Image to show on the UI, but I see in the Console of Google Play I only can create an id for the product and if I'd have to create it dynamic I could do that, because I have to store the Images on /res/mipmap right?

EDIT2

What I need is what @Alex Mamo told to me :

You cannot store images in your Firebase database. You need to store them in Firebase Storage. In Firebase database you need to store only the urls of those images.

The flow is like this: upload image to Firebase Storage -> get the url of the corresponding image (when uploading) -> store the url in Firebase Database -> use the reference to display the image

I've created the products on google console developer, and I have to connect my app to in-app billing

答:
Saw your comment from here. I paid attention to the edited part. Here's my two cents:

How do I store the product? I mean, I've read and watched videos on YouTube and I have to do it in Console of Google Play but do I need to send the .apk and then add the products?

You could store it directly from the Firebase Console. Afterwards, you could set your app to get the products by using the Firebase SDK. If you already have the app uploaded on Google Play, I think you just need to upload the updated APK that could perform the data retrieval (using the Firebase SDK).

If I do not need to create a Database, and I have to end up using Firebase, using the Storage stuff from Firebase will store my products? But I can assign it as a PURCHASED, PAID, AVAILABLE? Also I'll need to integrate the Authentication, right?

If I understand your requirement correctly, you would most certainly need a database. It would be easier for you to organize the products that way. From the (Firebase) Database itself, you could also put the user details there, set if they are already PAID or just using the app for FREE, this way, it'd be easier to check which products the user could access or not.

Firebase Database would work on it's own without Firebase Auth, however, it is strongly suggested to use it together, to make use of the Security Rules.

The products can be dynamics? I mean, you can create for example an "event" and put that product only for x days, as I'll need an Image to show the product, I mean the product will have also an Image to show on the UI, but I see in the Console of Google Play I only can create an id for the product and if I'd have to create it dynamic I could do that, because I have to store the Images on /res/mipmap right?

It depends on how you implement it, but yes it is most certainly possible to create a dynamic product. You could have the product details in the DB and the image file in Cloud Storage for Firebase. You could make this dynamic by adding something like an expirationDate parameter in the product details, and when retrieving the data in your app, you could simply check if it's already expired or not.


问:
round() for float in C++
I need a simple floating point rounding function, thus:

```<code>double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1
</code>```

I can find ceil() and floor() in the math.h - but not round().

Is it present in the standard C++ library under another name, or is it missing??

答:
These days it shouldn't be a problem to use a C++11 compiler which includes a C99/C++11 math library.  But then the question becomes: which rounding function do you pick?

C99/C++11 round() is often not actually the rounding function you want.  It uses a funky rounding mode that rounds away from 0 as a tie-break on half-way cases (+-xxx.5000).  If you do specifically want that rounding mode, or you're targeting a C++ implementation where round() is faster than rint(), then use it (or emulate its behaviour with one of the other answers on this question which took it at face value and carefully reproduced that specific rounding behaviour.)

round()'s rounding is different from the IEEE754 default round to nearest mode with even as a tie-break.  Nearest-even avoids statistical bias in the average magnitude of numbers, but does bias towards even numbers.

There are two math library rounding functions that use the current default rounding mode: std::nearbyint() and std::rint(), both added in C99/C++11, so they're available any time std::round() is.  The only difference is that nearbyint never raises FE_INEXACT.

Prefer rint() for performance reasons: gcc and clang both inline it more easily, but gcc never inlines nearbyint() (even with -ffast-math)

gcc/clang for x86-64 and AArch64

I put some test functions on Matt Godbolt's Compiler Explorer, where you can see source + asm output (for multiple compilers).  For more about reading compiler output, see this Q&A, and Matt's CppCon2017 talk: “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid”,

In FP code, it's usually a big win to inline small functions.  Especially on non-Windows, where the standard calling convention has no call-preserved registers, so the compiler can't keep any FP values in XMM registers across a call.  So even if you don't really know asm, you can still easily see whether it's just a tail-call to the library function or whether it inlined to one or two math instructions.  Anything that inlines to one or two instructions is better than a function call (for this particular task on x86 or ARM).

On x86, anything that inlines to SSE4.1 roundsd can auto-vectorize with SSE4.1 roundpd (or AVX vroundpd).  (FP->integer conversions are also available in packed SIMD form, except for FP->64-bit integer which requires AVX512.)

std::nearbyint():

x86 clang: inlines to a single insn with -msse4.1.

x86 gcc: inlines to a single insn only with -msse4.1 -ffast-math, and only on gcc 5.4 and earlier.  Later gcc never inlines it (maybe they didn't realize that one of the immediate bits can suppress the inexact exception?  That's what clang uses, but older gcc uses the same immediate as for rint when it does inline it)

AArch64 gcc6.3: inlines to a single insn by default.

std::rint:

x86 clang: inlines to a single insn with -msse4.1

x86 gcc7: inlines to a single insn with -msse4.1.  (Without SSE4.1, inlines to several instructions)

x86 gcc6.x and earlier: inlines to a single insn with -ffast-math -msse4.1.

AArch64 gcc: inlines to a single insn by default

std::round:

x86 clang: doesn't inline

x86 gcc: inlines to multiple instructions with -ffast-math -msse4.1, requiring two vector constants.

AArch64 gcc: inlines to a single instruction (HW support for this rounding mode as well as IEEE default and most others.)

std::floor / std::ceil / std::trunc

x86 clang: inlines to a single insn with -msse4.1

x86 gcc7.x: inlines to a single insn with -msse4.1

x86 gcc6.x and earlier: inlines to a single insn with -ffast-math -msse4.1

AArch64 gcc: inlines by default to a single instruction

Rounding to int / long / long long:

You have two options here: use lrint (like rint but returns long, or long long for llrint), or use an FP->FP rounding function and then convert to an integer type the normal way (with truncation).  Some compilers optimize one way better than the other.

```<code>long l = lrint(x);

int  i = (int)rint(x);
</code>```

Note that int i = lrint(x) converts float or double -> long first, and then truncates the integer to int.  This makes a difference for out-of-range integers: Undefined Behaviour in C++, but well-defined for the x86 FP -> int instructions (which the compiler will emit unless it sees the UB at compile time while doing constant propagation, then it's allowed to make code that breaks if it's ever executed).

On x86, an FP->integer conversion that overflows the integer produces INT_MIN or LLONG_MIN (a bit-pattern of 0x8000000 or the 64-bit equivalent, with just the sign-bit set).  Intel calls this the "integer indefinite" value.  (See the cvttsd2si manual entry, the SSE2 instruction that converts (with truncation) scalar double to signed integer.  It's available with 32-bit or 64-bit integer destination (in 64-bit mode only).  There's also a cvtsd2si (convert with current rounding mode), which is what we'd like the compiler to emit, but unfortunately gcc and clang won't do that without -ffast-math.

Also beware that FP to/from unsigned int / long is less efficient on x86 (without AVX512).  Conversion to 32-bit unsigned on a 64-bit machine is pretty cheap; just convert to 64-bit signed and truncate.  But otherwise it's significantly slower.

x86 clang with/without -ffast-math -msse4.1: (int/long)rint inlines to roundsd / cvttsd2si.  (missed optimization to cvtsd2si).  lrint doesn't inline at all.

x86 gcc6.x and earlier without -ffast-math: neither way inlines

x86 gcc7 without -ffast-math: (int/long)rint rounds and converts separately (with 2 total instructions of SSE4.1 is enabled, otherwise with a bunch of code inlined for rint without roundsd).  lrint doesn't inline.

x86 gcc with -ffast-math: all ways inline to cvtsd2si (optimal), no need for SSE4.1.

AArch64 gcc6.3 without -ffast-math: (int/long)rint inlines to 2 instructions.  lrint doesn't inline

AArch64 gcc6.3 with -ffast-math: (int/long)rint compiles to a call to lrint.  lrint doesn't inline.  This may be a missed optimization unless the two instructions we get without -ffast-math are very slow.

OwnerDisplayName: Roddy

Title: round() for float in C++

Body:
I need a simple floating point rounding function, thus:

double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1

I can find ceil() and floor() in the math.h - but not round().

Is it present in the standard C++ library under another name, or is it missing??

Body:
These days it shouldn't be a problem to use a C++11 compiler which includes a C99/C++11 math library.  But then the question becomes: which rounding function do you pick?

C99/C++11 round() is often not actually the rounding function you want.  It uses a funky rounding mode that rounds away from 0 as a tie-break on half-way cases (+-xxx.5000).  If you do specifically want that rounding mode, or you're targeting a C++ implementation where round() is faster than rint(), then use it (or emulate its behaviour with one of the other answers on this question which took it at face value and carefully reproduced that specific rounding behaviour.)

round()'s rounding is different from the IEEE754 default round to nearest mode with even as a tie-break.  Nearest-even avoids statistical bias in the average magnitude of numbers, but does bias towards even numbers.

There are two math library rounding functions that use the current default rounding mode: std::nearbyint() and std::rint(), both added in C99/C++11, so they're available any time std::round() is.  The only difference is that nearbyint never raises FE_INEXACT.

Prefer rint() for performance reasons: gcc and clang both inline it more easily, but gcc never inlines nearbyint() (even with -ffast-math)

gcc/clang for x86-64 and AArch64

<a href="https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSBnVAV2OUxAHIBSAJgGY8AMyxCA1AH0JyAA4AbZg3mLuABgCCfQQDtkCrGO78AwsgC2AQwIIj2NZoGY5DTPa15d%2BzIZOXrAOht%2BOw0tTG18ITcNAHoYsQsZGQticII5AE8xYGRkMXRUTAZtME4CMQBrbVQAdzEEWrEiMQ85D29rPAYxTAA3cLEawgQxIQsGAgBaPxsNAuYAIzlvRUwJbUwUhYyIeaXvAA8ASkMAdgAhMVSCVm0xDa2MjwIIY6NL7lOAEWj1OLEACoIbyobSZfLCISYVK6bwLTAEGqYAYTdAgEAPYjbZ4JCJiVHo4g4rpNBBWfEENEYzZYp7acobfrEK4WLpFMQAMWwEgAkgA5bAADXUxgB/ns/xyeQseL0MuAYgWqGslWqdQadWarXaV2e9j2yzEqwkRPpuxY%2BzExzOl2ut11Zre/A%2B31%2BBpWLhNLAi5sWhutn1tCPtxG96FeR3eZx%2BoVi8Slp1x6DEcu0CqGcjkLTBOs63T6AyG1hY5UmQmq0ysCEm0OI1Ql8dyADYkz0Um1ofdkcmxhNK9Z9RbDcxtAwLFCJEI5KgSL7LQGLvYxMursG66Np7ODoZeJdVP4AKyR51uV1x/JDj1rAjEEfIOf%2Bk6B5d29c3u8RqOfGOaDQ400EBIzwPocT6LhoK6rjc64QM8RwAZ%2BJ6hGe6jTmmDqAWhwAgVaYHnEuK6vncEBYfBwFOvhyE/jixpyAh7q4TaBEvmudx0eRx6UZo3ycEcpByFwB6cKQ2hcKowmoFwxh8Phu74iwbDeFotDCQQYm8XxFQgPw/D%2BAAnAALAeTZGacpwABy0KcqiqAeBn8VwBnCaJnDiaQkmcMJDAgKopBqa5vGkHAsAwIgKCoGYMh4MsZAUBAaCRdF0IgMApy8KQQjRQQ0LeRACzqaQCweCkGRcCppAJWYaQAPJgqVAWkFglhpssBX4KkyAEHg/TeQ1mAHJgyDMNlZXCc8TgFTeeBmKNfFtAs3mQHxqAyF1oK9ZMqJGF8wDaMwMkybQtBiJMADqFiZid1X8CdlhsEEXxkgwSKZl5CnsHQc2Cc5BUeQc5lNpMJnZLkYinP4vBiBAuCECQO78PQYjGBFUUxfDtBHKp6lHJp2m8IetBNnphOnAZqi8FZaX2QJnBOaQM0Hr5LluR5Xk%2BX52NBaFEBIAlqPQuQlB80lxApXZvmZXI2XELl%2BUNUV2glaNFURVV9K1ZkbWYM1wCtQ17WDV1PUFf1g3DRwnDleNNNuVNM2W4F82LRAy2rXg61cJMBx5JtlLbbtzB6XpJ3nZdkzXbdKTIA9T0vVmZa9lMMxvawH0Yw5nBCSJv1cP9gPA1KYgHv4BlQzDRDMsppBIyjIvw/wmMcwFOOkMCFhYKLLsZ3TDNMznnmMOz/niS3Wn8PjaW0OTqjmbPBl6U2Ta8AeGf8D9DWs03I9c/AwVhcLMWC/FtcxSgcjyvwekS1lOWUHLbkK0rDsq2YasEBr9VuU18p61/eAdUbIoJsBpDRGs/a2k0iT2xUnNPAC14CuzWqOT2W1%2BA7T2gdXcR0Q4XXjhHSs91tobDJMsMwKdFKfQzlnZmElc4AyBqXVMCpdJ6X8KoMu%2BAK7o2rsjRKaMtC8EbsPDSpAx66R0hIyRUju7CV7tnDeXA2a%2BWEXxPePNwp8IFnFA%2ByUUhmBMsAJs/Br5S1vnlAqj9iD1XKpVGqdUtY61/sJA2nVupAL6iA82ysIENTtrNficDnaIPdsgzgvt0D%2BwwbuQ6x0zq4KumvRg70ODpxptQ/u6gABKABZAuoMmz%2BF0uwkiHhmDWmhpwuGVca6aMrgIAyQjsZ8Tbh3SgX1aayJAIzeRLNFGD2UU00R2lxFSNGTpVe69ekDxUe03gkzaHTMGUyBgISQAGSAA%3D%3D%3D" rel="noreferrer">I put some test functions on Matt Godbolt's Compiler Explorer, where you can see source + asm output (for multiple compilers).  For more about reading compiler output, see this Q&A, and Matt's CppCon2017 talk: “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid”,

In FP code, it's usually a big win to inline small functions.  Especially on non-Windows, where the standard calling convention has no call-preserved registers, so the compiler can't keep any FP values in XMM registers across a call.  So even if you don't really know asm, you can still easily see whether it's just a tail-call to the library function or whether it inlined to one or two math instructions.  Anything that inlines to one or two instructions is better than a function call (for this particular task on x86 or ARM).

On x86, anything that inlines to SSE4.1 roundsd can auto-vectorize with SSE4.1 roundpd (or AVX vroundpd).  (FP->integer conversions are also available in packed SIMD form, except for FP->64-bit integer which requires AVX512.)

std::nearbyint():

x86 clang: inlines to a single insn with -msse4.1.

x86 gcc: inlines to a single insn only with -msse4.1 -ffast-math, and only on gcc 5.4 and earlier.  Later gcc never inlines it (maybe they didn't realize that one of the immediate bits can suppress the inexact exception?  That's what clang uses, but older gcc uses the same immediate as for rint when it does inline it)

AArch64 gcc6.3: inlines to a single insn by default.

std::rint:

x86 clang: inlines to a single insn with -msse4.1

x86 gcc7: inlines to a single insn with -msse4.1.  (Without SSE4.1, inlines to several instructions)

x86 gcc6.x and earlier: inlines to a single insn with -ffast-math -msse4.1.

AArch64 gcc: inlines to a single insn by default

std::round:

x86 clang: doesn't inline

x86 gcc: inlines to multiple instructions with -ffast-math -msse4.1, requiring two vector constants.

AArch64 gcc: inlines to a single instruction (HW support for this rounding mode as well as IEEE default and most others.)

std::floor / std::ceil / std::trunc

x86 clang: inlines to a single insn with -msse4.1

x86 gcc7.x: inlines to a single insn with -msse4.1

x86 gcc6.x and earlier: inlines to a single insn with -ffast-math -msse4.1

AArch64 gcc: inlines by default to a single instruction

Rounding to int / long / long long:

You have two options here: use lrint (like rint but returns long, or long long for llrint), or use an FP->FP rounding function and then convert to an integer type the normal way (with truncation).  Some compilers optimize one way better than the other.

long l = lrint(x);

int  i = (int)rint(x);

Note that int i = lrint(x) converts float or double -> long first, and then truncates the integer to int.  This makes a difference for out-of-range integers: Undefined Behaviour in C++, but well-defined for the x86 FP -> int instructions (which the compiler will emit unless it sees the UB at compile time while doing constant propagation, then it's allowed to make code that breaks if it's ever executed).

On x86, an FP->integer conversion that overflows the integer produces INT_MIN or LLONG_MIN (a bit-pattern of 0x8000000 or the 64-bit equivalent, with just the sign-bit set).  Intel calls this the "integer indefinite" value.  (See the cvttsd2si manual entry, the SSE2 instruction that converts (with truncation) scalar double to signed integer.  It's available with 32-bit or 64-bit integer destination (in 64-bit mode only).  There's also a cvtsd2si (convert with current rounding mode), which is what we'd like the compiler to emit, but unfortunately gcc and clang won't do that without -ffast-math.

Also beware that FP to/from unsigned int / long is less efficient on x86 (without AVX512).  Conversion to 32-bit unsigned on a 64-bit machine is pretty cheap; just convert to 64-bit signed and truncate.  But otherwise it's significantly slower.

x86 clang with/without -ffast-math -msse4.1: (int/long)rint inlines to roundsd / cvttsd2si.  (missed optimization to cvtsd2si).  lrint doesn't inline at all.

x86 gcc6.x and earlier without -ffast-math: neither way inlines

x86 gcc7 without -ffast-math: (int/long)rint rounds and converts separately (with 2 total instructions of SSE4.1 is enabled, otherwise with a bunch of code inlined for rint without roundsd).  lrint doesn't inline.

x86 gcc with -ffast-math: all ways inline to cvtsd2si (optimal), no need for SSE4.1.

AArch64 gcc6.3 without -ffast-math: (int/long)rint inlines to 2 instructions.  lrint doesn't inline

AArch64 gcc6.3 with -ffast-math: (int/long)rint compiles to a call to lrint.  lrint doesn't inline.  This may be a missed optimization unless the two instructions we get without -ffast-math are very slow.