问:
How Do I Save Tensorflow Predictions To A File? (CSV Preferred)
```<code>import pandas as pd
import manipulate_data as md
from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import datetime as dt
import tensorflow as tf
import matplotlib.pyplot as plt

df = pd.read_csv('중계동_dummies.csv')

# train Parameters
seq_length = 365
data_dim = 8
hidden_dim = 10
output_dim = 1
learning_rate = 0.032
iterations = 500

trainX, trainY, testX, testY = md.preprocess_data(df,seq_length)

X = tf.placeholder(tf.float32, [None, seq_length, data_dim])
Y = tf.placeholder(tf.float32, [None, 1])

# build a LSTM network
cell = tf.contrib.rnn.BasicLSTMCell(
    num_units=hidden_dim, state_is_tuple=True, activation=tf.nn.relu)
outputs, _states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
Y_pred = tf.contrib.layers.fully_connected(
    outputs[:, -1], output_dim, activation_fn=None)  # We use the last cell's output

# cost/loss
loss = tf.reduce_sum(tf.square(Y_pred - Y))  # sum of the squares
# optimizer
optimizer = tf.train.AdamOptimizer(learning_rate)
train = optimizer.minimize(loss)

# RMSE
targets = tf.placeholder(tf.float32, [None, 1])
predictions = tf.placeholder(tf.float32, [None, 1])
rmse = tf.sqrt(tf.reduce_mean(tf.square(targets - predictions)))
mape = tf.reduce_mean(tf.abs(tf.divide(tf.subtract(predictions,targets),(targets + 1e-10))))

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)

    saver = tf.train.Saver()
    # Training step
    for i in range(iterations):
        _, step_loss = sess.run([train, loss], feed_dict={
            X: trainX,
            Y: trainY
            })
        print("[step: {}] loss: {}".format(i, step_loss))

    saver.save(sess, 'my_test_model')

    # Test step
    test_predict = sess.run(Y_pred, feed_dict={X: testX})
    test_predict = np.asarray(test_predict)
    np.savetxt("prediction.csv", test_predict, delimiter=",")
    rmse_val = sess.run(rmse, feed_dict={
                    targets: testY, predictions: test_predict})
    mape_val = sess.run(mape, feed_dict={
                    targets: testY, predictions: test_predict})
    print("RMSE: {}, MAPE: {}".format(rmse_val, mape_val))

    # Plot predictions
    plt.plot(testY)
    plt.plot(test_predict)
    plt.xlabel("Time Period")
    plt.ylabel("Apartment Price")
    plt.show()
</code>```

This is my code. I have trained a model on housing price data from 2011-2018 and have attempted to predict housing prices for 2019. I want to save my prediction results to a .csv file.
My goal is to create a simple webpage and display the predictions using Google Maps API, so I would need each individual result. However, not much resources exist for saving prediction results to a .csv file.

How can I do so?
Or
What are some better ways to achieve my goal?

答:
Here is an example where I have built a simple model and doing the prediction. I am saving the prediction as csv file using np.savetxt. You can download the dataset I am using in the program from here.

Code -

```<code>%tensorflow_version 1.x
# MLP for Pima Indians Dataset saved to single file
import numpy as np
from numpy import loadtxt
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# load pima indians dataset
dataset = np.loadtxt("/content/pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

# define model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Model Summary
model.summary()

# Fit the model
model.fit(X, Y, epochs=150, batch_size=10, verbose=0)

# evaluate the model
scores = model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

# evaluate the model
score = model.predict(X,verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], score[1]*100))

# Save as csv
np.savetxt("score.csv", score, delimiter=",")
</code>```

Output -

```<code>1.15.2
WARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
WARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/ops/nn_impl.py:183: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense (Dense)                (None, 12)                108
_________________________________________________________________
dense_1 (Dense)              (None, 8)                 104
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 9
=================================================================
Total params: 221
Trainable params: 221
Non-trainable params: 0
_________________________________________________________________
acc: 74.48%
acc: 6.97%
</code>```

You can find that the score.csv is created in the folder.

Hope this answers your question. Happy Learning.

Body:
import pandas as pd
import manipulate_data as md
from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import datetime as dt
import tensorflow as tf
import matplotlib.pyplot as plt

df = pd.read_csv('중계동_dummies.csv')

# train Parameters
seq_length = 365
data_dim = 8
hidden_dim = 10
output_dim = 1
learning_rate = 0.032
iterations = 500

trainX, trainY, testX, testY = md.preprocess_data(df,seq_length)

X = tf.placeholder(tf.float32, [None, seq_length, data_dim])
Y = tf.placeholder(tf.float32, [None, 1])

# build a LSTM network
cell = tf.contrib.rnn.BasicLSTMCell(
    num_units=hidden_dim, state_is_tuple=True, activation=tf.nn.relu)
outputs, _states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
Y_pred = tf.contrib.layers.fully_connected(
    outputs[:, -1], output_dim, activation_fn=None)  # We use the last cell's output

# cost/loss
loss = tf.reduce_sum(tf.square(Y_pred - Y))  # sum of the squares
# optimizer
optimizer = tf.train.AdamOptimizer(learning_rate)
train = optimizer.minimize(loss)

# RMSE
targets = tf.placeholder(tf.float32, [None, 1])
predictions = tf.placeholder(tf.float32, [None, 1])
rmse = tf.sqrt(tf.reduce_mean(tf.square(targets - predictions)))
mape = tf.reduce_mean(tf.abs(tf.divide(tf.subtract(predictions,targets),(targets + 1e-10))))

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)

    saver = tf.train.Saver()
    # Training step
    for i in range(iterations):
        _, step_loss = sess.run([train, loss], feed_dict={
            X: trainX,
            Y: trainY
            })
        print("[step: {}] loss: {}".format(i, step_loss))

    saver.save(sess, 'my_test_model')

    # Test step
    test_predict = sess.run(Y_pred, feed_dict={X: testX})
    test_predict = np.asarray(test_predict)
    np.savetxt("prediction.csv", test_predict, delimiter=",")
    rmse_val = sess.run(rmse, feed_dict={
                    targets: testY, predictions: test_predict})
    mape_val = sess.run(mape, feed_dict={
                    targets: testY, predictions: test_predict})
    print("RMSE: {}, MAPE: {}".format(rmse_val, mape_val))

    # Plot predictions
    plt.plot(testY)
    plt.plot(test_predict)
    plt.xlabel("Time Period")
    plt.ylabel("Apartment Price")
    plt.show()

This is my code. I have trained a model on housing price data from 2011-2018 and have attempted to predict housing prices for 2019. I want to save my prediction results to a .csv file.
My goal is to create a simple webpage and display the predictions using Google Maps API, so I would need each individual result. However, not much resources exist for saving prediction results to a .csv file.

How can I do so?
Or
What are some better ways to achieve my goal?

Body:
Here is an example where I have built a simple model and doing the prediction. I am saving the prediction as csv file using np.savetxt. You can download the dataset I am using in the program from here.

Code -

%tensorflow_version 1.x
# MLP for Pima Indians Dataset saved to single file
import numpy as np
from numpy import loadtxt
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# load pima indians dataset
dataset = np.loadtxt("/content/pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

# define model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Model Summary
model.summary()

# Fit the model
model.fit(X, Y, epochs=150, batch_size=10, verbose=0)

# evaluate the model
scores = model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

# evaluate the model
score = model.predict(X,verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], score[1]*100))

# Save as csv
np.savetxt("score.csv", score, delimiter=",")

Output -

1.15.2
WARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
WARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/ops/nn_impl.py:183: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense (Dense)                (None, 12)                108
_________________________________________________________________
dense_1 (Dense)              (None, 8)                 104
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 9
=================================================================
Total params: 221
Trainable params: 221
Non-trainable params: 0
_________________________________________________________________
acc: 74.48%
acc: 6.97%

You can find that the score.csv is created in the folder.

Hope this answers your question. Happy Learning.


来源: stackexchange

问:
Simple connectivity to a Gremlin DB via a Javascript Appliaction
I apologies for such a basic question, but I can't seem to figure out how to do this and the docs are all very specific.

I'm just trying to connect to a standard Gremlin DB (Cosmos) using gremlin. It works great from the server, but when I connect from the browser, I get this error:

```<code>Error: ws does not work in the browser. Browser clients must use the native WebSocket object
</code>```

Nothing terribly complicated, and the error seems to be pretty clear.

Here is the code:

```<code>     constructor() {
        var authenticator = new Gremlin.driver.auth.PlainTextSaslAuthenticator(`/dbs/${config.database}/colls/${config.collection}`, config.primaryKey);
        this.gremlin_config_options = {
            authenticator,
            traversalsource: "g",
            rejectUnauthorized: true,
            mimeType: "application/vnd.gremlin-v2.0+json"
        }

       var DriverRemoteConnection = Gremlin.driver.DriverRemoteConnection;
        this.Graph = Gremlin.structure.Graph;

        var dc = new DriverRemoteConnection(this.gremlin_websocket,this.gremlin_config_options);

        this.graph = new this.Graph();
        this.g = this.graph.traversal().withRemote(this.gremlin_websocket);
      };

</code>```

When I do the following code, it completes without the Javascript error.

```<code>    constructor() {
        var authenticator = new Gremlin.driver.auth.PlainTextSaslAuthenticator(`/dbs/${config.database}/colls/${config.collection}`, config.primaryKey);
        this.gremlin_config_options = {
            authenticator,
            traversalsource: "g",
            rejectUnauthorized: true,
            mimeType: "application/vnd.gremlin-v2.0+json"
        }

        this.Graph = Gremlin.structure.Graph;

        this.gremlin_websocket = new WebSocket('ws://test_db.gremlin.cosmos.azure.com:8182/')

        this.graph = new this.Graph();
        this.g = this.graph.traversal().withRemote(this.gremlin_websocket);
      };

</code>```

However, I need to pass along authentication and collection information (currently in the authenticator object). But WebSocket doesn't seem to support it, and Driver Remote Connection doesn't seem to natively take the websocket. What should I do?

答: I don't think gremlin-javascript works well in a browser unfortunately. I assume that is the issue you are running into. Note that there already is an issue for this with TINKERPOP-2143 and an associated pull request that has been partially done now for a long time but has not yet been completed.</p>

ContentLicense: CC BY-SA 4.0

Body:
I apologies for such a basic question, but I can't seem to figure out how to do this and the docs are all very specific.

I'm just trying to connect to a standard Gremlin DB (Cosmos) using gremlin. It works great from the server, but when I connect from the browser, I get this error:

Error: ws does not work in the browser. Browser clients must use the native WebSocket object

Nothing terribly complicated, and the error seems to be pretty clear.

Here is the code:

     constructor() {
        var authenticator = new Gremlin.driver.auth.PlainTextSaslAuthenticator(`/dbs/${config.database}/colls/${config.collection}`, config.primaryKey);
        this.gremlin_config_options = {
            authenticator,
            traversalsource: "g",
            rejectUnauthorized: true,
            mimeType: "application/vnd.gremlin-v2.0+json"
        }

       var DriverRemoteConnection = Gremlin.driver.DriverRemoteConnection;
        this.Graph = Gremlin.structure.Graph;

        var dc = new DriverRemoteConnection(this.gremlin_websocket,this.gremlin_config_options);

        this.graph = new this.Graph();
        this.g = this.graph.traversal().withRemote(this.gremlin_websocket);
      };

When I do the following code, it completes without the Javascript error.

    constructor() {
        var authenticator = new Gremlin.driver.auth.PlainTextSaslAuthenticator(`/dbs/${config.database}/colls/${config.collection}`, config.primaryKey);
        this.gremlin_config_options = {
            authenticator,
            traversalsource: "g",
            rejectUnauthorized: true,
            mimeType: "application/vnd.gremlin-v2.0+json"
        }

        this.Graph = Gremlin.structure.Graph;

        this.gremlin_websocket = new WebSocket('ws://test_db.gremlin.cosmos.azure.com:8182/')

        this.graph = new this.Graph();
        this.g = this.graph.traversal().withRemote(this.gremlin_websocket);
      };

However, I need to pass along authentication and collection information (currently in the authenticator object). But WebSocket doesn't seem to support it, and Driver Remote Connection doesn't seem to natively take the websocket. What should I do?


问:
C++ Program communicating with MySQL Database
Does anyone know of a simple way for a C++ program to communicate directly with a MySQL database?  I have looked at MySQL++ and found it to be very confusing.  If anyone knows of a very simple way of doing this, please let me know.

Thanks

P.S. I am developing on a Windows machine.  PHP and MySQL web web application setup.  C++ setup to talk to the serial port.  Thus why I need a way for C++ to talk to the MySQL database directly.

答:
MySQL Connector/C++ is a C++ implementation of JDBC 4.0

The reference customers who use MySQL Connector/C++ are:
- OpenOffice
- MySQL Workbench

Learn more: http://forums.mysql.com/read.php?167,221298

OwnerDisplayName: Anomynous

LastEditorDisplayName: Keng

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: MySQL Workbench


问:
Is it possible to run a PHP function after each line of a PHP script is executed?
My question is similar to this: Is it possible to run code after each line in Ruby?
However I want to do it in PHP.

Is it possible and if so, how?

答:
You could try putting a wrapper around your original PHP, like so:</p>

```<code><?PHP
$lines = file('original.php');

foreach ($lines as $line) {
    eval($line);
    your_function();
}
?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You could try putting a wrapper around your original PHP, like so:

<?PHP
$lines = file('original.php');

foreach ($lines as $line) {
    eval($line);
    your_function();
}
?>


问:
How to implement a callback function in React Native?
I'm just wondering how to implement callback function in onPress function. I want to make sure the first function completed then the second process triggered.

```<code>onPress={() => {
          onSignIn(); //run this function first
          if(_values.success == 1){ //then run this after onSignIn() function completed
            navigation.navigate("SignedIn");
          }
        }}
</code>```

onSignIn()

```<code>export const onSignIn = async () => {
  if (_values.username && _values.password) {
    fetch("http://localhost:3001/sessions/create", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: _values.username,
        password: _values.password
      })
    })
    .then((response) => response.json())
    .then((responseData) => {
      if(responseData.access_token){
         AsyncStorage.setItem(USER_KEY, responseData.access_token);
        _values.success = 1;
        alert("Login successfully!");
        return _values.success;
      } else {
        alert("Wrong username and password!");
        _values.success = 0;
        return _values.success;
      }
    })
    .done();
  } else{
    alert("Please enter your username and password.");
  }
}
</code>```

Reference: https://github.com/datomnurdin/auth-reactnative

答:
Return a Promise from the method and add .then() to the function call

```<code>export const onSignIn = async () => {

  const promise =  new  Promise(async (resolve, reject) => {

    try {
    //do something and return result on success
    resolve(result);

   }catch(msg) { reject(msg);}

   });

  return promise;
}
</code>```

Call the method like this:

```<code>onSignIn ().then(
     (response,error) => {
     //get callback here
  });
