问:
LZ77 optimization
I have a code for LZ77 compression algorithm. It works fine with small files. But if I want to compress 100 kB and bigger files, it takes a lot of time.

I think, it's all because of this part:

```<code>do { // searchin for longest mathcing
                j++;
                i++;
                if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);

                if (j == strlen(searchBuffer) && lookBuffer[addJ] == lookBuffer[i]) {
                    do {
                        i++;
                        j++;
                        if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);
                        addJ++;
                    } while (lookBuffer[addJ] == lookBuffer[i] && i < lookLen);
                }
            } while (searchBuffer[j] == lookBuffer[i] && i < lookLen);
</code>```

This part searches the longest matching between search buffer and look-ahead buffer.

So, is there faster way to find this matching?

Full code for LZ77 compression:

```<code> void lz77(char *fileName, FILE *from, FILE *path, long long size) {

char *searchBuffer = (char*)malloc((searchLen) * sizeof(char)); // search array
memset(searchBuffer, 0x00, searchLen);

long i = 0, j = 0, length = 0, offset = 0, isMatching = 0, iForSearchBuff = 0, iForLookBuff = 0;
int isFirst = 1, n = 0;
unsigned char symbol;

while(!feof(from)) {
    isMatching = 0;
    length = 0;
    iForSearchBuff = 0;
    iForLookBuff = 0;
    offset = strlen(searchBuffer);
    if (isFirst) { // first symbol
        fread(searchBuffer, 1, 1, from);
        writeBit(0, 0, *searchBuffer, tmpFile); // writing(0, 0, symbol)
        isFirst = 0;
    } else {
        char *lookBuffer = (char*)malloc((lookLen) * sizeof(char)); // look array
        memset(lookBuffer, 0x00, lookLen);

        fread(lookBuffer, 1, 1, from);

        for (j = 0; j <= strlen(searchBuffer); j++) {

            i = 0;
            if (searchBuffer[j] == lookBuffer[i]) { // MATCHING
                isMatching = 1;
                long fixJ = j, fixI = i, addJ = 0;

                do { // searchin for longest mathcing
                    j++;
                    i++;
                    if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);

                    if (j == strlen(searchBuffer) && lookBuffer[addJ] == lookBuffer[i]) {
                        do {
                            i++;
                            j++;
                            if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);
                            addJ++;
                        } while (lookBuffer[addJ] == lookBuffer[i] && i < lookLen);
                    }
                } while (searchBuffer[j] == lookBuffer[i] && i < lookLen);

                if (((strlen(searchBuffer) - fixJ) <= offset) && ((i - fixI) >= length)) {
                    length = i - fixI;
                    offset = strlen(searchBuffer) - fixJ;
                    iForSearchBuff = fixI;
                    iForLookBuff = i;
                }

                j = fixJ;

            } else if (j >= (strlen(searchBuffer))) {
                if (isMatching) {
                    if (lookBuffer[iForLookBuff] == '\0') { writeBit(offset, length, ' ', tmpFile);}
                    else {
                        writeBit(offset, length, lookBuffer[iForLookBuff], tmpFile);
                        searchBuffer = insertIntoBuffer(searchBuffer, length + 1, &lookBuffer[iForSearchBuff]);
                    }

                    isMatching = 0;
                    break;
                } else {
                    writeBit(0, 0, lookBuffer[i], tmpFile);

                    searchBuffer = insertIntoBuffer(searchBuffer, 1, &lookBuffer[i]);
                    break;
                }
            }

        }
    }
}
</code>```

}

答: zlib's deflate keeps a hash table using the first three bytes at each location as the input to the hash function. For hash collisions a list is maintained for each hash value, where the length of the list is limited depending on the compression level. The hash value is computed for the first three bytes at the current position to be compressed. For each preceding position with the same hash value and within the allowed distance, the data at that position is then directly compared to find the length of the match. Then the longest match found is emitted, or the literal if there is no match of three or more bytes.</p>

Title: LZ77 optimization

Body:
I have a code for LZ77 compression algorithm. It works fine with small files. But if I want to compress 100 kB and bigger files, it takes a lot of time.

I think, it's all because of this part:

do { // searchin for longest mathcing
                j++;
                i++;
                if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);

                if (j == strlen(searchBuffer) && lookBuffer[addJ] == lookBuffer[i]) {
                    do {
                        i++;
                        j++;
                        if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);
                        addJ++;
                    } while (lookBuffer[addJ] == lookBuffer[i] && i < lookLen);
                }
            } while (searchBuffer[j] == lookBuffer[i] && i < lookLen);

This part searches the longest matching between search buffer and look-ahead buffer.

So, is there faster way to find this matching?

Full code for LZ77 compression:

 void lz77(char *fileName, FILE *from, FILE *path, long long size) {

char *searchBuffer = (char*)malloc((searchLen) * sizeof(char)); // search array
memset(searchBuffer, 0x00, searchLen);

long i = 0, j = 0, length = 0, offset = 0, isMatching = 0, iForSearchBuff = 0, iForLookBuff = 0;
int isFirst = 1, n = 0;
unsigned char symbol;

while(!feof(from)) {
    isMatching = 0;
    length = 0;
    iForSearchBuff = 0;
    iForLookBuff = 0;
    offset = strlen(searchBuffer);
    if (isFirst) { // first symbol
        fread(searchBuffer, 1, 1, from);
        writeBit(0, 0, *searchBuffer, tmpFile); // writing(0, 0, symbol)
        isFirst = 0;
    } else {
        char *lookBuffer = (char*)malloc((lookLen) * sizeof(char)); // look array
        memset(lookBuffer, 0x00, lookLen);

        fread(lookBuffer, 1, 1, from);

        for (j = 0; j <= strlen(searchBuffer); j++) {

            i = 0;
            if (searchBuffer[j] == lookBuffer[i]) { // MATCHING
                isMatching = 1;
                long fixJ = j, fixI = i, addJ = 0;

                do { // searchin for longest mathcing
                    j++;
                    i++;
                    if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);

                    if (j == strlen(searchBuffer) && lookBuffer[addJ] == lookBuffer[i]) {
                        do {
                            i++;
                            j++;
                            if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);
                            addJ++;
                        } while (lookBuffer[addJ] == lookBuffer[i] && i < lookLen);
                    }
                } while (searchBuffer[j] == lookBuffer[i] && i < lookLen);

                if (((strlen(searchBuffer) - fixJ) <= offset) && ((i - fixI) >= length)) {
                    length = i - fixI;
                    offset = strlen(searchBuffer) - fixJ;
                    iForSearchBuff = fixI;
                    iForLookBuff = i;
                }

                j = fixJ;

            } else if (j >= (strlen(searchBuffer))) {
                if (isMatching) {
                    if (lookBuffer[iForLookBuff] == '\0') { writeBit(offset, length, ' ', tmpFile);}
                    else {
                        writeBit(offset, length, lookBuffer[iForLookBuff], tmpFile);
                        searchBuffer = insertIntoBuffer(searchBuffer, length + 1, &lookBuffer[iForSearchBuff]);
                    }

                    isMatching = 0;
                    break;
                } else {
                    writeBit(0, 0, lookBuffer[i], tmpFile);

                    searchBuffer = insertIntoBuffer(searchBuffer, 1, &lookBuffer[i]);
                    break;
                }
            }

        }
    }
}

}


来源: stackexchange

问:
How to use query parameters in Nest.js?
I am a freshman in Nest.js.

And my code as below

```<code>  @Get('findByFilter/:params')
  async findByFilter(@Query() query): Promise<Article[]> {

  }
</code>```

I have used postman to test this router

http://localhost:3000/article/findByFilter/bug?google=1&baidu=2

Actually, I can get the query result { google: '1', baidu: '2' }. But I'm not clear why the url has a string 'bug'?

If I delete that word just like

http://localhost:3000/article/findByFilter?google=1&baidu=2

then the postman will shows statusCode 404.

Actually, I don't need the word bug, how to custom the router to realize my destination just like http://localhost:3000/article/findByFilter?google=1&baidu=2

Here's another question is how to make mutiple router point to one method?

答:
You can use the @Req decorator, and use param object, see :

