问:
Deep learning forecasting MIMO
I have a dataset with 20 features in a time series. The dimension of the dataset is 45000 x 20 (45000 timesteps and 20 features). Basically, 45000 rows and 20 columns

The data looks like this:
The problem is how to train the first few steps and predict the next few steps in order to get the output of 20 feature predictions which is (A, B, C...). I successfully train and predict 1-D (1 feature (A) for ex) array. But I have no idea how to predict the 20 features using same the dataset.

I tried doing it using LSTM timeseries prediction with multiple outputs this link with the same code and changed the feature from 3 to 20.

But I am getting below error

--------------------------------------------------------------------------- ValueError                                Traceback (most recent call
last) ~\AppData\Local\Temp/ipykernel_15020/722712485.py in
----> 1 history= model.fit(trainX, trainY,validation_split=0.33, epochs=20, batch_size=16)
2

~\anaconda3\lib\site-packages\keras\utils\traceback_utils.py in
error_handler(*args, **kwargs)
68             # To get the full stack trace, call:
69             # tf.debugging.disable_traceback_filtering()
---> 70             raise e.with_traceback(filtered_tb) from None
71         finally:
72             del filtered_tb

~\anaconda3\lib\site-packages\keras\engine\training.py in
tf__train_function(iterator)
13                 try:
14                     do_return = True
---> 15                     retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self),
ag__.ld(iterator)), None, fscope)
16                 except:
17                     do_return = False

ValueError: in user code:

```<code>File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\training.py",
</code>```

line 1249, in train_function  *
return step_function(self, iterator)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\training.py",
line 1233, in step_function  **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\training.py",
line 1222, in run_step  **
outputs = model.train_step(data)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\training.py",
line 1024, in train_step
loss = self.compute_loss(x, y, y_pred, sample_weight)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\training.py",
line 1082, in compute_loss
return self.compiled_loss(
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\compile_utils.py",
line 265, in call
loss_value = loss_obj(y_t, y_p, sample_weight=sw)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\losses.py", line
152, in call
losses = call_fn(y_true, y_pred)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\losses.py", line
284, in call  **
return ag_fn(y_true, y_pred, **self._fn_kwargs)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\losses.py", line
1500, in mean_squared_error
return backend.mean(tf.math.squared_difference(y_pred, y_true), axis=-1)

```<code>ValueError: Dimensions must be equal, but are 3 and 20 for '{{node mean_squared_error/SquaredDifference}} =
</code>```

SquaredDifference[T=DT_FLOAT](sequential_5/dense_5/BiasAdd,
IteratorGetNext:1)' with input shapes: [?,3], [?,20].

Please tell me how to proceed.

Title: Deep learning forecasting MIMO

Body:
I have a dataset with 20 features in a time series. The dimension of the dataset is 45000 x 20 (45000 timesteps and 20 features). Basically, 45000 rows and 20 columns

The data looks like this:
The problem is how to train the first few steps and predict the next few steps in order to get the output of 20 feature predictions which is (A, B, C...). I successfully train and predict 1-D (1 feature (A) for ex) array. But I have no idea how to predict the 20 features using same the dataset.

I tried doing it using LSTM timeseries prediction with multiple outputs this link with the same code and changed the feature from 3 to 20.

But I am getting below error

--------------------------------------------------------------------------- ValueError                                Traceback (most recent call
last) ~\AppData\Local\Temp/ipykernel_15020/722712485.py in
----> 1 history= model.fit(trainX, trainY,validation_split=0.33, epochs=20, batch_size=16)
2

~\anaconda3\lib\site-packages\keras\utils\traceback_utils.py in
error_handler(*args, **kwargs)
68             # To get the full stack trace, call:
69             # tf.debugging.disable_traceback_filtering()
---> 70             raise e.with_traceback(filtered_tb) from None
71         finally:
72             del filtered_tb

~\anaconda3\lib\site-packages\keras\engine\training.py in
tf__train_function(iterator)
13                 try:
14                     do_return = True
---> 15                     retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self),
ag__.ld(iterator)), None, fscope)
16                 except:
17                     do_return = False

ValueError: in user code:

File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\training.py",

line 1249, in train_function  *
return step_function(self, iterator)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\training.py",
line 1233, in step_function  **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\training.py",
line 1222, in run_step  **
outputs = model.train_step(data)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\training.py",
line 1024, in train_step
loss = self.compute_loss(x, y, y_pred, sample_weight)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\training.py",
line 1082, in compute_loss
return self.compiled_loss(
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\engine\compile_utils.py",
line 265, in call
loss_value = loss_obj(y_t, y_p, sample_weight=sw)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\losses.py", line
152, in call
losses = call_fn(y_true, y_pred)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\losses.py", line
284, in call  **
return ag_fn(y_true, y_pred, **self._fn_kwargs)
File "C:\Users\yashum\anaconda3\lib\site-packages\keras\losses.py", line
1500, in mean_squared_error
return backend.mean(tf.math.squared_difference(y_pred, y_true), axis=-1)

ValueError: Dimensions must be equal, but are 3 and 20 for '{{node mean_squared_error/SquaredDifference}} =

SquaredDifference[T=DT_FLOAT](sequential_5/dense_5/BiasAdd,
IteratorGetNext:1)' with input shapes: [?,3], [?,20].

Please tell me how to proceed.


来源: stackexchange

问:
Flutter: How to load user settings from SharedPreferences when a new version of the app introduces structural changes to the Settings class?
I am working on a flutter app which is meant for music students. The students can set the difficulty of the tasks they are shown. These settings are stored in an object of the Settings class and this object is stored in SharedPreferences. However, we frequently change the settings class in order to provide new options for the students. This causes problems when the app is loaded for the first time after the update.

Here is the part where the settings are loaded. I do not want the QuizView to load before the settings are available. Therefore, I use a FutureBuilder widget:

```<code>MaterialPageRoute(builder: (context) =>

    FutureBuilder<Settings>(
            // Fetching the settings from SharedPreferences. This is the asynchronous operation.
            future: loadSettings("Uebungsmodus"),
            builder: (BuildContext context,
                AsyncSnapshot<Settings> snapshot) {
              Widget child;
              if (snapshot.hasData) {
                // Extract the data from the snapshot.
                // There might be a better solution, but at least this works for now.
                Settings settings = Settings();
                settings.augmentedFrequency =
                    snapshot.data!.augmentedFrequency;
                settings.diminishedFrequency =
                    snapshot.data!.diminishedFrequency;
                settings.majorFrequency =
                    snapshot.data!.majorFrequency;
                settings.minorFrequency =
                    snapshot.data!.minorFrequency;
                settings.maxKeySignatureAccidentals =
                    snapshot.data!
                        .maxKeySignatureAccidentals;
                settings.snowmenOnly =
                    snapshot.data!.snowmenOnly;
                settings.standardClefArrangement =
                    snapshot
                        .data!.standardClefArrangement;
                settings.clefPreferences =
                    snapshot
                        .data!.clefPreferences;

                QuizPageViewModel qpvm =
                    QuizPageViewModel(
                        settings,
                        TriadProvider(),
                        ParamGenerator());

                child = QuizView(vm: qpvm);
              } else if (snapshot.hasError) {
                // Provide default settings in case of an error.
                QuizPageViewModel qpvm =
                QuizPageViewModel(
                    Settings(),
                    TriadProvider(),
                    ParamGenerator());
                child = QuizView(vm: qpvm);
              } else {
                // Show a circular progress indicator as long as the settings are loading.
                child = Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: const [SizedBox(
                  width: 60,
                  height: 60,
                  child: CircularProgressIndicator())
                ],
                );
              }
              return child;
            },
          )));
</code>```

The Map clefPreferences was not there before. Instead, there were two boolean variables. The problem now is that snapshot.data!.clefPreferences is null, since this part was never stored in SharedPreferences before. Since the data object is not null itself, flutter won't notice. If I try

```<code>settings.clefPreferences =
    snapshot
        .data!.clefPreferences ?? [some code initialising default preferences];
</code>```

flutter tells me that "the left operand can't be null, so the right operand is never executed". It is null though! In this scenario, the app crashes.

I am unsure how to deal with this. On loading the App, there will be an update screen informing users about the new version, storing new settings at the same time. However, I am worried that I might miss something and users might somehow bypass this update-screen. This will completely break the app on a user's device unless I do another check somewhere. How can I still make sure no null entries are loaded? Any advice is appreciated!

Update: Everything seems to work now and this problem does not occur any more. If any of the variables from the Settings class cannot be retrieved, if (snapshot.data) simply evaluates to false immediately and the default settings are loaded. I am still wondering why the problem described above occurred in the first place. Apparently, I was able to load snapshot data which were null without Flutter admitting it. I could see in the debugger that they were null. I am unable to reproduce this scenario whatever I try. Has anyone come across this problem before?

There is another thing which I am wondering about: When I manually write corrupt data into the file FlutterSharedPreferences.xml, it seems to fix itself, meaning the changes are reverted when I trigger loading the data. I noticed that SharedPreferences uses the two variables _store and _preferenceCache. Are these responsible for this? Are there any backup copies or cached data which are used to overwrite the changes I manually write into that file. I am asking this because it might be easier to reproduce the problem described above if I could manually change FlutterSharedPreferences.xml.

ContentLicense: CC BY-SA 4.0

Body:
I am working on a flutter app which is meant for music students. The students can set the difficulty of the tasks they are shown. These settings are stored in an object of the Settings class and this object is stored in SharedPreferences. However, we frequently change the settings class in order to provide new options for the students. This causes problems when the app is loaded for the first time after the update.

Here is the part where the settings are loaded. I do not want the QuizView to load before the settings are available. Therefore, I use a FutureBuilder widget:

MaterialPageRoute(builder: (context) =>

    FutureBuilder<Settings>(
            // Fetching the settings from SharedPreferences. This is the asynchronous operation.
            future: loadSettings("Uebungsmodus"),
            builder: (BuildContext context,
                AsyncSnapshot<Settings> snapshot) {
              Widget child;
              if (snapshot.hasData) {
                // Extract the data from the snapshot.
                // There might be a better solution, but at least this works for now.
                Settings settings = Settings();
                settings.augmentedFrequency =
                    snapshot.data!.augmentedFrequency;
                settings.diminishedFrequency =
                    snapshot.data!.diminishedFrequency;
                settings.majorFrequency =
                    snapshot.data!.majorFrequency;
                settings.minorFrequency =
                    snapshot.data!.minorFrequency;
                settings.maxKeySignatureAccidentals =
                    snapshot.data!
                        .maxKeySignatureAccidentals;
                settings.snowmenOnly =
                    snapshot.data!.snowmenOnly;
                settings.standardClefArrangement =
                    snapshot
                        .data!.standardClefArrangement;
                settings.clefPreferences =
                    snapshot
                        .data!.clefPreferences;

                QuizPageViewModel qpvm =
                    QuizPageViewModel(
                        settings,
                        TriadProvider(),
                        ParamGenerator());

                child = QuizView(vm: qpvm);
              } else if (snapshot.hasError) {
                // Provide default settings in case of an error.
                QuizPageViewModel qpvm =
                QuizPageViewModel(
                    Settings(),
                    TriadProvider(),
                    ParamGenerator());
                child = QuizView(vm: qpvm);
              } else {
                // Show a circular progress indicator as long as the settings are loading.
                child = Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: const [SizedBox(
                  width: 60,
                  height: 60,
                  child: CircularProgressIndicator())
                ],
                );
              }
              return child;
            },
          )));