</code>```

Body:
I'm just wondering how to implement callback function in onPress function. I want to make sure the first function completed then the second process triggered.

onPress={() => {
          onSignIn(); //run this function first
          if(_values.success == 1){ //then run this after onSignIn() function completed
            navigation.navigate("SignedIn");
          }
        }}

onSignIn()

export const onSignIn = async () => {
  if (_values.username && _values.password) {
    fetch("http://localhost:3001/sessions/create", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: _values.username,
        password: _values.password
      })
    })
    .then((response) => response.json())
    .then((responseData) => {
      if(responseData.access_token){
         AsyncStorage.setItem(USER_KEY, responseData.access_token);
        _values.success = 1;
        alert("Login successfully!");
        return _values.success;
      } else {
        alert("Wrong username and password!");
        _values.success = 0;
        return _values.success;
      }
    })
    .done();
  } else{
    alert("Please enter your username and password.");
  }
}

Reference: https://github.com/datomnurdin/auth-reactnative

Body:
Return a Promise from the method and add .then() to the function call

export const onSignIn = async () => {

  const promise =  new  Promise(async (resolve, reject) => {

    try {
    //do something and return result on success
    resolve(result);

   }catch(msg) { reject(msg);}

   });

  return promise;
}

Call the method like this:

onSignIn ().then(
     (response,error) => {
     //get callback here
  });


问:
.classList applicated to a null objectif without reasons
thanks for the help. For a homework i just have to create a form like the on i join.
I have to remove class of an object in a function, but it returns an error that tells it's a null object. As you'll be able to se, it is good in the HTML :/

THanks !

```<code>function checked(x) {
for (i=1; i <= x; i++) {
    let non = "#non"+i;
    let oui = "#oui"+i;
    document.getElementById("oui"+i).addEventListener('click', function() {
        this.className = 'cheked';
        if (document.getElementById("non"+i).classList.contains("cheked") ==  true) {
            $(this).classList.remove("cheked");
        }
    });
    document.getElementById("non"+i).addEventListener('click', function() {
        this.className = 'cheked';
        if (document.getElementById("oui"+i).classList.contains("cheked") ==  true) {
            $(this).classList.remove("cheked");
        }
    });
}
</code>```

}

```<code><form id="question1">
    <h2>Salamèche est-il de type feu ?</h2>
    <div class="row">
        <div>
            <input type="radio" name="question1" id="oui1" value="oui" >
            <label for="oui1" class="oui">OUI</label>
        </div>
        <div>
            <input type="radio" name="question1" id="non1" value="non">
            <label for="non1" class="non ">NON</label>
        </div>
    </div>
    <input type="submit" value="Submit">
</form>

<form id="question2">
    <h2>Tiplouf est-il de type plante ?</h2>
    <div class="row">
        <div>
            <input type="radio" name="question1" id="oui2" value="oui" >
            <label for="oui2" class="oui">OUI</label>
        </div>
        <div>
            <input type="radio" name="question1" id="non2" value="non">
            <label for="non2" class="non ">NON</label>
        </div>
    </div>
    <input type="submit" value="Submit">
</form>

<form id="question3">
    <h2>Wesh la cité</h2>
    <div class="row">
        <div>
            <input type="radio" name="question1" id="oui3" value="oui" >
            <label for="oui3" class="oui">OUI</label>
        </div>
        <div>
            <input type="radio" name="question1" id="non3" value="non">
            <label for="non3" class="non ">NON</label>
        </div>
    </div>
    <input type="submit" value="Submit">
</form>
</code>```

答:
Here's one way you could go about this:

// select all radio buttons and save them in an array
var radioButtons = [].slice.call(
  document.querySelectorAll("input[type='radio']")
);

// create an event handler for each `radio` button
// and listen for the `change` event, which will
// get triggered when you select one
radioButtons.forEach(function (button) {
  button.addEventListener("change", handleOnChange);
})

function handleOnChange(event) {
  // iterate through each `radio` button to check
  // which ones are `selected` and which ones are not
  radioButtons.forEach(function(button) {
    var CHECKED_CLASS = "checked";

    var buttonId = button.getAttribute("id");

    // grab `label` element corresponding to this `radio` button
    var label = document.querySelector("label[for='" + buttonId +"']");

    // if `button` is checked, add the `CHECKED_CLASS` to the `label`
    // element, otherwise remove it, or, alternatively, add/remove
    // class from the element itself
    if (button.checked) {
      label.classList.add(CHECKED_CLASS);
      // button.classList.add(CHECKED_CLASS);
    } else {
      label.classList.remove(CHECKED_CLASS);
      // button.classList.remove(CHECKED_CLASS);
    }
  })
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.checked {
  border: 3px solid green;
}</code>```

<form id="question1">

Salamèche est-il de type feu ?

      <input type="radio" name="question1" id="oui1" value="oui" />

        OUI

      <input type="radio" name="question1" id="non1" value="non" />

        NON

  <input type="submit" value="Submit" />
</form>
<form id="question2">

Tiplouf est-il de type plante ?

      <input type="radio" name="question1" id="oui2" value="oui" />

        OUI

      <input type="radio" name="question1" id="non2" value="non" />

        NON

  <input type="submit" value="Submit" />
</form>
<form id="question3">

Wesh la cité

      <input type="radio" name="question1" id="oui3" value="oui" />

        OUI

      <input type="radio" name="question1" id="non3" value="non" />

        NON

  <input type="submit" value="Submit" />
</form>```

Body:
thanks for the help. For a homework i just have to create a form like the on i join.
I have to remove class of an object in a function, but it returns an error that tells it's a null object. As you'll be able to se, it is good in the HTML :/

THanks !

function checked(x) {
for (i=1; i <= x; i++) {
    let non = "#non"+i;
    let oui = "#oui"+i;
    document.getElementById("oui"+i).addEventListener('click', function() {
        this.className = 'cheked';
        if (document.getElementById("non"+i).classList.contains("cheked") ==  true) {
            $(this).classList.remove("cheked");
        }
    });
    document.getElementById("non"+i).addEventListener('click', function() {
        this.className = 'cheked';
        if (document.getElementById("oui"+i).classList.contains("cheked") ==  true) {
            $(this).classList.remove("cheked");
        }
    });
}

}

<form id="question1">

Salamèche est-il de type feu ?

            <input type="radio" name="question1" id="oui1" value="oui" >
            OUI

            <input type="radio" name="question1" id="non1" value="non">
            NON

    <input type="submit" value="Submit">
</form>

<form id="question2">

Tiplouf est-il de type plante ?

            <input type="radio" name="question1" id="oui2" value="oui" >
            OUI

            <input type="radio" name="question1" id="non2" value="non">
            NON

    <input type="submit" value="Submit">
</form>

<form id="question3">

Wesh la cité

            <input type="radio" name="question1" id="oui3" value="oui" >
            OUI

            <input type="radio" name="question1" id="non3" value="non">
            NON

    <input type="submit" value="Submit">
</form>

Body:
Here's one way you could go about this:

// select all radio buttons and save them in an array
var radioButtons = [].slice.call(
  document.querySelectorAll("input[type='radio']")
);

// create an event handler for each `radio` button
// and listen for the `change` event, which will
// get triggered when you select one
radioButtons.forEach(function (button) {
  button.addEventListener("change", handleOnChange);
})

function handleOnChange(event) {
  // iterate through each `radio` button to check
  // which ones are `selected` and which ones are not
  radioButtons.forEach(function(button) {
    var CHECKED_CLASS = "checked";

    var buttonId = button.getAttribute("id");

    // grab `label` element corresponding to this `radio` button
    var label = document.querySelector("label[for='" + buttonId +"']");

    // if `button` is checked, add the `CHECKED_CLASS` to the `label`
    // element, otherwise remove it, or, alternatively, add/remove
    // class from the element itself
    if (button.checked) {
      label.classList.add(CHECKED_CLASS);
      // button.classList.add(CHECKED_CLASS);
    } else {
      label.classList.remove(CHECKED_CLASS);
      // button.classList.remove(CHECKED_CLASS);
    }
  })
}

.checked {
  border: 3px solid green;
}

<form id="question1">
  <h2>Salamèche est-il de type feu ?</h2>
  <div class="row">
    <div>
      <input type="radio" name="question1" id="oui1" value="oui" />
      <label for="oui1" class="oui">
        OUI
      </label>
    </div>
    <div>
      <input type="radio" name="question1" id="non1" value="non" />
      <label for="non1" class="non ">
        NON
      </label>
    </div>
  </div>
  <input type="submit" value="Submit" />
</form>
<form id="question2">
  <h2>Tiplouf est-il de type plante ?</h2>
  <div class="row">
    <div>
      <input type="radio" name="question1" id="oui2" value="oui" />
      <label for="oui2" class="oui">
        OUI
      </label>
    </div>
    <div>
      <input type="radio" name="question1" id="non2" value="non" />
      <label for="non2" class="non ">
        NON
      </label>
    </div>
  </div>
  <input type="submit" value="Submit" />
</form>
<form id="question3">
  <h2>Wesh la cité</h2>
  <div class="row">
    <div>
      <input type="radio" name="question1" id="oui3" value="oui" />
      <label for="oui3" class="oui">
        OUI
      </label>
    </div>
    <div>
      <input type="radio" name="question1" id="non3" value="non" />
      <label for="non3" class="non ">
        NON
      </label>
    </div>
  </div>
  <input type="submit" value="Submit" />
</form>


问:
Angular Material Theme - Selector on BODY tag
I have an application developed in Angular with Material components. I'm using Material Theme to have a few different themes to my app (Dark, Light, Colorful).

My main component - app.component html look like this:

```<code><div [ngClass]="appTheme">
  <router-outlet></router-outlet>
</div>
</code>```

The value of appTheme can be 'Light', 'Dark' or 'Colorful'. According to this different @mixin is being executed, that will color my app in different colors (you can read more about it on the official Material site).

My problem is that some 3rd party components, and event some Material components are floating pop-ups. These pop-ups are being attached to the BODY tag. So the html look like this:

```<code><body>
  <app-root>
    <div class="dark">
     ...
    </div>
  </app-root>
  <some-3rd-party-component>
    ...
  </some-3rd-party-component>
</body>
</code>```

As you can see the class dark will not effect the some-3rd-party-component - since it isn't a child element.

How can I set the [ngClass] on the body element. so I could control 3rd party components??

答:
Instead of setting the theme class manually like this
...
 you could set it programmatically by using pure js. You just need to get the document body and add the theme class to the list of classes:

setBodyClass() {
  // get html body element
  const bodyElement = document.body;

  if (bodyElement) {
    // remove existing class (needed if theme is being changed)
    bodyElement.classList.remove(activeClass);
    // add next theme class
    bodyElement.classList.add(nextClass);

    this.bodyClass = nextClass;
  }
}
```

<p>Here is a Stackblitz of that approach.</p>

<p>Another way (but not tested by be) is mentioned in this SO answer: Angular2 add class to body tag
. Here they are using Angular's document injector and renderer to change the class of the body.</p>

<p>Another way which I've used to theme all sorts of different Angular Material components within overlays is the <code>OverlayContainer</code> from @angular/cdk/overlay. Similar to the pure js approach, but won't work on elements which are neither inside a matOverlayContainer nor the app.</p>

<pre class="lang-js prettyprint-override"><code>const matOverlayContainerClassList = this.overlayContainer.getContainerElement().classList;

matOverlayContainerClassList.remove(previousThemeName);
matOverlayContainerClassList.add(currentThemeName);
</code>```

Body:
I have an application developed in Angular with Material components. I'm using Material Theme to have a few different themes to my app (Dark, Light, Colorful).

My main component - app.component html look like this:

  <router-outlet></router-outlet>

The value of appTheme can be 'Light', 'Dark' or 'Colorful'. According to this different @mixin is being executed, that will color my app in different colors (you can read more about it on the official Material site).

My problem is that some 3rd party components, and event some Material components are floating pop-ups. These pop-ups are being attached to the BODY tag. So the html look like this:

  <app-root>

     ...

  </app-root>
  <some-3rd-party-component>
    ...
  </some-3rd-party-component>

As you can see the class dark will not effect the some-3rd-party-component - since it isn't a child element.

How can I set the [ngClass] on the body element. so I could control 3rd party components??

Body:
Instead of setting the theme class manually like this <div [ngClass]="appTheme">...</div> you could set it programmatically by using pure js. You just need to get the document body and add the theme class to the list of classes:

setBodyClass() {
  // get html body element
  const bodyElement = document.body;

  if (bodyElement) {
    // remove existing class (needed if theme is being changed)
    bodyElement.classList.remove(activeClass);
    // add next theme class
    bodyElement.classList.add(nextClass);

    this.bodyClass = nextClass;
  }
}

Here is a Stackblitz of that approach.

Another way (but not tested by be) is mentioned in this SO answer: Angular2 add class to body tag
. Here they are using Angular's document injector and renderer to change the class of the body.

Another way which I've used to theme all sorts of different Angular Material components within overlays is the OverlayContainer from @angular/cdk/overlay. Similar to the pure js approach, but won't work on elements which are neither inside a matOverlayContainer nor the app.

const matOverlayContainerClassList = this.overlayContainer.getContainerElement().classList;

matOverlayContainerClassList.remove(previousThemeName);
matOverlayContainerClassList.add(currentThemeName);


问:
How do I update values without refreshing the page on my Flask project?
I have a website that shows the prices of items in a video game.

Currently, I have an "auto-refresh" script that refreshes the page every 5 seconds, but it is a bit annoying as every time you search for a product, it removes your search because the page refreshes.

I would like to update the numbers in my table without refreshing the page for the user. I read something about 'updating the DOM', in javascript but didn't get it.

Here is the link to my website: http://xeltool.com/

And here is my python code:

```<code>@app.route('/bprices', methods=['GET'])
def bPrices():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[cannot show]').json()

    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1],
            "buy_price": product["buy_summary"][:1],
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    return render_template("bprices.html", products=products)
</code>```

And here is my HTML code:

```<code><div class="container">
  <div class="search_div">
    <input
      type="text"
      onkeyup="myFunction()"
      id="myInput"
      title="Type in a product"
      class="search-box"
      placeholder="Search for a product..."
    />
    <button class="search-btn"><i class="fas fa-search"></i></button>
  </div>

  <table
    id="myTable"
    class="table table-striped table-bordered table-sm table-dark sortable"
    cellspacing="0"
  >
    <thead>
      <tr>
        <th aria-label="Product Name" data-balloon-pos="up">Product</th>
        <th aria-label="Product's buy price" data-balloon-pos="up">
          Buy Price
        </th>
        <th aria-label="Product's sell price" data-balloon-pos="up">
          Sell Price
        </th>
        <th aria-label="Product's buy volume" data-balloon-pos="up">
          Buy Volume
        </th>
        <th aria-label="Product's sell volume" data-balloon-pos="up">
          Sell Volume
        </th>
        <th>
          Margin
        </th>
      </tr>
    </thead>
    <tbody>
      {% for product in products %}
      <tr>
        <td>{{ product.id|replace("_", ' ')|lower()|title() }}</td>
        {% for buy in product.buy_price %}
        <td>{{ buy.pricePerUnit }}</td>
        {% for sell in product.sell_price %}
        <td>{{ sell.pricePerUnit }}</td>

        <td>{{ product.buy_volume| numberFormat }}</td>
        <td>{{ product.sell_volume| numberFormat }}</td>
        {% set margin = buy.pricePerUnit - sell.pricePerUnit%} {% set marginPer
        = margin/buy.pricePerUnit * 100%}
        <td
          aria-label="{{ marginPer|round(1, 'floor') }} % "
          data-balloon-pos="right"
        >
          {{ margin|round(1, 'floor')}}
        </td>
        {% endfor %}{% endfor %}
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>
</code>```

If you NEED the API to test this out, I can provide a link to it :)

答:
Use AJAX to ask for new prices. The API will return the values and then in the JS code just change the previous price to the new price.

AJAX will definitely help.

Have a look at the simple tutorial here: https://www.w3schools.com/xml/ajax_intro.asp.

Body:
I have a website that shows the prices of items in a video game.

Currently, I have an "auto-refresh" script that refreshes the page every 5 seconds, but it is a bit annoying as every time you search for a product, it removes your search because the page refreshes.

I would like to update the numbers in my table without refreshing the page for the user. I read something about 'updating the DOM', in javascript but didn't get it.

Here is the link to my website: http://xeltool.com/

And here is my python code:

@app.route('/bprices', methods=['GET'])
def bPrices():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[cannot show]').json()

    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1],
            "buy_price": product["buy_summary"][:1],
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    return render_template("bprices.html", products=products)

And here is my HTML code:

    <input
      type="text"
      onkeyup="myFunction()"
      id="myInput"
      title="Type in a product"
      class="search-box"
      placeholder="Search for a product..."
    />
    <button class="search-btn"></button>

        Product

          Buy Price

          Sell Price

          Buy Volume

          Sell Volume

          Margin

      {% for product in products %}

        {{ product.id|replace("_", ' ')|lower()|title() }}
        {% for buy in product.buy_price %}
        {{ buy.pricePerUnit }}
        {% for sell in product.sell_price %}
        {{ sell.pricePerUnit }}

        {{ product.buy_volume| numberFormat }}
        {{ product.sell_volume| numberFormat }}
        {% set margin = buy.pricePerUnit - sell.pricePerUnit%} {% set marginPer
        = margin/buy.pricePerUnit * 100%}

          {{ margin|round(1, 'floor')}}

        {% endfor %}{% endfor %}

      {% endfor %}

If you NEED the API to test this out, I can provide a link to it :)


问:
Bash gotcha: cat FILE | while read A ; do ... exit .. done
I had a long pause in writing bash script, and I got trapped again:

```<code>cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                exit
        fi