```<code>@Get()
  findAll(
    @Req() req: Request
  ): Promise<any[]> {
    console.log(req.query);
    // another code ....
  }
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to use query parameters in Nest.js?

Body:
I am a freshman in Nest.js.

And my code as below

  @Get('findByFilter/:params')
  async findByFilter(@Query() query): Promise
 {

  }

I have used postman to test this router

http://localhost:3000/article/findByFilter/bug?google=1&baidu=2

Actually, I can get the query result { google: '1', baidu: '2' }. But I'm not clear why the url has a string 'bug'?

If I delete that word just like

http://localhost:3000/article/findByFilter?google=1&baidu=2

then the postman will shows statusCode 404.

Actually, I don't need the word bug, how to custom the router to realize my destination just like http://localhost:3000/article/findByFilter?google=1&baidu=2

Here's another question is how to make mutiple router point to one method?

Body:
You can use the @Req decorator, and use param object, see :

@Get()
  findAll(
    @Req() req: Request
  ): Promise<any[]> {
    console.log(req.query);
    // another code ....
  }


问:
How to access elements in a specific way in json?
I want to learn JSON and I am using Python. I currently have a question about how to access elements. Here would be a generic example of the JSON information:

```<code>"data":{
   "Bob":{
      "name":"Bob",
      "age":"30",
      "state":"California",
      "job":"accountant"
   },
   "Joe":{
      "name":"Bob",
      "age":"30",
      "state":"Florida",
      "job":"engineer"
   },
   "Tom":{
      "name":"Bob",
      "age":"25",
      "state":"North Dakota",
      "job":"manager"
   }
}
</code>```

Now, I would want to make a for loop that gets a list of all the names that are age 30. How am I going to do this. I tried doing something like this:

```<code>array = []
for x in range(0,3):
    if data[x]['age'] is '30'
    array.append(data[x])
</code>```

but that is definitely wrong. Can somebody teach me how to sort the items in JSON in this way?

答:
You can iterate via JSON data the same as via Python dict

```<code>import json

with open('data.json') as json_file:
    input_data = json.load(json_file)

data = []
# use dict function items that iterate via key, value in our cause k - key, v - value
for k, v in input_data['data'].items():
    if v['age'] == '30':
        data.append(v)

print(data)
</code>```

Output:

```<code>[{'name': 'Bob', 'age': '30', 'state': 'California', 'job': 'accountant'}, {'name': 'Bob', 'age': '30', 'state': 'Florida', 'job': 'engineer'}]

</code>```

Body:
I want to learn JSON and I am using Python. I currently have a question about how to access elements. Here would be a generic example of the JSON information:

"data":{
   "Bob":{
      "name":"Bob",
      "age":"30",
      "state":"California",
      "job":"accountant"
   },
   "Joe":{
      "name":"Bob",
      "age":"30",
      "state":"Florida",
      "job":"engineer"
   },
   "Tom":{
      "name":"Bob",
      "age":"25",
      "state":"North Dakota",
      "job":"manager"
   }
}

Now, I would want to make a for loop that gets a list of all the names that are age 30. How am I going to do this. I tried doing something like this:

array = []
for x in range(0,3):
    if data[x]['age'] is '30'
    array.append(data[x])

but that is definitely wrong. Can somebody teach me how to sort the items in JSON in this way?

Body:
You can iterate via JSON data the same as via Python dict

import json

with open('data.json') as json_file:
    input_data = json.load(json_file)

data = []
# use dict function items that iterate via key, value in our cause k - key, v - value
for k, v in input_data['data'].items():
    if v['age'] == '30':
        data.append(v)

print(data)

Output:

[{'name': 'Bob', 'age': '30', 'state': 'California', 'job': 'accountant'}, {'name': 'Bob', 'age': '30', 'state': 'Florida', 'job': 'engineer'}]


问:
Multivariate and multistep LSTM
Giving this example (section: Train On Multiple Lag Timesteps Example), in order to predict the next 6 hours of Pollution based on the previous 2 years data, should I just set n_hours=17520, and the number of future steps I want to predict (set n_out=6) ?

Otherwise, I've read somewhere that I should also modify the Dense layer units to the number of the future steps to predict (here is 6), however, it always returns an error. What would be the problem ?

Thank you

The modified code:

```<code>from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM

# convert series to supervised learning
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
    n_vars = 1 if type(data) is list else data.shape[1]
    df = DataFrame(data)
    cols, names = list(), list()
    # input sequence (t-n, ... t-1)
    for i in range(n_in, 0, -1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
    # forecast sequence (t, t+1, ... t+n)
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i == 0:
            names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
    # put it all together
    agg = concat(cols, axis=1)
    agg.columns = names
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg

# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# integer encode direction
encoder = LabelEncoder()
values[:,4] = encoder.fit_transform(values[:,4])
# ensure all data is float
values = values.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# specify the number of lag hours
n_hours = 17520
n_features = 8
# frame as supervised learning
reframed = series_to_supervised(scaled, n_hours, 6) # predict the next 6 hours
print(reframed.shape)

# split into train and test sets
values = reframed.values
n_train_hours = 365 * 24 *2
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]
# split into input and outputs
n_obs = n_hours * n_features
train_X, train_y = train[:, :n_obs], train[:, -n_features]
test_X, test_y = test[:, :n_obs], test[:, -n_features]
print(train_X.shape, len(train_X), train_y.shape)
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], n_hours, n_features))
test_X = test_X.reshape((test_X.shape[0], n_hours, n_features))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)

# design network
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=50, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False)
# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()

# make a prediction
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], n_hours*n_features))
# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, -7:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)
</code>```

Edit:
I have changed the value of Dense layer units to 6 and the train_y.shape[1] as well as test_y.shape[1] to 6 as follows:

```<code># load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# integer encode direction
encoder = LabelEncoder()
values[:,4] = encoder.fit_transform(values[:,4])
# ensure all data is float
values = values.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# specify the number of lag hours
n_hours =48
n_out=6
n_features = 8
# frame as supervised learning
reframed = series_to_supervised(scaled, n_hours, n_out)
print(reframed.shape)

# split into train and test sets
values = reframed.values
n_train_hours = 365 * 24 * 2
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]

# split into input and outputs
n_obs = n_hours * n_features
train_X, train_y = train[:, :n_obs], train[:, :6]#I put 6 instead of -n_features
print(train_X.shape, len(train_X), train_y.shape)
test_X, test_y = test[:, :n_obs], test[:,:6] # I put 6 instead of -n_features
print(test_X.shape, len(test_X), test_y.shape)

# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], n_hours, n_features))
train_y = train_y
test_X = test_X.reshape((test_X.shape[0], n_hours, n_features))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)
train_y.shape

# design network
model = Sequential()
model.add(LSTM(5, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(6))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=5, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False)
# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()

# make a prediction
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], n_hours*n_features))

# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, -7:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)
</code>```

The error I've got :

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-57-8e17d1d76420> in <module>
      9 # invert scaling for forecast
     10 inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)
---> 11 inv_yhat = scaler.inverse_transform(inv_yhat)
     12 inv_yhat = inv_yhat[:,0]
     13 # invert scaling for actual

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\preprocessing\data.py in inverse_transform(self, X)
    404                         force_all_finite="allow-nan")
    405
--> 406         X -= self.min_
    407         X /= self.scale_
    408         return X

ValueError: operands could not be broadcast together with shapes (26227,13) (8,) (26227,13)
</code>```

答:
As the error output shows, the problem happens when you try to invert the min-max scale operation. The problem is that you have fit the scaler with all the columns and now you only need to reverse the scaling for the first column of your dataset. To solve that, the tutorial's author concatenates the predicted column to the rest of the attributes, but you cannot do that as you are predicting more than one value for each row. A possible solution could be this one:

Change this

```<code># invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, -7:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]
</code>```

with this

```<code># invert scaling for forecast
pred_scaler = MinMaxScaler(feature_range=(0, 1)).fit(dataset.values[:,0].reshape(-1, 1))
inv_yhat = pred_scaler.inverse_transform(yhat)
# invert scaling for actual
inv_y = pred_scaler.inverse_transform(test_y)
</code>```

Title: Multivariate and multistep LSTM

Body:
Giving this example (section: Train On Multiple Lag Timesteps Example), in order to predict the next 6 hours of Pollution based on the previous 2 years data, should I just set n_hours=17520, and the number of future steps I want to predict (set n_out=6) ?

Otherwise, I've read somewhere that I should also modify the Dense layer units to the number of the future steps to predict (here is 6), however, it always returns an error. What would be the problem ?

Thank you

The modified code:

from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM

# convert series to supervised learning
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
    n_vars = 1 if type(data) is list else data.shape[1]
    df = DataFrame(data)
    cols, names = list(), list()
    # input sequence (t-n, ... t-1)
    for i in range(n_in, 0, -1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
    # forecast sequence (t, t+1, ... t+n)
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i == 0:
            names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
    # put it all together
    agg = concat(cols, axis=1)
    agg.columns = names
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg

# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# integer encode direction
encoder = LabelEncoder()
values[:,4] = encoder.fit_transform(values[:,4])
# ensure all data is float
values = values.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# specify the number of lag hours
n_hours = 17520
n_features = 8
# frame as supervised learning
reframed = series_to_supervised(scaled, n_hours, 6) # predict the next 6 hours
print(reframed.shape)

# split into train and test sets
values = reframed.values
n_train_hours = 365 * 24 *2
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]
# split into input and outputs
n_obs = n_hours * n_features
train_X, train_y = train[:, :n_obs], train[:, -n_features]
test_X, test_y = test[:, :n_obs], test[:, -n_features]
print(train_X.shape, len(train_X), train_y.shape)
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], n_hours, n_features))
test_X = test_X.reshape((test_X.shape[0], n_hours, n_features))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)

