问:
How to make a realtime chart with Highcharts, Firebase, ReactJS with Typescript?
I need to create a graph in real time getting data from Firebase. I'm using ReactJs with typescript along with Highcharts.
I've already managed to simulate Highcharts in real time, but now I'm wondering how I can connect it to get the data that will be added to Firebase.

Global Graph Component:

```<code>import * as Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';

import HighchartsMore from 'highcharts/highcharts-more';
import HighchartsAccessibility from 'highcharts/modules/accessibility';
import HighchartsData from 'highcharts/modules/data';
import HighchartsExporting from 'highcharts/modules/exporting';
import HighchartsHeatmap from 'highcharts/modules/heatmap';
import HighchartsTreeChart from 'highcharts/modules/treemap';

import { defaultTheme } from '../../../styles/themes';

HighchartsAccessibility(Highcharts);
HighchartsMore(Highcharts);
HighchartsData(Highcharts);
HighchartsHeatmap(Highcharts);
HighchartsTreeChart(Highcharts);
HighchartsExporting(Highcharts);

interface IChartProps {
    options: Highcharts.Options;
}

export const labelsStyle = (
    fontSize = 20,
    color = defaultTheme.palette.grey[900]
) => ({
    color,
    fontSize: `${fontSize / 16}rem`,
    fontFamily: 'Poppins',
    margin: '0px',
    fontWeight: 400,
    lineHeight: `${(fontSize + 10) / 16}rem`,
});

export const Chart: React.FC<IChartProps> = ({ options }) => {
    Highcharts.setOptions({
        // rangeSelector: {
        //  enabled: false,
        // },
        // navigator: {
        //  enabled: false,
        // },
        xAxis: {
            labels: {
                style: labelsStyle(),
            },
        },
        yAxis: {
            labels: {
                style: labelsStyle(18, defaultTheme.palette.grey[200]),
            },
        },
        credits: {
            enabled: false,
        },
        exporting: {
            enabled: false,
        },
    });

    return <HighchartsReact highcharts={Highcharts} options={options} />;
};
</code>```

Realtime Graph Component:

```<code>import { TooltipFormatterContextObject } from 'highcharts';
import {
    Chart,
    labelsStyle,
} from '../../../../shared/components/DataDisplay/Chart';
import { defaultTheme } from '../../../../shared/styles/themes';
import { formatDate } from '../../../../shared/utils/date';
import { getRandomIntInclusive } from '../../../../shared/utils/math';

export const GraphHeartRateMonitor: React.FC = () => {
    const analyticsDataState = {
        dates: [],
        data: [],
    };

    const options: Highcharts.Options = {
        chart: {
            borderWidth: 0,
            height: '176px',
            plotBackgroundColor: defaultTheme.palette.background.default,
            type: 'line',
            marginRight: 10,
            events: {
                load() {
                    const series = this.series[0];
                    setInterval(function () {
                        const x = new Date().getTime(), // current time
                            y = getRandomIntInclusive(80, 120);
                        series.addPoint([x, y], true, true);
                    }, 1000);
                },
            },
        },
        title: {
            text: '',
        },
        xAxis: {
            type: 'datetime',
            tickPixelInterval: 300,
            labels: {
                enabled: false,
            },
        },
        yAxis: {
            title: {
                text: '',
            },
            gridLineColor: defaultTheme.palette.background.default,
            tickInterval: 10,
            labels: {
                enabled: false,
            },
            plotLines: [
                {
                    value: 120,
                    color: defaultTheme.palette.red[300],
                    width: 2,
                    label: {
                        text: '120',
                        useHTML: true,
                        verticalAlign: 'middle',
                        align: 'left',
                        style: {
                            background: defaultTheme.palette.red[300],
                            borderRadius: '24px',
                            height: '18px',
                            padding: '2px 12px',
                            color: defaultTheme.palette.common.white,
                            fontFamily: 'Roboto Mono',
                            fontSize: '12px',
                            fontWeight: '400',
                        },
                    },
                },
            ],
            // lineColor: defaultTheme.palette.background.default,
        },
        legend: {
            enabled: false,
        },
        exporting: {
            enabled: false,
        },
        series: [
            {
                name: 'Random data',
                color: defaultTheme.palette.grey[900],
                data: (function () {
                    // generate an array of random data
                    let data = [],
                        time = new Date().getTime(),
                        i;

                    for (i = -19; i <= 0; i++) {
                        data.push({
                            x: time + i * 1000,
                            y: getRandomIntInclusive(80, 120),
                        });
                    }
                    return data;
                })(),
            },
        ],
        tooltip: {
            useHTML: true,
            backgroundColor: defaultTheme.palette.background.paper,
            borderRadius: 4,
            shadow: {
                color: defaultTheme.palette.common.black,
            },
            padding: 12,
            style: labelsStyle(20, defaultTheme.palette.grey[300]),
            formatter() {
                const self: TooltipFormatterContextObject = this;

                return `
          <span> Time:</span>
          <strong>${formatDate(new Date(self.x), 'HH:mm:ss')}</strong>

          </br>
          <span>Heart Rate:</span>
          <strong >${self.y} bpm</strong>
        `;
            },
        },
    };
    return <Chart options={options} />;
};
</code>```

To call the component just call as a normal component <GraphHeartRateMonitor /> .

Body:
I need to create a graph in real time getting data from Firebase. I'm using ReactJs with typescript along with Highcharts.
I've already managed to simulate Highcharts in real time, but now I'm wondering how I can connect it to get the data that will be added to Firebase.

Global Graph Component:

import * as Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';

import HighchartsMore from 'highcharts/highcharts-more';
import HighchartsAccessibility from 'highcharts/modules/accessibility';
import HighchartsData from 'highcharts/modules/data';
import HighchartsExporting from 'highcharts/modules/exporting';
import HighchartsHeatmap from 'highcharts/modules/heatmap';
import HighchartsTreeChart from 'highcharts/modules/treemap';

import { defaultTheme } from '../../../styles/themes';

HighchartsAccessibility(Highcharts);
HighchartsMore(Highcharts);
HighchartsData(Highcharts);
HighchartsHeatmap(Highcharts);
HighchartsTreeChart(Highcharts);
HighchartsExporting(Highcharts);

interface IChartProps {
    options: Highcharts.Options;
}

export const labelsStyle = (
    fontSize = 20,
    color = defaultTheme.palette.grey[900]
) => ({
    color,
    fontSize: `${fontSize / 16}rem`,
    fontFamily: 'Poppins',
    margin: '0px',
    fontWeight: 400,
    lineHeight: `${(fontSize + 10) / 16}rem`,
});

export const Chart: React.FC<IChartProps> = ({ options }) => {
    Highcharts.setOptions({
        // rangeSelector: {
        //  enabled: false,
        // },
        // navigator: {
        //  enabled: false,
        // },
        xAxis: {
            labels: {
                style: labelsStyle(),
            },
        },
        yAxis: {
            labels: {
                style: labelsStyle(18, defaultTheme.palette.grey[200]),
            },
        },
        credits: {
            enabled: false,
        },
        exporting: {
            enabled: false,
        },
    });

    return <HighchartsReact highcharts={Highcharts} options={options} />;
};

Realtime Graph Component:

import { TooltipFormatterContextObject } from 'highcharts';
import {
    Chart,
    labelsStyle,
} from '../../../../shared/components/DataDisplay/Chart';
import { defaultTheme } from '../../../../shared/styles/themes';
import { formatDate } from '../../../../shared/utils/date';
import { getRandomIntInclusive } from '../../../../shared/utils/math';

