问:
TensorFlow Shape Error After Model is Already Trained
I am training a TensorFlow RNN model using LSTM layers to determine if sound is coming more from the right or left in a stereo audio signal. The model training goes smoothly, then, once it is done training, I get an Invalid Argument Error as shown below. Does anyone know what could be causing this? I have tried fixing it using the solution to a similar question found here, but to no avail.

I do not understand why it is expecting a tensor of shape [32,2]. Did I define that somewhere I am unaware of?

Here is my code:

```<code># -*- coding: utf-8 -*-
"""
Created on Tue Jan 18 15:51:56 2022

@author: andre
"""

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint
from sklearn.model_selection import train_test_split
from datetime import datetime
from sklearn import metrics
from scipy.io import wavfile
import os
import glob

# Load in Right Side .WAV Data.
X1 = []
count1 = 0
database_path = "C:\\Users\\andre\\OneDrive\\Documents\\ESI2022\\MLDatabases\\Right\\"
for filename in glob.glob(os.path.join(database_path, '*.wav')):
    X1.append(wavfile.read(filename)[1])
    count1 = count1 + 1

# Load in Left side .WAV Data.
X2 = []
count2 = 0
database_path2 = "C:\\Users\\andre\\OneDrive\\Documents\\ESI2022\\MLDatabases\\Right\\"
for filename2 in glob.glob(os.path.join(database_path2, '*.wav')):
    X2.append(wavfile.read(filename2)[1])
    count2 = count2 + 1

# Get the smallest size audio file (this will be sample size input to model)
sample_size = len(X1[0])
for data in X1:
    if len(data) < sample_size:
        sample_size = len(data)

# Make audio data into equal size chunks
X1e = []
for i in X1:
    num_chunks = len(i)//sample_size
    for j in range(num_chunks):
        X1e.append(i[(j+1)*sample_size-sample_size:(j+1)*sample_size])
X1 = X1e

X2e = []
for i in X2:
    num_chunks = len(i)//sample_size
    for j in range(num_chunks):
        X2e.append(i[(j+1)*sample_size-sample_size:(j+1)*sample_size])
X2=X2e

del X1e
del X2e

# Create Output data that is the same length as the input data.
Y1 = np.ones([X1.__len__()],dtype='float32').tolist()
Y2 = np.zeros([X2.__len__()],dtype='float32').tolist()

# Concatenate Left and Right .WAV data and output data as numpy arrays.
X1.extend(X2)
X = np.asarray(X1)
Y = np.asarray(Y1+Y2).astype(np.int16)

Xnew=X[0:4900][:][:]
Ynew=Y[0:4900][:][:]

# Split data into test training data.
X_train,X_test,Y_train,Y_test=train_test_split(Xnew,Ynew,test_size=0.204,random_state=0,shuffle=True)

'''
print(X[1])
time = np.linspace(0.,33792, 33792)
plt.plot(time, X[1][:,1], label="Left channel")
plt.plot(time, X[1][:,0], label="Right channel")
plt.legend()
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
plt.show()
'''

# Create the Model
model = Sequential()

# Add a LSTM layer with 1 output, and ambiguous input data length.
model.add(layers.LSTM(2,batch_input_shape=(100,sample_size,2),return_sequences=True))
model.add(layers.LSTM(2,return_sequences=False))

# Compile Model
#history = model.compile(loss='mean_absolute_error', metrics=['accuracy'],optimizer='adam',output='sparse_categorical_crossentropy')
optimizer = Adam(learning_rate=2*1e-4)

history = model.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer="adam",
    metrics=["accuracy"],
)
model.summary()

# Define Training Parameters
num_epochs = 5
num_batch_size = 100

# Save the most accurate model to file. (Verbosity Gives more information)
checkpointer = ModelCheckpoint(filepath="SavedModels/checkpointModel.hdf5", verbose=1,save_best_only=True)

# Start the timer
start = datetime.now()

# Train the model
model.fit(X_train,Y_train,batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test,Y_test), callbacks=[checkpointer],verbose=1)

# Get and Print Model Validation Accuracy
test_accuracy=model.evaluate(X_test,Y_test,verbose=0)
print(test_accuracy[1])
</code>```

And here is the full error message:

```<code>runfile('C:/Users/andre/OneDrive/Documents/ESI2022/PythonScripts/BeltML/testML.py', wdir='C:/Users/andre/OneDrive/Documents/ESI2022/PythonScripts/BeltML')
Model: "sequential_14"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 lstm_28 (LSTM)              (100, 3072, 2)            40

 lstm_29 (LSTM)              (100, 2)                  40

=================================================================
Total params: 80
Trainable params: 80
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
39/39 [==============================] - ETA: 0s - loss: 0.7387 - accuracy: 0.4936
Epoch 00001: val_loss improved from inf to 0.71954, saving model to SavedModels\checkpointModel.hdf5
39/39 [==============================] - 60s 1s/step - loss: 0.7387 - accuracy: 0.4936 - val_loss: 0.7195 - val_accuracy: 0.5100
Epoch 2/5
39/39 [==============================] - ETA: 0s - loss: 0.7217 - accuracy: 0.4995
Epoch 00002: val_loss improved from 0.71954 to 0.70838, saving model to SavedModels\checkpointModel.hdf5
39/39 [==============================] - 57s 1s/step - loss: 0.7217 - accuracy: 0.4995 - val_loss: 0.7084 - val_accuracy: 0.5090
Epoch 3/5
39/39 [==============================] - ETA: 0s - loss: 0.7105 - accuracy: 0.4990
Epoch 00003: val_loss improved from 0.70838 to 0.70385, saving model to SavedModels\checkpointModel.hdf5
39/39 [==============================] - 57s 1s/step - loss: 0.7105 - accuracy: 0.4990 - val_loss: 0.7038 - val_accuracy: 0.5070
Epoch 4/5
39/39 [==============================] - ETA: 0s - loss: 0.7043 - accuracy: 0.4995
Epoch 00004: val_loss improved from 0.70385 to 0.70144, saving model to SavedModels\checkpointModel.hdf5
39/39 [==============================] - 57s 1s/step - loss: 0.7043 - accuracy: 0.4995 - val_loss: 0.7014 - val_accuracy: 0.5070
Epoch 5/5
39/39 [==============================] - ETA: 0s - loss: 0.7010 - accuracy: 0.5018
Epoch 00005: val_loss improved from 0.70144 to 0.69969, saving model to SavedModels\checkpointModel.hdf5
39/39 [==============================] - 57s 1s/step - loss: 0.7010 - accuracy: 0.5018 - val_loss: 0.6997 - val_accuracy: 0.5130
Traceback (most recent call last):

  File "C:\Users\andre\OneDrive\Documents\ESI2022\PythonScripts\BeltML\testML.py", line 124, in <module>
    test_accuracy=model.evaluate(X_test,Y_test,verbose=0)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\eager\execute.py", line 58, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,

InvalidArgumentError:    Specified a list with shape [100,2] from a tensor with shape [32,2]
     [[{{node TensorArrayUnstack/TensorListFromTensor}}]]
     [[sequential_14/lstm_28/PartitionedCall]] [Op:__inference_test_function_121112]

Function call stack:
test_function -> test_function -> test_function
</code>```

答:
You get this error because you hard-coded the batch size in the first LSTM layer and the number of data samples is not evenly divisible by 100. You have to take care of the remainder somehow. I would recommend removing the batch size from the first layer and only entering the batch size in model.fit. This way your model will be able to handle the remaining smaller batch(es). Here is an example:

X_train = tf.random.normal((2632, 5, 2))
Y_train = tf.random.uniform((2632, 1), maxval=2, dtype=tf.int32)

model = Sequential()

model.add(layers.LSTM(2,input_shape=(5,2),return_sequences=True))
model.add(layers.LSTM(2,return_sequences=False))

optimizer = Adam(learning_rate=2*1e-4)

history = model.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer="adam",
    metrics=["accuracy"],
)
model.summary()

num_epochs = 5
num_batch_size = 100

checkpointer = ModelCheckpoint(filepath="SavedModels/checkpointModel.hdf5", verbose=1,save_best_only=True)

start = datetime.now()
num_epochs = 5
num_batch_size = 100