The Map clefPreferences was not there before. Instead, there were two boolean variables. The problem now is that snapshot.data!.clefPreferences is null, since this part was never stored in SharedPreferences before. Since the data object is not null itself, flutter won't notice. If I try

settings.clefPreferences =
    snapshot
        .data!.clefPreferences ?? [some code initialising default preferences];

flutter tells me that "the left operand can't be null, so the right operand is never executed". It is null though! In this scenario, the app crashes.

I am unsure how to deal with this. On loading the App, there will be an update screen informing users about the new version, storing new settings at the same time. However, I am worried that I might miss something and users might somehow bypass this update-screen. This will completely break the app on a user's device unless I do another check somewhere. How can I still make sure no null entries are loaded? Any advice is appreciated!

Update: Everything seems to work now and this problem does not occur any more. If any of the variables from the Settings class cannot be retrieved, if (snapshot.data) simply evaluates to false immediately and the default settings are loaded. I am still wondering why the problem described above occurred in the first place. Apparently, I was able to load snapshot data which were null without Flutter admitting it. I could see in the debugger that they were null. I am unable to reproduce this scenario whatever I try. Has anyone come across this problem before?

There is another thing which I am wondering about: When I manually write corrupt data into the file FlutterSharedPreferences.xml, it seems to fix itself, meaning the changes are reverted when I trigger loading the data. I noticed that SharedPreferences uses the two variables _store and _preferenceCache. Are these responsible for this? Are there any backup copies or cached data which are used to overwrite the changes I manually write into that file. I am asking this because it might be easier to reproduce the problem described above if I could manually change FlutterSharedPreferences.xml.


问:
Layout: paddings instead of container?
I have a problem with layout.

I have a .container with fixed width. I need to create block with left paddint like container and no padding in right side.

enter image description here

https://prnt.sc/thXfdJwbvUzG

How I can do it?

I tried to do padding-left: 130px and padding-right: 0. Is it ok?

Title: Layout: paddings instead of container?


问:
How do I set the name of the log file per logger but with the same appender?
I want to have several loggers that are using the same file appender.
I want each log file to have its own specific name that I define (such as requests.log...).
How can I define the log file's name per logger without having to create a file appender for each logger?

This is what my logback-spring.xml looks like right now:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="pattern" value="%d{dd-MM-yyyy HH:mm:ss.SSS} %-5level: %msg | request #%X{requestNumber}%n" />

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <encoder>
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>

    <logger name="request-logger">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </logger>
</configuration>
</code>```

Body:
I want to have several loggers that are using the same file appender.
I want each log file to have its own specific name that I define (such as requests.log...).
How can I define the log file's name per logger without having to create a file appender for each logger?

This is what my logback-spring.xml looks like right now:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="pattern" value="%d{dd-MM-yyyy HH:mm:ss.SSS} %-5level: %msg | request #%X{requestNumber}%n" />

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <encoder>
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>

    <logger name="request-logger">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </logger>
</configuration>


问:
the right way to make prediction using Spacy word vectors
Im learning how to convert text into numbers for NLP problems and following a course Im learning about word vectors provided by Spacy package. the code works all fine from learning and evaluation but I have some problems regarding:

making prediction for new sentences, I cannot seems to make it work and most examples just fit the model then use X_test set for evaluation. ( Code below)

The person explaining stated that its bad( won't give good results) if I used

""
doc.vector   over doc.vector.values

""

when trying both I don't see a difference, what is the difference between the two?

the example is to classify news title between fake and real

```<code>import spacy
import pandas as pd

df= pd.read_csv('Fake_Real_Data.csv')

print(df.head())
print(f"shape is: {df.shape}")

print("checking the impalance: \n ", df.label.value_counts())

df['label_No'] = df['label'].map({'Fake': 0, 'Real': 1})
print(df.head())

nlp= spacy.load('en_core_web_lg') # only large and medium model have word vectors

df['Text_vector'] = df['Text'].apply(lambda x: nlp(x).vector) #apply the function to EACH element in the column
print(df.head(5))

from sklearn.model_selection import train_test_split

X_train, X_test, y_train,y_test= train_test_split(df.Text_vector.values, df.label_No, test_size=0.2, random_state=2022)

x_train_2D= np.stack(X_train)
x_test_2D= np.stack(X_test)

from sklearn.naive_bayes import MultinomialNB

clf=MultinomialNB()

from sklearn.preprocessing import MinMaxScaler

scaler= MinMaxScaler()

scaled_train_2d= scaler.fit_transform(x_train_2D)
scaled_test_2d= scaler.transform(x_test_2D)

clf.fit(scaled_train_2d, y_train)

from sklearn.metrics import classification_report

y_pred=clf.predict(scaled_test_2d)

print(classification_report(y_test, y_pred))

</code>```

Body:
Im learning how to convert text into numbers for NLP problems and following a course Im learning about word vectors provided by Spacy package. the code works all fine from learning and evaluation but I have some problems regarding:

making prediction for new sentences, I cannot seems to make it work and most examples just fit the model then use X_test set for evaluation. ( Code below)

The person explaining stated that its bad( won't give good results) if I used

""
doc.vector   over doc.vector.values

""

when trying both I don't see a difference, what is the difference between the two?

the example is to classify news title between fake and real

import spacy
import pandas as pd

df= pd.read_csv('Fake_Real_Data.csv')

print(df.head())
print(f"shape is: {df.shape}")

print("checking the impalance: \n ", df.label.value_counts())

df['label_No'] = df['label'].map({'Fake': 0, 'Real': 1})
print(df.head())

nlp= spacy.load('en_core_web_lg') # only large and medium model have word vectors

df['Text_vector'] = df['Text'].apply(lambda x: nlp(x).vector) #apply the function to EACH element in the column
print(df.head(5))

from sklearn.model_selection import train_test_split

X_train, X_test, y_train,y_test= train_test_split(df.Text_vector.values, df.label_No, test_size=0.2, random_state=2022)

x_train_2D= np.stack(X_train)
x_test_2D= np.stack(X_test)

from sklearn.naive_bayes import MultinomialNB

clf=MultinomialNB()

from sklearn.preprocessing import MinMaxScaler

scaler= MinMaxScaler()

scaled_train_2d= scaler.fit_transform(x_train_2D)
scaled_test_2d= scaler.transform(x_test_2D)

clf.fit(scaled_train_2d, y_train)

from sklearn.metrics import classification_report

y_pred=clf.predict(scaled_test_2d)

print(classification_report(y_test, y_pred))


问:
How to resolve ERROR: cannot read command from socket, code 10054
I am trying to create a read and write operation for a server that I did not create.

The write operation works but for the read operation I am getting :

ERROR: cannot read command from socket, code 10054(This appears in the SERVER LOG and my app hangs)

If I use the example from the Microsoft website it works as expected out of the box here but when I modify the Microsft example I get the error above. My modification is below.

I don't want to keep opening and closing connections for every command(I am not knowledgeable in this area, so is that advisable?)

How does this communication work:

Is it that if I send command 1 command 2 won't send until we get a response from command 1?

Can TCP commands be sent simultaneously? If so how can I make sure the response I get belongs to the right command? The reason why I am asking I would like to check if a command fails and if it does try again.

C# Class:

```<code>public class TCPConnection : IConnection
{
    public TCPConnection(MachineInfo machineInfo) => this.MachineInfo = machineInfo as MachineInfo;

    TcpClient TcpClient ;
    private NetworkStream Stream;
    private readonly MachineInfo MachineInfo;

    public void Connect()
    {
        Disconnect();
        TcpClient = new TcpClient();
        TcpClient.Connect(hostname: MachineInfo.IPAddress, this.MachineInfo.Port);
        Stream = TcpClient.GetStream();
    }

    public void Disconnect()
    {
        TcpClient?.Close();
        Stream?.Close();
    }

    public string ReadData(string message)
    {
        WriteData(message);
        data = new Byte[256];
        String responseData = String.Empty;

        Int32 bytes = Stream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
        return responseData;
    }
    Byte[] data;
    public void WriteData(string message)
    {

        data = System.Text.Encoding.ASCII.GetBytes(message);
        Stream.Write(data, 0, data.Length);
    }
}
</code>```

Usage:

```<code>var v= new  TCPConnection(new MachineInfo("127.0.0.1",8900));
v.Connect();

var AllCommands = new List<string>();
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("This could go up to 1000");

foreach (var item in AllCommands)
{
    var test = v.ReadData(item);
    Console.WriteLine(test);
}