export const GraphHeartRateMonitor: React.FC = () => {
    const analyticsDataState = {
        dates: [],
        data: [],
    };

    const options: Highcharts.Options = {
        chart: {
            borderWidth: 0,
            height: '176px',
            plotBackgroundColor: defaultTheme.palette.background.default,
            type: 'line',
            marginRight: 10,
            events: {
                load() {
                    const series = this.series[0];
                    setInterval(function () {
                        const x = new Date().getTime(), // current time
                            y = getRandomIntInclusive(80, 120);
                        series.addPoint([x, y], true, true);
                    }, 1000);
                },
            },
        },
        title: {
            text: '',
        },
        xAxis: {
            type: 'datetime',
            tickPixelInterval: 300,
            labels: {
                enabled: false,
            },
        },
        yAxis: {
            title: {
                text: '',
            },
            gridLineColor: defaultTheme.palette.background.default,
            tickInterval: 10,
            labels: {
                enabled: false,
            },
            plotLines: [
                {
                    value: 120,
                    color: defaultTheme.palette.red[300],
                    width: 2,
                    label: {
                        text: '120',
                        useHTML: true,
                        verticalAlign: 'middle',
                        align: 'left',
                        style: {
                            background: defaultTheme.palette.red[300],
                            borderRadius: '24px',
                            height: '18px',
                            padding: '2px 12px',
                            color: defaultTheme.palette.common.white,
                            fontFamily: 'Roboto Mono',
                            fontSize: '12px',
                            fontWeight: '400',
                        },
                    },
                },
            ],
            // lineColor: defaultTheme.palette.background.default,
        },
        legend: {
            enabled: false,
        },
        exporting: {
            enabled: false,
        },
        series: [
            {
                name: 'Random data',
                color: defaultTheme.palette.grey[900],
                data: (function () {
                    // generate an array of random data
                    let data = [],
                        time = new Date().getTime(),
                        i;

                    for (i = -19; i <= 0; i++) {
                        data.push({
                            x: time + i * 1000,
                            y: getRandomIntInclusive(80, 120),
                        });
                    }
                    return data;
                })(),
            },
        ],
        tooltip: {
            useHTML: true,
            backgroundColor: defaultTheme.palette.background.paper,
            borderRadius: 4,
            shadow: {
                color: defaultTheme.palette.common.black,
            },
            padding: 12,
            style: labelsStyle(20, defaultTheme.palette.grey[300]),
            formatter() {
                const self: TooltipFormatterContextObject = this;

                return `
           Time:
          ${formatDate(new Date(self.x), 'HH:mm:ss')}

          Heart Rate:
          ${self.y} bpm
        `;
            },
        },
    };
    return <Chart options={options} />;
};

To call the component just call as a normal component <GraphHeartRateMonitor /> .


来源: stackexchange

问:
Redirect stdout to a file in python not entirely working
I have following setup:

parent.py:

```<code>from mpi4py import MPI

comm = MPI.COMM_WORLD

for i in range(10):

    print(something)

    child_comm = MPI.COMM_WORLD.Spawn(sys.executable, "child.py", maxprocs=9)
    child_comm.Disconnect()
</code>```

child.py:

```<code>import sys

sys.stdout = open("analysis_log.txt", "a")

# code related to running a solver

sys.stdout.close()

</code>```

The child.py is running a solver and prints a lot of stuff on terminal. I want to redirect only the output from child.py file. So, I cannot use python parent.py >> analysis_log.txt. Instead, I am assigning stdout to a file. But, the output is not redirected to the file and it still prints in terminal. The solver provides a python interface for working with it but it is using compiled fortran files for performing calculations, along with fortran write and print statements to output on terminal.

So, I am guessing that setting sys.stdout will only redirect the python print statements and not fortran stdout. I checked lot of other questions on this topis on stack overflow, but most of them suggest using open or contextlib.redirect_stdout. I tried the context redirection also, but it still prints in the terminal.

So, how to resolve this problem? Why is it that terminal redirection (>>) works, but setting sys.stdout is not working fully?

Please help!

Python: 3.8.13

ContentLicense: CC BY-SA 4.0

Body:
I have following setup:

parent.py:

from mpi4py import MPI

comm = MPI.COMM_WORLD

for i in range(10):

    print(something)

    child_comm = MPI.COMM_WORLD.Spawn(sys.executable, "child.py", maxprocs=9)
    child_comm.Disconnect()

child.py:

import sys

sys.stdout = open("analysis_log.txt", "a")

# code related to running a solver

sys.stdout.close()

The child.py is running a solver and prints a lot of stuff on terminal. I want to redirect only the output from child.py file. So, I cannot use python parent.py >> analysis_log.txt. Instead, I am assigning stdout to a file. But, the output is not redirected to the file and it still prints in terminal. The solver provides a python interface for working with it but it is using compiled fortran files for performing calculations, along with fortran write and print statements to output on terminal.

So, I am guessing that setting sys.stdout will only redirect the python print statements and not fortran stdout. I checked lot of other questions on this topis on stack overflow, but most of them suggest using open or contextlib.redirect_stdout. I tried the context redirection also, but it still prints in the terminal.

So, how to resolve this problem? Why is it that terminal redirection (>>) works, but setting sys.stdout is not working fully?

Please help!

Python: 3.8.13


问:
How do I find the XPATH of a certain element from a headless browser?
I'm accessing Google images with a headless linux chromeDriver browser. Here are my headers:

`

```<code>            headers = ({'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit\
            /537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'})
</code>```

`

I'm downloading an image from an XPATH. My script works fine on my desktop. But as I cronjob this script from a linux server with a headless Linux chromeDriver browser, it's downloading an image from a different XPATH.

The problem is that I can't manually see which XPATH the script is downloading whilst on the Linux server.

However, I'm certain this is a "browser" problem because I understand that XPATHs are different between browsers. Are my headers (above) telling my script to use Firefox? Am I actually using Chrome?

On my desktop, I'm running Chrome 108 on macOS (Big Sur) and my script works fine.

Tried:

```<code>            # Finding 2nd image

            small_image = browser.find_element('xpath',"//*[@id='islrg']/div[1]/div[2]")

            print("Clicking...")
            small_image.click()
            time.sleep(2)

            # Expanding image to full resolution

            big_image = browser.find_element('xpath',"//*[@id='Sva75c']/div[2]/div/div[2]/div[2]/div[2]/c-wiz/div[2]/div[1]/div[1]/div[2]/div/a/img")
            time.sleep(5)

            # Download image

            imageURL= big_image.get_attribute('src')
</code>```

Actual result:

got attribute('src) of SMALL_IMAGE instead of BIG_IMAGE, from what I can see.

Body:
I'm accessing Google images with a headless linux chromeDriver browser. Here are my headers:

`

            headers = ({'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit\
            /537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'})

`

I'm downloading an image from an XPATH. My script works fine on my desktop. But as I cronjob this script from a linux server with a headless Linux chromeDriver browser, it's downloading an image from a different XPATH.

The problem is that I can't manually see which XPATH the script is downloading whilst on the Linux server.

However, I'm certain this is a "browser" problem because I understand that XPATHs are different between browsers. Are my headers (above) telling my script to use Firefox? Am I actually using Chrome?

On my desktop, I'm running Chrome 108 on macOS (Big Sur) and my script works fine.

Tried:

            # Finding 2nd image

            small_image = browser.find_element('xpath',"//*[@id='islrg']/div[1]/div[2]")

            print("Clicking...")
            small_image.click()
            time.sleep(2)

            # Expanding image to full resolution

            big_image = browser.find_element('xpath',"//*[@id='Sva75c']/div[2]/div/div[2]/div[2]/div[2]/c-wiz/div[2]/div[1]/div[1]/div[2]/div/a/img")
            time.sleep(5)

            # Download image

            imageURL= big_image.get_attribute('src')

Actual result:

got attribute('src) of SMALL_IMAGE instead of BIG_IMAGE, from what I can see.


问:
How to add custom bias/offset in modeling neural network through neuralnet in R?
I have a code for a neural network model which uses keras.

```<code>features <- layer_input ( shape=c(ncol(feature_matrix)))
net <- features %>%
  layer_dense(units=q,activation='tanh') %>%
  layer_dense(units=1,activation=k_exp)
volumes <- layer_input(shape=c(1))
offset <- volumes %>%
  layer_dense(units=1,activation='linear',use_bias=FALSE,trainable=FALSE,
              weights=list(array(1,dim=c(1,1))))
merged <- list(net,offset) %>%
  layer_multiply()
model <- keras_model(inputs=list(features,volumes),outputs=merged)
model %>% compile(loss='mse',optimizer='rmsprop')

fit <- model %>% fit(list(feature_matrix,offset_matrix),response_matrix,epochs=100,
                     batch_size=10000,validation_split=0.1)
</code>```

However, I cannot find a way to display the network architecture with keras. I want to redefine my neural network using the neuralnet package instead.

I just encountered neuralnet and am clueless on where I should insert the custom bias/offset that I have.

Its usage is given by

```<code>neuralnet(formula, data, hidden = 1, threshold = 0.01,
  stepmax = 1e+05, rep = 1, startweights = NULL,
  learningrate.limit = NULL, learningrate.factor = list(minus = 0.5,
  plus = 1.2), learningrate = NULL, lifesign = "none",
  lifesign.step = 1000, algorithm = "rprop+", err.fct = "sse",
  act.fct = "logistic", linear.output = TRUE, exclude = NULL,
  constant.weights = NULL, likelihood = FALSE)
</code>```

How do I do that?

Body:
I have a code for a neural network model which uses keras.

features <- layer_input ( shape=c(ncol(feature_matrix)))
net <- features %>%
  layer_dense(units=q,activation='tanh') %>%
  layer_dense(units=1,activation=k_exp)
volumes <- layer_input(shape=c(1))
offset <- volumes %>%
  layer_dense(units=1,activation='linear',use_bias=FALSE,trainable=FALSE,
              weights=list(array(1,dim=c(1,1))))
merged <- list(net,offset) %>%
  layer_multiply()
model <- keras_model(inputs=list(features,volumes),outputs=merged)
model %>% compile(loss='mse',optimizer='rmsprop')

fit <- model %>% fit(list(feature_matrix,offset_matrix),response_matrix,epochs=100,
                     batch_size=10000,validation_split=0.1)

However, I cannot find a way to display the network architecture with keras. I want to redefine my neural network using the neuralnet package instead.

I just encountered neuralnet and am clueless on where I should insert the custom bias/offset that I have.

Its usage is given by

neuralnet(formula, data, hidden = 1, threshold = 0.01,
  stepmax = 1e+05, rep = 1, startweights = NULL,
  learningrate.limit = NULL, learningrate.factor = list(minus = 0.5,
  plus = 1.2), learningrate = NULL, lifesign = "none",
  lifesign.step = 1000, algorithm = "rprop+", err.fct = "sse",
  act.fct = "logistic", linear.output = TRUE, exclude = NULL,
  constant.weights = NULL, likelihood = FALSE)

How do I do that?


问:
Is there a way to use Socket.io for Private Server-client communication?
I am currently working on a project that requires server/client communication, but not with other connected people (a private building game). Anyone know?</p>


问:
Why is my neural network unable to solve MNIST? (debug help)
I have implemented a general neural network framework from scratch, and ensured it is ostensibly doing the right thing by solving the XOR problem (I have done so with both 1 and more hidden layers to ensure I don't have a bug in my multi-hidden layer implementation).

I've also implemented my own Matrix math library from scratch (more as an exercise in matrix math as a precursor to understanding the NN math rather than for lightweight reasons).

So now I am trying to finalise the successful functionality of the framework by trying to solve MNIST with a vector-input network with layers of size {784, 100, 50, 10}, a learning rate of 0.2, and weight initialisation of random float in range {-1, 1} and zero-initialisation of biases.

After training the network on all 60,000 training examples (running backprop for each one, no mini-batching), I'm getting rubbish out. I've verified that I'm not putting rubbish in, however I've written the framework in Java and the training data needs quite a bit of prep for it to be usable.

I have mapped each value {0, 255} between {0.01, 1} using transformation x -> x * (0.99 / 255) + 0.01 to prevent zero-adjustment of biases.

That's the background, I'll dump the code below, hopefully it isn't too terribly written:

Network class

```<code>public class Network {
    int inputNum, outputNum;
    Layer[] layers;
    float cost;
    float learning_rate;

    public Network(int input, int[] hidden, int output, float learning_rate, float weight_bound) {
        this.inputNum = input;
        this.outputNum = output;
        this.layers = new Layer[hidden.length + 1];

        this.learning_rate = learning_rate;

        this.layers[0] = new Layer(input, hidden[0], weight_bound);
        this.layers[this.layers.length - 1] = new Layer(hidden[hidden.length - 1], output, weight_bound);

        for (int i = 1; i < hidden.length; i++) {
            layers[i] = new Layer(hidden[i - 1], hidden[i], weight_bound);
        }
    }

    public Matrix predict(Matrix input) throws DimensionException {
        Matrix currentIn = input;
        for (Layer l : this.layers) {
            currentIn = l.forwardPropogate(currentIn);
        }

        return currentIn;
    }

    public void train(Matrix[] inputs, Matrix[] labels) throws DimensionException {
        for (int i = 0; i < inputs.length; i++) {
            Matrix currentIn = inputs[i];
            for (Layer l : this.layers) {
                currentIn = l.forwardPropogate(currentIn);
            }

            Matrix error = Matrix.sub(labels[i], currentIn);
            this.cost = Matrix.apply(error, x -> 0.5f * x * x).sum();
            for (int l = this.layers.length - 1; l >= 0; l--) {
                error = this.layers[l].backwardPropogate(error, learning_rate);
            }
        }
    }

    public static float sigmoid(float x) {
        return 1 / (1 + (float) Math.exp(-x));
    }

    public static float dsigmoid(float y) {
        return y * (1 - y);
    }
}
</code>```

Layer class

```<code>import java.util.concurrent.ThreadLocalRandom;

public class Layer {
    Matrix weights;
    Matrix biases;

    Matrix inValues;
    Matrix outValues;

    public Layer(int input_size, int output_size, float init_bound) {
        this.weights = new Matrix(output_size, input_size);
        this.weights.apply(x -> (float) ThreadLocalRandom.current().nextDouble(-init_bound, init_bound));
        this.biases = new Matrix(output_size, 1);

    }

    public Matrix forwardPropogate(Matrix in) throws DimensionException {
        this.inValues = in;
        this.outValues = this.weights.multiply(this.inValues);
        this.outValues.add(this.biases);
        this.outValues.apply(x -> Network.sigmoid(x));

        return outValues;
    }

    public Matrix backwardPropogate(Matrix out_error, float learning_rate) throws DimensionException {
        Matrix errorByDSig = Matrix.apply(this.outValues, x -> Network.dsigmoid(x)).multiply(out_error);

        Matrix weightAdjustment = errorByDSig.multiply(Matrix.transpose(this.inValues));
        weightAdjustment.multiply(learning_rate);

        Matrix biasAdjustment = errorByDSig.copy();
        biasAdjustment.multiply(learning_rate);

        Matrix newError = Matrix.transpose(this.weights).multiply(errorByDSig);

        this.weights.add(weightAdjustment);
        this.biases.add(biasAdjustment);

        return newError;
    }
}
</code>```

Matrix library

```<code>import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;

class Matrix {
    int rows, cols;
    float[][] matrix;

    public Matrix (int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
        this.matrix = new float[this.rows][this.cols];
    }

    public void multiply(float n) {
        this.apply(x -> (float)x * n);
    }

    public Matrix multiply(Matrix m) throws DimensionException {
        Matrix newM;

        if (this.cols == m.cols && this.rows == m.rows) {
            newM = this.copy();
            for (int r = 0; r < m.rows; r++) {
                for (int c = 0; c < m.cols; c++) {
                    newM.matrix[r][c] *= m.matrix[r][c];
                }
            }
            return newM;
        }

        if (this.cols == m.rows) {

            newM = new Matrix(this.rows, m.cols);

            for (int r = 0; r < this.rows; r++) {
                for (int c = 0; c < m.cols; c++) {
                    float sum = 0;
                    for (int s = 0; s < m.rows; s++) {
                        sum += this.matrix[r][s] * m.matrix[s][c];
                    }
                    newM.matrix[r][c] = sum;
                }
            }

            return newM;
        }

        throw new DimensionException("Matrix dimensions are incorrect");

    }

    public void add(float n) {
        this.apply(x -> x + n);
    }

    public void add(Matrix m) throws DimensionException{
        if (this.cols != m.cols || this.rows != m.rows) {
            throw new DimensionException("Matrix dimensions are incorrect");
        }

        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.cols; c++) {
                this.matrix[r][c] += m.matrix[r][c];
            }
        }
    }

    public void sub(float n) {
        this.add(-n);
    }

    public void sub(Matrix m) throws DimensionException {
        this.add(Matrix.apply(m, x -> -x));
    }

    public void apply(Function<Float, Float> f) {
        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.cols; c++) {
                this.matrix[r][c] = f.apply(this.matrix[r][c]);
            }
        }
    }

    public Matrix copy() {
        Matrix m = new Matrix(this.rows, this.cols);
        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.cols; c++) {
                m.matrix[r][c] = this.matrix[r][c];
            }
        }

        return m;
    }

    public String toString() {
        String s = "";
        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.cols; c++) {
                s += Float.toString(this.matrix[r][c]) + " ";
            }
            s += "\n";
        }

        return s;
    }

    public float sum() {
        float total = 0;

        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.cols; c++) {
                total += this.matrix[r][c];
            }
        }

        return total;
    }

    public static Matrix multiply(Matrix m, float n) {
        Matrix newM = m.copy();
        newM.add(n);

        return newM;
    }

    public static Matrix multiply(Matrix m, Matrix n) throws DimensionException {
        Matrix newM = m.copy();
        return newM.multiply(n);
    }

    public static Matrix add(Matrix m, float n) {
        Matrix newM = m.copy();
        newM.apply(x -> x + n);

        return newM;
    }

    public static Matrix add(Matrix m, Matrix n) throws DimensionException {
        Matrix newM = m.copy();
        newM.add(n);

        return newM;
    }

    public static Matrix sub(Matrix m, float n) {
        Matrix newM = m.copy();
        newM.sub(n);

        return newM;
    }

    public static Matrix sub(Matrix m, Matrix n) throws DimensionException {
        Matrix newM = m.copy();
        newM.sub(n);

        return newM;
    }

    public static Matrix apply(Matrix m, Function<Float, Float> f) {
        Matrix newM = m.copy();
        newM.apply(f);

        return newM;
    }

    public static Matrix random(int rows, int cols, int bound) {
        Matrix m = new Matrix(rows, cols);

        m.apply(x -> x + ThreadLocalRandom.current().nextInt(bound));

        return m;
    }

    public static Matrix fromArray(int rows, int cols, float[] array) {
        Matrix newMatrix = new Matrix(rows, cols);

        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                newMatrix.matrix[r][c] = array[r * cols + c];
            }
        }

        return newMatrix;
    }

    public static Matrix transpose(Matrix m) {
        Matrix newMatrix = new Matrix(m.cols, m.rows);

        for (int r = 0; r < m.rows; r++) {
            for (int c = 0; c < m.cols; c++) {
                newMatrix.matrix[c][r] = m.matrix[r][c];
            }
        }

        return newMatrix;

    }
}
</code>```

Training / getting an output

```<code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class tests {
    public static void main(String[] args) throws DimensionException, FileNotFoundException, IOException {
        File training_files = new File("C:/Users/2001b/OneDrive/Desktop/data/data/training");
        File label_file = new File("C:/Users/2001b/OneDrive/Desktop/data/data/labels.csv");

        Matrix[] training_data = new Matrix[60000];
        Matrix[] training_labels = new Matrix[60000];

        int file_count = 0;

        for (File f : training_files.listFiles()) {
            float[] pixels = new float[784];
            int p_count = 0;
            BufferedReader br = new BufferedReader(new FileReader(f));
            String line;
            while ((line = br.readLine()) != null) {
                double[] values = Arrays.stream(line.split(",")).mapToDouble(Double::parseDouble).toArray();
                for (double v : values) {
                    pixels[p_count++] = ((float) v * (0.99f / 255) + 0.01f);
                }
            }
            training_data[file_count++] = Matrix.fromArray(784, 1, pixels);
            br.close();
        }

        BufferedReader br = new BufferedReader(new FileReader(label_file));
        String line;
        int count = 0;
        while ((line = br.readLine()) != null) {
            int value = Integer.valueOf(line);
            Matrix answerMatrix = new Matrix(10, 1);
            answerMatrix.matrix[value][0] = 1;
            training_labels[count++] = answerMatrix;
        }
        br.close();

        System.out.println(training_labels[5]);

        Network network = new Network(784, new int[] {100, 50}, 10, 0.2f, 1);

        network.train(training_data, training_labels);
        System.out.println(network.predict(training_data[5]));
    }
}
</code>```

After training with 10-vector all-zero labels (other than the expected 1), I'm getting output vectors like this:

```<code>0.0629406
0.09087993
0.09197301
0.08965302
0.052927334
0.08770021
0.11267567
0.071576655
0.12798244
0.09146147
</code>```

Any help would be much appreciated

Body:
I have implemented a general neural network framework from scratch, and ensured it is ostensibly doing the right thing by solving the XOR problem (I have done so with both 1 and more hidden layers to ensure I don't have a bug in my multi-hidden layer implementation).

I've also implemented my own Matrix math library from scratch (more as an exercise in matrix math as a precursor to understanding the NN math rather than for lightweight reasons).

So now I am trying to finalise the successful functionality of the framework by trying to solve MNIST with a vector-input network with layers of size {784, 100, 50, 10}, a learning rate of 0.2, and weight initialisation of random float in range {-1, 1} and zero-initialisation of biases.

After training the network on all 60,000 training examples (running backprop for each one, no mini-batching), I'm getting rubbish out. I've verified that I'm not putting rubbish in, however I've written the framework in Java and the training data needs quite a bit of prep for it to be usable.

I have mapped each value {0, 255} between {0.01, 1} using transformation x -> x * (0.99 / 255) + 0.01 to prevent zero-adjustment of biases.

That's the background, I'll dump the code below, hopefully it isn't too terribly written:

Network class

public class Network {
    int inputNum, outputNum;
    Layer[] layers;
    float cost;
    float learning_rate;

    public Network(int input, int[] hidden, int output, float learning_rate, float weight_bound) {
        this.inputNum = input;
        this.outputNum = output;
        this.layers = new Layer[hidden.length + 1];

        this.learning_rate = learning_rate;

        this.layers[0] = new Layer(input, hidden[0], weight_bound);
        this.layers[this.layers.length - 1] = new Layer(hidden[hidden.length - 1], output, weight_bound);

        for (int i = 1; i < hidden.length; i++) {
            layers[i] = new Layer(hidden[i - 1], hidden[i], weight_bound);
        }
    }

    public Matrix predict(Matrix input) throws DimensionException {
        Matrix currentIn = input;
        for (Layer l : this.layers) {
            currentIn = l.forwardPropogate(currentIn);
        }

        return currentIn;
    }

    public void train(Matrix[] inputs, Matrix[] labels) throws DimensionException {
        for (int i = 0; i < inputs.length; i++) {
            Matrix currentIn = inputs[i];
            for (Layer l : this.layers) {
                currentIn = l.forwardPropogate(currentIn);
            }

            Matrix error = Matrix.sub(labels[i], currentIn);
            this.cost = Matrix.apply(error, x -> 0.5f * x * x).sum();
            for (int l = this.layers.length - 1; l >= 0; l--) {
                error = this.layers[l].backwardPropogate(error, learning_rate);
            }
        }
    }

    public static float sigmoid(float x) {
        return 1 / (1 + (float) Math.exp(-x));
    }

    public static float dsigmoid(float y) {
        return y * (1 - y);
    }
}

Layer class

import java.util.concurrent.ThreadLocalRandom;

public class Layer {
    Matrix weights;
    Matrix biases;

    Matrix inValues;
    Matrix outValues;

    public Layer(int input_size, int output_size, float init_bound) {
        this.weights = new Matrix(output_size, input_size);
        this.weights.apply(x -> (float) ThreadLocalRandom.current().nextDouble(-init_bound, init_bound));
        this.biases = new Matrix(output_size, 1);

    }

    public Matrix forwardPropogate(Matrix in) throws DimensionException {
        this.inValues = in;
        this.outValues = this.weights.multiply(this.inValues);
        this.outValues.add(this.biases);
        this.outValues.apply(x -> Network.sigmoid(x));

        return outValues;
    }

    public Matrix backwardPropogate(Matrix out_error, float learning_rate) throws DimensionException {
        Matrix errorByDSig = Matrix.apply(this.outValues, x -> Network.dsigmoid(x)).multiply(out_error);

        Matrix weightAdjustment = errorByDSig.multiply(Matrix.transpose(this.inValues));
        weightAdjustment.multiply(learning_rate);

        Matrix biasAdjustment = errorByDSig.copy();
        biasAdjustment.multiply(learning_rate);

        Matrix newError = Matrix.transpose(this.weights).multiply(errorByDSig);

        this.weights.add(weightAdjustment);
        this.biases.add(biasAdjustment);

        return newError;
    }
}

Matrix library

import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;

class Matrix {
    int rows, cols;
    float[][] matrix;

    public Matrix (int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
        this.matrix = new float[this.rows][this.cols];
    }

    public void multiply(float n) {
        this.apply(x -> (float)x * n);
    }

    public Matrix multiply(Matrix m) throws DimensionException {
        Matrix newM;

        if (this.cols == m.cols && this.rows == m.rows) {
            newM = this.copy();
            for (int r = 0; r < m.rows; r++) {
                for (int c = 0; c < m.cols; c++) {
                    newM.matrix[r][c] *= m.matrix[r][c];
                }
            }
            return newM;
        }

        if (this.cols == m.rows) {

            newM = new Matrix(this.rows, m.cols);

            for (int r = 0; r < this.rows; r++) {
                for (int c = 0; c < m.cols; c++) {
                    float sum = 0;
                    for (int s = 0; s < m.rows; s++) {
                        sum += this.matrix[r][s] * m.matrix[s][c];
                    }
                    newM.matrix[r][c] = sum;
                }
            }

            return newM;
        }

        throw new DimensionException("Matrix dimensions are incorrect");

    }

    public void add(float n) {
        this.apply(x -> x + n);
    }

    public void add(Matrix m) throws DimensionException{
        if (this.cols != m.cols || this.rows != m.rows) {
            throw new DimensionException("Matrix dimensions are incorrect");
        }

        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.cols; c++) {
                this.matrix[r][c] += m.matrix[r][c];
            }
        }
    }

    public void sub(float n) {
        this.add(-n);
    }

    public void sub(Matrix m) throws DimensionException {
        this.add(Matrix.apply(m, x -> -x));
    }

    public void apply(Function<Float, Float> f) {
        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.cols; c++) {
                this.matrix[r][c] = f.apply(this.matrix[r][c]);
            }
        }
    }

    public Matrix copy() {
        Matrix m = new Matrix(this.rows, this.cols);
        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.cols; c++) {
                m.matrix[r][c] = this.matrix[r][c];
            }
        }

        return m;
    }

    public String toString() {
        String s = "";
        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.cols; c++) {
                s += Float.toString(this.matrix[r][c]) + " ";
            }
            s += "\n";
        }

        return s;
    }

    public float sum() {
        float total = 0;

        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.cols; c++) {
                total += this.matrix[r][c];
            }
        }

        return total;
    }

    public static Matrix multiply(Matrix m, float n) {
        Matrix newM = m.copy();
        newM.add(n);

        return newM;
    }

    public static Matrix multiply(Matrix m, Matrix n) throws DimensionException {
        Matrix newM = m.copy();
        return newM.multiply(n);
    }

    public static Matrix add(Matrix m, float n) {
        Matrix newM = m.copy();
        newM.apply(x -> x + n);

        return newM;
    }

    public static Matrix add(Matrix m, Matrix n) throws DimensionException {
        Matrix newM = m.copy();
        newM.add(n);

        return newM;
    }

    public static Matrix sub(Matrix m, float n) {
        Matrix newM = m.copy();
        newM.sub(n);

        return newM;
    }

    public static Matrix sub(Matrix m, Matrix n) throws DimensionException {
        Matrix newM = m.copy();
        newM.sub(n);

        return newM;
    }

    public static Matrix apply(Matrix m, Function<Float, Float> f) {
        Matrix newM = m.copy();
        newM.apply(f);

        return newM;
    }

    public static Matrix random(int rows, int cols, int bound) {
        Matrix m = new Matrix(rows, cols);

        m.apply(x -> x + ThreadLocalRandom.current().nextInt(bound));

        return m;
    }

    public static Matrix fromArray(int rows, int cols, float[] array) {
        Matrix newMatrix = new Matrix(rows, cols);

        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                newMatrix.matrix[r][c] = array[r * cols + c];
            }
        }

        return newMatrix;
    }

    public static Matrix transpose(Matrix m) {
        Matrix newMatrix = new Matrix(m.cols, m.rows);

        for (int r = 0; r < m.rows; r++) {
            for (int c = 0; c < m.cols; c++) {
                newMatrix.matrix[c][r] = m.matrix[r][c];
            }
        }

        return newMatrix;

    }
}