model.fit(X_train,Y_train,batch_size=num_batch_size, epochs=num_epochs , callbacks=[checkpointer],verbose=1)
```

Also, the post you linked to should actually help you.

Body:
I am training a TensorFlow RNN model using LSTM layers to determine if sound is coming more from the right or left in a stereo audio signal. The model training goes smoothly, then, once it is done training, I get an Invalid Argument Error as shown below. Does anyone know what could be causing this? I have tried fixing it using the solution to a similar question found here, but to no avail.

I do not understand why it is expecting a tensor of shape [32,2]. Did I define that somewhere I am unaware of?

Here is my code:

# -*- coding: utf-8 -*-
"""
Created on Tue Jan 18 15:51:56 2022

@author: andre
"""

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint
from sklearn.model_selection import train_test_split
from datetime import datetime
from sklearn import metrics
from scipy.io import wavfile
import os
import glob

# Load in Right Side .WAV Data.
X1 = []
count1 = 0
database_path = "C:\\Users\\andre\\OneDrive\\Documents\\ESI2022\\MLDatabases\\Right\\"
for filename in glob.glob(os.path.join(database_path, '*.wav')):
    X1.append(wavfile.read(filename)[1])
    count1 = count1 + 1

# Load in Left side .WAV Data.
X2 = []
count2 = 0
database_path2 = "C:\\Users\\andre\\OneDrive\\Documents\\ESI2022\\MLDatabases\\Right\\"
for filename2 in glob.glob(os.path.join(database_path2, '*.wav')):
    X2.append(wavfile.read(filename2)[1])
    count2 = count2 + 1

# Get the smallest size audio file (this will be sample size input to model)
sample_size = len(X1[0])
for data in X1:
    if len(data) < sample_size:
        sample_size = len(data)

# Make audio data into equal size chunks
X1e = []
for i in X1:
    num_chunks = len(i)//sample_size
    for j in range(num_chunks):
        X1e.append(i[(j+1)*sample_size-sample_size:(j+1)*sample_size])
X1 = X1e

X2e = []
for i in X2:
    num_chunks = len(i)//sample_size
    for j in range(num_chunks):
        X2e.append(i[(j+1)*sample_size-sample_size:(j+1)*sample_size])
X2=X2e

del X1e
del X2e

# Create Output data that is the same length as the input data.
Y1 = np.ones([X1.__len__()],dtype='float32').tolist()
Y2 = np.zeros([X2.__len__()],dtype='float32').tolist()

# Concatenate Left and Right .WAV data and output data as numpy arrays.
X1.extend(X2)
X = np.asarray(X1)
Y = np.asarray(Y1+Y2).astype(np.int16)

Xnew=X[0:4900][:][:]
Ynew=Y[0:4900][:][:]

# Split data into test training data.
X_train,X_test,Y_train,Y_test=train_test_split(Xnew,Ynew,test_size=0.204,random_state=0,shuffle=True)

'''
print(X[1])
time = np.linspace(0.,33792, 33792)
plt.plot(time, X[1][:,1], label="Left channel")
plt.plot(time, X[1][:,0], label="Right channel")
plt.legend()
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
plt.show()
'''

# Create the Model
model = Sequential()

# Add a LSTM layer with 1 output, and ambiguous input data length.
model.add(layers.LSTM(2,batch_input_shape=(100,sample_size,2),return_sequences=True))
model.add(layers.LSTM(2,return_sequences=False))

# Compile Model
#history = model.compile(loss='mean_absolute_error', metrics=['accuracy'],optimizer='adam',output='sparse_categorical_crossentropy')
optimizer = Adam(learning_rate=2*1e-4)

history = model.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer="adam",
    metrics=["accuracy"],
)
model.summary()

# Define Training Parameters
num_epochs = 5
num_batch_size = 100

# Save the most accurate model to file. (Verbosity Gives more information)
checkpointer = ModelCheckpoint(filepath="SavedModels/checkpointModel.hdf5", verbose=1,save_best_only=True)

# Start the timer
start = datetime.now()

# Train the model
model.fit(X_train,Y_train,batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test,Y_test), callbacks=[checkpointer],verbose=1)

# Get and Print Model Validation Accuracy
test_accuracy=model.evaluate(X_test,Y_test,verbose=0)
print(test_accuracy[1])

And here is the full error message:

runfile('C:/Users/andre/OneDrive/Documents/ESI2022/PythonScripts/BeltML/testML.py', wdir='C:/Users/andre/OneDrive/Documents/ESI2022/PythonScripts/BeltML')
Model: "sequential_14"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 lstm_28 (LSTM)              (100, 3072, 2)            40

 lstm_29 (LSTM)              (100, 2)                  40

=================================================================
Total params: 80
Trainable params: 80
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
39/39 [==============================] - ETA: 0s - loss: 0.7387 - accuracy: 0.4936
Epoch 00001: val_loss improved from inf to 0.71954, saving model to SavedModels\checkpointModel.hdf5
39/39 [==============================] - 60s 1s/step - loss: 0.7387 - accuracy: 0.4936 - val_loss: 0.7195 - val_accuracy: 0.5100
Epoch 2/5
39/39 [==============================] - ETA: 0s - loss: 0.7217 - accuracy: 0.4995
Epoch 00002: val_loss improved from 0.71954 to 0.70838, saving model to SavedModels\checkpointModel.hdf5
39/39 [==============================] - 57s 1s/step - loss: 0.7217 - accuracy: 0.4995 - val_loss: 0.7084 - val_accuracy: 0.5090
Epoch 3/5
39/39 [==============================] - ETA: 0s - loss: 0.7105 - accuracy: 0.4990
Epoch 00003: val_loss improved from 0.70838 to 0.70385, saving model to SavedModels\checkpointModel.hdf5
39/39 [==============================] - 57s 1s/step - loss: 0.7105 - accuracy: 0.4990 - val_loss: 0.7038 - val_accuracy: 0.5070
Epoch 4/5
39/39 [==============================] - ETA: 0s - loss: 0.7043 - accuracy: 0.4995
Epoch 00004: val_loss improved from 0.70385 to 0.70144, saving model to SavedModels\checkpointModel.hdf5
39/39 [==============================] - 57s 1s/step - loss: 0.7043 - accuracy: 0.4995 - val_loss: 0.7014 - val_accuracy: 0.5070
Epoch 5/5
39/39 [==============================] - ETA: 0s - loss: 0.7010 - accuracy: 0.5018
Epoch 00005: val_loss improved from 0.70144 to 0.69969, saving model to SavedModels\checkpointModel.hdf5
39/39 [==============================] - 57s 1s/step - loss: 0.7010 - accuracy: 0.5018 - val_loss: 0.6997 - val_accuracy: 0.5130
Traceback (most recent call last):

  File "C:\Users\andre\OneDrive\Documents\ESI2022\PythonScripts\BeltML\testML.py", line 124, in <module>
    test_accuracy=model.evaluate(X_test,Y_test,verbose=0)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\eager\execute.py", line 58, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,

InvalidArgumentError:    Specified a list with shape [100,2] from a tensor with shape [32,2]
     [[{{node TensorArrayUnstack/TensorListFromTensor}}]]
     [[sequential_14/lstm_28/PartitionedCall]] [Op:__inference_test_function_121112]

Function call stack:
test_function -> test_function -> test_function

Body:
You get this error because you hard-coded the batch size in the first LSTM layer and the number of data samples is not evenly divisible by 100. You have to take care of the remainder somehow. I would recommend removing the batch size from the first layer and only entering the batch size in model.fit. This way your model will be able to handle the remaining smaller batch(es). Here is an example:

X_train = tf.random.normal((2632, 5, 2))
Y_train = tf.random.uniform((2632, 1), maxval=2, dtype=tf.int32)

model = Sequential()

model.add(layers.LSTM(2,input_shape=(5,2),return_sequences=True))
model.add(layers.LSTM(2,return_sequences=False))

optimizer = Adam(learning_rate=2*1e-4)

history = model.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer="adam",
    metrics=["accuracy"],
)
model.summary()

num_epochs = 5
num_batch_size = 100

checkpointer = ModelCheckpoint(filepath="SavedModels/checkpointModel.hdf5", verbose=1,save_best_only=True)

start = datetime.now()
num_epochs = 5
num_batch_size = 100

model.fit(X_train,Y_train,batch_size=num_batch_size, epochs=num_epochs , callbacks=[checkpointer],verbose=1)

Also, the post you linked to should actually help you.


来源: stackexchange

问:
Issue in functioning of radio input in dynamically adding row through jQuery
A new row is dynamically creating on clicking "add Row" button through function in jQuery.
But when I select radio input in new row then selected value of previous radio input is removing.
Please run and see the codes as below:
enter image description here

function add_row(table_row_count)
{
    $("#add-row_"+table_row_count).hide();
    $("#delete-row_"+table_row_count).hide();

    var table_row_count = parseInt(table_row_count);

    table_row_count += 1;

    var markup =
    '
'+
    ''+table_row_count+'	'+
    ''+
          'Value in Range? :'+
          '<input type="radio" name="option" id="option_1_row_'+table_row_count+'" value="1"  > YES'+
          '<input type="radio" name="option" id="option_2_row_'+table_row_count+'" value="2"  > NO'+
    '	'+
    ''+
            'Range From :
'+
            '<input type="text" name="capacity_from[]" id="capacity_from_'+table_row_count+'"  />'+
    '	'+
    ''+
            'Range Upto :
'+
            '<input type="text" name="capacity_upto[]" id="capacity_upto_'+table_row_count+'" />'+
     '	'+
    ' Add Row	'+
    ' Delete Row	'+
    '
';

    var table = $("#tbl_details tbody");
    table.append(markup);

}

function delete_row(table_row_count)
{
    var r = confirm("Are you sure to delete row");
    if(r == false){
        return;
    }

    var table_row_count = parseInt(table_row_count);
    var previous_row = table_row_count - 1;
    $("#add-row_"+previous_row).show();
    if(previous_row != 1){
        $("#delete-row_"+previous_row).show();
    }

    $("#tbl_row_"+table_row_count).remove();

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="add.js"></script>
</head>
<body>
        <h3>Enter Details</h3>
        <table class="table table-striped" id="tbl_details">
        <tbody>
        <tr id="row_1">
        <td>1.</td>
        <td>
          <label>Value in Range? :</label>
          <input type="radio" name="option" id="option_1_row_1" value="1" checked="checked" > YES
          <input type="radio" name="option" id="option_2_row_1" value="2" > NO
        </td>
        <td id="capacity_from_row_1" >
            <label>Range From :</label><br>
            <input type="text" name="capacity_from[]" id="capacity_from_1" />
        </td>
        <td>
            <label id="lbl_capacity_range_1" >Range Upto :</label><br>
            <input type="text" name="capacity_upto[]" id="capacity_upto_1" />
        </td>
        <td class="align-middle"><i class="fa fa-plus fa-lg text-success" aria-hidden="true"></i> Add Row</td>
        <td class="align-middle"></td>
        </tr>
        </tbody>
        </table>
</body>
</html></code>```

How to solve the issue. kindly help me.
Thanks in advance.

答:
Different radio button groups are created when the name attribute of the radio buttons is different. Also, in the solution below, I made it easier to express dynamic content by using template literals.

Note the following statement in the dynamic element written into the markup variable in the add_row() method:

<input type="radio" name="option${counter}" id="option_1_row_${table_row_count}" value="1"> YES
<input type="radio" name="option${counter}" id="option_2_row_${table_row_count}" value="2"> NO
```
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* This variable will be used to create new radio button groups. */
let counter = 0;

function add_row(table_row_count) {
    $("#add-row_"+table_row_count).hide();
    $("#delete-row_"+table_row_count).hide();
    var table_row_count = parseInt(table_row_count);
    table_row_count += 1;

    /* With each iteration, the content of the counter variable is incremented. */
    ++counter;

    var markup =
         `<tr id="tbl_row_${table_row_count}">
              <td>
                  <label>${table_row_count}</label>
              </td>

              <td>
                  <label>Value in Range? :</label>

                  <!-- Note the name="option${counter}" statement so that the radio buttons have different groups. -->
                  <input type="radio" name="option${counter}" id="option_1_row_${table_row_count}" value="1"> YES
                  <input type="radio" name="option${counter}" id="option_2_row_${table_row_count}" value="2"> NO
              </td>

              <td id="capacity_from_row_${table_row_count}">
                  <label>Range From :</label><br>
                  <input type="text" name="capacity_from[]" id="capacity_from_${table_row_count}"/>
              </td>

              <td>
                  <label id="lbl_capacity_range_${table_row_count}">Range Upto :</label><br>
                  <input type="text" name="capacity_upto[]" id="capacity_upto_${table_row_count}"/>
              </td>

              <td class="align-middle">

                      <i class="fa fa-plus fa-lg text-success" aria-hidden="true"></i> Add Row

              </td>

              <td class="align-middle">

                      <i class="fa fa-trash fa-lg text-danger" aria-hidden="true"></i> Delete Row

              </td>
          </tr>`

    var table = $("#tbl_details tbody");
    table.append(markup);
}

function delete_row(table_row_count) {
    var r = confirm("Are you sure to delete row");

    if(r == false){
        return;
    }

    var table_row_count = parseInt(table_row_count);
    var previous_row = table_row_count - 1;

    $("#add-row_"+previous_row).show();
    if(previous_row != 1){
        $("#delete-row_"+previous_row).show();
    }

    $("#tbl_row_"+table_row_count).remove();

}</code>```