v.Disconnect();
Console.ReadKey();
</code>```

Body:
I am trying to create a read and write operation for a server that I did not create.

The write operation works but for the read operation I am getting :

ERROR: cannot read command from socket, code 10054(This appears in the SERVER LOG and my app hangs)

If I use the example from the Microsoft website it works as expected out of the box here but when I modify the Microsft example I get the error above. My modification is below.

I don't want to keep opening and closing connections for every command(I am not knowledgeable in this area, so is that advisable?)

How does this communication work:

Is it that if I send command 1 command 2 won't send until we get a response from command 1?

Can TCP commands be sent simultaneously? If so how can I make sure the response I get belongs to the right command? The reason why I am asking I would like to check if a command fails and if it does try again.

C# Class:

public class TCPConnection : IConnection
{
    public TCPConnection(MachineInfo machineInfo) => this.MachineInfo = machineInfo as MachineInfo;

    TcpClient TcpClient ;
    private NetworkStream Stream;
    private readonly MachineInfo MachineInfo;

    public void Connect()
    {
        Disconnect();
        TcpClient = new TcpClient();
        TcpClient.Connect(hostname: MachineInfo.IPAddress, this.MachineInfo.Port);
        Stream = TcpClient.GetStream();
    }

    public void Disconnect()
    {
        TcpClient?.Close();
        Stream?.Close();
    }

    public string ReadData(string message)
    {
        WriteData(message);
        data = new Byte[256];
        String responseData = String.Empty;

        Int32 bytes = Stream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
        return responseData;
    }
    Byte[] data;
    public void WriteData(string message)
    {

        data = System.Text.Encoding.ASCII.GetBytes(message);
        Stream.Write(data, 0, data.Length);
    }
}

Usage:

var v= new  TCPConnection(new MachineInfo("127.0.0.1",8900));
v.Connect();

var AllCommands = new List<string>();
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("cmd1");
AllCommands.Add("This could go up to 1000");

foreach (var item in AllCommands)
{
    var test = v.ReadData(item);
    Console.WriteLine(test);
}

v.Disconnect();
Console.ReadKey();


问:
Plotting optimization objective and constraints in Matlab
I would like to plot my SOCP that looks something like this:

Link for the example

How can I do that?

I tried playing with this code:

```<code>[X,Y] = meshgrid(-2:0.1:2);
Z1 = sqrt(X.^2 + Y.^2);
Z2 = sqrt(X.^2 + 2*Y.^2);
Z3 = 2*X+Y;
figure(1)
surf(X,Y,Z1)
hold on
surf(X,Y,Z2)
hold on
surf(X,Y,Z3)
hold off
grid on
</code>```

How can I plot constraint with norm? Also I would like to know if it is somehow with colors possible to show intersection of those constraints?

Body:
I would like to plot my SOCP that looks something like this:

Link for the example

How can I do that?

I tried playing with this code:

[X,Y] = meshgrid(-2:0.1:2);
Z1 = sqrt(X.^2 + Y.^2);
Z2 = sqrt(X.^2 + 2*Y.^2);
Z3 = 2*X+Y;
figure(1)
surf(X,Y,Z1)
hold on
surf(X,Y,Z2)
hold on
surf(X,Y,Z3)
hold off
grid on

How can I plot constraint with norm? Also I would like to know if it is somehow with colors possible to show intersection of those constraints?


问:
Im trying to implement authentication in next.js using next-auth and next.js middleware, but im getting an error when using it in every route
Im trying to implement auth logic using this example but I am trying to implement it in every route like so

```<code>export const config = {
  matcher: ['/:path*'],
};
</code>```

but my browser breaks because too many requests, but when I change the matcher array to specific routes, it works, like this:

```<code> matcher: ['/teacher','/student'],
</code>```

with the matcher like this, auth works for the pages (student,teacher) but not other pages.

middleware.ts:

```<code>import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from 'next-auth/middleware';

const PUBLIC_FILE = /\.(.*)$/;

export default withAuth(
  async function middleware(req: NextRequest) {
    if (
      req.nextUrl.pathname.startsWith('/_next') ||
      req.nextUrl.pathname.includes('/api/') ||
      PUBLIC_FILE.test(req.nextUrl.pathname)
    ) {
      return;
    }

    if (req.nextUrl.locale === 'default') {
      const locale = req.cookies.get('NEXT_LOCALE') || 'en';

      return NextResponse.rewrite(
        new URL(
          `/${locale}${req.nextUrl.pathname}${req.nextUrl.search}`,
          req.url,
        ),
      );
    }
  },
  {
    callbacks: {
      authorized({ req, token }) {
        return !!token;
      },
    },
  },
);

export const config = {
  matcher: ['/:path*', '/teacher'],
};
</code>```

Body:
Im trying to implement auth logic using this example but I am trying to implement it in every route like so

export const config = {
  matcher: ['/:path*'],
};

but my browser breaks because too many requests, but when I change the matcher array to specific routes, it works, like this:

 matcher: ['/teacher','/student'],

with the matcher like this, auth works for the pages (student,teacher) but not other pages.

middleware.ts:

import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from 'next-auth/middleware';

const PUBLIC_FILE = /\.(.*)$/;

export default withAuth(
  async function middleware(req: NextRequest) {
    if (
      req.nextUrl.pathname.startsWith('/_next') ||
      req.nextUrl.pathname.includes('/api/') ||
      PUBLIC_FILE.test(req.nextUrl.pathname)
    ) {
      return;
    }

    if (req.nextUrl.locale === 'default') {
      const locale = req.cookies.get('NEXT_LOCALE') || 'en';

      return NextResponse.rewrite(
        new URL(
          `/${locale}${req.nextUrl.pathname}${req.nextUrl.search}`,
          req.url,
        ),
      );
    }
  },
  {
    callbacks: {
      authorized({ req, token }) {
        return !!token;
      },
    },
  },
);

export const config = {
  matcher: ['/:path*', '/teacher'],
};


问:
How to make phpunit faster on big bootstrap
I've tried opcache but it even makes it lower, in some cli programs there is a watch option, the cli keeps running that on changes it will redo something, I couldn't find that for phpunit.

Just to be clear, the tests are pretty fast, what's slow is the bootstrap because the codebase is rather big, the code base runs fine on a webserver thanks to opcache, but for phpunit opcache (which only should work with file cache I'd suppose?) seems to be hopeless...

I'm using PHP 8 and PHPUnit 9


问:
Laravel page expired 419 only sometimes
I have a view in my Laravel application that has a form with the @csrf inside. The problem is that I faced the 419 Page expired exception only sometimes.
When I refreshed the page, the login page appeared and after login, a few times the form submission was done successfully but again, 419 occurred.

I saw the other topics. All of them told that the solution is adding the @CSRF directive to the form.

But in my special case, the @CSRF exists.

Help me please.

Update

Here is a part of my source code. It's a simple html form with the @CSRF inside it.

```<code><form method="POST" action="/settingUrl">
    @csrf
    <input type="text" name="myfield" />
    <input type="submit" value="save" />
</form>
</code>```

Title: Laravel page expired 419 only sometimes

Body:
I have a view in my Laravel application that has a form with the @csrf inside. The problem is that I faced the 419 Page expired exception only sometimes.
When I refreshed the page, the login page appeared and after login, a few times the form submission was done successfully but again, 419 occurred.

I saw the other topics. All of them told that the solution is adding the @CSRF directive to the form.

But in my special case, the @CSRF exists.

Help me please.

Update

Here is a part of my source code. It's a simple html form with the @CSRF inside it.

<form method="POST" action="/settingUrl">
    @csrf
    <input type="text" name="myfield" />
    <input type="submit" value="save" />
</form>


问:
How to prevent two Top Most windows from competing for visibility when moving?
My executable creates a window that constantly moves left and right using SetWindowPos on a 1millisecond timer.

When NOT given the WS_EX_TOPMOST style, opening two of the executables would have the second window being consistantly covered by the first window while both windows are moving.

However, once I gave the executable the WS_EX_TOPMOST style, running the executable twice would have both windows consistantly competing to be shown above one another.

I'm trying to make the windows topmost so they would always be shown, but not compete for visibility.

I suspected this issue to occur because of something to do with the Z order of topmost Windows, so I tried to arrange the Z order as such:

```<code>//prior to this, the window is NOT given the WS_EX_TOPMOST style

case WM_CREATE:
{
HWND testhWnd=FindWindow("name","name");
int exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);

//Check if previous instance of window that was promoted to TOPMOST exists