# design network
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=50, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False)
# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()

# make a prediction
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], n_hours*n_features))
# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, -7:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)

Edit:
I have changed the value of Dense layer units to 6 and the train_y.shape[1] as well as test_y.shape[1] to 6 as follows:

# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# integer encode direction
encoder = LabelEncoder()
values[:,4] = encoder.fit_transform(values[:,4])
# ensure all data is float
values = values.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# specify the number of lag hours
n_hours =48
n_out=6
n_features = 8
# frame as supervised learning
reframed = series_to_supervised(scaled, n_hours, n_out)
print(reframed.shape)

# split into train and test sets
values = reframed.values
n_train_hours = 365 * 24 * 2
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]

# split into input and outputs
n_obs = n_hours * n_features
train_X, train_y = train[:, :n_obs], train[:, :6]#I put 6 instead of -n_features
print(train_X.shape, len(train_X), train_y.shape)
test_X, test_y = test[:, :n_obs], test[:,:6] # I put 6 instead of -n_features
print(test_X.shape, len(test_X), test_y.shape)

# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], n_hours, n_features))
train_y = train_y
test_X = test_X.reshape((test_X.shape[0], n_hours, n_features))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)
train_y.shape

# design network
model = Sequential()
model.add(LSTM(5, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(6))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=5, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False)
# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()

# make a prediction
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], n_hours*n_features))

# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, -7:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)

The error I've got :

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-57-8e17d1d76420> in <module>
      9 # invert scaling for forecast
     10 inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)
---> 11 inv_yhat = scaler.inverse_transform(inv_yhat)
     12 inv_yhat = inv_yhat[:,0]
     13 # invert scaling for actual

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\preprocessing\data.py in inverse_transform(self, X)
    404                         force_all_finite="allow-nan")
    405
--> 406         X -= self.min_
    407         X /= self.scale_
    408         return X

ValueError: operands could not be broadcast together with shapes (26227,13) (8,) (26227,13)

Body:
As the error output shows, the problem happens when you try to invert the min-max scale operation. The problem is that you have fit the scaler with all the columns and now you only need to reverse the scaling for the first column of your dataset. To solve that, the tutorial's author concatenates the predicted column to the rest of the attributes, but you cannot do that as you are predicting more than one value for each row. A possible solution could be this one:

Change this

# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, -7:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]

with this

# invert scaling for forecast
pred_scaler = MinMaxScaler(feature_range=(0, 1)).fit(dataset.values[:,0].reshape(-1, 1))
inv_yhat = pred_scaler.inverse_transform(yhat)
# invert scaling for actual
inv_y = pred_scaler.inverse_transform(test_y)


问:
Weird behavior while using Subjects/event emitters in services for cross component communication in angular?
I want to understand how observable, subjects and behavior subject work(have read a lot of articles , watched a lot of videos but its still not clear to me as i have failed to explain this behavior) so i created this simple example and got an unexpected behavior.
I have two components a parent component and a child component.

The parent component displays a list of having names of photos with buttons to show details. When this button is clicked it will take us into the child component where i wish to display the single photo along with the details. So, this is the idea.

I have used a service where i have a subject. Now whenever the button in the parent component is clicked , I am emitting a value from the subject. I want to catch this value in my child component, so I am subscribing to it.

There is a weird behavior--
For the first click i do not see any data in my child component.
Second click a single value in child component.
Third click two values in child component,
and so on....

Here are my components--

parent.component.ts

```<code>export class ParentComponent implements OnInit {
  photoList = [
    {
      albumId: 1,
      id: 1,
      title: "accusamus beatae ad facilis cum similique qui sunt",
      url: "https://via.placeholder.com/600/92c952",
      thumbnailUrl: "https://via.placeholder.com/150/92c952",
    },
    {
      albumId: 1,
      id: 2,
      title: "reprehenderit est deserunt velit ipsam",
      url: "https://via.placeholder.com/600/771796",
      thumbnailUrl: "https://via.placeholder.com/150/771796",
    },
    {
      albumId: 1,
      id: 3,
      title: "officia porro iure quia iusto qui ipsa ut modi",
      url: "https://via.placeholder.com/600/24f355",
      thumbnailUrl: "https://via.placeholder.com/150/24f355",
    },
  ];
  constructor(private _talkService: TalkService, private router: Router) {}

  ngOnInit() {}

  displayName(id, url, thumbnailUrl) {
    console.log({ id, url, thumbnailUrl });

    //this._talkService.talk.emit({ url, thumbnailUrl });
    this._talkService.talk.next({ id, url, thumbnailUrl });
    this.router.navigate(["/photo"]);
  }
}

</code>```

child.component.ts

```<code>export class ChildComponent implements OnInit {
  constructor(private _talkService: TalkService) {}

  ngOnInit() {
    console.log("child component created");
    this._talkService.talk.subscribe((data) => {
      console.log(data);
    });
  }
}
</code>```

talk.service.ts

```<code>@Injectable({
  providedIn: "root",
})
export class TalkService {
  // talk = new EventEmitter();
  talk = new Subject();
  constructor() {}
}

</code>```

Output console logs

I have used these three--

Event Emitters-->same behavior as described
Subjects-->same behavior as described
Behavior Subjects--> I get the first value as well(As it helps us to get the  the previously emitted value, that part I understand). A detailed explanation here is also welcome.

I was expecting a single value on each click, but this is not the case. Can someone please explain me the behavior. It must be the way observable work and I am not able to get it.

Here is the link to my github repo--

source code github

答:
Sounds like a classic memory leak. Every time you subscribe to talkService.talk you are creating a subscription that will only get cleaned after it is unsubscribed. So even though the Child components seem like they're being destroyed when you go back to the parent component, the subscription still exists and is doing the console log every time the talk subject emits a new value. You should unsubscribe when the Child component gets destroyed. An easy way of making sure subscriptions are unsubscribed is to use the async pipe in the html template.

child.component.ts

export class ChildComponent implements OnInit {
  data$: Observable<any> = this.talkService.talk;

  constructor(private talkService: TalkService) {}
}
```

<p><strong>child.component.html</strong></p>

<pre class="lang-html prettyprint-override"><code>```{{ data$ | async }}```
</code>```

Also, you can switch back to using BehaviorSubject since the child component will be subscribing to talk after the value is emitted from the parent component.

Body:
I want to understand how observable, subjects and behavior subject work(have read a lot of articles , watched a lot of videos but its still not clear to me as i have failed to explain this behavior) so i created this simple example and got an unexpected behavior.
I have two components a parent component and a child component.

The parent component displays a list of having names of photos with buttons to show details. When this button is clicked it will take us into the child component where i wish to display the single photo along with the details. So, this is the idea.

I have used a service where i have a subject. Now whenever the button in the parent component is clicked , I am emitting a value from the subject. I want to catch this value in my child component, so I am subscribing to it.

There is a weird behavior--
For the first click i do not see any data in my child component.
Second click a single value in child component.
Third click two values in child component,
and so on....

Here are my components--

parent.component.ts

export class ParentComponent implements OnInit {
  photoList = [
    {
      albumId: 1,
      id: 1,
      title: "accusamus beatae ad facilis cum similique qui sunt",
      url: "https://via.placeholder.com/600/92c952",
      thumbnailUrl: "https://via.placeholder.com/150/92c952",
    },
    {
      albumId: 1,
      id: 2,
      title: "reprehenderit est deserunt velit ipsam",
      url: "https://via.placeholder.com/600/771796",
      thumbnailUrl: "https://via.placeholder.com/150/771796",
    },
    {
      albumId: 1,
      id: 3,
      title: "officia porro iure quia iusto qui ipsa ut modi",
      url: "https://via.placeholder.com/600/24f355",
      thumbnailUrl: "https://via.placeholder.com/150/24f355",
    },
  ];
  constructor(private _talkService: TalkService, private router: Router) {}

  ngOnInit() {}

  displayName(id, url, thumbnailUrl) {
    console.log({ id, url, thumbnailUrl });

    //this._talkService.talk.emit({ url, thumbnailUrl });
    this._talkService.talk.next({ id, url, thumbnailUrl });
    this.router.navigate(["/photo"]);
  }
}

child.component.ts

export class ChildComponent implements OnInit {
  constructor(private _talkService: TalkService) {}

  ngOnInit() {
    console.log("child component created");
    this._talkService.talk.subscribe((data) => {
      console.log(data);
    });
  }
}