Enter Details

      1.

        Value in Range? :
        <input type="radio" name="option" id="option_1_row_1" value="1" checked="checked" > YES
        <input type="radio" name="option" id="option_2_row_1" value="2" > NO

          Range From :

          <input type="text" name="capacity_from[]" id="capacity_from_1" />

          Range Upto :

          <input type="text" name="capacity_upto[]" id="capacity_upto_1" />

       Add Row

```

ContentLicense: CC BY-SA 4.0

Body:
A new row is dynamically creating on clicking "add Row" button through function in jQuery.
But when I select radio input in new row then selected value of previous radio input is removing.
Please run and see the codes as below:
enter image description here

function add_row(table_row_count)
{
    $("#add-row_"+table_row_count).hide();
    $("#delete-row_"+table_row_count).hide();

    var table_row_count = parseInt(table_row_count);

    table_row_count += 1;

    var markup =
    '
'+
    ''+table_row_count+'	'+
    ''+
          'Value in Range? :'+
          '<input type="radio" name="option" id="option_1_row_'+table_row_count+'" value="1"  > YES'+
          '<input type="radio" name="option" id="option_2_row_'+table_row_count+'" value="2"  > NO'+
    '	'+
    ''+
            'Range From :
'+
            '<input type="text" name="capacity_from[]" id="capacity_from_'+table_row_count+'"  />'+
    '	'+
    ''+
            'Range Upto :
'+
            '<input type="text" name="capacity_upto[]" id="capacity_upto_'+table_row_count+'" />'+
     '	'+
    ' Add Row	'+
    ' Delete Row	'+
    '
';

    var table = $("#tbl_details tbody");
    table.append(markup);

}

function delete_row(table_row_count)
{
    var r = confirm("Are you sure to delete row");
    if(r == false){
        return;
    }

    var table_row_count = parseInt(table_row_count);
    var previous_row = table_row_count - 1;
    $("#add-row_"+previous_row).show();
    if(previous_row != 1){
        $("#delete-row_"+previous_row).show();
    }

    $("#tbl_row_"+table_row_count).remove();

}

Enter Details

        1.

          Value in Range? :
          <input type="radio" name="option" id="option_1_row_1" value="1" checked="checked" > YES
          <input type="radio" name="option" id="option_2_row_1" value="2" > NO

            Range From :

            <input type="text" name="capacity_from[]" id="capacity_from_1" />

            Range Upto :

            <input type="text" name="capacity_upto[]" id="capacity_upto_1" />

         Add Row

How to solve the issue. kindly help me.
Thanks in advance.

Body:
Different radio button groups are created when the name attribute of the radio buttons is different. Also, in the solution below, I made it easier to express dynamic content by using template literals.

Note the following statement in the dynamic element written into the markup variable in the add_row() method:

<input type="radio" name="option${counter}" id="option_1_row_${table_row_count}" value="1"> YES
<input type="radio" name="option${counter}" id="option_2_row_${table_row_count}" value="2"> NO

/* This variable will be used to create new radio button groups. */
let counter = 0;

function add_row(table_row_count) {
    $("#add-row_"+table_row_count).hide();
    $("#delete-row_"+table_row_count).hide();
    var table_row_count = parseInt(table_row_count);
    table_row_count += 1;

    /* With each iteration, the content of the counter variable is incremented. */
    ++counter;

    var markup =
         `<tr id="tbl_row_${table_row_count}">
              <td>
                  <label>${table_row_count}</label>
              </td>

              <td>
                  <label>Value in Range? :</label>

                  <!-- Note the name="option${counter}" statement so that the radio buttons have different groups. -->
                  <input type="radio" name="option${counter}" id="option_1_row_${table_row_count}" value="1"> YES
                  <input type="radio" name="option${counter}" id="option_2_row_${table_row_count}" value="2"> NO
              </td>

              <td id="capacity_from_row_${table_row_count}">
                  <label>Range From :</label><br>
                  <input type="text" name="capacity_from[]" id="capacity_from_${table_row_count}"/>
              </td>

              <td>
                  <label id="lbl_capacity_range_${table_row_count}">Range Upto :</label><br>
                  <input type="text" name="capacity_upto[]" id="capacity_upto_${table_row_count}"/>
              </td>

              <td class="align-middle">
                  <a href="javascript:void(0)" class="text-success add-row" id="add-row_${table_row_count}" onClick="add_row('${table_row_count}');" >
                      <i class="fa fa-plus fa-lg text-success" aria-hidden="true"></i> Add Row
                  </a>
              </td>

              <td class="align-middle">
                  <a href="javascript:void(0)" class="text-danger delete-row" id="delete-row_${table_row_count}" onClick="delete_row('${table_row_count}');" >
                      <i class="fa fa-trash fa-lg text-danger" aria-hidden="true"></i> Delete Row
                  </a>
              </td>
          </tr>`

    var table = $("#tbl_details tbody");
    table.append(markup);
}

function delete_row(table_row_count) {
    var r = confirm("Are you sure to delete row");

    if(r == false){
        return;
    }

    var table_row_count = parseInt(table_row_count);
    var previous_row = table_row_count - 1;

    $("#add-row_"+previous_row).show();
    if(previous_row != 1){
        $("#delete-row_"+previous_row).show();
    }

    $("#tbl_row_"+table_row_count).remove();

}

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="add.js"></script>
</head>
<body>
<h3>Enter Details</h3>
<table class="table table-striped" id="tbl_details">
  <tbody>
    <tr id="row_1">
      <td>1.</td>
      <td>
        <label>Value in Range? :</label>
        <input type="radio" name="option" id="option_1_row_1" value="1" checked="checked" > YES
        <input type="radio" name="option" id="option_2_row_1" value="2" > NO
      </td>
      <td id="capacity_from_row_1" >
          <label>Range From :</label><br>
          <input type="text" name="capacity_from[]" id="capacity_from_1" />
      </td>
      <td>
          <label id="lbl_capacity_range_1" >Range Upto :</label><br>
          <input type="text" name="capacity_upto[]" id="capacity_upto_1" />
      </td>
      <td class="align-middle"><a href="javascript:void(0)" class="text-success add-row" id="add-row_1" onClick="add_row(1);" ><i class="fa fa-plus fa-lg text-success" aria-hidden="true"></i> Add Row</a></td>
      <td class="align-middle"></td>
    </tr>
  </tbody>
</table>
</body>
</html>


问:
Run a Google Script only weekdays every 15-minute, between certain hours - using time-based trigger?
Hi I have a google app script that I need to run every weekday only between 09:30 AM to 15:45 PM. I am not being able to add the minutes. I have a code that has the hours in it. My code is given below. I tried to add minutes with && but that is giving funny results.

```<code>function Record() {

var today = new Date();
  var day = today.getDay();

  var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

  if(day == 6 || day == 0) {
    return;
  } else {

    var hour = today.getHours();
    var minute = today.getMinutes();
    if(hour < 10 || hour > 15) {
      return;
    }

  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var source1 = ss1.getRange("Nifty!C28:K28");
  var destSheet1 = ss1.getSheetByName("Record 1");
  destSheet1.appendRow(source1.getValues()[0]);

  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var source2 = ss2.getRange("Bank Nifty!C28:K28");
  var destSheet2 = ss2.getSheetByName("Record 2");
  destSheet2.appendRow(source2.getValues()[0]);

  }
}
</code>```

Can anyone help me out?

答:
This is not exactly the time but it's pretty close

```<code>function Record(e) {
  if (e['day-of-week'] < 6 && e.hour > 9 && e.hour < 16) {
    const ss1 = SpreadsheetApp.getActive();
    const src1 = ss1.getRange("Nifty!C28:K28");
    var dsh1 = ss1.getSheetByName("Record 1");
    dsh1.appendRow(src1.getValues()[0]);

    var ss2 = SpreadsheetApp.getActiveSpreadsheet();
    var src2 = ss2.getRange("Bank Nifty!C28:K28");
    var dsh2 = ss2.getSheetByName("Record 2");
    dsh2.appendRow(src2.getValues()[0]);
  }
}

//only creates one trigger for the handlerfunction
function createTimeBasedTrigger() {
  if (ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() == "Record").length == 0) {
    ScriptApp.newTrigger("Record").timeBased().everyMinutes(15).create();
  }
}
</code>```

Body:
Hi I have a google app script that I need to run every weekday only between 09:30 AM to 15:45 PM. I am not being able to add the minutes. I have a code that has the hours in it. My code is given below. I tried to add minutes with && but that is giving funny results.

function Record() {

var today = new Date();
  var day = today.getDay();

  var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

  if(day == 6 || day == 0) {
    return;
  } else {

    var hour = today.getHours();
    var minute = today.getMinutes();
    if(hour < 10 || hour > 15) {
      return;
    }

  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var source1 = ss1.getRange("Nifty!C28:K28");
  var destSheet1 = ss1.getSheetByName("Record 1");
  destSheet1.appendRow(source1.getValues()[0]);

  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var source2 = ss2.getRange("Bank Nifty!C28:K28");
  var destSheet2 = ss2.getSheetByName("Record 2");
  destSheet2.appendRow(source2.getValues()[0]);

  }
}

Can anyone help me out?

Body:
This is not exactly the time but it's pretty close

function Record(e) {
  if (e['day-of-week'] < 6 && e.hour > 9 && e.hour < 16) {
    const ss1 = SpreadsheetApp.getActive();
    const src1 = ss1.getRange("Nifty!C28:K28");
    var dsh1 = ss1.getSheetByName("Record 1");
    dsh1.appendRow(src1.getValues()[0]);

    var ss2 = SpreadsheetApp.getActiveSpreadsheet();
    var src2 = ss2.getRange("Bank Nifty!C28:K28");
    var dsh2 = ss2.getSheetByName("Record 2");
    dsh2.appendRow(src2.getValues()[0]);
  }
}

//only creates one trigger for the handlerfunction
function createTimeBasedTrigger() {
  if (ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() == "Record").length == 0) {
    ScriptApp.newTrigger("Record").timeBased().everyMinutes(15).create();
  }
}


问:
using PeriodIndex vs DateTimeIndex in pandas?
I am working with some financial data that is organized as a df with a MultiIndex that contains the ticker and the date and a column that contains the return. I am wondering whether one should convert the index to a PeriodIndex instead of a DateTimeIndex since returns are really over a period rather than an instant in time. Beside the philosophical argument, what practical functionality does PeriodIndex provide that may be useful in this particular use case vs DateTimeIndex?

答:
For me, the PeriodIndex can be automatically displayed as the corresponding month, quarter and year in the downsampling.

```<code>import pandas as pd
# https://github.com/jiahe224/bug_report/blob/main/resample_test.csv
temp = pd.read_csv('resample_test.csv',dtype={'stockcode':str, 'A股代码':str})
temp['date'] = pd.to_datetime(temp['date'])
temp = temp.set_index(['date'])