if((exStyle & WS_EX_TOPMOST) ==WS_EX_TOPMOST)
//Precede current window over previous window in Z order
{
SetWindowPos(hwnd,testhWnd,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
}
else
{
SetWindowPos(hwnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
}

break;
}
</code>```

But it doesn't seem to fix the issue. Is there even Z indexing in Topmost windows? How can I fix this issue? Thank you for reading!

Body:
My executable creates a window that constantly moves left and right using SetWindowPos on a 1millisecond timer.

When NOT given the WS_EX_TOPMOST style, opening two of the executables would have the second window being consistantly covered by the first window while both windows are moving.

However, once I gave the executable the WS_EX_TOPMOST style, running the executable twice would have both windows consistantly competing to be shown above one another.

I'm trying to make the windows topmost so they would always be shown, but not compete for visibility.

I suspected this issue to occur because of something to do with the Z order of topmost Windows, so I tried to arrange the Z order as such:

//prior to this, the window is NOT given the WS_EX_TOPMOST style

case WM_CREATE:
{
HWND testhWnd=FindWindow("name","name");
int exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);

//Check if previous instance of window that was promoted to TOPMOST exists

if((exStyle & WS_EX_TOPMOST) ==WS_EX_TOPMOST)
//Precede current window over previous window in Z order
{
SetWindowPos(hwnd,testhWnd,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
}
else
{
SetWindowPos(hwnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
}

break;
}

But it doesn't seem to fix the issue. Is there even Z indexing in Topmost windows? How can I fix this issue? Thank you for reading!


问:
Colorbar Help when updating using a combobox
I have been working with ttk to update two figures with a combobox event, the problem is that when updating the figure the colorbar isnt clearing, according to other threads I used d.remove() or d.ax.clear(), or fig.clear(), but is not working I really dont know why isnt removing old colorbar

The code just ask for a file directory where the excel files are stores(ill provide some files) and then just playing with combobox

the link (mediafire) to folder with excelfiles
folder with excel files

```<code>import tkinter as tk
from tkinter import ttk
from  matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import matplotlib.cm as cm
import matplotlib
import os
from msilib.schema import ComboBox
newWindow = tk.Tk()
newWindow.state('zoomed')
newWindow.title('Compare traces')
newWindow.attributes('-topmost',True)
file_path = askdirectory(parent=newWindow)
main_frame2_1=tk.Frame(newWindow,bg="pink")
main_frame2_1.pack(fill=tk.BOTH,expand=True)
main_frame2_1.grid_columnconfigure(0, weight=1)
main_frame2_1.grid_rowconfigure(0, weight=1,uniform=1)
main_frame2_1.grid_columnconfigure(1, weight=1)
main_frame2_1.grid_rowconfigure(1, weight=1)

frame1_1=tk.Frame(main_frame2_1,bg="red")
frame1_1.grid(row=0, column=0, sticky='nsew')
frame1_2=tk.Frame(main_frame2_1,bg="green")
frame1_2.grid(row=0, column=1, sticky='nsew')
frame1_3=tk.Frame(main_frame2_1,bg="black",width=500,height=500)
frame1_3.grid(column=0,row=1,sticky='nsew')
frame1_4=tk.Frame(main_frame2_1,bg="pink",width=500,height=500)
frame1_4.grid(column=1,row=1,sticky='nsew')

frame1_1.grid_columnconfigure(0, weight=1)
frame1_1.grid_rowconfigure(0, weight=1)
frame1_1.grid_columnconfigure(1, weight=1)
frame1_1.grid_columnconfigure(2, weight=1)

frame1_2.grid_columnconfigure(0, weight=1)
frame1_2.grid_rowconfigure(0, weight=1)
frame1_2.grid_columnconfigure(1, weight=1)
frame1_2.grid_columnconfigure(2, weight=1)

class VerticalNavigationToolbar2Tk(NavigationToolbar2Tk):
        def __init__(self, canvas, window):
            super().__init__(canvas, window, pack_toolbar=False)
        def _Button(self, text, file,toggle, command):
            img_file = os.path.join(matplotlib.get_data_path(), 'images', file )
            im = tk.PhotoImage(master=self, file=img_file)
            im = im.subsample(2, 2)
            b = tk.Button(master=self, text=text, padx=2, pady=2, image=im, command=command)
            b._ntimage = im
            b.pack(side=tk.TOP)
            return b
        def _Spacer(self):
            s = tk.Frame(self, width=10, relief=tk.RIDGE, bg="DarkGray", padx=2)
            s.pack(side=tk.TOP, pady=1)
            return s
        def set_message(self, s):
            pass

def selection(event):
    trace=textVar.get()
    fullname = os.path.join(file_path,trace)
    df=pd.read_excel(fullname,  header=[3])
    df = df.fillna(0)
    df1=df.iloc[1:, :].reset_index(drop=True).set_index("distance")
    df2=df1.T
    temperature=df2.to_numpy(dtype='float')
    depth=df1.index
    depth.to_numpy(dtype='float')
    df3=pd.read_excel(fullname)
    df3= df3.fillna(0)
    df5=df3.head(2)
    df6=df5.T
    df6.columns = df6.iloc[0]
    df6= df6[1:]
    df6 = pd.DataFrame(df6)
    df6['Column'] = range(1, len(df6)+1)
    df6=df6.set_index("Column")
    time1=df6.index
    time1.to_numpy()
    time2 = time1.astype("float")
    b, a  = np.meshgrid(depth, time2)
    b=b.astype('float64')
    c=temperature
    c=c.astype('float64')
    l_a=a.min()
    r_a=a.max()
    l_b=b.min()
    r_b=b.max()
    l_c,r_c  =0, np.abs(c).max()

    ax4.clear()
    c1 = ax4.pcolormesh(a, b, c, cmap='jet', vmin=l_c, vmax=r_c)
    ax4.set_title('Heatmap'+ trace)
    ax4.axis([l_a, r_a, l_b, r_b])
    plt.gca().xaxis.set_major_locator(plt.MultipleLocator(2))
    vmin=np.min(temperature)
    vmax=np.max(temperature)
    c1.set_clim(0,110)
    ax4.set_ylabel('Distance')
    ax4.set_xlabel('Column')
    d=fig4.colorbar(c1,ax=ax4)
    d.set_label('ºF')
    canvas2.draw_idle()

values1=sorted(os.listdir(file_path), key=len)
textVar = tk.StringVar(frame1_1)
textVar.set('')
ccbox=ttk.Combobox(frame1_1,values=values1,height=20,width=10,textvariable=textVar)
ccbox.grid(column=1,row=0,sticky= "we")
ccbox.bind("<<ComboboxSelected>>",  selection)

def selection1(event):
    trace1=textVar1.get()
    print(trace1)
values11=sorted(os.listdir(file_path), key=len)
textVar1 = tk.StringVar(frame1_2)
textVar1.set('')
ccbox1=ttk.Combobox(frame1_2,values=values11,height=20,width=10,textvariable=textVar1)
ccbox1.grid(column=1,row=0,sticky= "we")
ccbox1.bind("<<ComboboxSelected>>",  selection1)

np.random.seed(19680801)
Z = np.random.rand(6, 10)
x = np.arange(-0.5, 10, 1)  # len = 11
y = np.arange(4.5, 11, 1)  # len = 7
fig4, ax4 = plt.subplots()
c1=ax4.pcolormesh(x, y, Z)
c1.set_clim(0,110)
d=fig4.colorbar(c1,ax=ax4)

canvas2 = FigureCanvasTkAgg(fig4, master=frame1_3)
fig4.canvas.draw()
canvas2.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH, expand=1)
toolbar2 = VerticalNavigationToolbar2Tk(canvas2, frame1_3)
toolbar2.update()
toolbar2.pack(side=tk.LEFT, fill=tk.Y)
newWindow.mainloop()
</code>```

Heres is a SS of the problem:

Thanks in advance for any help, and Merry Christmas!!!!

Body:
I have been working with ttk to update two figures with a combobox event, the problem is that when updating the figure the colorbar isnt clearing, according to other threads I used d.remove() or d.ax.clear(), or fig.clear(), but is not working I really dont know why isnt removing old colorbar

The code just ask for a file directory where the excel files are stores(ill provide some files) and then just playing with combobox

the link (mediafire) to folder with excelfiles
folder with excel files

import tkinter as tk
from tkinter import ttk
from  matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import matplotlib.cm as cm
import matplotlib
import os
from msilib.schema import ComboBox
newWindow = tk.Tk()
newWindow.state('zoomed')
newWindow.title('Compare traces')
newWindow.attributes('-topmost',True)
file_path = askdirectory(parent=newWindow)
main_frame2_1=tk.Frame(newWindow,bg="pink")
main_frame2_1.pack(fill=tk.BOTH,expand=True)
main_frame2_1.grid_columnconfigure(0, weight=1)
main_frame2_1.grid_rowconfigure(0, weight=1,uniform=1)
main_frame2_1.grid_columnconfigure(1, weight=1)
main_frame2_1.grid_rowconfigure(1, weight=1)

frame1_1=tk.Frame(main_frame2_1,bg="red")
frame1_1.grid(row=0, column=0, sticky='nsew')
frame1_2=tk.Frame(main_frame2_1,bg="green")
frame1_2.grid(row=0, column=1, sticky='nsew')
frame1_3=tk.Frame(main_frame2_1,bg="black",width=500,height=500)
frame1_3.grid(column=0,row=1,sticky='nsew')
frame1_4=tk.Frame(main_frame2_1,bg="pink",width=500,height=500)
frame1_4.grid(column=1,row=1,sticky='nsew')

frame1_1.grid_columnconfigure(0, weight=1)
frame1_1.grid_rowconfigure(0, weight=1)
frame1_1.grid_columnconfigure(1, weight=1)
frame1_1.grid_columnconfigure(2, weight=1)

frame1_2.grid_columnconfigure(0, weight=1)
frame1_2.grid_rowconfigure(0, weight=1)
frame1_2.grid_columnconfigure(1, weight=1)
frame1_2.grid_columnconfigure(2, weight=1)

class VerticalNavigationToolbar2Tk(NavigationToolbar2Tk):
        def __init__(self, canvas, window):
            super().__init__(canvas, window, pack_toolbar=False)
        def _Button(self, text, file,toggle, command):
            img_file = os.path.join(matplotlib.get_data_path(), 'images', file )
            im = tk.PhotoImage(master=self, file=img_file)
            im = im.subsample(2, 2)
            b = tk.Button(master=self, text=text, padx=2, pady=2, image=im, command=command)
            b._ntimage = im
            b.pack(side=tk.TOP)
            return b
        def _Spacer(self):
            s = tk.Frame(self, width=10, relief=tk.RIDGE, bg="DarkGray", padx=2)
            s.pack(side=tk.TOP, pady=1)
            return s
        def set_message(self, s):
            pass

def selection(event):
    trace=textVar.get()
    fullname = os.path.join(file_path,trace)
    df=pd.read_excel(fullname,  header=[3])
    df = df.fillna(0)
    df1=df.iloc[1:, :].reset_index(drop=True).set_index("distance")
    df2=df1.T
    temperature=df2.to_numpy(dtype='float')
    depth=df1.index
    depth.to_numpy(dtype='float')
    df3=pd.read_excel(fullname)
    df3= df3.fillna(0)
    df5=df3.head(2)
    df6=df5.T
    df6.columns = df6.iloc[0]
    df6= df6[1:]
    df6 = pd.DataFrame(df6)
    df6['Column'] = range(1, len(df6)+1)
    df6=df6.set_index("Column")
    time1=df6.index
    time1.to_numpy()
    time2 = time1.astype("float")
    b, a  = np.meshgrid(depth, time2)
    b=b.astype('float64')
    c=temperature
    c=c.astype('float64')
    l_a=a.min()
    r_a=a.max()
    l_b=b.min()
    r_b=b.max()
    l_c,r_c  =0, np.abs(c).max()

    ax4.clear()
    c1 = ax4.pcolormesh(a, b, c, cmap='jet', vmin=l_c, vmax=r_c)
    ax4.set_title('Heatmap'+ trace)
    ax4.axis([l_a, r_a, l_b, r_b])
    plt.gca().xaxis.set_major_locator(plt.MultipleLocator(2))
    vmin=np.min(temperature)
    vmax=np.max(temperature)
    c1.set_clim(0,110)
    ax4.set_ylabel('Distance')
    ax4.set_xlabel('Column')
    d=fig4.colorbar(c1,ax=ax4)
    d.set_label('ºF')
    canvas2.draw_idle()

values1=sorted(os.listdir(file_path), key=len)
textVar = tk.StringVar(frame1_1)
textVar.set('')
ccbox=ttk.Combobox(frame1_1,values=values1,height=20,width=10,textvariable=textVar)
ccbox.grid(column=1,row=0,sticky= "we")
ccbox.bind("<<ComboboxSelected>>",  selection)

def selection1(event):
    trace1=textVar1.get()
    print(trace1)
values11=sorted(os.listdir(file_path), key=len)
textVar1 = tk.StringVar(frame1_2)
textVar1.set('')
ccbox1=ttk.Combobox(frame1_2,values=values11,height=20,width=10,textvariable=textVar1)
ccbox1.grid(column=1,row=0,sticky= "we")
ccbox1.bind("<<ComboboxSelected>>",  selection1)

np.random.seed(19680801)
Z = np.random.rand(6, 10)
x = np.arange(-0.5, 10, 1)  # len = 11
y = np.arange(4.5, 11, 1)  # len = 7
fig4, ax4 = plt.subplots()
c1=ax4.pcolormesh(x, y, Z)
c1.set_clim(0,110)
d=fig4.colorbar(c1,ax=ax4)

canvas2 = FigureCanvasTkAgg(fig4, master=frame1_3)
fig4.canvas.draw()
canvas2.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH, expand=1)
toolbar2 = VerticalNavigationToolbar2Tk(canvas2, frame1_3)
toolbar2.update()
toolbar2.pack(side=tk.LEFT, fill=tk.Y)
newWindow.mainloop()

Heres is a SS of the problem:

Thanks in advance for any help, and Merry Christmas!!!!


问:
How to escape character in .expect when doing ssh operations in pexpect
I am Learning pexpect and very new to it, I am trying to get the hostname of another machine by using pexpect module of python.

When I am calling child.expect('root@.*:~\#') it is throwing an error called
searcher: searcher_re:
0: re.compile(b'root@worker01:~#')

The expected string after successful(ssh) login is  root@worker01:~#

The code is below

```<code>#!/usr/bin/python3