talk.service.ts

@Injectable({
  providedIn: "root",
})
export class TalkService {
  // talk = new EventEmitter();
  talk = new Subject();
  constructor() {}
}

Output console logs

I have used these three--

Event Emitters-->same behavior as described
Subjects-->same behavior as described
Behavior Subjects--> I get the first value as well(As it helps us to get the  the previously emitted value, that part I understand). A detailed explanation here is also welcome.

I was expecting a single value on each click, but this is not the case. Can someone please explain me the behavior. It must be the way observable work and I am not able to get it.

Here is the link to my github repo--

source code github

Body:
Sounds like a classic memory leak. Every time you subscribe to talkService.talk you are creating a subscription that will only get cleaned after it is unsubscribed. So even though the Child components seem like they're being destroyed when you go back to the parent component, the subscription still exists and is doing the console log every time the talk subject emits a new value. You should unsubscribe when the Child component gets destroyed. An easy way of making sure subscriptions are unsubscribed is to use the async pipe in the html template.

child.component.ts

export class ChildComponent implements OnInit {
  data$: Observable<any> = this.talkService.talk;

  constructor(private talkService: TalkService) {}
}

child.component.html

<pre>{{ data$ | async }}</pre>

Also, you can switch back to using BehaviorSubject since the child component will be subscribing to talk after the value is emitted from the parent component.


问:
How can I get working keyframe animation?
I am trying to animate as ripple effect. It seems to work fine on chrome browser but not working on safari, also I have other animations in the same page that are working fine on chrome and safari both but not this one. I wonder what I am doing wrong.

I tried to debug it and I can see that there is a message in Safari Graphic Tab that says

"This animation has no keyframes"

My css code:

.ripple-animation {
    &::after {
        @include rings(2s, 40s);
    }
    &::before {
        @include rings(2s, 40s);
    }
}

@mixin rings($duration, $delay) {
    opacity: 0.5;
    // display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: -8px;
    left: -10px;
    right: 0;
    bottom: 0;
    content: '';
    height: 120%;
    width: 110%;
    border: 4px solid rgba(0, 0, 0, 0.4);
    border-radius: 100%;

    -webkit-animation-name: ripple;
    -webkit-animation-duration: $duration;
    -webkit-animation-delay: $delay;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: cubic-bezier(.65, 0, .34, 1);

    animation-name: ripple;
    animation-duration: $duration;
    animation-delay: $delay;
    animation-iteration-count: infinite;
    animation-timing-function: cubic-bezier(.65, 0, .34, 1);

}

@-webkit-keyframes ripple {
    from {
        opacity: 1;
        -webkit-transform: scale3d(0.8, 0.8, 0.5);
        transform: scale3d(0.8, 0.8, 0.5);
    }
    to {
        opacity: 0;
        -webkit-transform: scale3d(1.1, 1.1, 1);
        transform: scale3d(1.1, 1.1, 1);
    }

}

@keyframes ripple {
    from {
        opacity: 1;
        -webkit-transform: scale3d(0.8, 0.8, 0.5);
        transform: scale3d(0.8, 0.8, 0.5);
    }
    to {
        opacity: 0;
        -webkit-transform: scale3d(1.1, 1.1, 1);
        transform: scale3d(1.1, 1.1, 1);
    }
}
```

答: In iOS this seems to be related to having reduced motion turned off in the accessibility settings. You have to untick it and also i think you have to change the version of safari if still not works fine</p>


答:
```<code>json_data = {"data":{
   "Bob":{
      "name":"Bob",
      "age":"30",
      "state":"California",
      "job":"accountant"
   },
   "Joe":{
      "name":"Bob",
      "age":"30",
      "state":"Florida",
      "job":"engineer"
   },
   "Tom":{
      "name":"Bob",
      "age":"25",
      "state":"North Dakota",
      "job":"manager"
   }
}
}
names = []
for k, v in json_data['data'].items():
  if v['age'] == '30':
    names.append(k)

print(names)
</code>```

Title: How to access elements in a specific way in json?


问:
Convert Pandas DataFrame to JSON format
I have a Pandas DataFrame with two columns – one with the filename and one with the hour in which it was generated:

```<code> File       Hour
  F1         1
  F1         2
  F2         1
  F3         1
</code>```

I am trying to convert it to a JSON file with the following format:

```<code>{"File":"F1","Hour":"1"}
{"File":"F1","Hour":"2"}
{"File":"F2","Hour":"1"}
{"File":"F3","Hour":"1"}
</code>```

When I use the command DataFrame.to_json(orient = "records"), I get the records in the below format:

```<code>[{"File":"F1","Hour":"1"},
 {"File":"F1","Hour":"2"},
 {"File":"F2","Hour":"1"},
 {"File":"F3","Hour":"1"}]
</code>```

I'm just wondering whether there is an option to get the JSON file in the desired format. Any help would be appreciated.

答:
convert data-frame to list of dictionary </p>

```<code>list_dict = []

for index, row in list(df.iterrows()):
    list_dict.append(dict(row))
</code>```

<p>save file </p>

```<code>with open("output.json", mode) as f:
    f.write("\n".join(str(item) for item in list_dict))
</code>```

Title: Convert Pandas DataFrame to JSON format

Body:
I have a Pandas DataFrame with two columns – one with the filename and one with the hour in which it was generated:

 File       Hour
  F1         1
  F1         2
  F2         1
  F3         1

I am trying to convert it to a JSON file with the following format:

{"File":"F1","Hour":"1"}
{"File":"F1","Hour":"2"}
{"File":"F2","Hour":"1"}
{"File":"F3","Hour":"1"}

When I use the command DataFrame.to_json(orient = "records"), I get the records in the below format:

[{"File":"F1","Hour":"1"},
 {"File":"F1","Hour":"2"},
 {"File":"F2","Hour":"1"},
 {"File":"F3","Hour":"1"}]

I'm just wondering whether there is an option to get the JSON file in the desired format. Any help would be appreciated.

Body:
convert data-frame to list of dictionary

list_dict = []

for index, row in list(df.iterrows()):
    list_dict.append(dict(row))

save file

with open("output.json", mode) as f:
    f.write("\n".join(str(item) for item in list_dict))


问:
how to add log traces for django's (1.11) URL dispatcher (not for production)
I have an old (Django 1.11) over complicated Django application with overlapping and funnily ordered url matching rules and I want to update it to newer Django versions and to simplify / refactor.

For better understanding Id' like to navigate through the application (manually) and retrieve some traces

Would it be possible to achieve following without having to add log statements in every view.

I'd like to get traces telling me which rule was picked by the url dispatcher (and if possible, but not really necessary), which view with which parameter was called.

I'm for example sure, that some rules can just be deleted as they're no more used.

Example:
If I had following (not complicated with non overlapping rules) url dispacher rules.

```<code>urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^app1/', app1.views.top_view),
    url(r'^app1/a', app1.views.a_view),
]
</code>```

and I acessed http://myserver/app1. I'd like to have a trace telling me,
that http://myserver/app1 triggered rule ^app1/ and (not so important) view app1.views.top_view will be used to handle the request.

midllewares, decorators, monkeypatches, whatever will do as long as I don't have to change all individual rules and  all views to get my traces.
Even a considerable performance hit is not an issue this is for debugging

P.S.

I am aware of the django-extensions module and the management command show_urls.

This is already helpful, but for more complicated urls showing up in my app I'd like to have the logging.

答:
You may have to upgrade to 2.2 first, or backport this commit else you can't get information from the router about the exact match it has used to resolve the request URI.

That said, it should be done in middleware during request phase. The ResolverMatch instance is available in the WSGIRequest as request.resolver_match. Using the fix above, it's trivial to add a log to each request.

If you cannot backport or upgrade, there is a way to do it, which basically involves building a cache on start up of all known urlconfs and then matching each one and I've done it at some point, yet don't have it laying around any more. You basically have to do the work of URLResolver.resolve() and then add the route to it, when it creates the ResolverMatch instance. Hopefully this helps you get started.

Body:
I have an old (Django 1.11) over complicated Django application with overlapping and funnily ordered url matching rules and I want to update it to newer Django versions and to simplify / refactor.

For better understanding Id' like to navigate through the application (manually) and retrieve some traces

Would it be possible to achieve following without having to add log statements in every view.

I'd like to get traces telling me which rule was picked by the url dispatcher (and if possible, but not really necessary), which view with which parameter was called.

I'm for example sure, that some rules can just be deleted as they're no more used.

Example:
If I had following (not complicated with non overlapping rules) url dispacher rules.

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^app1/', app1.views.top_view),
    url(r'^app1/a', app1.views.a_view),
]

and I acessed http://myserver/app1. I'd like to have a trace telling me,
that http://myserver/app1 triggered rule ^app1/ and (not so important) view app1.views.top_view will be used to handle the request.

midllewares, decorators, monkeypatches, whatever will do as long as I don't have to change all individual rules and  all views to get my traces.
Even a considerable performance hit is not an issue this is for debugging

P.S.

I am aware of the django-extensions module and the management command show_urls.

This is already helpful, but for more complicated urls showing up in my app I'd like to have the logging.


问:
Need help trying to set an object on a daily basis until i decide to change it
this may sound bizarre to read, but i got this component (react-native-calendar-strip), and my idea is to click on a day and create an object to display, starting from that day and beyond

i click on that day, and in a second screen i select a bunch of items that will be displayed on the first screen.

```<code>{2020-05-28: Array(2)}
2020-05-28: Array(2)
  0: {title: "CODELCO - CONTRATO LEGACY y SHAREPOINT - SWD-PROY", cliente: "Axity", tipoProyecto: "Tradicional", idCliente: "4", idTipoProyecto: "2", …}
  1: {title: "Celula One Pay FX", cliente: "Banco Santander", tipoProyecto: "Agil", idCliente: "7", idTipoProyecto: "1", …}