result = temp['北向占自由流通比'].resample('Q',closed='left').first()
result
</code>```

```<code>result = temp['北向占自由流通比'].resample('Q',closed='left').first().to_period()
result
</code>```

Off topic, there is a problem with resample that has not been fixed as of yet, the bug report at https://github.com/pandas-dev/pandas/issues/45869

Body:
For me, the PeriodIndex can be automatically displayed as the corresponding month, quarter and year in the downsampling.

import pandas as pd
# https://github.com/jiahe224/bug_report/blob/main/resample_test.csv
temp = pd.read_csv('resample_test.csv',dtype={'stockcode':str, 'A股代码':str})
temp['date'] = pd.to_datetime(temp['date'])
temp = temp.set_index(['date'])

result = temp['北向占自由流通比'].resample('Q',closed='left').first()
result

result = temp['北向占自由流通比'].resample('Q',closed='left').first().to_period()
result

Off topic, there is a problem with resample that has not been fixed as of yet, the bug report at https://github.com/pandas-dev/pandas/issues/45869


问:
Edge case in C program to find and replace words from a text file
I'm new to C and would greatly appreciate some help in fixing a bug in my program.

I've identified an edge case and I'm not quite sure how to resolve it.

Currently, the function will find and replace words and words within words given a text file. For instance, changing 'water' to 'snow' will change the string 'waterfall' into 'snowfall'. This is an intended result.

However, when I input 'waterfalls' to change the word 'waterfall', the program seems to get stuck in an endless loop. I'm not quite sure why but I would appreciate if anyone could point me in the right direction.

Here is my code:

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

#define BUFFER_SIZE 20

void replaceWord(char *str, const char *oldWord, const char *newWord)
{
    char *position, buffer[BUFFER_SIZE];
    int index, oldWordLength;
    oldWordLength = (long)strlen(oldWord);
    while ((position = strstr(str, oldWord)) != NULL)
    {
        strcpy(buffer, str);
        index = position - str;
        str[index] = '\0';
        strcat(str, newWord);
        strcat(str, buffer + index + oldWordLength);
    }
}

int main()
{
    char msg[100] = "This is some text with the word snowfall to replace";
    puts(msg);
    replaceWord(msg, "snowfall", "snowfalls");
    puts(msg);
    return 0;
}
</code>```

答:
Ok. First, you have a severely undersized buffer. This:

```<code>char buffer[BUFFER_SIZE];
</code>```

is the target of what ends up being a full-string copy of the original message. But in main, the original message:

```<code>char msg[100] = "This is some text with the word snowfall to replace";
</code>```

is 51 characters wide (not including the terminator). That's not going to work, and running through a debug address sanitizer (or a regular debugger, ideally) would show that. :

```<code>==1==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffd578054d4 at pc 0x7f7457e4c846 bp 0x7ffd57805460 sp 0x7ffd57804c10
WRITE of size 52 at 0x7ffd578054d4 thread T0
    #0 0x7f7457e4c845  (/opt/compiler-explorer/gcc-11.2.0/lib64/libasan.so.6+0x55845)
    #1 0x4012a7 in replaceWord /app/example.c:15
    #2 0x401592 in main /app/example.c:27
    #3 0x7f7457c2c0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
    #4 0x40112d in _start (/app/output.s+0x40112d)

Address 0x7ffd578054d4 is located in stack of thread T0 at offset 52 in frame
    #0 0x4011f5 in replaceWord /app/example.c:9
</code>```

So that clearly isn't any good. Fixing that by increasing the buffer size will "work", but to really do this right the source/target buffer (in your function they're one in the same) should have its full writable width (and that includes space for a terminator) provided as an argument (which you should definitely do.

Second, the code that does this:

```<code>while ((position = strstr(str, oldWord)) != NULL)
</code>```

is always starting the search for oldWord from the beginning of the input string. that's wrong (well, it's right exactly once; the first time through; after that, it's wrong). Consider this:

```<code>i love c++
</code>```

Suppose I look or i and I want to replace it with is. I would find it here:

```<code>i love c++
^
</code>```

After replacement my new string I'm building looks like this:

```<code>is love c++
</code>```

So where do you know to start the next search from? You start at the position where the original string started, plus the length of the replacement string value. The original was in pos 0. the length of the replacement was 2, so we start the next search at pos 2.

```<code>is love c++
  ^
</code>```

Note that this gets a LOT more complicated when you're doing everything in-place (e.g. no intermediate buffer), but that doesn't seem to be a goal for you right now, and is likely off your radar.  Therefore, a not-very-efficient, but functional way to do this is:

Start at the beginning of the string (src = str)

Search for the old word, starting at src.

If found, copy the original string up-to, but not including, the old word to a buffer.

Append the replacement string to the buffer.

Append the remainder of the original string passed the old word to the buffer.

Copy the buffer back to the source string.

Reposition src to be the length of the replacement word past the original position of the found old word from (3)

Loop back to (2) until the old word is no longer found.

As I said; not very efficient, but it is fairly easy to understand. It looks like this in code. Note the buffer size was significantly increased, and is used to declare both the temp buffer and the array in main. This still isn't good, but it was what you brought, so I'm sticking with it. I urge you to consider doing this algorithm with dynamic memory management, or size-restrictions passed as additional argument(s):

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

#define BUFFER_SIZE 100

void replaceWord(char *str, const char *oldWord, const char *newWord)
{
    char buffer[ BUFFER_SIZE ];
    char *src = str;
    char *oldpos = NULL;

    size_t lenOldWord = strlen(oldWord);
    size_t lenNewWord = strlen(newWord);

    while ((oldpos = strstr(src, oldWord)) != NULL)
    {
        // 1. copy everything up to the old word.
        // 2. append the new word
        // 3. copy the remainder of source string *past* the old word
        // 4. copy back to the original string.
        memcpy(buffer, str, (size_t)(oldpos - str));
        memcpy(buffer + (oldpos - str), newWord, lenNewWord);
        strcpy(buffer + (oldpos - str) + lenNewWord, oldpos + lenOldWord);
        strcpy(str, buffer);

        // the new starting point will be the previous discovry
        //  location plus the length of the new word.
        src = oldpos + lenNewWord;
    }
}

int main()
{
    char msg[BUFFER_SIZE] = "This is some text with the word snowfall to replace";
    puts(msg);
    replaceWord(msg, "snowfall", "snowfalls");
    puts(msg);
    return 0;
}
</code>```

Output

```<code>This is some text with the word snowfall to replace
This is some text with the word snowfalls to replace
</code>```

I strongly suggest you to run this in a debugger and watch how it works, step by step. It will help you understand where you were missing the start-search-here logic. And I urge you even more, as an exercise, address the blatant vulnerability of this algorithm. think of ways you could easily invoke undefined behavior (hint: short, common old word, very very long replacement word), and the things you should to do address those problems.

Body:
I'm new to C and would greatly appreciate some help in fixing a bug in my program.

I've identified an edge case and I'm not quite sure how to resolve it.

Currently, the function will find and replace words and words within words given a text file. For instance, changing 'water' to 'snow' will change the string 'waterfall' into 'snowfall'. This is an intended result.

However, when I input 'waterfalls' to change the word 'waterfall', the program seems to get stuck in an endless loop. I'm not quite sure why but I would appreciate if anyone could point me in the right direction.

Here is my code:

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

#define BUFFER_SIZE 20

void replaceWord(char *str, const char *oldWord, const char *newWord)
{
    char *position, buffer[BUFFER_SIZE];
    int index, oldWordLength;
    oldWordLength = (long)strlen(oldWord);
    while ((position = strstr(str, oldWord)) != NULL)
    {
        strcpy(buffer, str);
        index = position - str;
        str[index] = '\0';
        strcat(str, newWord);
        strcat(str, buffer + index + oldWordLength);
    }
}

int main()
{
    char msg[100] = "This is some text with the word snowfall to replace";
    puts(msg);
    replaceWord(msg, "snowfall", "snowfalls");
    puts(msg);
    return 0;
}

Body:
Ok. First, you have a severely undersized buffer. This:

char buffer[BUFFER_SIZE];

is the target of what ends up being a full-string copy of the original message. But in main, the original message:

char msg[100] = "This is some text with the word snowfall to replace";

is 51 characters wide (not including the terminator). That's not going to work, and running through a debug address sanitizer (or a regular debugger, ideally) would show that. :

==1==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffd578054d4 at pc 0x7f7457e4c846 bp 0x7ffd57805460 sp 0x7ffd57804c10
WRITE of size 52 at 0x7ffd578054d4 thread T0
    #0 0x7f7457e4c845  (/opt/compiler-explorer/gcc-11.2.0/lib64/libasan.so.6+0x55845)
    #1 0x4012a7 in replaceWord /app/example.c:15
    #2 0x401592 in main /app/example.c:27
    #3 0x7f7457c2c0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
    #4 0x40112d in _start (/app/output.s+0x40112d)

Address 0x7ffd578054d4 is located in stack of thread T0 at offset 52 in frame
    #0 0x4011f5 in replaceWord /app/example.c:9

So that clearly isn't any good. Fixing that by increasing the buffer size will "work", but to really do this right the source/target buffer (in your function they're one in the same) should have its full writable width (and that includes space for a terminator) provided as an argument (which you should definitely do.

Second, the code that does this:

while ((position = strstr(str, oldWord)) != NULL)

is always starting the search for oldWord from the beginning of the input string. that's wrong (well, it's right exactly once; the first time through; after that, it's wrong). Consider this:

i love c++

Suppose I look or i and I want to replace it with is. I would find it here:

i love c++
^

After replacement my new string I'm building looks like this:

is love c++

So where do you know to start the next search from? You start at the position where the original string started, plus the length of the replacement string value. The original was in pos 0. the length of the replacement was 2, so we start the next search at pos 2.

is love c++
  ^

Note that this gets a LOT more complicated when you're doing everything in-place (e.g. no intermediate buffer), but that doesn't seem to be a goal for you right now, and is likely off your radar.  Therefore, a not-very-efficient, but functional way to do this is:

Start at the beginning of the string (src = str)

Search for the old word, starting at src.

If found, copy the original string up-to, but not including, the old word to a buffer.

Append the replacement string to the buffer.

Append the remainder of the original string passed the old word to the buffer.

Copy the buffer back to the source string.

Reposition src to be the length of the replacement word past the original position of the found old word from (3)

Loop back to (2) until the old word is no longer found.

As I said; not very efficient, but it is fairly easy to understand. It looks like this in code. Note the buffer size was significantly increased, and is used to declare both the temp buffer and the array in main. This still isn't good, but it was what you brought, so I'm sticking with it. I urge you to consider doing this algorithm with dynamic memory management, or size-restrictions passed as additional argument(s):

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

#define BUFFER_SIZE 100

void replaceWord(char *str, const char *oldWord, const char *newWord)
{
    char buffer[ BUFFER_SIZE ];
    char *src = str;
    char *oldpos = NULL;

    size_t lenOldWord = strlen(oldWord);
    size_t lenNewWord = strlen(newWord);

    while ((oldpos = strstr(src, oldWord)) != NULL)
    {
        // 1. copy everything up to the old word.
        // 2. append the new word
        // 3. copy the remainder of source string *past* the old word
        // 4. copy back to the original string.
        memcpy(buffer, str, (size_t)(oldpos - str));
        memcpy(buffer + (oldpos - str), newWord, lenNewWord);
        strcpy(buffer + (oldpos - str) + lenNewWord, oldpos + lenOldWord);
        strcpy(str, buffer);

        // the new starting point will be the previous discovry
        //  location plus the length of the new word.
        src = oldpos + lenNewWord;
    }
}

int main()
{
    char msg[BUFFER_SIZE] = "This is some text with the word snowfall to replace";
    puts(msg);
    replaceWord(msg, "snowfall", "snowfalls");
    puts(msg);
    return 0;
}

Output

This is some text with the word snowfall to replace
This is some text with the word snowfalls to replace

I strongly suggest you to run this in a debugger and watch how it works, step by step. It will help you understand where you were missing the start-search-here logic. And I urge you even more, as an exercise, address the blatant vulnerability of this algorithm. think of ways you could easily invoke undefined behavior (hint: short, common old word, very very long replacement word), and the things you should to do address those problems.


问:
Getting Undefined error at the end of sets Iteration in JavaScript
I am getting an undefined error after logging each element of the set.
please have a look at the code snippet bellow</p>
```<code>  let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];