Training / getting an output

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class tests {
    public static void main(String[] args) throws DimensionException, FileNotFoundException, IOException {
        File training_files = new File("C:/Users/2001b/OneDrive/Desktop/data/data/training");
        File label_file = new File("C:/Users/2001b/OneDrive/Desktop/data/data/labels.csv");

        Matrix[] training_data = new Matrix[60000];
        Matrix[] training_labels = new Matrix[60000];

        int file_count = 0;

        for (File f : training_files.listFiles()) {
            float[] pixels = new float[784];
            int p_count = 0;
            BufferedReader br = new BufferedReader(new FileReader(f));
            String line;
            while ((line = br.readLine()) != null) {
                double[] values = Arrays.stream(line.split(",")).mapToDouble(Double::parseDouble).toArray();
                for (double v : values) {
                    pixels[p_count++] = ((float) v * (0.99f / 255) + 0.01f);
                }
            }
            training_data[file_count++] = Matrix.fromArray(784, 1, pixels);
            br.close();
        }

        BufferedReader br = new BufferedReader(new FileReader(label_file));
        String line;
        int count = 0;
        while ((line = br.readLine()) != null) {
            int value = Integer.valueOf(line);
            Matrix answerMatrix = new Matrix(10, 1);
            answerMatrix.matrix[value][0] = 1;
            training_labels[count++] = answerMatrix;
        }
        br.close();

        System.out.println(training_labels[5]);

        Network network = new Network(784, new int[] {100, 50}, 10, 0.2f, 1);

        network.train(training_data, training_labels);
        System.out.println(network.predict(training_data[5]));
    }
}