import pexpect

child = pexpect.spawn('ssh shobhit@xxx.xx.xx.xx')
child.expect('shobhit@.*password:')
child.sendline('y@9')
print('Logged In')
child.expect('root@.*:~\\#')
child.sendline('hostname')
print(child.before)
print('Got Hostname')
child.expect('root@.*:~\#')
print(child.before)
child.sendline('exit')
print('logged Out')
</code>```

I have tried escaping #, but I can't find that it is a regex pattern to be escaped. tried giving without \ too, but nothing seems to be working

Body:
I am Learning pexpect and very new to it, I am trying to get the hostname of another machine by using pexpect module of python.

When I am calling child.expect('root@.*:~\#') it is throwing an error called
searcher: searcher_re:
0: re.compile(b'root@worker01:~#')

The expected string after successful(ssh) login is  root@worker01:~#

The code is below

#!/usr/bin/python3

import pexpect

child = pexpect.spawn('ssh shobhit@xxx.xx.xx.xx')
child.expect('shobhit@.*password:')
child.sendline('y@9')
print('Logged In')
child.expect('root@.*:~\\#')
child.sendline('hostname')
print(child.before)
print('Got Hostname')
child.expect('root@.*:~\#')
print(child.before)
child.sendline('exit')
print('logged Out')

I have tried escaping #, but I can't find that it is a regex pattern to be escaped. tried giving without \ too, but nothing seems to be working


问:
Django Show var as Label name
models.py

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    telefoon = models.CharField(max_length=10, blank=True)
    telefoon_mobiel = models.CharField(max_length=10, blank=True)
    woonplaats = models.CharField(max_length=20, blank=True)
    postcode = models.CharField(max_length=6, blank=True)
    straat = models.CharField(max_length=20, blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

</code>```

form.py

```<code>class ProfileForm(forms.ModelForm):
    straat = forms.CharField(required=False,
                             widget=forms.TextInput(attrs={'class': 'form-control'}))
    postcode = forms.CharField(required=False,
                         widget=forms.TextInput(attrs={'class': 'form-control'}))
    woonplaats = forms.CharField(required=False,
                         widget=forms.TextInput(attrs={'class': 'form-control'}))
    telefoon = forms.CharField(required=False,
                         widget=forms.TextInput(attrs={'class': 'form-control'}))
    telefoon_mobiel = forms.CharField(required=False,
                         widget=forms.TextInput(attrs={'class': 'form-control'}))
    class Meta:
        model = Profile
        fields = ('telefoon', 'telefoon_mobiel', 'woonplaats', 'postcode', 'straat')
</code>```

views.py

```<code>@login_required
@transaction.atomic
def profiel(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, ('Profiel aangepast'))
            return redirect('user')
        else:
            messages.error(request, ('Los ondestaande probleem op'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)

    return render(request, 'public/profiel.html', {
        'user_form': user_form,
        'profile_form': profile_form,
    })

</code>```

template:

```<code><div class="card-body">
                <h5 class="card-title">Profiel {{ user.get_full_name }}</h5>
                <hr>
                <div class="container">
                    <div class="row">
                        <div class="col-sm">
                            {{ user.first_name }} {{ user.last_name }}
                        </div>
                        <div class="col-sm">
                            {{ straat }}
                        </div>
                    </div>
                    <br/>
                    <div class="row">
                        <div class="col-sm">
                            <label>Achternaam:</label>
                        </div>
                        <div class="col-sm">
                            {{ user_form.last_name }}
                        </div>
                    </div>
</code>```

When I call for example the field straat I am getting an editable field and I just want to show the value of it as text.

Title: Django Show var as Label name

Body:
models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    telefoon = models.CharField(max_length=10, blank=True)
    telefoon_mobiel = models.CharField(max_length=10, blank=True)
    woonplaats = models.CharField(max_length=20, blank=True)
    postcode = models.CharField(max_length=6, blank=True)
    straat = models.CharField(max_length=20, blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

form.py

class ProfileForm(forms.ModelForm):
    straat = forms.CharField(required=False,
                             widget=forms.TextInput(attrs={'class': 'form-control'}))
    postcode = forms.CharField(required=False,
                         widget=forms.TextInput(attrs={'class': 'form-control'}))
    woonplaats = forms.CharField(required=False,
                         widget=forms.TextInput(attrs={'class': 'form-control'}))
    telefoon = forms.CharField(required=False,
                         widget=forms.TextInput(attrs={'class': 'form-control'}))
    telefoon_mobiel = forms.CharField(required=False,
                         widget=forms.TextInput(attrs={'class': 'form-control'}))
    class Meta:
        model = Profile
        fields = ('telefoon', 'telefoon_mobiel', 'woonplaats', 'postcode', 'straat')

views.py

@login_required
@transaction.atomic
def profiel(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, ('Profiel aangepast'))
            return redirect('user')
        else:
            messages.error(request, ('Los ondestaande probleem op'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)

    return render(request, 'public/profiel.html', {
        'user_form': user_form,
        'profile_form': profile_form,
    })

template:

Profiel {{ user.get_full_name }}

                            {{ user.first_name }} {{ user.last_name }}

                            {{ straat }}

                            Achternaam:

                            {{ user_form.last_name }}

When I call for example the field straat I am getting an editable field and I just want to show the value of it as text.


问:
yolov7 deepSORT object tracking IDs are different in all video frames
I am trying to detect objects in a certain area using yolov7 and deepSORT algorithm, but in the results I get, I see that the IDs are always changing. I leave 3 photos for you to understand.

As you can see the IDs are different in all frames.

`

```<code>#class base virtual zone tracking
import random
import torch
import numpy as np
from models.experimental import attempt_load
from utils.torch_utils import TracedModel
from utils.datasets import letterbox
from utils.plots import plot_one_box, plot_one_box_center
from utils.general import check_img_size, non_max_suppression, scale_coords
import cv2
import time

from google.colab.patches import cv2_imshow
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

#deep sort
import os
import tensorflow as tf

physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
    tf.config.experimental.set_memory_growth(physical_devices[0], True)

from tensorflow.compat.v1 import ConfigProto
from deep_sort.tracker import Tracker
from deep_sort.detection import Detection
import matplotlib.pyplot as plt
from deep_sort import preprocessing, nn_matching
from tracking_helpers import read_class_names, create_box_encoder
from detection_helpers import *

class YOLOv7:
    def __init__(self, weights: str, image_size:int,device:str):
        self.device = device
        self.weights = weights
        self.model = attempt_load(self.weights, map_location=self.device) # Model Load FP32
        self.stride = int(self.model.stride.max())
        self.image_size = check_img_size(image_size, self.stride)

        if self.device != 'cpu':
            self.half = True
        else:
            self.half = False

        if self.half:
            self.model.half() # FP16

        self.names = self.model.module.names if hasattr(self.model , 'module') else self.model.names
        color_values = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(self.names))]
        self.colors = {i:color_values[i] for i in range(len(self.names))}

    def detect(self, raw_image: np.ndarray, conf_thresh =0.45, iou_thresh =0.45, classes = [0]): #default class people
        # Run inference
        if self.device != 'cpu':
            self.model(torch.zeros(1, 3, self.image_size, self.image_size).to(self.device).type_as(next(self.model.parameters())))
        with torch.no_grad():
            image = letterbox(raw_image, self.image_size, stride=self.stride)[0]
            image = image[:, :, ::-1].transpose(2, 0, 1)
            image = np.ascontiguousarray(image)
            image = torch.from_numpy(image).to(self.device)
            image = image.half() if self.half else image.float()
            image /= 255.0
            if image.ndimension() == 3:
                image = image.unsqueeze(0)
            # Inference
            detections = self.model(image, augment=False)[0]
            # Apply NMS
            detections = non_max_suppression(detections, conf_thresh, iou_thresh, classes=classes, agnostic=False)[0]
               # Rescale boxes from img_size to raw image size
            detections[:, :4] = scale_coords(image.shape[2:], detections[:, :4], raw_image.shape).round()
            return detections

    def tracking(self, video_frame, yolo_dets, inside_poly = True, count_objects:bool=False,verbose=False, reID_model_path = "./deep_sort/model_weights/mars-small128.pb", nms_max_overlap:float=1.0, max_cosine_distance:float=0.4, nn_budget:float=None):
        class_names = read_class_names()
        encoder = create_box_encoder(reID_model_path, batch_size=1)
        nms_max_overlap = nms_max_overlap
        metric = nn_matching.NearestNeighborDistanceMetric("cosine", max_cosine_distance, nn_budget)
        tracker = Tracker(metric)
        *xyxy, conf, cls = yolo_dets
        frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)
        if yolo_dets is None:
            bboxes = []
            scores = []
            classes = []
            num_objects = 0

        else:
            bboxes = yolo_dets[:,:4]
            bboxes[:,2] = bboxes[:,2] - bboxes[:,0] # convert from xyxy to xywh
            bboxes[:,3] = bboxes[:,3] - bboxes[:,1]

            scores = yolo_dets[:,4]
            classes = yolo_dets[:,-1]
            num_objects = bboxes.shape[0]
        #how many object you track
        names = []
        for i in range(num_objects): # loop through objects and use class index to get class name
            class_indx = int(classes[i])
            class_name = class_names[class_indx]
            names.append(class_name)

        names = np.array(names)
        count = len(names)

        if count_objects:
            cv2.putText(frame, "both inside and outside the polygon detection: {}".format(count), (5, 35), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5, (0, 0, 0), 2)

        # DeepSORT tacker work starts here
        features = encoder(frame, bboxes) # encode detections and feed to tracker. [No of BB / detections per frame, embed_size]
        detections = [Detection(bbox, score, class_name, feature) for bbox, score, class_name, feature in zip(bboxes, scores, names, features)] # [No of BB per frame] deep_sort.detection.Detection object

        cmap = plt.get_cmap('tab20b') #initialize color map
        colors = [cmap(i)[:3] for i in np.linspace(0, 1, 20)]

        boxs = np.array([d.tlwh for d in detections])  # run non-maxima supression below
        scores = np.array([d.confidence for d in detections])
        classes = np.array([d.class_name for d in detections])
        indices = preprocessing.non_max_suppression(boxs, classes, nms_max_overlap, scores)
        detections = [detections[i] for i in indices]

        tracker.predict()  # Call the tracker
        tracker.update(detections) #  updtate using Kalman Gain

        for track in tracker.tracks:  # update new findings AKA tracks
            #if not track.is_confirmed() or track.time_since_update > 1:
                #continue
            bbox = track.to_tlbr()
            class_name = track.get_class()
            color = colors[int(track.track_id) % len(colors)]  # draw bbox on screen
            color = [i * 255 for i in color]

            #drawing poly
            #pts = np.array([[6,449], [1052, 2], [1914, 6], [1766, 1074], [2, 1076]])
            #frame = cv2.polylines(frame, [pts], True, (0,0,255), 5)

            #creating poly
            #poli = Polygon([(6,449), (1052, 2), (1914, 6), (1766, 1074), (2, 1076)])
            #center = (int((bbox[0] + bbox[2]) / 2), int((bbox[1] + bbox[3]) / 2)) #center point  ( (x1 + x2) / 2, (y1 + y2) / 2 )
            #point = Point(center)
            if inside_poly:
                #drawing poly
                pts = np.array([[6,449], [1052, 2], [1914, 6], [1766, 1074], [2, 1076]])
                frame = cv2.polylines(frame, [pts], True, (0,0,255), 5)

                #creating poly
                poli = Polygon([(6,449), (1052, 2), (1914, 6), (1766, 1074), (2, 1076)])
                center = (int((bbox[0] + bbox[2]) / 2), int((bbox[1] + bbox[3]) / 2)) #center point  ( (x1 + x2) / 2, (y1 + y2) / 2 )
                point = Point(center)

                if poli.contains(point):
                    cv2.rectangle(frame, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2)
                    cv2.rectangle(frame, (int(bbox[0]), int(bbox[1]-30)), (int(bbox[0])+(len(class_name)+len(str(track.track_id)))*17, int(bbox[1])), color, -1)
                    cv2.putText(frame, class_name + " : " + str(track.track_id),(int(bbox[0]), int(bbox[1]-11)),0, 0.6, (255,255,255),1, lineType=cv2.LINE_AA)
                    cv2.putText(frame, "0", center,0, 0.6, (255,255,255),1, lineType=cv2.LINE_AA)
            else:
                cv2.rectangle(frame, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2)
                cv2.rectangle(frame, (int(bbox[0]), int(bbox[1]-30)), (int(bbox[0])+(len(class_name)+len(str(track.track_id)))*17, int(bbox[1])), color, -1)
                cv2.putText(frame, class_name + " : " + str(track.track_id),(int(bbox[0]), int(bbox[1]-11)),0, 0.6, (255,255,255),1, lineType=cv2.LINE_AA)

            if verbose == 2:
                print("Tracker ID: {}, Class: {},  BBox Coords (xmin, ymin, xmax, ymax): {}".format(str(track.track_id), class_name, (int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3]))))
        result = np.asarray(frame)
        result = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        return result