const fruits = new Set(arrayFruits);

const itrate = fruits.forEach(fruit =>{
    console.log(fruit);

});

console.log(itrate);
</code>```

答:
what you probably need</p>
```<code>let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];

const fruits = new Set(arrayFruits);

let itrate = []
fruits.forEach(fruit =>{
  itrate.push(fruit)
});

console.log(itrate);
</code>```

Body:
I am getting an undefined error after logging each element of the set.
please have a look at the code snippet bellow

  let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];

const fruits = new Set(arrayFruits);

const itrate = fruits.forEach(fruit =>{
    console.log(fruit);

});

console.log(itrate);

Body:
what you probably need

let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];

const fruits = new Set(arrayFruits);

let itrate = []
fruits.forEach(fruit =>{
  itrate.push(fruit)
});

console.log(itrate);


问:
How to test old linux kernel?
We can change OS kernel, ex: CentOS, by 'yum update kernel-xxxx'

However, I think we can not downgrade the kernel to an old version.

The purpose is to test the old kernel ( ex: 0.11, 0.96, 2.0 ....etc )

Is there any way to test it without OS bundle(ex: CentOS)? ( especially I want to test it with VirtualBox )

答: bump.  in tonight's quest to find the oldest sysvinit available, I have run across a few files (mirror while hot!):  https://mirror.math.princeton.edu/pub/oldlinux/Linux.old/bin/tools-old/  notably init.c and sysvinit-2.0.  (use mkdir before unpacking.)  such versions appear in the release notes for linux-0.95 and the changelog for sysvinit.  you will need an extra-old gcc to compile them.  when done, use an old-style ext2 partition, and place in the location /bin/init or /etc/init from the release notes.  make sure you have /dev/console and /dev/tty*  ;with earlier kernels, the file init/init.c performs this function.  let me know if you'd like me to try this myself sometime.</p>

Title: How to test old linux kernel?


问:
getStaticPaths is required for dynamic SSG
I am new to Next.js and
I've been trying to to use  getStaticProps in my dynamic pages in my Next.js app
and I get this error:

Error: getStaticPaths is required for dynamic SSG pages and is missing
for '/query/[itmid]'

[itmid].jsx

```<code>function Query({ posts }) {

  return (

        {posts.map((itm, k) => {
          return (
            <>
              <Head>
                <title> {itm.Name} - wixten </title>
              </Head>

              <div key={itm._id} className="Question-one">
                <h1> {itm.Name}</h1>
                <h2>{itm.Summary}</h2>
              </div>
              <div className="username">
                <span className="username2">--{itm.username}</span>
              </div>
            </>
          );
        })}
      </>

      <div className="multi-container">
        <Answershooks id={gotid} />
        <RealtedPost />
      </div>
    </>
  );
}

export async function getStaticProps() {

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + gotid);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  return {
    props: {
      posts,
    },
  };
}
export default Query;
</code>```

Why am I getting this error?

答:
What getStaticProps does is to generate the static page, but you need to tell next js, what are the paths to generate?

```<code>export async function getStaticPaths() {

    return {
      paths: [
          { params: { query: 'slug-1' }},
          { params: { query: 'slug-2' }}
      ],
      fallback: true // false or 'blocking'
    };
  }
</code>```

Then in your getStaticProp

```<code>export async function getStaticProps({ params }) {

  //params.query will return slug-1 and slug-2
  const res = await fetch("https://ask-over.herokuapp.com/questone/" + params.query);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  return {
    props: {
      posts,
    },
  };
}
</code>```

You need to use params.query if you name your file [query].js.

The above codes will generate static paths /slug-1 and /slug-1.

If you are not trying to generate static pages (which seems like it), then you should probably use getServerSideProps which generates page on the go.

Body:
I am new to Next.js and
I've been trying to to use  getStaticProps in my dynamic pages in my Next.js app
and I get this error:

Error: getStaticPaths is required for dynamic SSG pages and is missing
for '/query/[itmid]'

[itmid].jsx

function Query({ posts }) {

  return (

        {posts.map((itm, k) => {
          return (
            <>

                <title> {itm.Name} - wixten </title>

 {itm.Name}

{itm.Summary}

                --{itm.username}

            </>
          );
        })}
      </>

        <Answershooks id={gotid} />
        <RealtedPost />

    </>
  );
}

export async function getStaticProps() {

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + gotid);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  return {
    props: {
      posts,
    },
  };
}
export default Query;

Why am I getting this error?

Body:
What getStaticProps does is to generate the static page, but you need to tell next js, what are the paths to generate?

export async function getStaticPaths() {

    return {
      paths: [
          { params: { query: 'slug-1' }},
          { params: { query: 'slug-2' }}
      ],
      fallback: true // false or 'blocking'
    };
  }

Then in your getStaticProp

export async function getStaticProps({ params }) {

  //params.query will return slug-1 and slug-2
  const res = await fetch("https://ask-over.herokuapp.com/questone/" + params.query);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  return {
    props: {
      posts,
    },
  };
}

You need to use params.query if you name your file [query].js.

The above codes will generate static paths /slug-1 and /slug-1.

If you are not trying to generate static pages (which seems like it), then you should probably use getServerSideProps which generates page on the go.


问:
Updating headers of ApolloClient after Firebase login
I'm having a problem with sending an authorization header with a graphql request when a user signs up with my react app.

My flow is:

User signs up with Firebase, react app receives id token.

User is redirected to another page where they can fill out more information.

User clicks submit, a request is sent via graphql (Apollo) to custom backend to create user.

The problem is when the user clicks submit on the secondary sign up page to enter their name, the request that is sent to the backend does not contain the authorization header. If I reload that page before clicking submit (this is after firebase sign up was successful), then it works as expected.

index.js:

```<code>const token = localStorage.getItem(AUTH_TOKEN);

const client = new ApolloClient({
  link: new HttpLink({
  uri: 'http://localhost:9000/graphql',
  headers: {
    authorization: token ? `Bearer ${token}` : ''
  }
  }),
  cache: new InMemoryCache()
});
</code>```

App.js:

```<code>componentWillMount() {
  const _this = this;
  firebaseApp.auth().onAuthStateChanged((user) => {
    if (user) {
      console.log('AUTH STATE CHANGED', user);
      // If logged in...
      _this.setState({ loggedin: true });
      user.getToken()
        .then((result) => {
          localStorage.setItem(AUTH_TOKEN, result);
        });
    } else {
      // If not logged in...
      _this.setState({ loggedin: false });
    }
  });
}
</code>```

SignUp.js (this is where the user can authenticate with firebase):

```<code>handleSubmit(e) {
    e.preventDefault()
    const email = this.state.email.trim()
    const password = this.state.password.trim()
    if (isEmail(email)) {
        firebaseApp
            .auth()
            .createUserWithEmailAndPassword(email, password)
            .then(() => {
              browserHistory.push('/signupcontinued');
            })
            .catch((error) => {
                // Handle Errors here.
                const errorMessage = error.message
                alert(`errorMessage: ${  errorMessage}`)
            })
    } else {
        alert('Email Address in not valid')
    }
}
</code>```

SignUpContinued.js (where the user enters their name before sending create user request to custom backend):

```<code>const SignUpMutation = gql`
    mutation CreateUser($userInput: UserInput!) {
      user {
        create(organizationId: 3, userInput: $userInput) {
          id
          firstName
          lastName
          email
          organizationId
          balance
        }
      }
    }
`