After training with 10-vector all-zero labels (other than the expected 1), I'm getting output vectors like this:

0.0629406
0.09087993
0.09197301
0.08965302
0.052927334
0.08770021
0.11267567
0.071576655
0.12798244
0.09146147

Any help would be much appreciated


问:
Handler Python Exit Code 1 with OpenAI API
im working with OpenAI API and I want generate a request from a list, but when the request fails the script stops with Exit Code 1 and dont continue with the next in the list. This is the function called from my "For"

```<code>try:
    response = openai.Completion.create(
        engine=config['OPENAI']['engine'].strip(),
        prompt=prompt,
        temperature=float(config['OPENAI']['temperature'].strip()),
        max_tokens=int(config['OPENAI']['max_tokens'].strip()),
        top_p=float(config['OPENAI']['top_p'].strip()),
        frequency_penalty=float(config['OPENAI']['frequency_penalty'].strip()),
        presence_penalty=float(config['OPENAI']['presence_penalty'].strip()),
    )
    with open('./output/openai_log.txt', 'a') as f:
        f.write(prompt + '\n')
        f.write(json.dumps(response, indent=4,) + '\n')
        f.write('-_' * 60 + '\n')
    return response
except openai.APIError as e:
    print(f'\nFailed to generate for: {prompt}', e)
    return None
</code>```

Ive tried with try/catch but fails

Body:
im working with OpenAI API and I want generate a request from a list, but when the request fails the script stops with Exit Code 1 and dont continue with the next in the list. This is the function called from my "For"