length: 2
  __proto__: Array(0)
  __proto__: Object
</code>```

the object here is saving a list of elements INSIDE the date.

here is my issue. i've been told that the object should be displayed from that day AND beyond, UNTIL i click on "Editar Favoritos" (depending on which day i clicked) where i edit the object and at that moment, the object will be displayed from that day and beyond, EXCEPT, those those from previous days.

what's the best approach for this issue? help :(

答:
The best approach to take would be to have a start date and an end date for your data instead of using the date as the key which will make things really complex. This will make it easier for you to store in your database as well.
The calendar component you use utilizes moment which will make things easy for you.
Based on the start date and end date you can display the item in the grid.
The below component would give you the sample approach. You have to filter the data array based on the selected date. To show an item on multiple date you just have to update the end date.

```<code>const data = [
  { id: 1, title: 'test 123', startDate: moment('2020-06-01') },
  { id: 2, title: 'test item 2', startDate: moment('2020-06-01') },
  { id: 3, title: 'test item 3', startDate: moment('2020-06-02'),endDate: moment('2020-06-07')},
  { id: 4, title: 'test item 4',startDate: moment('2020-06-04'),endDate: moment('2020-06-06')}
];

const Planner = () => {
  const [selectedDate, setSelectedDate] = React.useState(moment('2020-06-01'));

  const filteredArray = data.filter(item => {
    if (item.startDate && !item.endDate) {
      return selectedDate.isSame(item.startDate);
    }
    if (item.startDate && item.endDate)
      return (
        selectedDate.isBetween(item.startDate, item.endDate) ||
        selectedDate.isSame(item.startDate) ||
        selectedDate.isSame(item.endDate)
      );
    return false;
  });

  return (
    <View>
      <CalendarStrip
        style={{ height: 150, paddingTop: 20, paddingBottom: 10 }}
        onDateSelected={prop => setSelectedDate(moment(prop))}
        selectedDate={selectedDate}
      />
      <View>
        {filteredArray.map(item => (
          <Text>{item.title}</Text>
        ))}
      </View>
    </View>
  );
};
</code>```

Hope this helps.

Body:
this may sound bizarre to read, but i got this component (react-native-calendar-strip), and my idea is to click on a day and create an object to display, starting from that day and beyond

i click on that day, and in a second screen i select a bunch of items that will be displayed on the first screen.

{2020-05-28: Array(2)}
2020-05-28: Array(2)
  0: {title: "CODELCO - CONTRATO LEGACY y SHAREPOINT - SWD-PROY", cliente: "Axity", tipoProyecto: "Tradicional", idCliente: "4", idTipoProyecto: "2", …}
  1: {title: "Celula One Pay FX", cliente: "Banco Santander", tipoProyecto: "Agil", idCliente: "7", idTipoProyecto: "1", …}
length: 2
  __proto__: Array(0)
  __proto__: Object

the object here is saving a list of elements INSIDE the date.

here is my issue. i've been told that the object should be displayed from that day AND beyond, UNTIL i click on "Editar Favoritos" (depending on which day i clicked) where i edit the object and at that moment, the object will be displayed from that day and beyond, EXCEPT, those those from previous days.

what's the best approach for this issue? help :(

Body:
The best approach to take would be to have a start date and an end date for your data instead of using the date as the key which will make things really complex. This will make it easier for you to store in your database as well.
The calendar component you use utilizes moment which will make things easy for you.
Based on the start date and end date you can display the item in the grid.
The below component would give you the sample approach. You have to filter the data array based on the selected date. To show an item on multiple date you just have to update the end date.

const data = [
  { id: 1, title: 'test 123', startDate: moment('2020-06-01') },
  { id: 2, title: 'test item 2', startDate: moment('2020-06-01') },
  { id: 3, title: 'test item 3', startDate: moment('2020-06-02'),endDate: moment('2020-06-07')},
  { id: 4, title: 'test item 4',startDate: moment('2020-06-04'),endDate: moment('2020-06-06')}
];

const Planner = () => {
  const [selectedDate, setSelectedDate] = React.useState(moment('2020-06-01'));

  const filteredArray = data.filter(item => {
    if (item.startDate && !item.endDate) {
      return selectedDate.isSame(item.startDate);
    }
    if (item.startDate && item.endDate)
      return (
        selectedDate.isBetween(item.startDate, item.endDate) ||
        selectedDate.isSame(item.startDate) ||
        selectedDate.isSame(item.endDate)
      );
    return false;
  });

  return (
    <View>
      <CalendarStrip
        style={{ height: 150, paddingTop: 20, paddingBottom: 10 }}
        onDateSelected={prop => setSelectedDate(moment(prop))}
        selectedDate={selectedDate}
      />
      <View>
        {filteredArray.map(item => (
          <Text>{item.title}</Text>
        ))}
      </View>
    </View>
  );
};

Hope this helps.


问:
Removing block html tags. TinyMCE
I have added TinyMCE to my project. I have styled text and sent its value to database. Then I want it to be shown in the view. But it shown in HTML tags. How can I get rid of HTML tags?

Js:

```<code>  <script>
    tinymce.init({
        selector: '#Content',
        height: 500,
        theme: 'modern',
        plugins: [
            'advlist autolink lists link image charmap print preview hr anchor pagebreak',
            'searchreplace wordcount visualblocks visualchars code fullscreen',
            'insertdatetime media nonbreaking save table contextmenu directionality',
            'emoticons template paste textcolor colorpicker textpattern imagetools'
        ],
        forecolor: { inline: 'span', classes: 'forecolor', styles: { color: '%value' } },
        hilitecolor: { inline: 'span', classes: 'hilitecolor', styles: { backgroundColor: '%value' } },
        custom_format: { block: 'h1', attributes: { title: 'Header' }, styles: { color: 'red' } },
        toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
        toolbar2: 'print preview media | forecolor backcolor emoticons ',
        image_advtab: true,

    });
</script>
</code>```

View:

```<code>   @foreach (Blog blog in Model.Blog)
      {
    @blog.posttext
                   }
</code>```

posttext is shown like:
hi

答:
Finally, I solved it by disabling HTML encoding:</p>

```<code>@Html.Raw(HttpUtility.HtmlDecode(blog.posttext))
</code>```

Title: Removing block html tags. TinyMCE

Body:
I have added TinyMCE to my project. I have styled text and sent its value to database. Then I want it to be shown in the view. But it shown in HTML tags. How can I get rid of HTML tags?

Js:

View:

   @foreach (Blog blog in Model.Blog)
      {
    @blog.posttext
                   }

posttext is shown like:
hi

Body:
Finally, I solved it by disabling HTML encoding:

@Html.Raw(HttpUtility.HtmlDecode(blog.posttext))


问:
What does "static this()" outside of a class mean?
I'm very well aware of static constructors, but what does it mean to have a static this() outside of a class?

```<code>import std.stdio;

static this(){

  int x = 0;

}

int main(){

  writeln(x); // error

  return 0;
}
</code>```

And how do I access the variables define in static this() ?

答:
This is the module constructor. You can read about them here: http://www.digitalmars.com/d/2.0/module.html

Obviously, you can't access x in your sample, because it's a module constructor's local variable, just as well as you couldn't have done it with a class constructor's one. But you can access module-scope globals there (and initialise them, which is what the module constructors are for).

ContentLicense: CC BY-SA 3.0

Body:
I'm very well aware of static constructors, but what does it mean to have a static this() outside of a class?

import std.stdio;

static this(){

  int x = 0;

}

int main(){

  writeln(x); // error

  return 0;
}

And how do I access the variables define in static this() ?


问:
Segmentation fault (core dumped) - argv - c
I am trying to open a txt file for a program entering the name of the file as a command line argument. if I provide the path as a string it works, so the problem in my code is with the command line argument. I have the following:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char* argv[])
{
    char* filename = "/path/";
    char* name = argv[1];
    printf("%s\n", filename);
    printf("%s\n", name);
    strcat(filename, name);
    printf("%s\n", filename);
    strcat(filename, ".txt");
    printf("%s\n", filename);
    return 0;
}
</code>```