done
</code>```

I happily assumed the exit will exit the whole bash script, as it should, but as it is in pipe, it probably exits just the sub-process dispatched to run while part.

I already forgot how to easily workaround this. Please remind me! :-)

**EDIT: ** now I have changed the code (for some other reason) to use variable instead, and I am looking for workaround for this:

```<code>EXIST="no"
cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                EXIST="yes"
        fi
done
</code>```

but I guess this is the same case, I need the inside of the loop to be run with the same shell as runs the whole script.

答:
You could exit with a code in your sub-shell, then check it's exit code when the while loop is done:

```<code>cat FILE | while read SPID ; do
    if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
        echo Error: some files exist in the directory $ODIR:
        ls -la $ODIR/*$SPID*.csv
        exit 1
    fi
done

# Exit script if exit code from the previous command is 1
if [ $? = 1 ] ; then
    exit
fi
</code>```

I think @KamilCuk's answer for refactoring this as while ... done < file is preferable in this case. But the above shows an alternative for the sub-shell process, in case you have a lot more going into the stdin than the simple cat of a file.

Body:
I had a long pause in writing bash script, and I got trapped again:

cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                exit
        fi
done

I happily assumed the exit will exit the whole bash script, as it should, but as it is in pipe, it probably exits just the sub-process dispatched to run while part.

I already forgot how to easily workaround this. Please remind me! :-)

**EDIT: ** now I have changed the code (for some other reason) to use variable instead, and I am looking for workaround for this:

EXIST="no"
cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                EXIST="yes"
        fi
done

but I guess this is the same case, I need the inside of the loop to be run with the same shell as runs the whole script.

Body:
You could exit with a code in your sub-shell, then check it's exit code when the while loop is done:

cat FILE | while read SPID ; do
    if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
        echo Error: some files exist in the directory $ODIR:
        ls -la $ODIR/*$SPID*.csv
        exit 1
    fi
done

# Exit script if exit code from the previous command is 1
if [ $? = 1 ] ; then
    exit
fi

I think @KamilCuk's answer for refactoring this as while ... done < file is preferable in this case. But the above shows an alternative for the sub-shell process, in case you have a lot more going into the stdin than the simple cat of a file.


问:
How to use ffmpeg with drawtext and a emoji TTF
I'm trying to overlay some text emoticons on top of a video using ffmpeg.. This works fine for normal TTF's e.g.

```<code>ffmpeg -i video.mp4 -vf drawtext="Arial.ttf: text='YENTL  Bresseleers ': fontcolor=white: fontsize=24: x=(w-text_w)/2: y=(h-text_h-line_h)/2" -codec:a copy output.mp4 -y
</code>```

I can use the OpenSansEmoji font which gets me closer to what I need..

```<code>ffmpeg -i video.mp4 -vf drawtext="OpenSansEmoji.ttf.ttf: text='YENTL  Bresseleers ': fontcolor=white: fontsize=24: x=(w-text_w)/2: y=(h-text_h-line_h)/2" -codec:a copy output.mp4 -y`
</code>```

However when I try with a TTF file with coloured emoji's like emojione or Noto Color Emoji I get the below error:

```<code>[Parsed_drawtext_0 @ 0x7fd643700000] Could not set font size to 24 pixels: invalid module handle
[AVFilterGraph @ 0x7fd643608b80] Error initializing filter 'drawtext' with args 'fontfile=AppleColorEmoji.ttf: text=YENTL  Bresseleers : fontcolor=white: fontsize=24: x=(w-text_w)/2: y=(h-text_h-line_h)/2'
Error opening filters!`
</code>```

Any ideas?

答:
For a dirty workaround one can manually adjust the emoji on top of a character like so

```<code>ffmpeg -i video.mp4 -i "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/smiling-face-with-sunglasses_1f60e.png" -filter_complex "[1:v]scale=24:24,format=argb,colorchannelmixer=aa=0.5[ovrl],[0:v]drawtext=text='YENTL O Bresseleers':fontcolor=white:fontsize=24:x='(w-text_w)/2':y='(h-text_h-line_h)/2'[text],[text][ovrl]overlay=main_w/2-46:main_h/2-20" -codec:a copy output.mp4 -y
</code>```

and then remove the ,format=argb,colorchannelmixer=aa=0.5 part when the position is correct.

Body:
I'm trying to overlay some text emoticons on top of a video using ffmpeg.. This works fine for normal TTF's e.g.

ffmpeg -i video.mp4 -vf drawtext="Arial.ttf: text='YENTL  Bresseleers ': fontcolor=white: fontsize=24: x=(w-text_w)/2: y=(h-text_h-line_h)/2" -codec:a copy output.mp4 -y

I can use the OpenSansEmoji font which gets me closer to what I need..

ffmpeg -i video.mp4 -vf drawtext="OpenSansEmoji.ttf.ttf: text='YENTL  Bresseleers ': fontcolor=white: fontsize=24: x=(w-text_w)/2: y=(h-text_h-line_h)/2" -codec:a copy output.mp4 -y`

However when I try with a TTF file with coloured emoji's like emojione or Noto Color Emoji I get the below error:

[Parsed_drawtext_0 @ 0x7fd643700000] Could not set font size to 24 pixels: invalid module handle
[AVFilterGraph @ 0x7fd643608b80] Error initializing filter 'drawtext' with args 'fontfile=AppleColorEmoji.ttf: text=YENTL  Bresseleers : fontcolor=white: fontsize=24: x=(w-text_w)/2: y=(h-text_h-line_h)/2'
Error opening filters!`

Any ideas?

Body:
For a dirty workaround one can manually adjust the emoji on top of a character like so

ffmpeg -i video.mp4 -i "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/smiling-face-with-sunglasses_1f60e.png" -filter_complex "[1:v]scale=24:24,format=argb,colorchannelmixer=aa=0.5[ovrl],[0:v]drawtext=text='YENTL O Bresseleers':fontcolor=white:fontsize=24:x='(w-text_w)/2':y='(h-text_h-line_h)/2'[text],[text][ovrl]overlay=main_w/2-46:main_h/2-20" -codec:a copy output.mp4 -y

and then remove the ,format=argb,colorchannelmixer=aa=0.5 part when the position is correct.


问:
Angular 2: External configuration befor bootstrap - passing the value to AppModule
I am would like to configure my Angular 2 App from external json file.

In my main.ts I load the config.json

```<code>getHttp().get('/config.json')
         .map(response => response.json();)
         .subscribe(
           data => {
             let clientConf: ClientConfig = data;

             // here I want to pass clientConf to AppModule
             platformBrowserDynamic().bootstrapModule(AppModule);

          });
</code>```

I wonder how to pass clientConf to AppModule to use in app.module.ts:

```<code>@NgModule({
     ...
    providers: [
          { provide: Configuration, useValue: clientConf }
           ...
</code>```

答:
I had trouble to follow the accepted answer by @tomas-marik which I think was otherwise good. Below is my adaptations in main.ts for use in Angular 8:</p>

```<code>fetch('/assets/config.json').then(async res => {
  var clientConf = <ClientConfig>await res.json();

  platformBrowserDynamic(
    [{ provide: ClientConfig, useValue: clientConf }]
  ).bootstrapModule(AppModule)
    .catch(err => console.error(err));
});
</code>```

Body:
I am would like to configure my Angular 2 App from external json file.

In my main.ts I load the config.json

getHttp().get('/config.json')
         .map(response => response.json();)
         .subscribe(
           data => {
             let clientConf: ClientConfig = data;

             // here I want to pass clientConf to AppModule
             platformBrowserDynamic().bootstrapModule(AppModule);

          });

I wonder how to pass clientConf to AppModule to use in app.module.ts:

@NgModule({
     ...
    providers: [
          { provide: Configuration, useValue: clientConf }
           ...

Body:
I had trouble to follow the accepted answer by @tomas-marik which I think was otherwise good. Below is my adaptations in main.ts for use in Angular 8:

fetch('/assets/config.json').then(async res => {
  var clientConf = <ClientConfig>await res.json();

  platformBrowserDynamic(
    [{ provide: ClientConfig, useValue: clientConf }]
  ).bootstrapModule(AppModule)
    .catch(err => console.error(err));
});


问:
RSA key generation error in RSA_generate_key_ex function call
I'm trying to generate RSA keys using openssl. I've got error on RSA_generate_key_ex and have no idea why the error occures.

I combine ERR_get_error() and ERR_error_string() and I've got next message: error:2506906C:lib(37):func(105):reason(108). Also I found out that 108 error code means RSA_R_DATA_GREATER_THAN_MOD_LEN

I'm trying to generate RSA keys using C code below. For sake of brevity I reduce free calls and error output

```<code>RSA* generateRSA()
{
  BIGNUM *bne = BN_new();
  if (bne == NULL)
  {
    return NULL;
  }
  if (BN_set_word(bne, RSA_F4) != 1)
  {
    return NULL;
  }

  RSA *r = RSA_new();
  if (r == NULL)
  {
    return NULL;
  }
  // THERE I'VE GOT ERROR
  if (RSA_generate_key_ex(r, 2048, bne, NULL)!= 1)
  {
    // ERR_get_error() returns 2506906C
    // ERR_error_string() gives me RSA_R_DATA_GREATER_THAN_MOD_LEN
    return NULL;
  }

  return r;
}
</code>```

The question is what does the error mean and how can I fix it?

Edit: I use OpenSSL 1.1.0e 16 Feb 2017. I use it as part of EDK II Project

答:
I figured out that random generator need to be seeded (openssl versions 1.0.2 and 1.1.0 random generators must be explicitly seeded).

I check RAND_status(). It returned 0. So the solution is just add RAND_seed() before key generation:

```<code>const void* getSeedBuffer(int num);

RSA* generateRSA()
{
  RAND_seed(getSeedBuffer(1000), 1000); // don't forget to free memory
  BIGNUM *bne = BN_new();
  if (bne == NULL)
  {
    return NULL;
  }
  if (BN_set_word(bne, RSA_F4) != 1)
  {
    return NULL;
  }

  RSA *r = RSA_new();
  if (r == NULL)
  {
    return NULL;
  }
  if (RSA_generate_key_ex(r, 2048, bne, NULL)!= 1)
  {
    return NULL;
  }

  return r;
}
</code>```

Body:
I'm trying to generate RSA keys using openssl. I've got error on RSA_generate_key_ex and have no idea why the error occures.

I combine ERR_get_error() and ERR_error_string() and I've got next message: error:2506906C:lib(37):func(105):reason(108). Also I found out that 108 error code means RSA_R_DATA_GREATER_THAN_MOD_LEN

I'm trying to generate RSA keys using C code below. For sake of brevity I reduce free calls and error output

RSA* generateRSA()
{
  BIGNUM *bne = BN_new();
  if (bne == NULL)
  {
    return NULL;
  }
  if (BN_set_word(bne, RSA_F4) != 1)
  {
    return NULL;
  }

  RSA *r = RSA_new();
  if (r == NULL)
  {
    return NULL;
  }
  // THERE I'VE GOT ERROR
  if (RSA_generate_key_ex(r, 2048, bne, NULL)!= 1)
  {
    // ERR_get_error() returns 2506906C
    // ERR_error_string() gives me RSA_R_DATA_GREATER_THAN_MOD_LEN
    return NULL;
  }

  return r;
}

The question is what does the error mean and how can I fix it?

Edit: I use OpenSSL 1.1.0e 16 Feb 2017. I use it as part of EDK II Project

Body:
I figured out that random generator need to be seeded (openssl versions 1.0.2 and 1.1.0 random generators must be explicitly seeded).

I check RAND_status(). It returned 0. So the solution is just add RAND_seed() before key generation:

const void* getSeedBuffer(int num);

RSA* generateRSA()
{
  RAND_seed(getSeedBuffer(1000), 1000); // don't forget to free memory
  BIGNUM *bne = BN_new();
  if (bne == NULL)
  {
    return NULL;
  }
  if (BN_set_word(bne, RSA_F4) != 1)
  {
    return NULL;
  }

  RSA *r = RSA_new();
  if (r == NULL)
  {
    return NULL;
  }
  if (RSA_generate_key_ex(r, 2048, bne, NULL)!= 1)
  {
    return NULL;
  }

  return r;
}


问:
Creating SQLite database in intellij
I have to create a SQLite database that I will ultimately have to insert lines of data from a parsed .csv file. The issue that I'm having is creating the SQLite database in the intellij idea. Using the code below I continue to get the "No suitable driver" error.  I believe that I've added the classpath correctly by using Project Structure-> Modules-> Add then selecting my downloaded SQLite .jar file, which in this case is sqlite-jdbc-3.30.1 (1).jar

```<code>import java.sql.Connection;

import java.sql.DatabaseMetaData;

import java.sql.DriverManager;

import java.sql.SQLException;

public class mint {

    public static void createNewDatabase(String fileName) {

        String url = "C:\\SQLite\\sqlite-jdbc-3.30.1 (1).jar" + fileName;

        try {
            Connection conn = DriverManager.getConnection(url);
            if (conn != null) {
                DatabaseMetaData meta = conn.getMetaData();
                System.out.println("The driver name is " + meta.getDriverName());
                System.out.println("A new database has been created.");
            }

        } catch (SQLException e) {
            System.out.println(e.getMessage());
            System.out.println("An error occurred while connecting MySQL database");
        }
    }

    public static void main(String[] args) {
        createNewDatabase("input-filename.db");

    }
}
</code>```

Screenshot of output

答:
You need to read this tutorial - URL should be like this</p>

```<code>String url = "jdbc:sqlite:C:/sqlite/" + fileName;
</code>```

Title: Creating SQLite database in intellij

Body:
I have to create a SQLite database that I will ultimately have to insert lines of data from a parsed .csv file. The issue that I'm having is creating the SQLite database in the intellij idea. Using the code below I continue to get the "No suitable driver" error.  I believe that I've added the classpath correctly by using Project Structure-> Modules-> Add then selecting my downloaded SQLite .jar file, which in this case is sqlite-jdbc-3.30.1 (1).jar

import java.sql.Connection;

import java.sql.DatabaseMetaData;

import java.sql.DriverManager;

import java.sql.SQLException;

public class mint {

    public static void createNewDatabase(String fileName) {

        String url = "C:\\SQLite\\sqlite-jdbc-3.30.1 (1).jar" + fileName;

        try {
            Connection conn = DriverManager.getConnection(url);
            if (conn != null) {
                DatabaseMetaData meta = conn.getMetaData();
                System.out.println("The driver name is " + meta.getDriverName());
                System.out.println("A new database has been created.");
            }

        } catch (SQLException e) {
            System.out.println(e.getMessage());
            System.out.println("An error occurred while connecting MySQL database");
        }
    }

    public static void main(String[] args) {
        createNewDatabase("input-filename.db");

    }
}

Screenshot of output

Body:
You need to read this tutorial - URL should be like this

String url = "jdbc:sqlite:C:/sqlite/" + fileName;


问:
How to convert a nested object to an Array in JavaScript
How can I convert this object

```<code>{
    priorities: {
        1: "categoryOne"
        2: "categoryTwo"
    }
}
</code>```

to this array :

```<code>[ {1: "categoryOne"}, {2: "categoryOne"} ]
</code>```

答:
Take entries of object and then map it:

var obj= { priorities: { 1: "categoryOne", 2: "categoryTwo" }};
var result = Object.entries(obj.priorities).map(([k,v])=>({[k]:v}));

console.log(result);```

Body:
How can I convert this object

{
    priorities: {
        1: "categoryOne"
        2: "categoryTwo"
    }
}

to this array :

[ {1: "categoryOne"}, {2: "categoryOne"} ]


问:
How to plot multiple Y-axes keeping the same X-axes using python plotly?
I tried to do it using add_trace method as shown below:

figure = go.Figure()

for i in variables:
    figure.add_trace(go.Scatter(x=records["time"],
                                y=records[i],
                                yaxis="y"))
```

Here, the yaxis value should change for each value in the loop... like y1, y2, y3 and so on as different y axis variable should have different value for yaxis. Is there a way to achieve this ?
Or is there a different way to plot multiple y-axes dynamically ?

答:
If you simply want the Yaxis tilte to display as 'y1' 'y2' etc, then you can do:

```<code>for i in variables:
    figure.add_trace(
       go.Scatter(
         x=records["time"],
         y=records[i],
         yaxis="y"+str(i),
       ),
    )
</code>```

Else, if it is from a list of y values then you can do something like:

```<code>yaxis_titles = ['State', 'Country', 'Continent']
for i in variables:
    figure.add_trace(
       go.Scatter(
         x=records["time"],
         y=records[i],
         yaxis=yaxis_titles[i],
       ),
    )
</code>```

Body:
I tried to do it using add_trace method as shown below:

figure = go.Figure()

for i in variables:
    figure.add_trace(go.Scatter(x=records["time"],
                                y=records[i],
                                yaxis="y"))

Here, the yaxis value should change for each value in the loop... like y1, y2, y3 and so on as different y axis variable should have different value for yaxis. Is there a way to achieve this ?
Or is there a different way to plot multiple y-axes dynamically ?

Body:
If you simply want the Yaxis tilte to display as 'y1' 'y2' etc, then you can do:

for i in variables:
    figure.add_trace(
       go.Scatter(
         x=records["time"],
         y=records[i],
         yaxis="y"+str(i),
       ),
    )

Else, if it is from a list of y values then you can do something like:

yaxis_titles = ['State', 'Country', 'Continent']
for i in variables:
    figure.add_trace(
       go.Scatter(
         x=records["time"],
         y=records[i],
         yaxis=yaxis_titles[i],
       ),
    )


问:
Listeners for changes to app config/resources files
I have an app running in tomcat6 which reads a resource file (a simple text file, no xml) at startup to configure/instantiate some classes. Now I want to be able to modify that file and the changes to be reflected in the app without having to restart the server. Is there a way to do that? </p>

<p>Basically if I could define and attach a listener to that resource, that's all I need. </p>

答:
Try one of the following:

jpoller

JNotify

Java Native Access (JNA)

Roll your own thread

NOTE

With Java 7, Watching a Directory for Changes becomes part of the standard API.

Body:
I have an app running in tomcat6 which reads a resource file (a simple text file, no xml) at startup to configure/instantiate some classes. Now I want to be able to modify that file and the changes to be reflected in the app without having to restart the server. Is there a way to do that?

Basically if I could define and attach a listener to that resource, that's all I need.


问:
How to remove black border from option when hover in chrome 83
I update my chrome browser to 83 and saw the option tag and it looks ugly, It shows the black border when hovering in option.

I tried

```<code>option {
    box-shadow: none;
    border: none;
    -webkit-appearance: none;
}

option:hover {
    box-shadow: none;
    border: none;
    -webkit-appearance: none;
}
</code>```

option {
  box-shadow: none;
  border: none;
  -webkit-appearance: none;
}

option:hover {
  box-shadow: none;
  border: none;
  -webkit-appearance: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
</select></code>```

but still no luck!! why? I don't know.

I want to remove that black border because In my project it looks ugly.

MY NEED

I need same result as previous select and option tag have.

答:
#Problem solution:

Go to below link or copy paste chrome url tab and hits enter.

chrome://flags/#form-controls-refresh

and Disabled Web Platform Controls updated UI

Body:
I update my chrome browser to 83 and saw the option tag and it looks ugly, It shows the black border when hovering in option.

I tried

option {
    box-shadow: none;
    border: none;
    -webkit-appearance: none;
}

option:hover {
    box-shadow: none;
    border: none;
    -webkit-appearance: none;
}

option {
  box-shadow: none;
  border: none;
  -webkit-appearance: none;
}

option:hover {
  box-shadow: none;
  border: none;
  -webkit-appearance: none;
}

<select>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
</select>

but still no luck!! why? I don't know.

I want to remove that black border because In my project it looks ugly.

MY NEED

I need same result as previous select and option tag have.


问:
Filter RSS feeds to show today's content and sort by datetime descending
I have a little script (found on the web) that collects RSS feed(s) into an array, sorts the array and then display how you want it. Now I would like to be able to only display the items from the feed from specific date (today only). Can anyone help filtering the sorted array?</p>

```<code>   <?php
    //Feed URLs
    $feeds = array(
        "https://www.abda.de/?type=1102",
        "https://www.abda.de/?type=1100",
    );

    //Read each feed's items
    $entries = array();
    foreach($feeds as $feed) {
        $xml = simplexml_load_file($feed);
        $entries = array_merge($entries, $xml->xpath("//item"));
    }

    //Sort feed entries by pubDate

    usort($entries, function ($feed1, $feed2) {
        return strtotime($feed2->pubDate) - strtotime($feed1->pubDate);
    });

    function showrssitem($i) {
        global $entries;
        $backgroundbutton = 'd3d3d3';
        switch ($entries[$i]->category) {
            case "Chargenrückrufe" :
                $backgroundbutton = 'ff9933';       /* orange */
                break;
            case "Rückrufe" :
                $backgroundbutton = 'ff9933';       /* orange */
                break;
            case "Informationen der Institutionen und Behörden" :
                $backgroundbutton = 'ff3300';       /* red */
                break;
            case "Informationen der Hersteller" :
                $backgroundbutton = 'ff5500';       /* red 2 */
                break;
            case "AMK-PhaGro-Schnellinformationen" :
                $backgroundbutton = 'ff7700';       /* red3  */
                break;
        }

        $strippedentry1 = str_replace ("Online-Nachricht: ","", $entries[$i]->title);
        $strippedentry2 = str_replace ("Informationen der Institutionen und Behörden: ","", $strippedentry1);
        $strippedentry3 = str_replace ("Informationen der Hersteller: ","", $strippedentry2);
        echo '<a style="text-decoration: none;" target="_blank" href="' . $entries[$i]->link . '"><button style="background-color: #' . $backgroundbutton . '; margin-bottom: 10px; width: 100%; height:75px; display: block; border-radius: 10px;">' . $entries[$i]->category . '</button></a>';
        echo mb_strimwidth($strippedentry3,0,100,"...") . "<br>";
        echo "<i>[" . strftime('%d/%m/%Y', strtotime($entries[$i]->pubDate)) . "]</i><br>";

    }

    ?>