try:
    response = openai.Completion.create(
        engine=config['OPENAI']['engine'].strip(),
        prompt=prompt,
        temperature=float(config['OPENAI']['temperature'].strip()),
        max_tokens=int(config['OPENAI']['max_tokens'].strip()),
        top_p=float(config['OPENAI']['top_p'].strip()),
        frequency_penalty=float(config['OPENAI']['frequency_penalty'].strip()),
        presence_penalty=float(config['OPENAI']['presence_penalty'].strip()),
    )
    with open('./output/openai_log.txt', 'a') as f:
        f.write(prompt + '\n')
        f.write(json.dumps(response, indent=4,) + '\n')
        f.write('-_' * 60 + '\n')
    return response
except openai.APIError as e:
    print(f'\nFailed to generate for: {prompt}', e)
    return None

Ive tried with try/catch but fails


问:
Static Date Picker Embedded in Sidebar of a Google Sheet to Keep it Always Visible
We are trying to reduce the number of clicks required when selecting dates in a Google sheet side bar. In this specific case the side bar will be always open with several form fields to fill in and submit. On top of the form there should be a field for selecting a date.

The below experimental snippet works just fine (using a common date field, and a ‘materialize’ version as well), except that we want the date picker to stay always visible, embedded on top of the form. Currently one has to click into the date field and only then will the date picker pop-up. Also, after date selection it will disappear. This is what I am trying to avoid.

Is it possible to embed a date picker into the side bar and keep it always visible (while we should be able to fill in all other fields as well, and submit the form data)?

I have attempted to achieve this using the the container: property of the Materialize date picker without success (commented out in the code). Also, I could not find a usable answer to this subject on this platform even after considerable digging.

Code.gs

function showUserForm() {
  var template = HtmlService.createTemplateFromFile("userform");
  var html = template.evaluate().setTitle("Data Input");
  SpreadsheetApp.getUi().showSidebar(html);
}

function appendData(data) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("Sheet2");
  var arrOut = [data.name,data.phone];
  sh.appendRow(arrOut);
}
```
<p>userform.html</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <!--Import Google Icon Font-->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  </head>

  <body>
    <div class="container">
      <div class="row">
        <div class="input-field col s12">
          <i class="material-icons prefix">account_circle</i>
          <input id="date" type="date" class="validate">
          <label for="date">Date</label>
        </div>

        <div class="input-field col s12">
          <input id="prefDate" type="text" class="datepicker">
          <label for="prefDate" >Transaction Date</label>
        </div><!-- Close Date -->

        <div class="input-field col s12">
          <i class="material-icons prefix">account_circle</i>
          <input id="username" type="text" class="validate">
          <label for="username">Your Name</label>
        </div>

        <div class="input-field col s12">
          <i class="material-icons prefix">phone</i>
          <input id="tel" type="text" class="validate">
          <label for="tel">Telephone</label>
        </div>

        <div class="input-field col s12">
          <button class="btn waves-effect waves-light" id="btn">Submit
            <i class="material-icons right">send</i>
          </button>
        </div>
      </div>
    </div>

    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

    <script>
      var nameField = document.getElementById("username");
      var phoneField = document.getElementById("tel");

      document.getElementById("btn").addEventListener("click",addRecord);

      //Date Picker Initialization
      var datePicker = document.getElementById('prefDate');
      M.Datepicker.init(datePicker,{
        showClearBtn:true,
        //container:"prefDate",
        //autoClose:true,
      });

      function addRecord() {
        var data = {
          name: nameField.value,
          phone: phoneField.value
        };

        google.script.run.appendData(data);
        nameField.value = "";
        phoneField.value = "";

        M.toast({html: 'Record was updated.'})
      }
    </script>
  </body>
</html>
</code>```

Body:
We are trying to reduce the number of clicks required when selecting dates in a Google sheet side bar. In this specific case the side bar will be always open with several form fields to fill in and submit. On top of the form there should be a field for selecting a date.

The below experimental snippet works just fine (using a common date field, and a ‘materialize’ version as well), except that we want the date picker to stay always visible, embedded on top of the form. Currently one has to click into the date field and only then will the date picker pop-up. Also, after date selection it will disappear. This is what I am trying to avoid.

Is it possible to embed a date picker into the side bar and keep it always visible (while we should be able to fill in all other fields as well, and submit the form data)?

I have attempted to achieve this using the the container: property of the Materialize date picker without success (commented out in the code). Also, I could not find a usable answer to this subject on this platform even after considerable digging.

Code.gs

function showUserForm() {
  var template = HtmlService.createTemplateFromFile("userform");
  var html = template.evaluate().setTitle("Data Input");
  SpreadsheetApp.getUi().showSidebar(html);
}

function appendData(data) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("Sheet2");
  var arrOut = [data.name,data.phone];
  sh.appendRow(arrOut);
}

userform.html

<!DOCTYPE html>

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

          account_circle
          <input id="date" type="date" class="validate">
          Date

          <input id="prefDate" type="text" class="datepicker">
          Transaction Date

          account_circle
          <input id="username" type="text" class="validate">
          Your Name

          phone
          <input id="tel" type="text" class="validate">
          Telephone

          <button class="btn waves-effect waves-light" id="btn">Submit
            send
          </button>


问:
Accessing refs in dynamically created child components react
How would I go about creating refs on child components created by a map function?

So I'm trying to use

```<code>"@react-google-maps/api"
</code>```

to create input fields wrapped by google's autocomplete. However I'm running into an issue where I want to allow the user to create inputs (to add waypoints) and the only way to get their input into an arry is by using refs

```<code>                <div className={style.form}>
                        <Autocomplete>
                            <input type="text" id="from" ref={originRef} placeholder="Enter Starting Location"/>
                        </Autocomplete>
                        {wayPoints.map((input, index) => {
                                return(
                                    <Autocomplete key={index} onChange={e => handleInputChange(index, e)}>
                                        <input type="text" id="from" placeholder="Enter Stop"/>
                                    </Autocomplete>
                                )
                            })
                        }
                        <Autocomplete>
                            <input type="text" id="from" ref={destinationRef} placeholder="Enter Ending Location"/>
                        </Autocomplete>

                        <div className={style.add} onClick={addNewStop}>
                            <FaPlus/>
                        </div>
                </div>
</code>```

However since I'm creating child compoents I'm not sure how to use refs to solve the problem. I tried using a onChange handler function but if you click on the autocomplete recommendation it doesnt save.

Body:
How would I go about creating refs on child components created by a map function?

So I'm trying to use

"@react-google-maps/api"

to create input fields wrapped by google's autocomplete. However I'm running into an issue where I want to allow the user to create inputs (to add waypoints) and the only way to get their input into an arry is by using refs

                        <Autocomplete>
                            <input type="text" id="from" ref={originRef} placeholder="Enter Starting Location"/>
                        </Autocomplete>
                        {wayPoints.map((input, index) => {
                                return(
                                    <Autocomplete key={index} onChange={e => handleInputChange(index, e)}>
                                        <input type="text" id="from" placeholder="Enter Stop"/>
                                    </Autocomplete>
                                )
                            })
                        }
                        <Autocomplete>
                            <input type="text" id="from" ref={destinationRef} placeholder="Enter Ending Location"/>
                        </Autocomplete>

                            <FaPlus/>

However since I'm creating child compoents I'm not sure how to use refs to solve the problem. I tried using a onChange handler function but if you click on the autocomplete recommendation it doesnt save.


问:
How can I convert an FFmpeg command line to python code
I'm trying to combine an image with an audio file and convert them to mp4.
I found this command line and I used it. It works perfectly.

ffmpeg -loop 1 -i 01_Prologue.png -i 01_Prologue.wav -c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -shortest out.mp4

I want to use python because I want to combine multiple images with multiple audio files

I used this code to combine the same audio and image files but it gave me a blank video file.

```<code>import ffmpeg

input_still = ffmpeg.input("image.jpg")
input_audio = ffmpeg.input("audio.wav")

(
ffmpeg
.concat(input_still, input_audio, v=1, a=1)
.output("output.mp4")
.run(overwrite_output=True)
)
</code>```

I'm guessing that is  because I didn't add the filters to the code, and the problem happened.

but how to do it?

Body:
I'm trying to combine an image with an audio file and convert them to mp4.
I found this command line and I used it. It works perfectly.