I run it like so:

./program filenamewithoutextension

I get the following output when I run it:

```<code>/path/
filenamewithoutextension
Segmentation fault (core dumped)
</code>```

I don't understand what is happening.

答:
char* filename = "/path/"; is still accepted in C to consider old code written
in the early days, when the const keyword did not exist yet.

But it should be const char * because "/path/" here is actually a constant
string.

(the -Wwrite-strings compiler option can help detect this)

If you want to append something to this string you need more storage for the
following chars.

char filename[100]="/path/";

In this case, the 100 chars are local to your function and can be changed.

They start with the given chars but are followed by many zeroes (up to 100).

Then, afterwards, it makes sense to put some new chars after the last /.

Body:
I am trying to open a txt file for a program entering the name of the file as a command line argument. if I provide the path as a string it works, so the problem in my code is with the command line argument. I have the following:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char* argv[])
{
    char* filename = "/path/";
    char* name = argv[1];
    printf("%s\n", filename);
    printf("%s\n", name);
    strcat(filename, name);
    printf("%s\n", filename);
    strcat(filename, ".txt");
    printf("%s\n", filename);
    return 0;
}

I run it like so:

./program filenamewithoutextension

I get the following output when I run it:

/path/
filenamewithoutextension
Segmentation fault (core dumped)

I don't understand what is happening.


问:
How do I customize the display of username field of default User Model in Django ModelForm without extending User Model?
I have a default User Model, with which I have connected a ModelForm. In the ModelForm, I am accessing the username field of the default User Model. It works fine as usual, it shows the username(s) of the users. But I don't want it to just show username, instead I want to show the custom content of each user. I want to show first_name, last_name and username of the user in the following format:
{first_name last_name - (username)}

Current display of the username filed:

```<code>user1
user2
user3
user4
#
#
#
</code>```

Desired display of the `username field:

```<code>John Doe - (user1)
Doni Marquart - (user2)
Geoff Roberts - (user3)
Alice Woods - (user4)
#
#
#
</code>```

Does anyone know how can I accomplish it without extending the default User Model? Thanks

答:
in you'r templates :</p>

```<code>{% for user in user_list %}
    {{ user.first_name }}
    {{ user.last_name }}
<!--  ....    --/>

{% endfor %}
</code>```

Body:
I have a default User Model, with which I have connected a ModelForm. In the ModelForm, I am accessing the username field of the default User Model. It works fine as usual, it shows the username(s) of the users. But I don't want it to just show username, instead I want to show the custom content of each user. I want to show first_name, last_name and username of the user in the following format:
{first_name last_name - (username)}

Current display of the username filed:

user1
user2
user3
user4
#
#
#

Desired display of the `username field:

John Doe - (user1)
Doni Marquart - (user2)
Geoff Roberts - (user3)
Alice Woods - (user4)
#
#
#

Does anyone know how can I accomplish it without extending the default User Model? Thanks

Body:
in you'r templates :

{% for user in user_list %}
    {{ user.first_name }}
    {{ user.last_name }}
<!--  ....    --/>

{% endfor %}


问:
How to display items inline using angular's *ngFor
I am trying to display items inline instead of appearing in different row. Please see code and picture below. I have tried to look online for solutions but everyone else is asking a different use case. Please let me know. Thanks!

```<code><!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Document</title>
 </head>
 <body>
    <div>
        <div class="pimg1">
           <div class="ptext">
               <span class="borderStyle">
                   Kenny's Site
               </span>
           </div>
        </div>
        <section class="section section-light">
            <h2>Skills</h2>
            <p class="skills" *ngFor="let skill of skills">{{skill.skill}}</p>
        </section>
        <div class="pimg2">
           <div class="ptext">
               <span class="borderStyle">
                   Image2 Text
               </span>
           </div>
        </div>
        <section class="section section-dark">
           <h2>Section 1</h2>
           <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, saepe.</p>
       </section>
       <div class="pimg3">
           <div class="ptext">
               <span class="borderStyle">
                   Image3 Text
               </span>
           </div>
        </div>
        <section class="section section-dark">
           <h2>Section 3</h2>
           <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, saepe.</p>
       </section>
       <div class="pimg1">
           <div class="ptext">
               <span class="borderStyle">
                   Kenny's Site
               </span>
           </div>
        </div>
    </div>
 </body>
 </html>
</code>```

答:
I think it's not an angular problem case here.
you need to manage css to make skills displayed in flex or grid.

maybe you can try making all skills in a div container, and flex them.

html :

```<code><section class="section section-light">
      <h2>Skills</h2>
      <div class="skill-list">
         <p class="skills" *ngFor="let skill of skills">{{skill.skill}}</p>
      </div>
 </section>
</code>```

css :

```<code>.skill-list{
     display : flex;
     justify-content: between;
}
</code>```

Body:
I am trying to display items inline instead of appearing in different row. Please see code and picture below. I have tried to look online for solutions but everyone else is asking a different use case. Please let me know. Thanks!

<!DOCTYPE html>

     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Document</title>

                   Kenny's Site

Skills

{{skill.skill}}

                   Image2 Text

Section 1

Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, saepe.

                   Image3 Text

Section 3

Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, saepe.

                   Kenny's Site

Body:
I think it's not an angular problem case here.
you need to manage css to make skills displayed in flex or grid.

maybe you can try making all skills in a div container, and flex them.

html :

<section class="section section-light">
      <h2>Skills</h2>
      <div class="skill-list">
         <p class="skills" *ngFor="let skill of skills">{{skill.skill}}</p>
      </div>
 </section>

css :

.skill-list{
     display : flex;
     justify-content: between;
}


问:
How to remove text on topbar in wordpress i-max theme(remove blue color)

Trying to change the HTML OF THE THEME but don't get any option for it in topbar with wp-admin is there any other way

答:
There are a few ways you can go about this.

1) Find the desired element and target it with CSS to set the property of the element to hidden. You can find the element by using the browser developer tools (ctrl+shift+i in Chrome), select the blue area, figure out the class, id or whatever selector it has.

2) Create a Child theme of the existing theme and edit the HTML code directly.
There should be more than enough information on Google on how to create a Child Theme. There are even "one click" Child Theme add-ons out there as far as I'm aware of.
The reason you'd want to do this in a Child Theme, is because if you do it on the original theme, the changes you make will be overwritten when the theme has an update.


问:
Problem with React making Get request to Node(express)
As the title says, i have  a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:

So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"

```<code>async handleClickLicencia (event) {
        event.preventDefault();
        console.log(this.state);
        console.log("licenciaInput: "+this.state.licenciaInput);
        const datoBuscar = this.state.licenciaInput;

        axios.get('http://localhost:3001/atletas/:licencia',this.state)
            .then(response =>{
                console.log(response)

            })
            .catch(error =>{
                console.log(error)
            })
</code>```

And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:

```<code>const getAtletasByLicencia = (request, response) => {
   const licencia = request.body.licenciaInput;
   console.log("Request: "+request);
   console.log("what the server gets: "+licencia);
   // const licencia = request.licenciaInput;
   const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
   pool.query(sentencia, (error, results) =>{
        if(error){
            throw error
        }
        response.status(200).json(results.rows)
    })
}
</code>```

As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.

TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work

I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance

EDIT: Im also adding this code that i have which shows the route for my method in the server:

app.get('/atletas/:licencia', db.getAtletasByLicencia)

As @Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client

答: As you are using request.body you should send a POST request with axios and add a body.

Body:
As the title says, i have  a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:

So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"