</code>```

答:
The following solution works for me now.
If you have any suggestions for a cleaner way, don't hesitate to comment ;)</p>

```<code>   <?php
    //Feed URLs
    $feeds = array(
        "https://www.abda.de/?type=1102",
        "https://www.abda.de/?type=1100",
    );

    //Read each feed's items
    $entries = array();
    foreach($feeds as $feed) {
        $xml = simplexml_load_file($feed);
        $entries = array_merge($entries, ($xml->xpath("//item")));
    }

    //Sort feed entries by pubDate

    usort($entries, function ($feed1, $feed2) {
        return strtotime($feed2->pubDate) - strtotime($feed1->pubDate);
    });

    //Find latest date in array         $max = max(array_map('strtotime', $arr));
    $highestdate_entries = date('d-m-Y', max(array_map('strtotime', $entries)));    /* returns format 02-06-2020 */
    $entries_filtered = array_filter($entries, function ($var) use ($highestdate_entries) {

        return date('d-m-Y',(strtotime($var->pubDate))) === $highestdate_entries;       /* -> returns 1 */
    });

    //Reset the array so eg. id 10 moves to id 0
    $entries_filtered = array_values($entries_filtered);
    //Count the amount of items, so the for loop can be adjusted to that
    $numberofitems_entries = count($entries);
    $numberofitems_entries_filtered = count($entries_filtered);
    //echo "Items in entries : " . $numberofitems_entries . "<br>";
    //echo "Items in entries_filtered : " . $numberofitems_entries_filtered . "<br>" ;
    //echo "Latest date in entries : " . $highestdate_entries . "<br>" ;
    //echo strtotime($entries_filtered[0]->pubDate) . " === " . strtotime($dateoftoday);

    // XML feed provides 50 items per feed. Total is 100 items.

    // $dateoffeed=strftime("%d-%m-%y",strtotime($entries[0]->pubDate));
    // echo $dateoftoday;
    // Date format in xml feed:     Thu, 28 May 2020 12:17:38 +0200
    // Date format from date:       Mon, 01 Jun 2020 10:13:48 +0200
    // $dateoftoday=date(DATE_RFC2822);

    function showrssitem($i) {
        global $entries_filtered;
        $backgroundbutton = 'd3d3d3';
        switch ($entries_filtered[$i]->category) {
            case "Chargenrückrufe" :
                $backgroundbutton = 'ff9933';       /* orange */
                break;
            case "Rückrufe" :
                $backgroundbutton = 'ff9933';       /* orange */
                break;
            case "Informationen der Institutionen und Behörden" :
                $backgroundbutton = 'ff3300';       /* red */
                break;
            case "Informationen der Hersteller" :
                $backgroundbutton = 'ff5500';       /* red 2 */
                break;
            case "AMK-PhaGro-Schnellinformationen" :
                $backgroundbutton = 'ff7700';       /* red3  */
                break;
        }

        $strippedentry1 = str_replace ("Online-Nachricht: ","", $entries_filtered[$i]->title);
        $strippedentry2 = str_replace ("Informationen der Institutionen und Behörden: ","", $strippedentry1);
        $strippedentry3 = str_replace ("Informationen der Hersteller: ","", $strippedentry2);
        echo '<td style = "border=0px !important; width:20%"><a style="text-decoration: none;" target="_blank" href="' . $entries_filtered[$i]->link . '"><button style="background-color: #' . $backgroundbutton . '; margin-bottom: 0px; width: 100%; height:50px; display: block; border-radius: 10px;">' . $entries_filtered[$i]->category . '</button></a></td>';
        echo "<td><i>" . strftime('%d/%m/%Y', strtotime($entries_filtered[$i]->pubDate)) . ":</i>   ";
        echo mb_strimwidth($strippedentry3,0,200,"...") . '</td>';
    }

    ?>