ffmpeg -loop 1 -i 01_Prologue.png -i 01_Prologue.wav -c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -shortest out.mp4

I want to use python because I want to combine multiple images with multiple audio files

I used this code to combine the same audio and image files but it gave me a blank video file.

import ffmpeg

input_still = ffmpeg.input("image.jpg")
input_audio = ffmpeg.input("audio.wav")

(
ffmpeg
.concat(input_still, input_audio, v=1, a=1)
.output("output.mp4")
.run(overwrite_output=True)
)

I'm guessing that is  because I didn't add the filters to the code, and the problem happened.

but how to do it?


问:
how to solve flutter iOS framework error?
when running app in flutter on iOS simulator I get this error

```<code>** BUILD FAILED **
Xcode's output:
↳
    Writing result bundle at path:
        /var/folders/_q/npnlj1jx73dbftdw4k23clvm0000gn/T/flutter_tools.laUDdB/flutter_ios_build_temp_dirp6AQZ0/temporary_xcresult_bundle
    ld: framework not found Flutter
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    note: Building targets in dependency order
    warning: Run script build phase 'Run Script' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'Runner' from project 'Runner')
    warning: Run script build phase 'Thin Binary' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'Runner' from project 'Runner')
    Result bundle written to path:
        /var/folders/_q/npnlj1jx73dbftdw4k23clvm0000gn/T/flutter_tools.laUDdB/flutter_ios_build_temp_dirp6AQZ0/temporary_xcresult_bundle
Error (Xcode): Framework not found Flutter

Could not build the application for the simulator.
Error launching application on iPhone 14 Pro Max.
Exited
</code>```

I tried flutter clean and flutter pub get but nothing changed

Body:
when running app in flutter on iOS simulator I get this error

** BUILD FAILED **
Xcode's output:
↳
    Writing result bundle at path:
        /var/folders/_q/npnlj1jx73dbftdw4k23clvm0000gn/T/flutter_tools.laUDdB/flutter_ios_build_temp_dirp6AQZ0/temporary_xcresult_bundle
    ld: framework not found Flutter
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    note: Building targets in dependency order
    warning: Run script build phase 'Run Script' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'Runner' from project 'Runner')
    warning: Run script build phase 'Thin Binary' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'Runner' from project 'Runner')
    Result bundle written to path:
        /var/folders/_q/npnlj1jx73dbftdw4k23clvm0000gn/T/flutter_tools.laUDdB/flutter_ios_build_temp_dirp6AQZ0/temporary_xcresult_bundle
Error (Xcode): Framework not found Flutter

Could not build the application for the simulator.
Error launching application on iPhone 14 Pro Max.
Exited

I tried flutter clean and flutter pub get but nothing changed


问:
How can I access and modify the attributes of a class stored in a vector if I delete the "original" object?
I'm making an application that allows to quote clothes in a store.

In my Store class, I have defined a vector of class Clothes, where I must store the different types of clothing to sell (derived clothing classes such as Shirt and Pants).

My problem arises in that, it does not allow me to access the objects stored in the vector if I have deleted the "original" object. From what I understood, std::vector performed a copy constructor and had its own space to store data, so it is not clear to me why I am not being able to access and modify the attributes of the objects that are already inside the vector. Depending on the different solutions that I tried, the compiler showed me different read or write access errors.

PS: If I don't delete the original object (after having entered the vector), the code works fine for me, and allows me to remove it from the vector and add another object, which I CAN DELETE after entering it into the vector.

Store.h

#pragma once
#ifndef STORE_H
#define STORE_H
#include <string>
#include <vector>

class Clothes;
class Shirt;
class Pants;

class Store
{
private:
    std::string storeName;
    std::string address;
    std::vector<Clothes*> clothesList;

    Shirt* _shirt;
    Pants* _pants;

public:
    Store();
    ~Store();
    void setClothesPreferences(int clothesType, int alternative1, int alternative2, int quality);

};

#endif // !STORE_H
```
<p>Store.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "Store.h"
#include "Clothes.h"
#include "Shirt.h"
#include "Pants.h"
#include <iostream>

Store::Store()
{
    std::cout << "Please, introduce your store name: ";
    std::getline(std::cin, storeName);
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::cout << "Store address: ";
    std::getline(std::cin, address);
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    _shirt = new Shirt();
    _pants = new Pants();

    clothesList.push_back(_shirt);
    clothesList.push_back(_pants);

// If I use delete _shirt here then I would get an error in setClothesPreferences()
}

Store::~Store()
{
    std::cout << "Store closed" << std::endl;
}

void Store::setClothesPreferences(int clothesType, int alternative1, int alternative2, int quality)
{
    if (clothesType == 1)
    {
        Shirt* _shirt2 = dynamic_cast<Shirt*>(clothesList.front()); // Type-casting from Clothes (base class) to Shirt again (derived class)
        clothesList.erase(clothesList.begin());

        // SHIRT SPECIFICATIONS FOR FURTHER QUOTE
        if (alternative1 == 1)
            _shirt2->shortSleeve = true;
        else
            _shirt2->shortSleeve = false; // longSleeve

        if (alternative2 == 1)
            _shirt2->mandarinCollar = true;
        else
            _shirt2->mandarinCollar = false; // regularCollar

        if (quality == 1)
            _shirt2->quality; // Standard
        else
            _shirt2->quality; // Premium

        clothesList.insert(clothesList.begin(), _shirt2);
    }
}
</code>```

Clothes.h

#pragma once
#ifndef CLOTHES_H
#define CLOTHES_H
#include <string>

class Clothes
{
public:
    std::string derivedName;
    std::string quality[2];
    double unitPrice;
    int stockAmount;

    Clothes();
    virtual ~Clothes();
};
#endif // !CLOTHES_H
```
<p>Clothes.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "Clothes.h"

Clothes::Clothes()
{
    derivedName = "Base default";

    quality[0] = "Standard";
    quality[1] = "Premium";

    unitPrice = NULL;
}

Clothes::~Clothes()
{
}
</code>```

Shirt.h

#pragma once
#ifndef SHIRT_H
#define SHIRT_H
#include "Clothes.h"

class Shirt : public Clothes
{
public:
    bool shortSleeve;
    bool mandarinCollar;

    Shirt();
    ~Shirt() override;
};

#endif // !SHIRT_H
```
<p>Shirt.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "Shirt.h"

Shirt::Shirt()
{
    derivedName = "Shirt";
    stockAmount = 2000;
}

Shirt::~Shirt()
{
}
</code>```

My idea is actually to create a local object of class Shirt, insert it into the vector, and when the Clothes function or constructor is finished, it would be deleted, but I would still have access and modify its data from what is stored in the vector.

Body:
I'm making an application that allows to quote clothes in a store.

In my Store class, I have defined a vector of class Clothes, where I must store the different types of clothing to sell (derived clothing classes such as Shirt and Pants).

My problem arises in that, it does not allow me to access the objects stored in the vector if I have deleted the "original" object. From what I understood, std::vector performed a copy constructor and had its own space to store data, so it is not clear to me why I am not being able to access and modify the attributes of the objects that are already inside the vector. Depending on the different solutions that I tried, the compiler showed me different read or write access errors.

PS: If I don't delete the original object (after having entered the vector), the code works fine for me, and allows me to remove it from the vector and add another object, which I CAN DELETE after entering it into the vector.

Store.h

#pragma once
#ifndef STORE_H
#define STORE_H
#include <string>
#include <vector>

class Clothes;
class Shirt;
class Pants;

class Store
{
private:
    std::string storeName;
    std::string address;
    std::vector<Clothes*> clothesList;

    Shirt* _shirt;
    Pants* _pants;

public:
    Store();
    ~Store();
    void setClothesPreferences(int clothesType, int alternative1, int alternative2, int quality);

};

#endif // !STORE_H

Store.cpp

#include "Store.h"
#include "Clothes.h"
#include "Shirt.h"
#include "Pants.h"
#include <iostream>

Store::Store()
{
    std::cout << "Please, introduce your store name: ";
    std::getline(std::cin, storeName);
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::cout << "Store address: ";
    std::getline(std::cin, address);
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    _shirt = new Shirt();
    _pants = new Pants();

    clothesList.push_back(_shirt);
    clothesList.push_back(_pants);

// If I use delete _shirt here then I would get an error in setClothesPreferences()
}