async handleClickLicencia (event) {
        event.preventDefault();
        console.log(this.state);
        console.log("licenciaInput: "+this.state.licenciaInput);
        const datoBuscar = this.state.licenciaInput;

        axios.get('http://localhost:3001/atletas/:licencia',this.state)
            .then(response =>{
                console.log(response)

            })
            .catch(error =>{
                console.log(error)
            })

And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:

const getAtletasByLicencia = (request, response) => {
   const licencia = request.body.licenciaInput;
   console.log("Request: "+request);
   console.log("what the server gets: "+licencia);
   // const licencia = request.licenciaInput;
   const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
   pool.query(sentencia, (error, results) =>{
        if(error){
            throw error
        }
        response.status(200).json(results.rows)
    })
}

As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.

TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work

I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance

EDIT: Im also adding this code that i have which shows the route for my method in the server:

app.get('/atletas/:licencia', db.getAtletasByLicencia)

As @Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client


问:
DATESINPERIOD measure not returning the correct total when trying to get the current month sales in a month table
I am trying to show the current months sales in a table that also looks at Median, average. The figure returned for each month is correct. However the total is not correct.

SalesMostRecentdaMonth = CALCULATE(Sum('Sales'[Sales]),DATESINPERIOD(Dates[Date],MAX(Dates[Date]),-1,MONTH))

答:
So I figured out the answer it was to create a measure that calculated sales in the previous 12 months (trailing 12 months). The video linked below helped.
https://www.youtube.com/watch?v=duMSovyosXE</p>

```<code>Last 12 Months =
VAR CurrentDate = MAX(Dates[Date])
VAR PreviousDate = DATE(YEAR(CurrentDate),MONTH(CurrentDate)-12,DAY(CurrentDate)+1)
VAR Results =
CALCULATE(SUM('Sales'[Sales]),
FILTER(Dates,Dates[Date] >= PreviousDate&&Dates[Date]<=CurrentDate))
Return
Results
</code>```

Body:
So I figured out the answer it was to create a measure that calculated sales in the previous 12 months (trailing 12 months). The video linked below helped.
https://www.youtube.com/watch?v=duMSovyosXE

Last 12 Months =
VAR CurrentDate = MAX(Dates[Date])
VAR PreviousDate = DATE(YEAR(CurrentDate),MONTH(CurrentDate)-12,DAY(CurrentDate)+1)
VAR Results =
CALCULATE(SUM('Sales'[Sales]),
FILTER(Dates,Dates[Date] >= PreviousDate&&Dates[Date]<=CurrentDate))
Return
Results


问:
Normalize dataset so that median is 0.5
I have a dataset of positive integers that I want to scale so that the output range is [0.0,1.0] and the median maps to 0.5.

Is this possible to do at all?

If so, how can I do it in Python using scipy or sklearn?

答:
Scaling the data to the [0,1] interval is easy. It should be x=(x-min(x))/(max(x)-min(x).

If you just wanted the data to have a median of 0.5 without the [0,1] requirement, you could do x = 0.5*x/median(x).

But if you want both to be true, it can't be done with scaling.

Title: Normalize dataset so that median is 0.5


答:
You can use css flexbox pattern here.Try adding a class to your
 tag and give them the following properties

```<code>.<your class name> {
  display: flex;
  flex-wrap: nowrap;
}
</code>```

Title: How to display items inline using angular's *ngFor

Body:
You can use css flexbox pattern here.Try adding a class to your <p> tag and give them the following properties

.<your class name> {
  display: flex;
  flex-wrap: nowrap;
}


问:
react-transition-group doesnt slideUp component React.js
I have a component where when o clicking the button, the div with more info will slideUp and slideDown.
Below the code and css style

import { CSSTransition } from "react-transition-group";
const Card = () => {
  const [showMoreInfo, setShowMoreInfo] = useState(false);

  return (

      <ButtonShowMore isOpen={showMoreInfo} click={() => setShowMoreInfo(!showMoreInfo)} />
      <CSSTransition in={showMoreInfo} classNames="Card-Details" timeout={1000}>

          {showMoreInfo && (
            <>

details

details

            </>
          )}

      </CSSTransition>

  );
};

```

<pre class="lang-css prettyprint-override"><code>.Card-Details-enter {
  height: 0px;
}

.Card-Details-enter-active {
  height: 100%;
  -webkit-transition: height 1s ease;
  -moz-transition: height 1s ease;
  -o-transition: height 1s ease;
  transition: height 1s ease;
}

.Card-Details-enter-done {
  height: 100%;
}

.Card-Details-exit {
  height: 100%;
}
.Card-Details-exit-active {
  height: 0px;
  -webkit-transition: height 1s ease;
  -moz-transition: height 1s ease;
  -o-transition: height 1s ease;
  transition: height 1s ease;
}
.Card-Details-exit-done {
  height: 0px;
}

</code>```

But it doesnt work, I don't know why. I tred to put the transition to the parent element like here
and add transition to the class *-exit-done like here, and nothing helped.

答:
The reason why it doesn't work is because transitioning on percentage height isn't quite what you would expect.

Percentage height and width in CSS refer to their parent's height and width rather than their own height.

MDN Percentage

The  CSS data type represents a percentage value. It is
  often used to define a size as relative to an element's parent object.
  Numerous properties can use percentages, such as width, height,
  margin, padding, and font-size.

Example with the same element transitioning using a percentage height/width. One has a container element with a height/width of 50px, and the other doesn't.

div.container {
  width: 50px;
  height: 50px;
}

div.transition {
  width: 100%;
  height: 100%;
  background: red;
  transition: width 2s, height 4s;
}

div.transition:hover {
  width: 300%;
  height: 500%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Transition div with a 50px container
<div class="container">
  <div class="transition">
    <p>test</p>
  </div>
</div>

Transition div without a container:
<div class="transition">
  <p>test</p>
</div></code>```

What we'd actually want is to transition from 0px to auto height. Unfortunately browsers don't support transitioning on auto height.

A good write up of this is in Using CSS Transitions Auto Dimensions include some approaches to get what you want and their downsides.

Why hasn’t this problem been fixed at the browser level?

According to the Mozilla Developer Network docs, auto values have been
  intentionally excluded from the CSS transitions spec. It looks like
  it’s been requested by a few people, but when you think about it, it
  makes at least a little sense that it hasn’t been included. The
  browser process that re-calculates the sizes and positions of all
  elements based on their content and the way they interact with each
  other (known as “reflow”) is expensive. If you were to transition an
  element into a height of auto, the browser would have to perform a
  reflow for every stage of that animation, to determine how all the
  other elements should move. This couldn’t be cached or calculated in a
  simple way, since it doesn’t know the starting and/or ending values
  until the moment the transition happens. This would significantly
  complicate the math that has to be done under the hood and probably
  degrade performance in a way that might not be obvious to the
  developer.

How can I transition height: 0; to height: auto; using CSS? also has some good workarounds, though there really is no magic bullet for this.

It is definitely a very well known issue, and there's a request for the spec to change to allow transitions on auto, though I don't think it's gone anywhere yet.

As for support for the type of transition you are working on in React Transition Group:

Slide Down Animation and Trying to fade out element then slide up both have the same answer overall: pointing at how React Bootstrap's Collapse component does it.

You need to rely on finding the dom node's actual height and using that as part of the transition:

```<code>  getDimension() {
    return typeof this.props.dimension === 'function'
      ? this.props.dimension()
      : this.props.dimension;
  }

  // for testing
  _getScrollDimensionValue(elem, dimension) {
    return `${elem[`scroll${capitalize(dimension)}`]}px`;
  }

  /* -- Expanding -- */
  handleEnter = (elem) => {
    elem.style[this.getDimension()] = '0';
  }

  handleEntering = (elem) => {
    const dimension = this.getDimension();
    elem.style[dimension] = this._getScrollDimensionValue(elem, dimension);
  }

  handleEntered = (elem) => {
    elem.style[this.getDimension()] = null;
  }

  /* -- Collapsing -- */
  handleExit = (elem) => {
    const dimension = this.getDimension();
    elem.style[dimension] = `${this.props.getDimensionValue(dimension, elem)}px`;
    triggerBrowserReflow(elem);
  }

  handleExiting = (elem) => {
    elem.style[this.getDimension()] = '0';
  }

</code>```

A quick and dirty example of using the functionality from the Collapse class for a working example of the code using a less fully featured solution (note, based heavily on the Collapse.js code linked above):

const { Transition } = ReactTransitionGroup;
const { EXITED, ENTERED, ENTERING, EXITING } = Transition;
const { useState } = React;

// Quick and dirty classNames functionality
const classNames = (...names) => names.filter((name) => name).join(' ');

const ButtonShowMore = ({ isOpen, click }) => {
  return <button onClick={click}>{isOpen ? 'Close' : 'Open'}</button>;
};

// Heavily based on https://github.com/react-bootstrap/react-bootstrap/blob/next/src/Collapse.js#L150
// for the purpose of demonstration without just pulling in the module:

function triggerBrowserReflow(node) {
  node.offsetHeight; // eslint-disable-line no-unused-expressions
}

const collapseStyles = {
  [EXITED]: 'collapse',
  [EXITING]: 'collapsing',
  [ENTERING]: 'collapsing',
  [ENTERED]: 'collapse in',
};
const Collapse = ({ children, ...props }) => {
  const handleEnter = (elem) => (elem.style.height = '0');
  const handleEntering = (elem) =>
    (elem.style.height = `${elem.scrollHeight}px`);
  const handleEntered = (elem) => (elem.style.height = null);
  const handleExit = (elem) => {
    elem.style.height = `${elem.scrollHeight}px`;
    triggerBrowserReflow(elem);
  };
  const handleExiting = (elem) => (elem.style.height = '0');
  return (
    <Transition
      {...props}
      onEnter={handleEnter}
      onEntering={handleEntering}
      onEntered={handleEntered}
      onExit={handleExit}
      onExiting={handleExiting}
    >
      {(state, innerProps) =>
        React.cloneElement(children, {
          ...innerProps,
          className: classNames(
            props.className,
            children.props.className,
            collapseStyles[state]
          ),
        })
      }
    </Transition>
  );
};

const Card = () => {
  const [showMoreInfo, setShowMoreInfo] = useState(false);

  return (

      <ButtonShowMore
        isOpen={showMoreInfo}
        click={() => setShowMoreInfo(!showMoreInfo)}
      />
      <Collapse in={showMoreInfo} className="Card-Details" timeout={1000}>

details

details

      </Collapse>

  );
};

ReactDOM.render(<Card />, document.querySelector('#root'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.collapsing {
  -webkit-transition: height 1s ease;
  -moz-transition: height 1s ease;
  -o-transition: height 1s ease;
  transition: height 1s ease;
  overflow: hidden;
}

.collapse {
  overflow: hidden;
}</code>```

```

Body:
I have a component where when o clicking the button, the div with more info will slideUp and slideDown.
Below the code and css style

import { CSSTransition } from "react-transition-group";
const Card = () => {
  const [showMoreInfo, setShowMoreInfo] = useState(false);

  return (

      <ButtonShowMore isOpen={showMoreInfo} click={() => setShowMoreInfo(!showMoreInfo)} />
      <CSSTransition in={showMoreInfo} classNames="Card-Details" timeout={1000}>

          {showMoreInfo && (
            <>

details

details

            </>
          )}

      </CSSTransition>

  );
};

.Card-Details-enter {
  height: 0px;
}

.Card-Details-enter-active {
  height: 100%;
  -webkit-transition: height 1s ease;
  -moz-transition: height 1s ease;
  -o-transition: height 1s ease;
  transition: height 1s ease;
}

.Card-Details-enter-done {
  height: 100%;
}

.Card-Details-exit {
  height: 100%;
}
.Card-Details-exit-active {
  height: 0px;
  -webkit-transition: height 1s ease;
  -moz-transition: height 1s ease;
  -o-transition: height 1s ease;
  transition: height 1s ease;
}
.Card-Details-exit-done {
  height: 0px;
}

But it doesnt work, I don't know why. I tred to put the transition to the parent element like here
and add transition to the class *-exit-done like here, and nothing helped.

Body:
The reason why it doesn't work is because transitioning on percentage height isn't quite what you would expect.

Percentage height and width in CSS refer to their parent's height and width rather than their own height.

MDN Percentage

The  CSS data type represents a percentage value. It is
  often used to define a size as relative to an element's parent object.
  Numerous properties can use percentages, such as width, height,
  margin, padding, and font-size.

Example with the same element transitioning using a percentage height/width. One has a container element with a height/width of 50px, and the other doesn't.

div.container {
  width: 50px;
  height: 50px;
}

div.transition {
  width: 100%;
  height: 100%;
  background: red;
  transition: width 2s, height 4s;
}

div.transition:hover {
  width: 300%;
  height: 500%;
}

Transition div with a 50px container
<div class="container">
  <div class="transition">
    <p>test</p>
  </div>
</div>

Transition div without a container:
<div class="transition">
  <p>test</p>
</div>

What we'd actually want is to transition from 0px to auto height. Unfortunately browsers don't support transitioning on auto height.

A good write up of this is in Using CSS Transitions Auto Dimensions include some approaches to get what you want and their downsides.

Why hasn’t this problem been fixed at the browser level?

According to the Mozilla Developer Network docs, auto values have been
  intentionally excluded from the CSS transitions spec. It looks like
  it’s been requested by a few people, but when you think about it, it
  makes at least a little sense that it hasn’t been included. The
  browser process that re-calculates the sizes and positions of all
  elements based on their content and the way they interact with each
  other (known as “reflow”) is expensive. If you were to transition an
  element into a height of auto, the browser would have to perform a
  reflow for every stage of that animation, to determine how all the
  other elements should move. This couldn’t be cached or calculated in a
  simple way, since it doesn’t know the starting and/or ending values
  until the moment the transition happens. This would significantly
  complicate the math that has to be done under the hood and probably
  degrade performance in a way that might not be obvious to the
  developer.

How can I transition height: 0; to height: auto; using CSS? also has some good workarounds, though there really is no magic bullet for this.

It is definitely a very well known issue, and there's a request for the spec to change to allow transitions on auto, though I don't think it's gone anywhere yet.

As for support for the type of transition you are working on in React Transition Group:

Slide Down Animation and Trying to fade out element then slide up both have the same answer overall: pointing at how React Bootstrap's Collapse component does it.

You need to rely on finding the dom node's actual height and using that as part of the transition:

  getDimension() {
    return typeof this.props.dimension === 'function'
      ? this.props.dimension()
      : this.props.dimension;
  }

  // for testing
  _getScrollDimensionValue(elem, dimension) {
    return `${elem[`scroll${capitalize(dimension)}`]}px`;
  }

  /* -- Expanding -- */
  handleEnter = (elem) => {
    elem.style[this.getDimension()] = '0';
  }

  handleEntering = (elem) => {
    const dimension = this.getDimension();
    elem.style[dimension] = this._getScrollDimensionValue(elem, dimension);
  }

  handleEntered = (elem) => {
    elem.style[this.getDimension()] = null;
  }

  /* -- Collapsing -- */
  handleExit = (elem) => {
    const dimension = this.getDimension();
    elem.style[dimension] = `${this.props.getDimensionValue(dimension, elem)}px`;
    triggerBrowserReflow(elem);
  }

  handleExiting = (elem) => {
    elem.style[this.getDimension()] = '0';
  }

A quick and dirty example of using the functionality from the Collapse class for a working example of the code using a less fully featured solution (note, based heavily on the Collapse.js code linked above):

const { Transition } = ReactTransitionGroup;
const { EXITED, ENTERED, ENTERING, EXITING } = Transition;
const { useState } = React;

// Quick and dirty classNames functionality
const classNames = (...names) => names.filter((name) => name).join(' ');

const ButtonShowMore = ({ isOpen, click }) => {
  return <button onClick={click}>{isOpen ? 'Close' : 'Open'}</button>;
};

// Heavily based on https://github.com/react-bootstrap/react-bootstrap/blob/next/src/Collapse.js#L150
// for the purpose of demonstration without just pulling in the module:

function triggerBrowserReflow(node) {
  node.offsetHeight; // eslint-disable-line no-unused-expressions
}

const collapseStyles = {
  [EXITED]: 'collapse',
  [EXITING]: 'collapsing',
  [ENTERING]: 'collapsing',
  [ENTERED]: 'collapse in',
};
const Collapse = ({ children, ...props }) => {
  const handleEnter = (elem) => (elem.style.height = '0');
  const handleEntering = (elem) =>
    (elem.style.height = `${elem.scrollHeight}px`);
  const handleEntered = (elem) => (elem.style.height = null);
  const handleExit = (elem) => {
    elem.style.height = `${elem.scrollHeight}px`;
    triggerBrowserReflow(elem);
  };
  const handleExiting = (elem) => (elem.style.height = '0');
  return (
    <Transition
      {...props}
      onEnter={handleEnter}
      onEntering={handleEntering}
      onEntered={handleEntered}
      onExit={handleExit}
      onExiting={handleExiting}
    >
      {(state, innerProps) =>
        React.cloneElement(children, {
          ...innerProps,
          className: classNames(
            props.className,
            children.props.className,
            collapseStyles[state]
          ),
        })
      }
    </Transition>
  );
};

const Card = () => {
  const [showMoreInfo, setShowMoreInfo] = useState(false);

  return (
    <div className="Card">
      <ButtonShowMore
        isOpen={showMoreInfo}
        click={() => setShowMoreInfo(!showMoreInfo)}
      />
      <Collapse in={showMoreInfo} className="Card-Details" timeout={1000}>
        <div style={{ height: 0 }}>
          <p>details</p>
          <p>details</p>
        </div>
      </Collapse>
    </div>
  );
};

ReactDOM.render(<Card />, document.querySelector('#root'));

.collapsing {
  -webkit-transition: height 1s ease;
  -moz-transition: height 1s ease;
  -o-transition: height 1s ease;
  transition: height 1s ease;
  overflow: hidden;
}

.collapse {
  overflow: hidden;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-transition-group/4.4.1/react-transition-group.min.js"></script>

<div id="root" />