</code>```

Body:
I have a little script (found on the web) that collects RSS feed(s) into an array, sorts the array and then display how you want it. Now I would like to be able to only display the items from the feed from specific date (today only). Can anyone help filtering the sorted array?

   <?php
    //Feed URLs
    $feeds = array(
        "https://www.abda.de/?type=1102",
        "https://www.abda.de/?type=1100",
    );

    //Read each feed's items
    $entries = array();
    foreach($feeds as $feed) {
        $xml = simplexml_load_file($feed);
        $entries = array_merge($entries, $xml->xpath("//item"));
    }

    //Sort feed entries by pubDate

    usort($entries, function ($feed1, $feed2) {
        return strtotime($feed2->pubDate) - strtotime($feed1->pubDate);
    });

    function showrssitem($i) {
        global $entries;
        $backgroundbutton = 'd3d3d3';
        switch ($entries[$i]->category) {
            case "Chargenrückrufe" :
                $backgroundbutton = 'ff9933';       /* orange */
                break;
            case "Rückrufe" :
                $backgroundbutton = 'ff9933';       /* orange */
                break;
            case "Informationen der Institutionen und Behörden" :
                $backgroundbutton = 'ff3300';       /* red */
                break;
            case "Informationen der Hersteller" :
                $backgroundbutton = 'ff5500';       /* red 2 */
                break;
            case "AMK-PhaGro-Schnellinformationen" :
                $backgroundbutton = 'ff7700';       /* red3  */
                break;
        }

        $strippedentry1 = str_replace ("Online-Nachricht: ","", $entries[$i]->title);
        $strippedentry2 = str_replace ("Informationen der Institutionen und Behörden: ","", $strippedentry1);
        $strippedentry3 = str_replace ("Informationen der Hersteller: ","", $strippedentry2);
        echo 'link . '"><button style="background-color: #' . $backgroundbutton . '; margin-bottom: 10px; width: 100%; height:75px; display: block; border-radius: 10px;">' . $entries[$i]->category . '</button>';
        echo mb_strimwidth($strippedentry3,0,100,"...") . "
";
        echo "[" . strftime('%d/%m/%Y', strtotime($entries[$i]->pubDate)) . "]
";

    }

    ?>

Body:
The following solution works for me now.
If you have any suggestions for a cleaner way, don't hesitate to comment ;)

   <?php
    //Feed URLs
    $feeds = array(
        "https://www.abda.de/?type=1102",
        "https://www.abda.de/?type=1100",
    );

    //Read each feed's items
    $entries = array();
    foreach($feeds as $feed) {
        $xml = simplexml_load_file($feed);
        $entries = array_merge($entries, ($xml->xpath("//item")));
    }

    //Sort feed entries by pubDate

    usort($entries, function ($feed1, $feed2) {
        return strtotime($feed2->pubDate) - strtotime($feed1->pubDate);
    });

    //Find latest date in array         $max = max(array_map('strtotime', $arr));
    $highestdate_entries = date('d-m-Y', max(array_map('strtotime', $entries)));    /* returns format 02-06-2020 */
    $entries_filtered = array_filter($entries, function ($var) use ($highestdate_entries) {

        return date('d-m-Y',(strtotime($var->pubDate))) === $highestdate_entries;       /* -> returns 1 */
    });

    //Reset the array so eg. id 10 moves to id 0
    $entries_filtered = array_values($entries_filtered);
    //Count the amount of items, so the for loop can be adjusted to that
    $numberofitems_entries = count($entries);
    $numberofitems_entries_filtered = count($entries_filtered);
    //echo "Items in entries : " . $numberofitems_entries . "<br>";
    //echo "Items in entries_filtered : " . $numberofitems_entries_filtered . "<br>" ;
    //echo "Latest date in entries : " . $highestdate_entries . "<br>" ;
    //echo strtotime($entries_filtered[0]->pubDate) . " === " . strtotime($dateoftoday);

    // XML feed provides 50 items per feed. Total is 100 items.

    // $dateoffeed=strftime("%d-%m-%y",strtotime($entries[0]->pubDate));
    // echo $dateoftoday;
    // Date format in xml feed:     Thu, 28 May 2020 12:17:38 +0200
    // Date format from date:       Mon, 01 Jun 2020 10:13:48 +0200
    // $dateoftoday=date(DATE_RFC2822);

    function showrssitem($i) {
        global $entries_filtered;
        $backgroundbutton = 'd3d3d3';
        switch ($entries_filtered[$i]->category) {
            case "Chargenrückrufe" :
                $backgroundbutton = 'ff9933';       /* orange */
                break;
            case "Rückrufe" :
                $backgroundbutton = 'ff9933';       /* orange */
                break;
            case "Informationen der Institutionen und Behörden" :
                $backgroundbutton = 'ff3300';       /* red */
                break;
            case "Informationen der Hersteller" :
                $backgroundbutton = 'ff5500';       /* red 2 */
                break;
            case "AMK-PhaGro-Schnellinformationen" :
                $backgroundbutton = 'ff7700';       /* red3  */
                break;
        }

        $strippedentry1 = str_replace ("Online-Nachricht: ","", $entries_filtered[$i]->title);
        $strippedentry2 = str_replace ("Informationen der Institutionen und Behörden: ","", $strippedentry1);
        $strippedentry3 = str_replace ("Informationen der Hersteller: ","", $strippedentry2);
        echo '<td style = "border=0px !important; width:20%"><a style="text-decoration: none;" target="_blank" href="' . $entries_filtered[$i]->link . '"><button style="background-color: #' . $backgroundbutton . '; margin-bottom: 0px; width: 100%; height:50px; display: block; border-radius: 10px;">' . $entries_filtered[$i]->category . '</button></a></td>';
        echo "<td><i>" . strftime('%d/%m/%Y', strtotime($entries_filtered[$i]->pubDate)) . ":</i>&nbsp;&nbsp;&nbsp;";
        echo mb_strimwidth($strippedentry3,0,200,"...") . '</td>';
    }

    ?>


问:
TypeScript type inference issue with string literal
In a react-native application, I have the style

```<code>const styles = StyleSheet.create({
    text: {
        textAlign: "center"
    },
})
</code>```

used in <Text style={styles.text} />, but the tsc compiler gives the following error:

```<code>Types of property 'textAlign' are incompatible.
Type 'string' is not assignable to type '"center" | "auto" | "left" | "right"'.
</code>```

The definition of TextStyle in @types/react-native includes:

```<code>export interface TextStyle extends TextStyleIOS, TextStyleAndroid,
ViewStyle {
    // ...
    textAlign?: "auto" | "left" | "right" | "center"
    // ...
}
</code>```

Why is the compiler complaining about incompatibility? It seems that it is inferring the type of textAlign to be the too general string instead of checking the actual value ("center").

I know that I can use a as TextStyle to avoid the problem, but I would like to know why it is happening and if I should file a ticket against the compiler.

答:
Another option whould be:</p>

```<code>import { TextAlignProperty } from 'csstype'