if __name__=='__main__':
    yolov7=YOLOv7(weights='yolov7x.pt', device='cpu', image_size=800)
    cap = cv2.VideoCapture('street5sn.mp4')
    torch.cuda.empty_cache()

    #writer
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))  # by default VideoCapture returns float instead of int
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = int(cap.get(cv2.CAP_PROP_FPS))
    codec = cv2.VideoWriter_fourcc(*"DIVX")
    out = cv2.VideoWriter("./output/video_out_track5sn-d2.mp4", codec, fps, (width, height))

    while True:

        t1 = time.time()
        ret, frame = cap.read()
        if not ret:
            break

        detections=yolov7.detect(frame)
        vir = yolov7.tracking(frame, detections, count_objects = True, inside_poly = False)
        out.write(vir)
        cv2_imshow(vir) #colab imshow kodu
        print("add frame ...")
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    out.release()
    cap.release()
    cv2.destroyAllWindows()
</code>```

`

I use this repo repo
I did not make any changes to other files.

Body:
I am trying to detect objects in a certain area using yolov7 and deepSORT algorithm, but in the results I get, I see that the IDs are always changing. I leave 3 photos for you to understand.

As you can see the IDs are different in all frames.

`

#class base virtual zone tracking
import random
import torch
import numpy as np
from models.experimental import attempt_load
from utils.torch_utils import TracedModel
from utils.datasets import letterbox
from utils.plots import plot_one_box, plot_one_box_center
from utils.general import check_img_size, non_max_suppression, scale_coords
import cv2
import time

from google.colab.patches import cv2_imshow
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

#deep sort
import os
import tensorflow as tf

physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
    tf.config.experimental.set_memory_growth(physical_devices[0], True)

from tensorflow.compat.v1 import ConfigProto
from deep_sort.tracker import Tracker
from deep_sort.detection import Detection
import matplotlib.pyplot as plt
from deep_sort import preprocessing, nn_matching
from tracking_helpers import read_class_names, create_box_encoder
from detection_helpers import *

class YOLOv7:
    def __init__(self, weights: str, image_size:int,device:str):
        self.device = device
        self.weights = weights
        self.model = attempt_load(self.weights, map_location=self.device) # Model Load FP32
        self.stride = int(self.model.stride.max())
        self.image_size = check_img_size(image_size, self.stride)

        if self.device != 'cpu':
            self.half = True
        else:
            self.half = False

        if self.half:
            self.model.half() # FP16

        self.names = self.model.module.names if hasattr(self.model , 'module') else self.model.names
        color_values = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(self.names))]
        self.colors = {i:color_values[i] for i in range(len(self.names))}

    def detect(self, raw_image: np.ndarray, conf_thresh =0.45, iou_thresh =0.45, classes = [0]): #default class people
        # Run inference
        if self.device != 'cpu':
            self.model(torch.zeros(1, 3, self.image_size, self.image_size).to(self.device).type_as(next(self.model.parameters())))
        with torch.no_grad():
            image = letterbox(raw_image, self.image_size, stride=self.stride)[0]
            image = image[:, :, ::-1].transpose(2, 0, 1)
            image = np.ascontiguousarray(image)
            image = torch.from_numpy(image).to(self.device)
            image = image.half() if self.half else image.float()
            image /= 255.0
            if image.ndimension() == 3:
                image = image.unsqueeze(0)
            # Inference
            detections = self.model(image, augment=False)[0]
            # Apply NMS
            detections = non_max_suppression(detections, conf_thresh, iou_thresh, classes=classes, agnostic=False)[0]
               # Rescale boxes from img_size to raw image size
            detections[:, :4] = scale_coords(image.shape[2:], detections[:, :4], raw_image.shape).round()
            return detections

    def tracking(self, video_frame, yolo_dets, inside_poly = True, count_objects:bool=False,verbose=False, reID_model_path = "./deep_sort/model_weights/mars-small128.pb", nms_max_overlap:float=1.0, max_cosine_distance:float=0.4, nn_budget:float=None):
        class_names = read_class_names()
        encoder = create_box_encoder(reID_model_path, batch_size=1)
        nms_max_overlap = nms_max_overlap
        metric = nn_matching.NearestNeighborDistanceMetric("cosine", max_cosine_distance, nn_budget)
        tracker = Tracker(metric)
        *xyxy, conf, cls = yolo_dets
        frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)
        if yolo_dets is None:
            bboxes = []
            scores = []
            classes = []
            num_objects = 0

        else:
            bboxes = yolo_dets[:,:4]
            bboxes[:,2] = bboxes[:,2] - bboxes[:,0] # convert from xyxy to xywh
            bboxes[:,3] = bboxes[:,3] - bboxes[:,1]

            scores = yolo_dets[:,4]
            classes = yolo_dets[:,-1]
            num_objects = bboxes.shape[0]
        #how many object you track
        names = []
        for i in range(num_objects): # loop through objects and use class index to get class name
            class_indx = int(classes[i])
            class_name = class_names[class_indx]
            names.append(class_name)

        names = np.array(names)
        count = len(names)

        if count_objects:
            cv2.putText(frame, "both inside and outside the polygon detection: {}".format(count), (5, 35), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5, (0, 0, 0), 2)

        # DeepSORT tacker work starts here
        features = encoder(frame, bboxes) # encode detections and feed to tracker. [No of BB / detections per frame, embed_size]
        detections = [Detection(bbox, score, class_name, feature) for bbox, score, class_name, feature in zip(bboxes, scores, names, features)] # [No of BB per frame] deep_sort.detection.Detection object

        cmap = plt.get_cmap('tab20b') #initialize color map
        colors = [cmap(i)[:3] for i in np.linspace(0, 1, 20)]

        boxs = np.array([d.tlwh for d in detections])  # run non-maxima supression below
        scores = np.array([d.confidence for d in detections])
        classes = np.array([d.class_name for d in detections])
        indices = preprocessing.non_max_suppression(boxs, classes, nms_max_overlap, scores)
        detections = [detections[i] for i in indices]

        tracker.predict()  # Call the tracker
        tracker.update(detections) #  updtate using Kalman Gain

        for track in tracker.tracks:  # update new findings AKA tracks
            #if not track.is_confirmed() or track.time_since_update > 1:
                #continue
            bbox = track.to_tlbr()
            class_name = track.get_class()
            color = colors[int(track.track_id) % len(colors)]  # draw bbox on screen
            color = [i * 255 for i in color]

            #drawing poly
            #pts = np.array([[6,449], [1052, 2], [1914, 6], [1766, 1074], [2, 1076]])
            #frame = cv2.polylines(frame, [pts], True, (0,0,255), 5)

            #creating poly
            #poli = Polygon([(6,449), (1052, 2), (1914, 6), (1766, 1074), (2, 1076)])
            #center = (int((bbox[0] + bbox[2]) / 2), int((bbox[1] + bbox[3]) / 2)) #center point  ( (x1 + x2) / 2, (y1 + y2) / 2 )
            #point = Point(center)
            if inside_poly:
                #drawing poly
                pts = np.array([[6,449], [1052, 2], [1914, 6], [1766, 1074], [2, 1076]])
                frame = cv2.polylines(frame, [pts], True, (0,0,255), 5)

                #creating poly
                poli = Polygon([(6,449), (1052, 2), (1914, 6), (1766, 1074), (2, 1076)])
                center = (int((bbox[0] + bbox[2]) / 2), int((bbox[1] + bbox[3]) / 2)) #center point  ( (x1 + x2) / 2, (y1 + y2) / 2 )
                point = Point(center)

                if poli.contains(point):
                    cv2.rectangle(frame, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2)
                    cv2.rectangle(frame, (int(bbox[0]), int(bbox[1]-30)), (int(bbox[0])+(len(class_name)+len(str(track.track_id)))*17, int(bbox[1])), color, -1)
                    cv2.putText(frame, class_name + " : " + str(track.track_id),(int(bbox[0]), int(bbox[1]-11)),0, 0.6, (255,255,255),1, lineType=cv2.LINE_AA)
                    cv2.putText(frame, "0", center,0, 0.6, (255,255,255),1, lineType=cv2.LINE_AA)
            else:
                cv2.rectangle(frame, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2)
                cv2.rectangle(frame, (int(bbox[0]), int(bbox[1]-30)), (int(bbox[0])+(len(class_name)+len(str(track.track_id)))*17, int(bbox[1])), color, -1)
                cv2.putText(frame, class_name + " : " + str(track.track_id),(int(bbox[0]), int(bbox[1]-11)),0, 0.6, (255,255,255),1, lineType=cv2.LINE_AA)

            if verbose == 2:
                print("Tracker ID: {}, Class: {},  BBox Coords (xmin, ymin, xmax, ymax): {}".format(str(track.track_id), class_name, (int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3]))))
        result = np.asarray(frame)
        result = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        return result

if __name__=='__main__':
    yolov7=YOLOv7(weights='yolov7x.pt', device='cpu', image_size=800)
    cap = cv2.VideoCapture('street5sn.mp4')
    torch.cuda.empty_cache()

    #writer
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))  # by default VideoCapture returns float instead of int
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = int(cap.get(cv2.CAP_PROP_FPS))
    codec = cv2.VideoWriter_fourcc(*"DIVX")
    out = cv2.VideoWriter("./output/video_out_track5sn-d2.mp4", codec, fps, (width, height))

    while True:

        t1 = time.time()
        ret, frame = cap.read()
        if not ret:
            break

        detections=yolov7.detect(frame)
        vir = yolov7.tracking(frame, detections, count_objects = True, inside_poly = False)
        out.write(vir)
        cv2_imshow(vir) #colab imshow kodu
        print("add frame ...")
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    out.release()
    cap.release()
    cv2.destroyAllWindows()

`