Store::~Store()
{
    std::cout << "Store closed" << std::endl;
}

void Store::setClothesPreferences(int clothesType, int alternative1, int alternative2, int quality)
{
    if (clothesType == 1)
    {
        Shirt* _shirt2 = dynamic_cast<Shirt*>(clothesList.front()); // Type-casting from Clothes (base class) to Shirt again (derived class)
        clothesList.erase(clothesList.begin());

        // SHIRT SPECIFICATIONS FOR FURTHER QUOTE
        if (alternative1 == 1)
            _shirt2->shortSleeve = true;
        else
            _shirt2->shortSleeve = false; // longSleeve

        if (alternative2 == 1)
            _shirt2->mandarinCollar = true;
        else
            _shirt2->mandarinCollar = false; // regularCollar

        if (quality == 1)
            _shirt2->quality; // Standard
        else
            _shirt2->quality; // Premium

        clothesList.insert(clothesList.begin(), _shirt2);
    }
}

Clothes.h

#pragma once
#ifndef CLOTHES_H
#define CLOTHES_H
#include <string>

class Clothes
{
public:
    std::string derivedName;
    std::string quality[2];
    double unitPrice;
    int stockAmount;

    Clothes();
    virtual ~Clothes();
};
#endif // !CLOTHES_H

Clothes.cpp

#include "Clothes.h"

Clothes::Clothes()
{
    derivedName = "Base default";

    quality[0] = "Standard";
    quality[1] = "Premium";

    unitPrice = NULL;
}

Clothes::~Clothes()
{
}

Shirt.h

#pragma once
#ifndef SHIRT_H
#define SHIRT_H
#include "Clothes.h"

class Shirt : public Clothes
{
public:
    bool shortSleeve;
    bool mandarinCollar;

    Shirt();
    ~Shirt() override;
};

#endif // !SHIRT_H

Shirt.cpp

#include "Shirt.h"

Shirt::Shirt()
{
    derivedName = "Shirt";
    stockAmount = 2000;
}

Shirt::~Shirt()
{
}

My idea is actually to create a local object of class Shirt, insert it into the vector, and when the Clothes function or constructor is finished, it would be deleted, but I would still have access and modify its data from what is stored in the vector.


问:
Support AOT and spring native in eureka server
am reading about sprint native and AOT and i noticed that eureka-server does not support native image, resource: https://docs.spring.io/spring-cloud-netflix/docs/current/reference/html/#aot-and-native-image-support-2

any reason for not supporting native-image ? will it be supported in future ?

Thanks in advance


问:
.tracer() in python turtle
I am working on a python project that involves setting a screen where the turtle can move. This is what the code looks like:

```<code>import turtle

window = turtle.screen()
window.title("My game")
window.bgcolor("black")
window.setup(800,800)
window.tracer(0)`
</code>```

In the last line I have no clue what the .tracer(0) command is doing, and what it means. I would appreciate some help.

I ran the code including and excluding the line window.tracer(0). I didn't see any difference.

Title: .tracer() in python turtle

Body:
I am working on a python project that involves setting a screen where the turtle can move. This is what the code looks like:

import turtle

window = turtle.screen()
window.title("My game")
window.bgcolor("black")
window.setup(800,800)
window.tracer(0)`

In the last line I have no clue what the .tracer(0) command is doing, and what it means. I would appreciate some help.

I ran the code including and excluding the line window.tracer(0). I didn't see any difference.


问:
Dev Server with vite + vue3, route 404 not found
Im in the process of moving an app from Vue 2 -> 3

I decided to take a moment to really upgrade and refactor all my repo and that led to using Vue3 recs on new tech, one being vite

My problem is I don't totally understand how the backend API process works so im struggling to move my api route from vue-cli to vite.

I would like to keep using the logic that call functions from api/users to remain in place but im open to a better option

Ultimately I get 404 - Not Found as my response which means its cant find the route

Heres my api/user.js

```<code>import request from '../utils/request'

export function login(data) {
  return request({
    url: '/user/login',
    method: 'post',
    data
  })
}

export function getInfo(token) {
  return request({
    url: '/user/info',
    method: 'get',
    params: { token }
  })
}

export function logout() {
  return request({
    url: '/user/logout',
    method: 'post'
  })
}

</code>```

utils/Request.js

```<code>import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import { userStore } from '../stores/user'
import { getToken } from '../utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const useStore = userStore;

    console.log("Req", "Req Init");

    if (useStore.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    console.log("failed") // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    console.log("Res", "Res Init");

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        ElMessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

</code>```

And a peek at my store that actually calls the endpoint

```<code>
import { login, logout, getInfo } from '../api/user'
</code>```
```<code>
  actions: {  // user login
    login({ commit }, userInfo) {
      const { username, password } = userInfo

      // **Call is made here to 'login'**

      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password: password }).then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

</code>```

Lastly where the call originates from: this.store.login in my login.vue component

```<code>this.store.login('user/login', this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || '/' })
            this.loading = false
         }).catch(() => {
           this.loading = false
         })
</code>```

This is my first StackOverflow post, so be kind if I need to include something else and thanks to any ideas or tips. Thank you

I've tried to search on different ports but the route still comes back as undefined.
I tried to change the vite config to include the server option but it still doesn't seem to help.

Not sure If I need to modify the config or not but I did have some settings related to the server mock on my old webpack config

Body:
Im in the process of moving an app from Vue 2 -> 3

I decided to take a moment to really upgrade and refactor all my repo and that led to using Vue3 recs on new tech, one being vite

My problem is I don't totally understand how the backend API process works so im struggling to move my api route from vue-cli to vite.

I would like to keep using the logic that call functions from api/users to remain in place but im open to a better option

Ultimately I get 404 - Not Found as my response which means its cant find the route

Heres my api/user.js

import request from '../utils/request'

export function login(data) {
  return request({
    url: '/user/login',
    method: 'post',
    data
  })
}

export function getInfo(token) {
  return request({
    url: '/user/info',
    method: 'get',
    params: { token }
  })
}

export function logout() {
  return request({
    url: '/user/logout',
    method: 'post'
  })
}

utils/Request.js

import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import { userStore } from '../stores/user'
import { getToken } from '../utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const useStore = userStore;

    console.log("Req", "Req Init");

    if (useStore.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    console.log("failed") // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    console.log("Res", "Res Init");

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        ElMessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

And a peek at my store that actually calls the endpoint

import { login, logout, getInfo } from '../api/user'

  actions: {  // user login
    login({ commit }, userInfo) {
      const { username, password } = userInfo

      // **Call is made here to 'login'**

      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password: password }).then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

Lastly where the call originates from: this.store.login in my login.vue component

this.store.login('user/login', this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || '/' })
            this.loading = false
         }).catch(() => {
           this.loading = false
         })

This is my first StackOverflow post, so be kind if I need to include something else and thanks to any ideas or tips. Thank you

I've tried to search on different ports but the route still comes back as undefined.
I tried to change the vite config to include the server option but it still doesn't seem to help.

Not sure If I need to modify the config or not but I did have some settings related to the server mock on my old webpack config


问:
How to parallel two elements processing in Java Reactor Core Flux publisher
I want to complete few tasks parallel using reactive Reactor Core streams. So if there are the long timed task - the next emitted objects must be processed without delay.

So, I have two object, the first took a lot of time to complete. I expect no exact order, but parallel execution. What's wrong?

Flux.just(obj1, obj2)
        .subscribeOn(Schedulers.newParallel("parallel", 5))
        .flatMap(Transformator::process)

```

Program is stopped by first element if there are an infinite loop in it's processing.

Body:
I want to complete few tasks parallel using reactive Reactor Core streams. So if there are the long timed task - the next emitted objects must be processed without delay.

So, I have two object, the first took a lot of time to complete. I expect no exact order, but parallel execution. What's wrong?

Flux.just(obj1, obj2)
        .subscribeOn(Schedulers.newParallel("parallel", 5))
        .flatMap(Transformator::process)

Program is stopped by first element if there are an infinite loop in it's processing.