const styles = StyleSheet.create({
    text: {
        textAlign: "center" as TextAlignProperty
    },
})
</code>```

Body:
In a react-native application, I have the style

const styles = StyleSheet.create({
    text: {
        textAlign: "center"
    },
})

used in <Text style={styles.text} />, but the tsc compiler gives the following error:

Types of property 'textAlign' are incompatible.
Type 'string' is not assignable to type '"center" | "auto" | "left" | "right"'.

The definition of TextStyle in @types/react-native includes:

export interface TextStyle extends TextStyleIOS, TextStyleAndroid,
ViewStyle {
    // ...
    textAlign?: "auto" | "left" | "right" | "center"
    // ...
}

Why is the compiler complaining about incompatibility? It seems that it is inferring the type of textAlign to be the too general string instead of checking the actual value ("center").

I know that I can use a as TextStyle to avoid the problem, but I would like to know why it is happening and if I should file a ticket against the compiler.

Body:
Another option whould be:

import { TextAlignProperty } from 'csstype'

const styles = StyleSheet.create({
    text: {
        textAlign: "center" as TextAlignProperty
    },
})


问:
React functional component inside a loop calls api only returns the response for last element passed on api
Parent component

```<code>  data.map(eachData => (
     <ChildComponent
     key={eachData.id}
     child={eachData}
     />
  ))
</code>```

Child Component

props.getChildData({id: id}); code calls Redux action and store it in a reducer

```<code>function ChildComponent(props) {
const [id, setId] = React.useState(props.eachData.id)
useEffect(() => {
    let handler
    (function () {
      handler = setTimeout(() => {
        props.getChildData({id: id})
      }, 1000)
    })();
    return () => {
      clearTimeout(handler)
    }
  }, [id])

}
</code>```

Api calls are happening and verified in the network tab. Redux store returns only the api response has last api response

答:
You are incorrectly accessing the id in child component.
The id is inside props.child and not props.eachData
So change the useState to access id like this:

```<code>const [id, setId] = React.useState(props.child.id);
</code>```

And it will work fine.

Body:
Parent component

  data.map(eachData => (
     <ChildComponent
     key={eachData.id}
     child={eachData}
     />
  ))

Child Component

props.getChildData({id: id}); code calls Redux action and store it in a reducer

function ChildComponent(props) {
const [id, setId] = React.useState(props.eachData.id)
useEffect(() => {
    let handler
    (function () {
      handler = setTimeout(() => {
        props.getChildData({id: id})
      }, 1000)
    })();
    return () => {
      clearTimeout(handler)
    }
  }, [id])

}

Api calls are happening and verified in the network tab. Redux store returns only the api response has last api response

Body:
You are incorrectly accessing the id in child component.
The id is inside props.child and not props.eachData
So change the useState to access id like this:

const [id, setId] = React.useState(props.child.id);

And it will work fine.


问:
Compare Two values using Custom validator in dynamic formArray Angular 7
I have from group "additionalForm" in that i have formArray called "validations"
here the formArray is dynamic which is binding the values to validtionsField array. In the validtionsField array i have three objects in which i have two values which needs to be compared and they are Min-length and Max-Length.

ex. If i enter min length greater then the max length it should give error.

here is code for the above functionality

import {
  Component,
  OnInit,
  Inject
} from "@angular/core";
import {
  FormControl,
  FormArray,
  FormGroup,
  FormBuilder,
  Validators,
  AbstractControl,
  ValidationErrors,
  NgControlStatus,
  ValidatorFn
} from "@angular/forms";
import {
  MatDialogRef,
  MAT_DIALOG_DATA,
  MatSnackBar
} from "@angular/material";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
  validtionsField = [{
      validField: "Min Length",
      type: false,
      fieldType: "input",
      value: 1,
      keyval: "minLength"
    },
    {
      validField: "Max Length",
      type: false,
      fieldType: "input",
      value: 50,
      keyval: "maxLength"
    },
    {
      validField: "DataType",
      type: false,
      fieldType: "dropDown",
      dataTypeList: [],
      dataTypeId: "minLength",
      keyval: "dataTypeId",
      value: 874
    }
  ];

  dataType = [{
      id: 3701,
      localeId: 1,
      tenantId: 1,
      parentCategoryId: null,
      parentContentId: 873,
      name: "Alphabets",
      description: null
    },
    {
      id: 3702,
      localeId: 1,
      tenantId: 1,
      parentCategoryId: null,
      parentContentId: 874,
      name: "Alphanumeric",
      description: null
    }
  ];
  additionalForm: FormGroup = this.fb.group({
    fieldName: ["", [Validators.required]],
    validations: this.fb.array([])
  });

  constructor(public fb: FormBuilder) {}

  ngOnInit() {
    let frmArray = this.additionalForm.get("validations") as FormArray;

    for (let data of this.validtionsField) {
      frmArray.push(this.initSection(data));
    }
  }
  initSection(data) {
    return this.fb.group({
      validField: [data.validField, [Validators.required]],
      type: [data.type, [Validators.required]],
      value: [data.value, [Validators.required]],
      dataTypeList: [this.dataType, [Validators.required]],
      fieldType: [data.fieldType, [Validators.required]],
      validArray: []
    }, {
      validator: this.customValidator
    });
  }

  checkFieldType(data): any {
    return data === "dropDown";
  }

  // trying to access using below functioa to compare values min and max length
  public customValidator(control: AbstractControl): ValidationErrors | null {
    const newValue = control.get("value") ? control.get("value").value : null;
    const values = control.get("value") ? control.get("value").value : [];
    console.log("1 " + newValue);
    console.log(values);
    for (let i = 0, j = values.length; i < j; i++) {
      if (newValue === values[i]) {
        return {
          duplicate2: true
        };
      }
    }
    return null;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form [formGroup]="additionalForm">
  <mat-form-field>
    <input formControlName='fieldName' placeholder="Field Name" required matInput>
  </mat-form-field>
  <div class="row">
    <div class="col-md-12 col-sm-12">
      \
      <div formArrayName="validations">
        <ng-container *ngFor="let validationForm of  additionalForm.controls.validations.controls; let i = index">
          <div class="valid-data" [formGroupName]="i">
            <span>
                  <label>{{validationForm.value.validField }}</label>

                </span>
            <span>
                  <ng-container *ngIf="checkFieldType(validationForm.value.fieldType ); else input">
                    <mat-form-field class="select-dataType">
                      <mat-select required formControlName='value'  placeholder="Datatype">
                        <mat-option *ngFor="let fieldTypeData of validationForm.value.dataTypeList"
                          [value]='fieldTypeData.parentContentId'>
                          {{fieldTypeData.name}}</mat-option>
                      </mat-select>
                    </mat-form-field>
                  </ng-container>
                  <ng-template #input>
                    <mat-form-field>
                      <input required  formControlName='value' pattern= "[0-9]+" matInput>
                    </mat-form-field>
                  </ng-template>
                </span>
            <div *ngIf="validationForm.get('value')?.touched ">
              <div class="error" *ngIf="validationForm.get('value').hasError('required')">
                {{validationForm.value.validField}} is required
              </div>
            </div>
          </div>
        </ng-container>
      </div>
    </div>
  </div>
</form></code>```

above is the TS and HTML code and below is the function which i am trying to get old and new value from control but its failing, its giving me value from same input field from same min-length

/// trying this below functio to compare the min and max length.