I use this repo repo
I did not make any changes to other files.


问:
System cannot find org.apache.maven.wrapper.MavenWrapperMain which exists
When attempting to use maven's clean or install function on a SpringBoot Java program, I ran into the following error (Full error at the bottom). The main issue appears to be what I have highlighted below.

```<code>The system cannot find the file D:\01. GitHub\springBootTutorial\.mvn\wrapper\maven-wrapper.properties.
</code>```

Currently, I have verified that the file exists and these are the contents (unchanged from creation). The error pops up when I attempt to do other actions like install, test.

maven-wrapper.properties

```<code>distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
</code>```

I believe this is something to do with filepath, currently when I execute the clean command by clicking on the button inside VSCode, I am in D:\01. GitHub\springBootTutorial> which seems to work when running the Java program. I have ensured that Maven is indeed installed with mvn -v which returns the version I have.

Do let me know how I can begin troubleshooting this!

Full error

```<code>D:\01. GitHub\springBootTutorial>"d:\01. GitHub\springBootTutorial\demo\mvnw.cmd" install -f "d:\01. GitHub\springBootTutorial\demo\pom.xml"
The system cannot find the file D:\01. GitHub\springBootTutorial\.mvn\wrapper\maven-wrapper.properties.
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:1 char:282
+ ... pe]::Tls12; $webclient.DownloadFile('https://repo.maven.apache.org/ma ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

Error: Could not find or load main class org.apache.maven.wrapper.MavenWrapperMain
Caused by: java.lang.ClassNotFoundException: org.apache.maven.wrapper.MavenWrapperMain
</code>```

Body:
When attempting to use maven's clean or install function on a SpringBoot Java program, I ran into the following error (Full error at the bottom). The main issue appears to be what I have highlighted below.

The system cannot find the file D:\01. GitHub\springBootTutorial\.mvn\wrapper\maven-wrapper.properties.

Currently, I have verified that the file exists and these are the contents (unchanged from creation). The error pops up when I attempt to do other actions like install, test.

maven-wrapper.properties

distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar

I believe this is something to do with filepath, currently when I execute the clean command by clicking on the button inside VSCode, I am in D:\01. GitHub\springBootTutorial> which seems to work when running the Java program. I have ensured that Maven is indeed installed with mvn -v which returns the version I have.

Do let me know how I can begin troubleshooting this!

Full error

D:\01. GitHub\springBootTutorial>"d:\01. GitHub\springBootTutorial\demo\mvnw.cmd" install -f "d:\01. GitHub\springBootTutorial\demo\pom.xml"
The system cannot find the file D:\01. GitHub\springBootTutorial\.mvn\wrapper\maven-wrapper.properties.
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:1 char:282
+ ... pe]::Tls12; $webclient.DownloadFile('https://repo.maven.apache.org/ma ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

Error: Could not find or load main class org.apache.maven.wrapper.MavenWrapperMain
Caused by: java.lang.ClassNotFoundException: org.apache.maven.wrapper.MavenWrapperMain


问:
How to create shared element transition on Android 12 Splashscreen API?
Is it possible to create a shared element transition of an iconView from the splashscreen into the main activity? If so, how?

I've looked around but it seems that with previous posts they utilize fragments or two separate activities to create this effect. Am relatively new to Android dev and Kotlin so would very much appreciate some guidance.

Thanks


问:
I was trying to access the database from my python program but getting error for the connection
```<code>from flask import Flask,render_template,request
from flask_sqlalchemy import SQLAlchemy
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:@localhost/digifit"
db = SQLAlchemy(app)

'''class is the table created in the database'''
class Details(db.Model):
    sno = db.Column(db.Integer(), primary_key=True)
    username = db.Column(db.String(100), unique=True, nullable=False)
    password = db.Column(db.String(8), unique=True, nullable=False)
@app.route("/login",methods=["GET","POST"])
def login():
    if request.method=='POST':
        '''add entry to the database'''
        username=request.form.get('username')
        Password=request.form.get('password')
        entry = Details(username=username,password=Password)
        db.session.add(entry)
        db.session.commit()
    return render_template("login.html")
</code>```

this is the code for the program . I am using flask sql alchemy.
The error I am getting on submiting information on login page created is :
1045, "Access denied for user 'root'@'localhost' (using password: NO)")
(Background on this error at: https://sqlalche.me/e/14/e3q8

Body:
from flask import Flask,render_template,request
from flask_sqlalchemy import SQLAlchemy
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:@localhost/digifit"
db = SQLAlchemy(app)

'''class is the table created in the database'''
class Details(db.Model):
    sno = db.Column(db.Integer(), primary_key=True)
    username = db.Column(db.String(100), unique=True, nullable=False)
    password = db.Column(db.String(8), unique=True, nullable=False)
@app.route("/login",methods=["GET","POST"])
def login():
    if request.method=='POST':
        '''add entry to the database'''
        username=request.form.get('username')
        Password=request.form.get('password')
        entry = Details(username=username,password=Password)
        db.session.add(entry)
        db.session.commit()
    return render_template("login.html")

this is the code for the program . I am using flask sql alchemy.
The error I am getting on submiting information on login page created is :
1045, "Access denied for user 'root'@'localhost' (using password: NO)")
(Background on this error at: https://sqlalche.me/e/14/e3q8


问:
The LINQ expression 'DbSet<Bank>().OrderBy(b => new BankViewModel{ }.Id)' could not be translated
dotnet core6:
when add to list :(var list = _bankService.GetAll();) , its ok , but i don't want fetch all data , then filter it (odata)

my controller:

```<code> public class BankOdataController : ODataController
{
    private readonly IBankService _bankService;
    public BankOdataController(IBankService bankService)
    {

        _bankService = bankService;
    }

    [EnableQuery]

    public ActionResult<BankViewModel> Get()
    {
        var list = _bankService.GetAll();
        return Ok(list);
    }
}
</code>```

bank service intefrace :

```<code>   public interface IBankService : IDisposable
{
    IQueryable<BankViewModel> GetAll();

}
</code>```

bank Service:

```<code>public class BankService : IBankService
{
    private readonly IMapper _mapper;
    private readonly IEventStoreRepository _eventStoreRepository;
    private readonly IBankRepository _bankRepository;
    private readonly IMediatorHandler _mediator;

    public BankService(IMapper mapper,
                             IBankRepository bankRepository,
                             IMediatorHandler mediator,
                             IEventStoreRepository eventStoreRepository)
    {
        _mapper = mapper;
        _bankRepository = bankRepository;
        _mediator = mediator;
        _eventStoreRepository = eventStoreRepository;
    }

    public IQueryable<BankViewModel> GetAll()
    {
        var banks =  _bankRepository.GetAll();
        return banks.ProjectTo<BankViewModel>(_mapper.ConfigurationProvider);
    }

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}
</code>```

IBank Repository:

```<code>  public interface IBankRepository : IRepository<Bank>
{
   IQueryable<Bank> GetAll();

}
</code>```

Bank Repository:

```<code> public class BankRepository : IBankRepository
{
    protected readonly CargoContext Db;
    protected readonly DbSet<Bank> DbSet;

    public BankRepository(CargoContext context)
    {
        Db = context;
        DbSet = Db.Set<Bank>();
    }

    public IUnitOfWork UnitOfWork => Db;

    public void Dispose()
    {
        Db.Dispose();
    }

    public IQueryable<Bank> GetAll()
    {
        return  DbSet.AsQueryable();
    }

}
</code>```

AutoMapper:

```<code> public class DomainToViewModelMappingProfile : Profile
{
    public DomainToViewModelMappingProfile()
    {
        CreateMap<Bank, BankViewModel>();
    }
}
</code>```

program.cs:

```<code>var modelBuilder = new ODataConventionModelBuilder();
</code>```

modelBuilder.EntitySet("BankOdata");

builder.Services.AddControllers().AddOData(

```<code>options =>
{
    options.EnableQueryFeatures(1000);
    options.AddRouteComponents("odata", modelBuilder.GetEdmModel());
}
);
</code>```

Body:
dotnet core6:
when add to list :(var list = _bankService.GetAll();) , its ok , but i don't want fetch all data , then filter it (odata)

my controller:

 public class BankOdataController : ODataController
{
    private readonly IBankService _bankService;
    public BankOdataController(IBankService bankService)
    {

        _bankService = bankService;
    }

    [EnableQuery]

    public ActionResult<BankViewModel> Get()
    {
        var list = _bankService.GetAll();
        return Ok(list);
    }
}

bank service intefrace :

   public interface IBankService : IDisposable
{
    IQueryable<BankViewModel> GetAll();

}

bank Service:

public class BankService : IBankService
{
    private readonly IMapper _mapper;
    private readonly IEventStoreRepository _eventStoreRepository;
    private readonly IBankRepository _bankRepository;
    private readonly IMediatorHandler _mediator;

    public BankService(IMapper mapper,
                             IBankRepository bankRepository,
                             IMediatorHandler mediator,
                             IEventStoreRepository eventStoreRepository)
    {
        _mapper = mapper;
        _bankRepository = bankRepository;
        _mediator = mediator;
        _eventStoreRepository = eventStoreRepository;
    }

    public IQueryable<BankViewModel> GetAll()
    {
        var banks =  _bankRepository.GetAll();
        return banks.ProjectTo<BankViewModel>(_mapper.ConfigurationProvider);
    }

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}

IBank Repository:

  public interface IBankRepository : IRepository<Bank>
{
   IQueryable<Bank> GetAll();

}

Bank Repository:

 public class BankRepository : IBankRepository
{
    protected readonly CargoContext Db;
    protected readonly DbSet<Bank> DbSet;

    public BankRepository(CargoContext context)
    {
        Db = context;
        DbSet = Db.Set<Bank>();
    }

    public IUnitOfWork UnitOfWork => Db;

    public void Dispose()
    {
        Db.Dispose();
    }

    public IQueryable<Bank> GetAll()
    {
        return  DbSet.AsQueryable();
    }

}

AutoMapper:

 public class DomainToViewModelMappingProfile : Profile
{
    public DomainToViewModelMappingProfile()
    {
        CreateMap<Bank, BankViewModel>();
    }
}

program.cs:

var modelBuilder = new ODataConventionModelBuilder();

modelBuilder.EntitySet("BankOdata");

builder.Services.AddControllers().AddOData(

options =>
{
    options.EnableQueryFeatures(1000);
    options.AddRouteComponents("odata", modelBuilder.GetEdmModel());
}
);


问:
500 internal error trying get a response from test
I am keep getting 500 error trying to make any calls from my test project. I am following microsoft guide https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0. Now I am using sqlite for dev part, later I'll switch to sqlite.
Test case:

```<code>public class CategoryContollerTests
{
    private readonly WebApplicationFactory<Program> _factory;
    public CategoryContollerTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }
    [Fact]
    public async Task Get_ReturnCategory()
    {
        var client = _factory.CreateClient();

        var response = await client.GetAsync("api/Categories");
        int i = 0;
    }
}
</code>```

Main project Program file:

```<code>    var myAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();

builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo() { Title = "Test API", Version = "v1" });
});

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddDbContext<DataContext>(opt =>
{
    opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
});

//Enable CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: myAllowSpecificOrigins,
    builder =>
    {
        builder.WithOrigins("http://localhost:4200")
        .AllowAnyMethod()
        .AllowAnyHeader();
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API v1");
    });
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

public partial class Program { }
</code>```

What could cause the problem? (App works fine)
Read the logs, and occured that the problem is with the database

[2022-12-24 15:52:22.034 +01:00  ERR]  An unhandled exception has occurred while executing the request.
Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'no such table: Categories'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
Still don't know how to fix this, it should simply use my database which works fine.

Body:
I am keep getting 500 error trying to make any calls from my test project. I am following microsoft guide https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0. Now I am using sqlite for dev part, later I'll switch to sqlite.
Test case:

public class CategoryContollerTests
{
    private readonly WebApplicationFactory<Program> _factory;
    public CategoryContollerTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }
    [Fact]
    public async Task Get_ReturnCategory()
    {
        var client = _factory.CreateClient();

        var response = await client.GetAsync("api/Categories");
        int i = 0;
    }
}

Main project Program file:

    var myAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();

builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo() { Title = "Test API", Version = "v1" });
});

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddDbContext<DataContext>(opt =>
{
    opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
});