class SignupContinued extends Component {
    render() {
      let firstname;
      let lastname;
        return (
            <div>
                <Mutation mutation={SignUpMutation}>
                  {(signup, { data }) => (
                    <div>
                      <form
                        onSubmit={e => {
                          e.preventDefault();

                          const userInput = {
                            firstName: firstname.value,
                            lastName: lastname.value,
                            email: (firebaseApp.auth().currentUser) ? firebaseApp.auth().currentUser.email : ''
                          }

                          signup({ variables: {
                              userInput
                          }}).then(() => {
                            browserHistory.push('/home')
                          });
                          firstname.value = '';
                          lastname.value = '';
                        }}
                      >
                        <input
                          placeholder='Enter First name'
                          ref={node => {
                            firstname = node;
                          }}
                        />
                        <input
                          placeholder='Enter Last name'
                          ref={node => {
                            lastname = node;
                          }}
                        />
                        <button type='submit'>Submit</button>
                      </form>
                    </div>
                  )}
                </Mutation>
            </div>
        )
    }
}
</code>```

Am I correctly redirecting the user so that react reloads (and the ApolloClient updates its headers? Or is the issue something to do with my .then functions and onAuthStateChanged isn't done running before the redirect?

Thanks!

答: Apollo client gets token data from localStorage before firebase set token to localstorage. you should refresh apollo header after firebase setup</p>

Body:
I'm having a problem with sending an authorization header with a graphql request when a user signs up with my react app.

My flow is:

User signs up with Firebase, react app receives id token.

User is redirected to another page where they can fill out more information.

User clicks submit, a request is sent via graphql (Apollo) to custom backend to create user.

The problem is when the user clicks submit on the secondary sign up page to enter their name, the request that is sent to the backend does not contain the authorization header. If I reload that page before clicking submit (this is after firebase sign up was successful), then it works as expected.

index.js:

const token = localStorage.getItem(AUTH_TOKEN);

const client = new ApolloClient({
  link: new HttpLink({
  uri: 'http://localhost:9000/graphql',
  headers: {
    authorization: token ? `Bearer ${token}` : ''
  }
  }),
  cache: new InMemoryCache()
});

App.js:

componentWillMount() {
  const _this = this;
  firebaseApp.auth().onAuthStateChanged((user) => {
    if (user) {
      console.log('AUTH STATE CHANGED', user);
      // If logged in...
      _this.setState({ loggedin: true });
      user.getToken()
        .then((result) => {
          localStorage.setItem(AUTH_TOKEN, result);
        });
    } else {
      // If not logged in...
      _this.setState({ loggedin: false });
    }
  });
}

SignUp.js (this is where the user can authenticate with firebase):

handleSubmit(e) {
    e.preventDefault()
    const email = this.state.email.trim()
    const password = this.state.password.trim()
    if (isEmail(email)) {
        firebaseApp
            .auth()
            .createUserWithEmailAndPassword(email, password)
            .then(() => {
              browserHistory.push('/signupcontinued');
            })
            .catch((error) => {
                // Handle Errors here.
                const errorMessage = error.message
                alert(`errorMessage: ${  errorMessage}`)
            })
    } else {
        alert('Email Address in not valid')
    }
}

SignUpContinued.js (where the user enters their name before sending create user request to custom backend):

const SignUpMutation = gql`
    mutation CreateUser($userInput: UserInput!) {
      user {
        create(organizationId: 3, userInput: $userInput) {
          id
          firstName
          lastName
          email
          organizationId
          balance
        }
      }
    }
`

class SignupContinued extends Component {
    render() {
      let firstname;
      let lastname;
        return (

                <Mutation mutation={SignUpMutation}>
                  {(signup, { data }) => (

                      <form
                        onSubmit={e => {
                          e.preventDefault();

                          const userInput = {
                            firstName: firstname.value,
                            lastName: lastname.value,
                            email: (firebaseApp.auth().currentUser) ? firebaseApp.auth().currentUser.email : ''
                          }

                          signup({ variables: {
                              userInput
                          }}).then(() => {
                            browserHistory.push('/home')
                          });
                          firstname.value = '';
                          lastname.value = '';
                        }}
                      >
                        <input
                          placeholder='Enter First name'
                          ref={node => {
                            firstname = node;
                          }}
                        />
                        <input
                          placeholder='Enter Last name'
                          ref={node => {
                            lastname = node;
                          }}
                        />
                        <button type='submit'>Submit</button>
                      </form>

                  )}
                </Mutation>

        )
    }
}

Am I correctly redirecting the user so that react reloads (and the ApolloClient updates its headers? Or is the issue something to do with my .then functions and onAuthStateChanged isn't done running before the redirect?

Thanks!


问:
Problem with php variable to using MySQL query
Two variables, one is $current_shop another is $shop (see below). Both are printed same value: "sps-app-test.com". But when I use them in the below SQL Update query, the $shop variable works fine by SQL condition, but when using the $current_shop variable, it does not work.

However, the store_url = 'sps-app-test.com'.

I have tried without success, and posted this problem in many other places.

```<code>$shopify = $_GET;
$current_shop = $shopify['shop'];
print_r($current_shop); // sps-app-test.com

$shop = "sps-app-test.com";
print_r($shop);

// form_title
if(!empty($_POST['form_title'])  ){

    $form_title = mysqli_real_escape_string($conn,
    $_POST['form_title']);

    if( isset($form_title)  ){

        $query_form_title = "UPDATE widget_cont SET
        form_title='$form_title' WHERE store_url='$current_shop'  ";

        echo  $_POST['form_title'];

    }

    if( !mysqli_query($conn, $query_form_title) ){
        echo "ERROR: " . mysqli_error($conn);
    }
}
</code>```

More details in this image

MySQL row

答:
Please try not to include image instead write the code and can you try this :

```<code>$current_shop = $_GET['shop']
</code>```

since the error is from this one try to use $_GET without assign it to a variable

Body:
Two variables, one is $current_shop another is $shop (see below). Both are printed same value: "sps-app-test.com". But when I use them in the below SQL Update query, the $shop variable works fine by SQL condition, but when using the $current_shop variable, it does not work.

However, the store_url = 'sps-app-test.com'.

I have tried without success, and posted this problem in many other places.

$shopify = $_GET;
$current_shop = $shopify['shop'];
print_r($current_shop); // sps-app-test.com

$shop = "sps-app-test.com";
print_r($shop);

// form_title
if(!empty($_POST['form_title'])  ){

    $form_title = mysqli_real_escape_string($conn,
    $_POST['form_title']);

    if( isset($form_title)  ){

        $query_form_title = "UPDATE widget_cont SET
        form_title='$form_title' WHERE store_url='$current_shop'  ";

        echo  $_POST['form_title'];

    }

    if( !mysqli_query($conn, $query_form_title) ){
        echo "ERROR: " . mysqli_error($conn);
    }
}

More details in this image

MySQL row

Body:
Please try not to include image instead write the code and can you try this :

$current_shop = $_GET['shop']

since the error is from this one try to use $_GET without assign it to a variable


问:
Android Text Fields default to Chinese
I'm working off of code that isn't originally my own. Right now, I'm having this problem when the user inputs text, it defaults first to the Chinese IME.

I'm sure it's not a java locale setting or anything of the sort. Everything else displays correctly. I'm also not prepopulating the input areas or anything besides having the standard (name) (password) etc.

Thanks.

答: If you are using an emulator, I think your keyboard is set to use the chinese keyboard and if you change the keyboard setting your problem should be resolved.</p>

ContentLicense: CC BY-SA 3.0

Title: Android Text Fields default to Chinese


问:
Ensure That Node Cron Job is Only Configured Once
I'm writing a Discord bot and having it schedule a cron job when it starts up using node-cron. I've defined it as follows (very basic so far):

```<code>    cron.schedule('15 1,3,5,7,9,11,13,15,17,19,21,23 * * *', () => {
        GameUpdater.sendGameUpdatesToLeagueChannels(this.guilds);
    });
</code>```

The problem is, Discord bots will often reconnect which will rerun the portion of the code where this has to be. I'm considering having a check of an external value, perhaps in my database, that manages whether or not it's run recently or is already running or something like that, but I was wondering if there was a proper way to make a cron job unique using node-cron?

答: if the cron schedule is fired on startup from Client.on('ready') have your cronjob to be scheduled at a separate event Client.once('ready'), this way it won't fire the routine again when the bot reconnects. Only if the entire shard/cluster process is terminated and restarted.

Body:
I'm writing a Discord bot and having it schedule a cron job when it starts up using node-cron. I've defined it as follows (very basic so far):

    cron.schedule('15 1,3,5,7,9,11,13,15,17,19,21,23 * * *', () => {
        GameUpdater.sendGameUpdatesToLeagueChannels(this.guilds);
    });

The problem is, Discord bots will often reconnect which will rerun the portion of the code where this has to be. I'm considering having a check of an external value, perhaps in my database, that manages whether or not it's run recently or is already running or something like that, but I was wondering if there was a proper way to make a cron job unique using node-cron?


问:
Search data in C# from Database SQL Server
I want to ask you regarding for the searching in C# and why there is a Not Found statement if already found the answer or the data itself.

Here is the code:

```<code>                    Console.WriteLine("Enter Plate Number: ");
                    string plateNumber1 = Console.ReadLine();
                    var searchPlateNumberDAL = new ParkingSystemDAL(_iconfiguration);
                    var listSlotParking = searchPlateNumberDAL.GetList();
                    listSlotParking.ForEach(item =>
                    {
                        bool searchItem = item.plateNumber == plateNumber1;
                        if (searchItem == true)
                        {
                            Console.WriteLine(item.parkingId);
                        }
                        else
                        {
                            Console.WriteLine("Not Found");
                        }
                    });
</code>```

output

答:
Try

item.plateNumber.Trim() == plateNumber1.Trim()

Body:
I want to ask you regarding for the searching in C# and why there is a Not Found statement if already found the answer or the data itself.

Here is the code:

                    Console.WriteLine("Enter Plate Number: ");
                    string plateNumber1 = Console.ReadLine();
                    var searchPlateNumberDAL = new ParkingSystemDAL(_iconfiguration);
                    var listSlotParking = searchPlateNumberDAL.GetList();
                    listSlotParking.ForEach(item =>
                    {
                        bool searchItem = item.plateNumber == plateNumber1;
                        if (searchItem == true)
                        {
                            Console.WriteLine(item.parkingId);
                        }
                        else
                        {
                            Console.WriteLine("Not Found");
                        }
                    });

output


问:
Pass in bash terminal variables to a bash script
If I am in a Linux terminal and I start setting variables such as export AGE=45.

Then I have a script to read user data from terminal variables and process it, is this possible to do?

```<code>IE:

user@linux$ export AGE=45

user@linux$ ./age.sh

#script asks for input

read -p "what is your age?" scriptAGE

#user inputs variable set in terminal