public customValidator(control: AbstractControl): ValidationErrors | null {
  const newValue = control.get('value') ? control.get('value').value : null;
  const values = control.get('value') ? control.get('value').value : [];
  console.log("1 " + newValue);
  console.log(values);
  for (let i = 0, j = values.length; i < j; i++) {
    if (newValue === values[i]) {
      return {
        'duplicate2': true
      };
    }
  }
  return null;
}```

Please help me to compare values from dynamic form array, and here what ever values enters to from-array object are all bind to formcontrolName "value"

here is the link for code :

https://stackblitz.com/edit/angular6-material-components-demo-wgtafn

答:
Since you have two fields minLength & maxLength which validation depends on each other, you can add a validator to the parent group and use a custom ErrorStateMatcher to translate the parent group errors to the children. I also used a FormGroup instead of FormArray, in this case it's more convenient.

@Component({...})
export class AppComponent {
  ...

  readonly invalidLengthMatcher: ErrorStateMatcher = {
    isErrorState: () => {
      const control = this.additionalForm.get('validations');
      return control.hasError('invalidLength');
    }
  };

  readonly controlFields = this.validtionsField.map(field => ({
    field,
    control: new FormControl(field.value, Validators.required),
    errorMatcher: this.errorMatcherByFieldId(field.keyval)
  }));

  private readonly controlMap = this.controlFields.reduce((controls, controlField) => {
    controls[controlField.field.keyval] = controlField.control;
    return controls;
  }, {});

  readonly additionalForm = new FormGroup({
    fieldName: new FormControl("", [Validators.required]),
    validations: new FormGroup(this.controlMap, {
      validators: (group: FormGroup) => {
        const [minLength, maxLength] = ['minLength', 'maxLength'].map(fieldId => {
          const control = group.get(fieldId);
          return Number(control.value);
        });

        if (minLength > maxLength) {
          return {
            'invalidLength': true
          };
        } else {
          return null;
        }
      }
    })
  });

  private errorMatcherByFieldId(fieldId: string): ErrorStateMatcher | undefined {
    switch (fieldId) {
      case 'minLength':
      case 'maxLength':
        return this.invalidLengthMatcher;
    }
  }
}
```

<pre class="lang-html prettyprint-override"><code><form [formGroup]="additionalForm">
  <mat-form-field>
    <input formControlName='fieldName' placeholder="Field Name" required matInput>
  </mat-form-field>
  <div class="row">
    <div class="col-md-12 col-sm-12">
      <div formGroupName="validations" >
        <div *ngFor="let controlField of controlFields" class="valid-data">
          <span>
            <label>{{controlField.field.validField}}</label>
          </span>
          <span [ngSwitch]="controlField.field.fieldType">
            <mat-form-field *ngSwitchCase="'dropDown'" class="select-dataType">
              <mat-select required placeholder="Datatype" [formControlName]="controlField.field.keyval">
                <mat-option *ngFor="let fieldTypeData of dataType"
                            [value]='fieldTypeData.parentContentId'>{{fieldTypeData.name}}</mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field *ngSwitchCase="'input'">
              <input matInput
                      required
                      type="number"
                      pattern= "[0-9]+"
                      [formControlName]="controlField.field.keyval"
                      [errorStateMatcher]="controlField.errorMatcher">
            </mat-form-field>
          </span>
          ...
        </div>
      </div>
    </div>
  </div>
</form>
</code>```

StackBlitz

Body:
I have from group "additionalForm" in that i have formArray called "validations"
here the formArray is dynamic which is binding the values to validtionsField array. In the validtionsField array i have three objects in which i have two values which needs to be compared and they are Min-length and Max-Length.

ex. If i enter min length greater then the max length it should give error.

here is code for the above functionality

import {
  Component,
  OnInit,
  Inject
} from "@angular/core";
import {
  FormControl,
  FormArray,
  FormGroup,
  FormBuilder,
  Validators,
  AbstractControl,
  ValidationErrors,
  NgControlStatus,
  ValidatorFn
} from "@angular/forms";
import {
  MatDialogRef,
  MAT_DIALOG_DATA,
  MatSnackBar
} from "@angular/material";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
  validtionsField = [{
      validField: "Min Length",
      type: false,
      fieldType: "input",
      value: 1,
      keyval: "minLength"
    },
    {
      validField: "Max Length",
      type: false,
      fieldType: "input",
      value: 50,
      keyval: "maxLength"
    },
    {
      validField: "DataType",
      type: false,
      fieldType: "dropDown",
      dataTypeList: [],
      dataTypeId: "minLength",
      keyval: "dataTypeId",
      value: 874
    }
  ];

  dataType = [{
      id: 3701,
      localeId: 1,
      tenantId: 1,
      parentCategoryId: null,
      parentContentId: 873,
      name: "Alphabets",
      description: null
    },
    {
      id: 3702,
      localeId: 1,
      tenantId: 1,
      parentCategoryId: null,
      parentContentId: 874,
      name: "Alphanumeric",
      description: null
    }
  ];
  additionalForm: FormGroup = this.fb.group({
    fieldName: ["", [Validators.required]],
    validations: this.fb.array([])
  });

  constructor(public fb: FormBuilder) {}

  ngOnInit() {
    let frmArray = this.additionalForm.get("validations") as FormArray;

    for (let data of this.validtionsField) {
      frmArray.push(this.initSection(data));
    }
  }
  initSection(data) {
    return this.fb.group({
      validField: [data.validField, [Validators.required]],
      type: [data.type, [Validators.required]],
      value: [data.value, [Validators.required]],
      dataTypeList: [this.dataType, [Validators.required]],
      fieldType: [data.fieldType, [Validators.required]],
      validArray: []
    }, {
      validator: this.customValidator
    });
  }

  checkFieldType(data): any {
    return data === "dropDown";
  }

  // trying to access using below functioa to compare values min and max length
  public customValidator(control: AbstractControl): ValidationErrors | null {
    const newValue = control.get("value") ? control.get("value").value : null;
    const values = control.get("value") ? control.get("value").value : [];
    console.log("1 " + newValue);
    console.log(values);
    for (let i = 0, j = values.length; i < j; i++) {
      if (newValue === values[i]) {
        return {
          duplicate2: true
        };
      }
    }
    return null;
  }
}

<form [formGroup]="additionalForm">
  <mat-form-field>
    <input formControlName='fieldName' placeholder="Field Name" required matInput>
  </mat-form-field>

      \

        <ng-container *ngFor="let validationForm of  additionalForm.controls.validations.controls; let i = index">

                  {{validationForm.value.validField }}

                  <ng-container *ngIf="checkFieldType(validationForm.value.fieldType ); else input">
                    <mat-form-field class="select-dataType">
                      <mat-select required formControlName='value'  placeholder="Datatype">
                        <mat-option *ngFor="let fieldTypeData of validationForm.value.dataTypeList"
                          [value]='fieldTypeData.parentContentId'>
                          {{fieldTypeData.name}}</mat-option>
                      </mat-select>
                    </mat-form-field>
                  </ng-container>
                  <ng-template #input>
                    <mat-form-field>
                      <input required  formControlName='value' pattern= "[0-9]+" matInput>
                    </mat-form-field>
                  </ng-template>

                {{validationForm.value.validField}} is required

        </ng-container>

</form>

above is the TS and HTML code and below is the function which i am trying to get old and new value from control but its failing, its giving me value from same input field from same min-length

/// trying this below functio to compare the min and max length.

public customValidator(control: AbstractControl): ValidationErrors | null {
  const newValue = control.get('value') ? control.get('value').value : null;
  const values = control.get('value') ? control.get('value').value : [];
  console.log("1 " + newValue);
  console.log(values);
  for (let i = 0, j = values.length; i < j; i++) {
    if (newValue === values[i]) {
      return {
        'duplicate2': true
      };
    }
  }
  return null;
}

Please help me to compare values from dynamic form array, and here what ever values enters to from-array object are all bind to formcontrolName "value"

here is the link for code :

https://stackblitz.com/edit/angular6-material-components-demo-wgtafn

Body:
Since you have two fields minLength & maxLength which validation depends on each other, you can add a validator to the parent group and use a custom ErrorStateMatcher to translate the parent group errors to the children. I also used a FormGroup instead of FormArray, in this case it's more convenient.

@Component({...})
export class AppComponent {
  ...

  readonly invalidLengthMatcher: ErrorStateMatcher = {
    isErrorState: () => {
      const control = this.additionalForm.get('validations');
      return control.hasError('invalidLength');
    }
  };

  readonly controlFields = this.validtionsField.map(field => ({
    field,
    control: new FormControl(field.value, Validators.required),
    errorMatcher: this.errorMatcherByFieldId(field.keyval)
  }));

  private readonly controlMap = this.controlFields.reduce((controls, controlField) => {
    controls[controlField.field.keyval] = controlField.control;
    return controls;
  }, {});

  readonly additionalForm = new FormGroup({
    fieldName: new FormControl("", [Validators.required]),
    validations: new FormGroup(this.controlMap, {
      validators: (group: FormGroup) => {
        const [minLength, maxLength] = ['minLength', 'maxLength'].map(fieldId => {
          const control = group.get(fieldId);
          return Number(control.value);
        });

        if (minLength > maxLength) {
          return {
            'invalidLength': true
          };
        } else {
          return null;
        }
      }
    })
  });

  private errorMatcherByFieldId(fieldId: string): ErrorStateMatcher | undefined {
    switch (fieldId) {
      case 'minLength':
      case 'maxLength':
        return this.invalidLengthMatcher;
    }
  }
}

<form [formGroup]="additionalForm">
  <mat-form-field>
    <input formControlName='fieldName' placeholder="Field Name" required matInput>
  </mat-form-field>
  <div class="row">
    <div class="col-md-12 col-sm-12">
      <div formGroupName="validations" >
        <div *ngFor="let controlField of controlFields" class="valid-data">
          <span>
            <label>{{controlField.field.validField}}</label>
          </span>
          <span [ngSwitch]="controlField.field.fieldType">
            <mat-form-field *ngSwitchCase="'dropDown'" class="select-dataType">
              <mat-select required placeholder="Datatype" [formControlName]="controlField.field.keyval">
                <mat-option *ngFor="let fieldTypeData of dataType"
                            [value]='fieldTypeData.parentContentId'>{{fieldTypeData.name}}</mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field *ngSwitchCase="'input'">
              <input matInput
                      required
                      type="number"
                      pattern= "[0-9]+"
                      [formControlName]="controlField.field.keyval"
                      [errorStateMatcher]="controlField.errorMatcher">
            </mat-form-field>
          </span>
          ...
        </div>
      </div>
    </div>
  </div>
</form>

StackBlitz