//Enable CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: myAllowSpecificOrigins,
    builder =>
    {
        builder.WithOrigins("http://localhost:4200")
        .AllowAnyMethod()
        .AllowAnyHeader();
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API v1");
    });
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

public partial class Program { }

What could cause the problem? (App works fine)
Read the logs, and occured that the problem is with the database

[2022-12-24 15:52:22.034 +01:00  ERR]  An unhandled exception has occurred while executing the request.
Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'no such table: Categories'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
Still don't know how to fix this, it should simply use my database which works fine.


问:
how copy marker location in leaflet
i have a map leaflet and show on map marker whit lat,lug.

how now create location link from marker lat,lug ?

enter image description here

i for create link used this code :

```<code>if (navigator && navigator.clipboard && navigator.clipboard.writeText)
        navigator.clipboard.writeText(
          `https://maps.google.com/?q=${this.orderInfo.latitude},${this.orderInfo.longitude}`
        );
</code>```

Title: how copy marker location in leaflet

Body:
i have a map leaflet and show on map marker whit lat,lug.

how now create location link from marker lat,lug ?

enter image description here

i for create link used this code :

if (navigator && navigator.clipboard && navigator.clipboard.writeText)
        navigator.clipboard.writeText(
          `https://maps.google.com/?q=${this.orderInfo.latitude},${this.orderInfo.longitude}`
        );


问:
Make custom keyboard independent of text field
I have implemented a custom keyboard, that is drawn in an ImageView. Now I want to make it floating, it should be placeable anywhere.

The position, width and height is set in the following way:

```<code>    private void setKeyboardDimensionAndPosition(int widthPI, int heightPI, int xDP, int yDP) {
        WindowManager.LayoutParams windowParams = getWindow().getWindow().getAttributes();
        windowParams.x = (int) (xDP * GUIManager.getDensity());
        windowParams.y = (int) (yDP * GUIManager.getDensity());
        windowParams.width = widthPI;
        windowParams.height = heightPI;

        (new Handler(Looper.getMainLooper())).post(() -> {
            getWindow().getWindow().setAttributes(windowParams);
        });
    }
</code>```

But the keyboard is always sticked to the text box - it is always below it! It would even be fine when the text box is covered by the keyboard, it should be totally free!

Body:
I have implemented a custom keyboard, that is drawn in an ImageView. Now I want to make it floating, it should be placeable anywhere.

The position, width and height is set in the following way:

    private void setKeyboardDimensionAndPosition(int widthPI, int heightPI, int xDP, int yDP) {
        WindowManager.LayoutParams windowParams = getWindow().getWindow().getAttributes();
        windowParams.x = (int) (xDP * GUIManager.getDensity());
        windowParams.y = (int) (yDP * GUIManager.getDensity());
        windowParams.width = widthPI;
        windowParams.height = heightPI;

        (new Handler(Looper.getMainLooper())).post(() -> {
            getWindow().getWindow().setAttributes(windowParams);
        });
    }

But the keyboard is always sticked to the text box - it is always below it! It would even be fine when the text box is covered by the keyboard, it should be totally free!


问:
Where to make changes in Flora for another FloraNode creation instead of default?
So,there is the implementation of Flora present in omnet++.Now,I have to  implement another LoraNode inside the default code.By default there is only one LoraNode available .So, how to create the another node in the default implementation.Can somebody help me out?
[1]: https://i.stack.imgur.com/dMJMU.png
I am talking about loRaNodes[0]part.
The code is-

```<code>     package flora.LoraNode;

     import inet.mobility.static.StationaryMobility;
     import inet.networklayer.common.InterfaceTable;
     import inet.applications.contract.IApp;
     import flora.LoRa.LoRaNic;
    module LoRaNode
     {
        parameters:
            int numApps = default(0);
            string deploymentType = default("");
            double maxGatewayDistance = default(320.0);
            double gatewayX = default(320.0);
            double gatewayY = default(320.0);
            @networkNode();
            *.interfaceTableModule =    default(absPath(".interfaceTable"));
            @display("bgb=297,313;i=device/accesspoint;is=vs");
        submodules:
            interfaceTable: InterfaceTable {
                @display("p=30,26");
            }
            mobility: StationaryMobility {
                @display("p=24,88");
            }
            LoRaNic: LoRaNic {
                @display("p=137,239");
            }
            app[numApps]: <> like IApp {
                parameters:
                    @display("p=375,76,row,150");
                }
        connections allowunconnected:
            for i=0..numApps-1 {
                app[i].socketOut --> LoRaNic.upperLayerIn;
                LoRaNic.upperLayerOut --> app[i].socketIn;
             }
    }
</code>```

I tried changing the default (0) to defaullt (1) or created another ned file file similar to this one and name it as module loRaNode(2) but nothing happen.

Body:
So,there is the implementation of Flora present in omnet++.Now,I have to  implement another LoraNode inside the default code.By default there is only one LoraNode available .So, how to create the another node in the default implementation.Can somebody help me out?
[1]: https://i.stack.imgur.com/dMJMU.png
I am talking about loRaNodes[0]part.
The code is-

     package flora.LoraNode;

     import inet.mobility.static.StationaryMobility;
     import inet.networklayer.common.InterfaceTable;
     import inet.applications.contract.IApp;
     import flora.LoRa.LoRaNic;
    module LoRaNode
     {
        parameters:
            int numApps = default(0);
            string deploymentType = default("");
            double maxGatewayDistance = default(320.0);
            double gatewayX = default(320.0);
            double gatewayY = default(320.0);
            @networkNode();
            *.interfaceTableModule =    default(absPath(".interfaceTable"));
            @display("bgb=297,313;i=device/accesspoint;is=vs");
        submodules:
            interfaceTable: InterfaceTable {
                @display("p=30,26");
            }
            mobility: StationaryMobility {
                @display("p=24,88");
            }
            LoRaNic: LoRaNic {
                @display("p=137,239");
            }
            app[numApps]: <> like IApp {
                parameters:
                    @display("p=375,76,row,150");
                }
        connections allowunconnected:
            for i=0..numApps-1 {
                app[i].socketOut --> LoRaNic.upperLayerIn;
                LoRaNic.upperLayerOut --> app[i].socketIn;
             }
    }

I tried changing the default (0) to defaullt (1) or created another ned file file similar to this one and name it as module loRaNode(2) but nothing happen.


问:
Calculate the percentage of worst cases for quick sort
if I have n! options for array of n different numbers (1 till n) as input in quicksort ,how many of them can be worst cases? I understand that worst case is when the array is sorted/almost sorted , or reversed sorted/almost reversed sorted.
but I need to find out how much in percentage of all n! options I have, can be the worst cases , cant find the mathematical way to calculate that. is there anyway to calculate it ?</p>