$AGE
</code>```

#echo output

```<code>echo "your age is: " $scriptAGE"
</code>```

#should say your age is: 45

答:
Variables are not expanded in input, only in the script itself.

You could use eval to force it to process the variable value as shell syntax.

```<code>eval "echo 'your age is:' $scriptAGE"
</code>```

But this will also process other shell syntax. If they enter $AGE; rm * it will say their age is 45 and then delete all their files.

Body:
If I am in a Linux terminal and I start setting variables such as export AGE=45.

Then I have a script to read user data from terminal variables and process it, is this possible to do?

IE:

user@linux$ export AGE=45

user@linux$ ./age.sh

#script asks for input

read -p "what is your age?" scriptAGE

#user inputs variable set in terminal

$AGE

#echo output

echo "your age is: " $scriptAGE"

#should say your age is: 45

Body:
Variables are not expanded in input, only in the script itself.

You could use eval to force it to process the variable value as shell syntax.

eval "echo 'your age is:' $scriptAGE"

But this will also process other shell syntax. If they enter $AGE; rm * it will say their age is 45 and then delete all their files.


问:
HAProxy stick table fails?
I have a HAProxy balancing load on tcp-connections. For some reason, it seems that the stick-table fails once in a while. Here are few rows from my log where we can see that there has been an connection to both backends from single ip. Connections are made at the exact same timestamp, could it be that the stick table is not thread safe?
Expire time is only 10s for a reason, tcp connections in our software are quite sticky so we need short expire time for possible server maintenance procedures.

Any idea how this is possible? Why two simultaneous connections are routed to different backends? Our software cannot handle this situation, WCF is used for the communication.

```<code>Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:12872 [11/Apr/2017:14:05:21.608] https_frontend https_backend/srv1
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:12872 [11/Apr/2017:14:05:21.608] https_frontend https_backend/srv1
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:3342 [11/Apr/2017:14:05:21.608] https_frontend https_backend/srv2
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:3342 [11/Apr/2017:14:05:21.608] https_frontend https_backend/srv2
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:22543 [11/Apr/2017:14:05:34.994] https_frontend https_backend/srv2
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:22543 [11/Apr/2017:14:05:34.994] https_frontend https_backend/srv2
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:26566 [11/Apr/2017:14:05:34.995] https_frontend https_backend/srv2
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:26566 [11/Apr/2017:14:05:34.995] https_frontend https_backend/srv2
</code>```

HAproxy settings:

```<code>backend https_backend
       mode tcp
       option tcplog
       balance leastconn
       stick-table type ip size 200k expire 10s store conn_cur
       tcp-request content track-sc0 src
       stick on src
       server srv1 10.1.4.210:443 check
       server srv2 10.1.5.38:443 check
</code>```

答:
Since I met the same problem five years later, maybe it's not stressed enough in the docs. Turned out, my stick on rule

```<code>stick on req.payload(0,0),mqtt_field_value(connect,username) table mqtt_usernames
</code>```

was checked too fast, before the content has arrived. I adjusted it with an inspect delay in my frontend config:

```<code>tcp-request inspect-delay 10s
acl content_present req_len gt 0
tcp-request content accept if content_present
</code>```

and hopefully it's correct. At least, it passes my tests.

Title: HAProxy stick table fails?

Body:
I have a HAProxy balancing load on tcp-connections. For some reason, it seems that the stick-table fails once in a while. Here are few rows from my log where we can see that there has been an connection to both backends from single ip. Connections are made at the exact same timestamp, could it be that the stick table is not thread safe?
Expire time is only 10s for a reason, tcp connections in our software are quite sticky so we need short expire time for possible server maintenance procedures.

Any idea how this is possible? Why two simultaneous connections are routed to different backends? Our software cannot handle this situation, WCF is used for the communication.

Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:12872 [11/Apr/2017:14:05:21.608] https_frontend https_backend/srv1
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:12872 [11/Apr/2017:14:05:21.608] https_frontend https_backend/srv1
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:3342 [11/Apr/2017:14:05:21.608] https_frontend https_backend/srv2
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:3342 [11/Apr/2017:14:05:21.608] https_frontend https_backend/srv2
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:22543 [11/Apr/2017:14:05:34.994] https_frontend https_backend/srv2
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:22543 [11/Apr/2017:14:05:34.994] https_frontend https_backend/srv2
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:26566 [11/Apr/2017:14:05:34.995] https_frontend https_backend/srv2
Apr 11 14:06:07 accuna haproxy[22129]: xx.xx.133.145:26566 [11/Apr/2017:14:05:34.995] https_frontend https_backend/srv2

HAproxy settings:

backend https_backend
       mode tcp
       option tcplog
       balance leastconn
       stick-table type ip size 200k expire 10s store conn_cur
       tcp-request content track-sc0 src
       stick on src
       server srv1 10.1.4.210:443 check
       server srv2 10.1.5.38:443 check

Body:
Since I met the same problem five years later, maybe it's not stressed enough in the docs. Turned out, my stick on rule

stick on req.payload(0,0),mqtt_field_value(connect,username) table mqtt_usernames

was checked too fast, before the content has arrived. I adjusted it with an inspect delay in my frontend config:

tcp-request inspect-delay 10s
acl content_present req_len gt 0
tcp-request content accept if content_present

and hopefully it's correct. At least, it passes my tests.


问:
Image is not getting added on UIBarButtonItem in iPhone
I am trying to add the image on to the  UIBarButtonItem .But it is not getting added I don't what's going wrong in it this my code

```<code>-(void)viewDidLoad
{
    UIToolbar *tools = [[UIToolbar alloc]
    initWithFrame:CGRectMake(0.0f, 0.0f, 103.0f, 44.01f)]; // 44.01 shifts it up 1px for some reason
        //tools.clearsContextBeforeDrawing = YES;
        //tools.clipsToBounds = YES;
        //tools.tintColor = [UIColor colorWithWhite:0.305f alpha:0.0f]; // closest I could get by eye to black, translucent style.
        // anyone know how to get it perfect?
        //tools.barStyle = -1; // clear background
        NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:3];

        // Create a standard refresh button.
        bi = [[UIBarButtonItem alloc]
        initWithImage:[UIImage imageNamed:@"map.png"] style:UIBarButtonItemStylePlain  target:self action:@selector(changeMapType:)];
        [buttons addObject:bi];
        [bi release];

        // Create a spacer.
        bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        bi.width = 12.0f;
        [buttons addObject:bi];
        [bi release];

        // Add profile button.
        bi = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"map.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goToProfile)];
        bi.style = UIBarButtonItemStyleBordered;
        [buttons addObject:bi];
        [bi release];

        // Add buttons to toolbar and toolbar to nav bar.
        [tools setItems:buttons animated:NO];
        [buttons release];
        twoButtons = [[UIBarButtonItem alloc] initWithCustomView:tools];
        [tools release];
        self.navigationItem.rightBarButtonItem = twoButtons;
        [twoButtons release];
}
</code>```

Thank you

答:
You are creating your button as a UIBarButtonItemStylePlain, try:

```<code>UIBarButtonItem *button = [[UIBarButtonItem alloc] init];
[button setImage:[UIImage imageNamed:@"map.png"]];
</code>```

Body:
I am trying to add the image on to the  UIBarButtonItem .But it is not getting added I don't what's going wrong in it this my code

-(void)viewDidLoad
{
    UIToolbar *tools = [[UIToolbar alloc]
    initWithFrame:CGRectMake(0.0f, 0.0f, 103.0f, 44.01f)]; // 44.01 shifts it up 1px for some reason
        //tools.clearsContextBeforeDrawing = YES;
        //tools.clipsToBounds = YES;
        //tools.tintColor = [UIColor colorWithWhite:0.305f alpha:0.0f]; // closest I could get by eye to black, translucent style.
        // anyone know how to get it perfect?
        //tools.barStyle = -1; // clear background
        NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:3];

        // Create a standard refresh button.
        bi = [[UIBarButtonItem alloc]
        initWithImage:[UIImage imageNamed:@"map.png"] style:UIBarButtonItemStylePlain  target:self action:@selector(changeMapType:)];
        [buttons addObject:bi];
        [bi release];

        // Create a spacer.
        bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        bi.width = 12.0f;
        [buttons addObject:bi];
        [bi release];

        // Add profile button.
        bi = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"map.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goToProfile)];
        bi.style = UIBarButtonItemStyleBordered;
        [buttons addObject:bi];
        [bi release];

        // Add buttons to toolbar and toolbar to nav bar.
        [tools setItems:buttons animated:NO];
        [buttons release];
        twoButtons = [[UIBarButtonItem alloc] initWithCustomView:tools];
        [tools release];
        self.navigationItem.rightBarButtonItem = twoButtons;
        [twoButtons release];
}

Thank you

Body:
You are creating your button as a UIBarButtonItemStylePlain, try:

UIBarButtonItem *button = [[UIBarButtonItem alloc] init];
[button setImage:[UIImage imageNamed:@"map.png"]];


问:
How to make MavenProject injected into the mojo during test lookup?
This is my test (maven-plugin-testing-harness 3.3.0, junit 5.6.2):

```<code>import java.io.File;
import org.apache.maven.plugin.testing.AbstractMojoTestCase;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public final class MyMojoTest extends AbstractMojoTestCase {
  @BeforeEach
  public void setup() throws Exception {
    this.setUp();
  }
  @Test
  public void executeIt() throws Exception {
   final File pom = new File("src/test/resources/my-test-pom.xml");
    final MyMojo mojo = MyMojo.class.cast(
      this.lookupMojo("mygoal", pom)
    );
    mojo.execute();
  }
}
</code>```

This is what I have in MyMojo (maven-plugin-api 3.8.4):

```<code>import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

@Mojo(name = "my", defaultPhase = LifecyclePhase.COMPILE)
public final class MyMojo extends AbstractMojo {
  @Parameter(defaultValue = "${project}", readonly = true)
  private MavenProject project;
}
</code>```

The problem is that mojo returned by lookupMojo() doesn't have the project attribute set (it's null).

Some solution was proposed here, but I'm not sure how it  can work with JUnit 5.

答:
I tried with the same configurations as mentioned above. The plugin works fine but none of the tests having lookupMojo() seems to be working.

A similar test example can be referred here. There is a difference in the setUp method from your class MyMojoTest and example provided in the link.

super.setUp();  should be called instead of this.setUp() so as to initialize all the objects in AbstractMojoTestCase class.

The possible reason that the test case with maven-plugin-testing-harness 3.3.0  and junit 5.6.2 will not work because they are not compatible.

The reasons are

maven-plugin-testing-harness was built to be compatible with Junit4. Latest update was a long time ago i.e. Dec 17, 2014. Junit 4 and Junit 5 are not compatible. We have to make use of Junit-Vintage-Engine to make it work.

maven-plugin-testing-harness was develop using JDk-7 and minimum requirements for Junit 5 is Jdk-8.
Information from the harness plugin Manifest file

Implementation-Vendor-Id: org.apache.maven.plugin-testing

Built-By: igor

Build-Jdk: 1.7.0_55

Specification-Vendor: The Apache Software

Foundation Specification-Title: Maven Plugin Testing Mechanism

Maven version supported is also different for both the jars.
link

Few other links confirm the same.

There are very few libraries and informational link available for plugin testing with Junit5. I could find only a handful of them, although I haven't tried them yet.

Library:

```<code><dependency>
    <groupId>com.soebes.itf.jupiter.extension</groupId>
    <artifactId>itf-assertj</artifactId>
    <version>0.11.0</version>
    <scope>test</scope>
</dependency>
</code>```

Few more Jupiter extension libraries in this link

Examples related to it.

Example 1

Example 2

Example 3

Body:
This is my test (maven-plugin-testing-harness 3.3.0, junit 5.6.2):

import java.io.File;
import org.apache.maven.plugin.testing.AbstractMojoTestCase;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public final class MyMojoTest extends AbstractMojoTestCase {
  @BeforeEach
  public void setup() throws Exception {
    this.setUp();
  }
  @Test
  public void executeIt() throws Exception {
   final File pom = new File("src/test/resources/my-test-pom.xml");
    final MyMojo mojo = MyMojo.class.cast(
      this.lookupMojo("mygoal", pom)
    );
    mojo.execute();
  }
}

This is what I have in MyMojo (maven-plugin-api 3.8.4):

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

@Mojo(name = "my", defaultPhase = LifecyclePhase.COMPILE)
public final class MyMojo extends AbstractMojo {
  @Parameter(defaultValue = "${project}", readonly = true)
  private MavenProject project;
}

The problem is that mojo returned by lookupMojo() doesn't have the project attribute set (it's null).

Some solution was proposed here, but I'm not sure how it  can work with JUnit 5.

Body:
I tried with the same configurations as mentioned above. The plugin works fine but none of the tests having lookupMojo() seems to be working.

A similar test example can be referred here. There is a difference in the setUp method from your class MyMojoTest and example provided in the link.

super.setUp();  should be called instead of this.setUp() so as to initialize all the objects in AbstractMojoTestCase class.

The possible reason that the test case with maven-plugin-testing-harness 3.3.0  and junit 5.6.2 will not work because they are not compatible.

The reasons are

maven-plugin-testing-harness was built to be compatible with Junit4. Latest update was a long time ago i.e. Dec 17, 2014. Junit 4 and Junit 5 are not compatible. We have to make use of Junit-Vintage-Engine to make it work.

maven-plugin-testing-harness was develop using JDk-7 and minimum requirements for Junit 5 is Jdk-8.
Information from the harness plugin Manifest file

Implementation-Vendor-Id: org.apache.maven.plugin-testing

Built-By: igor

Build-Jdk: 1.7.0_55

Specification-Vendor: The Apache Software

Foundation Specification-Title: Maven Plugin Testing Mechanism

Maven version supported is also different for both the jars.
link

Few other links confirm the same.

There are very few libraries and informational link available for plugin testing with Junit5. I could find only a handful of them, although I haven't tried them yet.

Library:

<dependency>
    <groupId>com.soebes.itf.jupiter.extension</groupId>
    <artifactId>itf-assertj</artifactId>
    <version>0.11.0</version>
    <scope>test</scope>
</dependency>

Few more Jupiter extension libraries in this link

Examples related to it.

Example 1

Example 2

Example 3


问:
Flutter - Warning (CocoaPods not installed Skipping pod install) Even While Installed
I am trying to build a Flutter app with Geolocator plugin on Android Studio.
When I am running the app I have the following warning - that prevents the app from running:

Warning: CocoaPods not installed. Skipping pod install.
CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

Exception: CocoaPods not installed or not in valid state.

I tried every solution i found in the internet (Stackoverflow & GitHub) but nothing seems to work.

Important: When I tried to run the app from Xcode instead of from Android Studio, I had this error:

The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.

So what I did was - Change directory to ios (on the Flutter project) and running:

```<code>pod init
pod install
</code>```

Tried to run again from Xcode and it worked perfectly.
After it works on Xcode I tried to run it from Android Studio and the same error happens to me, preventing the app to launch.

Flutter Doctor:

```<code>[✓] Flutter (Channel stable, 2.2.2, on macOS 11.4 20F71 darwin-x64, locale en-IL)
    • Flutter version 2.2.2 at /Users/idanrefaeli/Developer/flutter
    • Framework revision d79295af24 (5 weeks ago), 2021-06-11 08:56:01 -0700
    • Engine revision 91c9fc8fe0
    • Dart version 2.13.3

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/idanrefaeli/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.5.1, Build version 12E507
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] VS Code (version 1.57.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.23.0

[✓] Connected device (2 available)
    • Idan’s (mobile) • 00008020-0011092101A2002E • ios            • iOS 14.6
    • Chrome (web)    • chrome                    • web-javascript • Google Chrome 91.0.4472.114

! Doctor found issues in 1 category.
</code>```

Extra logs:
'Run' log in Android Studio: pastebin.com/7iYtdcTQ
Also this terminal log after running 'pod install': pastebin.com/1cCNuFYM

-- UPDATE --

I finally was able to run the app, all I did was to copy all the project files to a new project from scratch and it worked.
Maybe it happened because of a certain conflict, since I imported someone else's project (from Angela Yu's Flutter Udemy course).
Anyway, I still didn't find a fix for this fraustrating problem so if anyone recognizes something it would be great!

答:
```<code># uninstall
sudo gem uninstall cocoapods
brew uninstall cocoapods

# reinstall
sudo gem install cocoapods
pod setup

# rebuild
flutter build ios

</code>```

Then, restart vscode and iTerm (it is important), and debug

Body:
I am trying to build a Flutter app with Geolocator plugin on Android Studio.
When I am running the app I have the following warning - that prevents the app from running:

Warning: CocoaPods not installed. Skipping pod install.
CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

Exception: CocoaPods not installed or not in valid state.

I tried every solution i found in the internet (Stackoverflow & GitHub) but nothing seems to work.

Important: When I tried to run the app from Xcode instead of from Android Studio, I had this error:

The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.

So what I did was - Change directory to ios (on the Flutter project) and running:

pod init
pod install

Tried to run again from Xcode and it worked perfectly.
After it works on Xcode I tried to run it from Android Studio and the same error happens to me, preventing the app to launch.

Flutter Doctor:

[✓] Flutter (Channel stable, 2.2.2, on macOS 11.4 20F71 darwin-x64, locale en-IL)
    • Flutter version 2.2.2 at /Users/idanrefaeli/Developer/flutter
    • Framework revision d79295af24 (5 weeks ago), 2021-06-11 08:56:01 -0700
    • Engine revision 91c9fc8fe0
    • Dart version 2.13.3

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/idanrefaeli/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.5.1, Build version 12E507
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] VS Code (version 1.57.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.23.0

[✓] Connected device (2 available)
    • Idan’s (mobile) • 00008020-0011092101A2002E • ios            • iOS 14.6
    • Chrome (web)    • chrome                    • web-javascript • Google Chrome 91.0.4472.114

! Doctor found issues in 1 category.

Extra logs:
'Run' log in Android Studio: pastebin.com/7iYtdcTQ
Also this terminal log after running 'pod install': pastebin.com/1cCNuFYM

-- UPDATE --

I finally was able to run the app, all I did was to copy all the project files to a new project from scratch and it worked.
Maybe it happened because of a certain conflict, since I imported someone else's project (from Angela Yu's Flutter Udemy course).
Anyway, I still didn't find a fix for this fraustrating problem so if anyone recognizes something it would be great!

Body:
# uninstall
sudo gem uninstall cocoapods
brew uninstall cocoapods

# reinstall
sudo gem install cocoapods
pod setup

# rebuild
flutter build ios

Then, restart vscode and iTerm (it is important), and debug


问:
Unload Assembly or AppDomain after Use (like in Object Browser)
I am trying to load external Assembly to list out all Types, Methods and Properties during run time, just like Object Browser in Visual Studio. My requirement is, I want to Load external Assembly list out its Members in a treeview and Unload the Assembly or AppDomain after the use. Later in the same project I am using the same assembly to modify and add some more code to it. Since I have already opened the assembly, CompileAssemblyFromFile is not allowing me to Compile and produce the output. How can I deal with this situation? How is Object Browser works in Visual Studio without creating the instance of Assembly or if at all it is created, how to unload it after usage?

P.S.

I have already tried to use another AppDomain to load the assembly but did not success. As the treeview is created in main appdomain, I cannot access this in custom appdomain to add nodes.

答:
Based on Mathieu Guindon's Comment. I am loading assembly in my ASP.Net Web API and Serializing the assembly content to JSON Array. Later in my client application I am Deserializing the response with the help HttpClient and populating the WinForms TreeView.

Here's how I did. Sample code.

```<code>//Action Model
public class ActionModel
{
   public string ActionName {get;set;}
   public IList<MethodInformation> ActionMethods {get;set;}
}

public class MethodInformation
{
   public string MethodName {get;set;}
   public IList<ParameterInformation> GetParameters {get;set;}
}

//API
public Object Get(string id)
{
    switch(id)
    {
        case "Assembly1":
           Type[] typesInAssembly = Assembly.LoadFrom(pathToAssembly).GetTypes();

           List<ActionModel> actionModel = new List<ActionModel>();

           for(var t in typesInAssembly)
           {
               /* add the items to the List actionModel */
           }
           return actionModel;
     }
}
</code>```

On the client side I am having one more Class which consumes this API and parses the content by Deserializing the JSON Content and display it in treeview.

Now the requirement is met. I can use the same copy of Assembly to show and build which was main requirement. Hope I am doing this correctly.

Body:
Based on Mathieu Guindon's Comment. I am loading assembly in my ASP.Net Web API and Serializing the assembly content to JSON Array. Later in my client application I am Deserializing the response with the help HttpClient and populating the WinForms TreeView.

Here's how I did. Sample code.

//Action Model
public class ActionModel
{
   public string ActionName {get;set;}
   public IList<MethodInformation> ActionMethods {get;set;}
}

public class MethodInformation
{
   public string MethodName {get;set;}
   public IList<ParameterInformation> GetParameters {get;set;}
}

//API
public Object Get(string id)
{
    switch(id)
    {
        case "Assembly1":
           Type[] typesInAssembly = Assembly.LoadFrom(pathToAssembly).GetTypes();

           List<ActionModel> actionModel = new List<ActionModel>();

           for(var t in typesInAssembly)
           {
               /* add the items to the List actionModel */
           }
           return actionModel;
     }
}

On the client side I am having one more Class which consumes this API and parses the content by Deserializing the JSON Content and display it in treeview.

Now the requirement is met. I can use the same copy of Assembly to show and build which was main requirement. Hope I am doing this correctly.


问:
Difference between tensor.permute and tensor.view in PyTorch?
What is the difference between tensor.permute() and tensor.view()?

They seem to do the same thing.

答:
The link gives a clear explanation about view, reshape, and permute:

view works on contiguous tensors.

reshape works on non-contigous tensors.

permute returns a view of the original tensor input with its dimensions permuted. It is quite different to view and reshape.